Compare commits

...
Author SHA1 Message Date
nosami 32bcd6c6a9 [F#] Reinstate _DebugFileExt as it's needed for mobile debugging.
Also added a mechanism for users to override DebugType
2017-09-11 10:58:55 +01:00
Ankit Jain 794f7a7612 Update roslyn-binaries to be >= than VS 15.4
Version based on
https://github.com/dotnet/cli/blob/release/2.0-vs/build/DependencyVersions.props#L6

	<CLI_Roslyn_Version>2.3.2-beta1-61921-05</CLI_Roslyn_Version>
2017-09-08 23:20:44 +02:00
Sebastien Pouliot fe516ba0bd [linker] Bump to HEAD (master)
This will allow the SDK (XI/XM) to use the latest version directly from
mono (like cecil) and avoid potential out of sync issues
2017-09-08 18:48:39 +02:00
Bernhard Urban b2acee0ade Merge pull request #5513 from lewurm/2017-06-gethashcode-delegate
[2017-06][bcl] Use RuntimeHelpers.GetHashCode () for getting the hash code of …
2017-09-06 14:03:26 +02:00
Zoltan Varga 8af44d2b16 [bcl] Use RuntimeHelpers.GetHashCode () for getting the hash code of … (#5511)
* [bcl] Use RuntimeHelpers.GetHashCode () for getting the hash code of the delegate target to avoid calling user defined hash code implementations which can throw exceptions. Fixes a regression introduced by a48bc43985.

* add test for #59235

https://bugzilla.xamarin.com/show_bug.cgi?id=59235

* [fixup] RuntimeHelpers.GetHashCode handles null
2017-09-06 13:58:03 +02:00
Jason Imison f4cf17d61d Add portable pdb metadata fix from https://github.com/Microsoft/visualfsharp/pull/3553 (#5510) 2017-09-05 22:51:36 +02:00
nosami 8f3ddb716e Revert "Add portable pdb metadata fix from https://github.com/Microsoft/visualfsharp/pull/3553"
This reverts commit a4cd00b333.
2017-09-05 21:44:30 +01:00
nosami a4cd00b333 Add portable pdb metadata fix from https://github.com/Microsoft/visualfsharp/pull/3553 2017-09-05 21:36:51 +01:00
nosami cb6a2fc7ff Switch F# builds over to portable pdb 2017-09-05 15:52:41 +01:00
Rodrigo Kumpera c81fe5e84d [mini] Handle magic interfaces in common_trampoline as if they were variant.
With the introduction of magic array interfaces, they must be handled as if they
were variant if they are being dispatched against an array.

This was not being done in common_trampoline and resulted in the IMT thunk never
getting rebuilt and getting decent perf.

With this patch, dispatch to simple methods such as Array::Count over a magic interface
in a covariant case (such as IList<object> dispatch onto string[]) will accrue gvi's.

On a trivial benchmark of executing Count 1M times, perf goes from 760ms to 50ms.
2017-09-04 11:04:28 +02:00
Bernhard Urban 1cf175e95c Merge pull request #5493 from lewurm/2017-06-mono-api-html
[2017-06][mono-api-html] Allow `-r` to ignore class removals
2017-09-04 10:42:56 +02:00
Zoltan Varga 01d1582fb7 [llvm] Set the MonoJitInfo.from_llvm flag for methods loaded from llvm, it got broken by 1debf39341. (#5223) 2017-09-02 06:36:01 +02:00
Jonathan Pryor f177485aaf [mono-api-html] Allow -r to ignore class removals
Allow `mono-api-html -r REGEX` to be used to silence messages
regarding class and namespace removals in addition to member removals.
2017-09-01 23:23:56 +02:00
Martin Baulig 1d4fc17faa [System]: Fix minor leaks in AppleTls. (#5369) (#5379)
These should be automatically collected by the GC, but explicitly disposing
will keep memory usage more stable over time and keep pressure off the GC.

(cherry picked from commit 093915cf83)
(cherry picked from commit 9b8bb0edbe)
2017-08-31 12:49:33 -04:00
Martin Baulig dc29ba37a6 [System]: Fix major AppleTls memory leak. Bug #56814. (#5370) (#5376)
(cherry picked from commit c74f44126e)
2017-08-31 12:49:18 -04:00
Marek Safar 8bcbd3cc89 Bump cecil 2017-08-31 15:32:55 +02:00
Ludovic Henry 24901ef720 [w32error] Add ENODEV -> ERROR_DEV_NOT_EXIST error translation (#5385) (#5392)
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=58738
2017-08-30 17:57:58 -04:00
Ludovic Henry b263d37e15 [marshal] Rethrow in native-to-managed wrapper to keep exception stacktrace (#5384) (#5394)
* [marshal] Rethrow in native-to-managed wrapper to keep exception stacktrace

Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=58782

* [interp] disable tests for 58782 as they rely on appdomains
2017-08-30 17:57:46 -04:00
Zoltan Varga 56267e8476 [amd64] Make code patching smp safe for the case where we emit a mov + call_reg. Hopefully fixes #57959. (#5452) 2017-08-28 16:29:14 -04:00
Alexander Köplinger 1afb931de6 Fix typo from 63b57ba7a1 2017-08-28 12:45:10 +02:00
Alexander Köplinger 63b57ba7a1 [configure.ac] Don't include the .build number in runtime-corlib version (#5449)
It's causing unnecessary complexity because we need to create a new
monolite when bumping the .build number in a major.minor.build
version like from 5.2.0 -> 5.2.1

corlib version bumps are very rare in those cases and even then
you can just increment the MONO_CORLIB_COUNTER variable.
(cherry picked from commit ec9a95dd53)
2017-08-25 22:01:16 +02:00
Marek Safar cbeae56621 [threadpool] Reduce logging verbosity level. Fixes #58829 2017-08-23 09:52:35 +02:00
Jo Shields f527b26e19 [msi] Fix typos in f9bdab7928
(cherry picked from commit da9287e432)
2017-08-22 10:18:53 -04:00
Alexander Köplinger ebee14deca Bump timeout for TaskTests.Delay_Simple (#5410)
Should be reverted once https://bugzilla.xamarin.com/show_bug.cgi?id=58877 is investigated and fixed.
(cherry picked from commit f567c2e5eb)
2017-08-21 17:29:05 +02:00
Jo Shields 929575bb0e [msi] Pull in MSI changes from Mono 5.2 branch 2017-08-21 09:59:36 -04:00
Aleksey Kliger 4fe608c216 [threads] Use designated initializer syntax in MAKE_SPECIAL_STATIC_OFFSET
Originally we used a C90-style struct initializer `{ (index), (offset), (type)
}`.  Unfortunately, SpecialStaticOffset is defined with fields in a different
order on big-endian and little-endian machines.  Using a designated
initializer, we don't have to care about the order.
2017-08-18 18:25:15 -04:00
Alexander Köplinger 6b8abfeb7c Bump bockbuild to remove gtk+ screen patch 2017-08-17 21:17:25 +02:00
Ludovic Henry 000682fe19 [corlib] Increase timeout for MonoTests.System.Runtime.Remoting.TestSynchronizationReleasedOnMultipleAcquire (#5373)
(cherry picked from commit 6e30ded242)
2017-08-17 19:01:59 +02:00
Ankit Jain 282e0fb6d3 Empty commit to trigger a wrench build 2017-08-16 20:16:43 -04:00
Ankit Jain 4cadbfc272 Bump roslyn-binaries 2017-08-16 20:12:06 -04:00
Ankit Jain 2071615b87 [msbuild] Bump to d15.4 branch HEAD 2017-08-16 14:45:40 -04:00
Ankit Jain cbc738c44d [msbuild] Install a deniedAssembliesList.txt to support denied ... (#5358)
... assemblies.

msbuild tries to filter out the denied assemblies, which mono refuses to
load, during a build. It uses the `deniedAssembliesList.txt` installed
to `$mono_prefix/lib/mono/xbuild` to identify them.

This was generated with:

 `$ mono tools/nuget-hash-extractor/nuget-hash-extractor.exe nugets guids_for_msbuild > mcs/tools/xbuild/data/deniedAssembliesList.txt`

This file needs to be kept in sync with any changes in the assemblies
denied by the runtime.

msbuild PR that adds support for this -
https://github.com/mono/msbuild/pull/23 .

cherry-pick 823bca4aed
2017-08-16 14:37:25 -04:00
Ankit Jain 7f9739d414 Install Roslyn binaries, including msbuild tasks to msbuild/Roslyn (#5251)
.. directory, which is `$mono_prefix/lib/mono/msbuild/15.0/bin/Roslyn/`

Mono installs `csc.exe` but the corresponding
`Microsoft.Build.Tasks.CodeAnalysis.dll` required for supporting msbuild C#
projects is installed by msbuild. But these two can get out of sync,
like they did and had to be worked around in
https://github.com/mono/msbuild/pull/19 .

Instead, we now install all the relevant roslyn bits (C# and VB) from the same
source. Only the msbuild specific files are copied to the Roslyn folder.
VBCSCompiler, csi and their dependencies are symlinked from `lib/mono/4.5`.

Also:

- csi.exe is included since the tool is surfaced as an msbuild task,
  and that requires the *Scripting.dll assemblies.
- VBCSCompiler* - shared compiler is installed
- vbc.exe doesn't work on mono currently, so skipping that
- And `Microsoft.DiaSymReader.Native.{amd64,x86}.dll` are dropped.

Cherry-picking 43cec6c0dd
2017-08-16 14:31:38 -04:00
Alexander Köplinger 4432d94f47 Bump bockbuild 2017-08-16 18:38:13 +02:00
Cody Russell 84a67e67e0 Bump bockbuild to get latest gtk patches (#5278) 2017-08-16 18:30:01 +02:00
Aleksey Kliger (λgeek) 3d2159b391 Merge pull request #5366 from lambdageek/bug-17325-2017-06
[2017-06][remoting] transparent proxy GetType of an interface should return the interface Type, not MarshalByRefObject. (Fixes #17325)
2017-08-14 17:41:38 -04:00
Alexander Köplinger 2cc5ff0ef3 Bump nuget to latest 4.3.0 release (#5368)
(cherry picked from commit a9a08890cb)
2017-08-14 19:30:00 +02:00
Alexis Christoforides ab5dc2d67e [MacSDK] Switch to HTTPS for downloading SQLite
(cherry picked from commit aa2ea3b812)
2017-08-14 19:29:23 +02:00
Alexander Köplinger b339b6677c Bump nuget-buildtasks (#5363)
Includes https://github.com/NuGet/NuGet.BuildTasks/pull/35

(cherry picked from commit e88178655b)
2017-08-14 17:54:37 +02:00
Aleksey Kliger a6db6112ca [remoting] transparent proxy GetType of an interface should return the
interface Type, not MarshalByRefObject. (Fixes #17325)

If a RealProxy instance is created (using the protected RealProxy(Type)
constructor) for an interface, mono internally sets up a MonoRemoteClass which
looks like a proxy for a MarshalByRefObject instance that happens to implement
the given interface.  However mono_class_proxy_vtable just does a memcpy() to
setup the MonoVTable:type field of the transparent proxy's vtable.  That type
field is hit by the JIT when System.Object.GetType() is called - and on .NET
Framework GetType for a transparent proxy of an interface returns the interface
not (as Mono used to) typeof(MarshalByRefObject).

Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=17325
2017-08-14 11:37:51 -04:00
Aleksey Kliger fd2303ecb6 [test] Add regression test for GetType() of a transparent proxy.
Check that calling GetType() on a transparent proxy of a RealProxy of an
interface returns that interface type.
2017-08-14 11:37:50 -04:00
Alexander Köplinger 490cc373e4 [System.ServiceProcess] Remove "browser" service from dependencies in test (#5183) (#5351)
LanmanWorkstation and SamSs services don't depend on the Browser
service anymore, at least in the Windows Server build that our
Azure VM agents on Jenkins are using now. This started failing a
few days ago so I assume a new build was rolled out.
(cherry picked from commit 1418f0d58b)
2017-08-10 19:26:39 +02:00
Ankit Jain b65d1a9ffc [msbuild] Bump to the d15.4 branch HEAD (#5342) 2017-08-09 11:46:41 -04:00
Zoltan Varga 8531639386 [runtime] Fix a case where klass->blittable was written without holding the loader locked. (#5331) 2017-08-08 16:36:39 -04:00
Jason Imison 25ef6061fd Merge pull request #5334 from mono/2017-06-fsharp-resources
Bump F# to 4.1.25
2017-08-08 12:54:47 +01:00
nosami 066fde97d3 Bump F# to 4.1.25 and remove already merged patches 2017-08-08 12:32:12 +01:00
Zoltan Varga 28a417c2c0 [btls] Disable BUILD_SHARED_LIBS while building boringssl, so its symbols are not exported from the btls shared lib. (#5307) 2017-08-04 11:39:52 -04:00
Marek Safar c97a3fcfd2 [mcs] Pending implementation of accessors cannot hide base implementation with different member type 2017-08-04 15:18:49 +02:00
Zoltan Varga 3acee7af00 [bcl] Fix Delegate.GetHashCode () so it takes into account the target too. Fixes #58399. (#5296) 2017-08-02 13:02:04 -04:00
Zoltan Varga b6cd01f017 [llvm] Fix the calling of fault clauses in llvm compiled code. Fixes #58446. (#5287) 2017-08-01 14:12:07 -04:00
Aleksey Kliger (λgeek) 67a2f14e73 Merge pull request #5289 from lambdageek/bug-58454-2017-06
[2017-06][sre] Pass declaring type to GetMethodFromHandle in GenericTypeParameterBuilder:InternalResolve (Fixes #58454)
2017-08-01 12:16:29 -04:00
Aleksey Kliger 8043db4c77 [sre] Pass declaring type to GetMethodFromHandle in
GenericTypeParameterBuilder:InternalResolve (Fixes #58454)

When the parameter belongs to a method builder, we need to pass the declaring
type (appropriately resolved) to GetMethodFromHandle to avoid an
ArgumentException.

Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=58454
2017-07-31 18:47:45 -04:00
Aleksey Kliger 252415606d [test] Check that GenericTypeParamBuilder:InternalResolve passes declaring type
to GetMethodFromHandle

Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=58454
2017-07-31 18:40:41 -04:00
Aleksey Kliger (λgeek) 50f2938561 Merge pull request #5275 from lambdageek/bug-58361-2017-06
[2017-06][sre] Resolve EnumBuilder tokens in managed (Fixes #58361)
2017-07-31 10:42:48 -04:00
Aleksey Kliger (λgeek) 6425f06ff6 Merge pull request #5277 from lambdageek/bug-58421-2017-06
[2017-06][sre] Handle typeref tokens in fixup_method (Fixes #58421)
2017-07-28 12:00:17 -04:00
Aleksey Kliger 485d5205f9 Bump corlib version
Due to changed semantics of ModuleBuilder:RegisterToken icall (it now does not
allow an EnumBuilder argument)
2017-07-28 11:58:51 -04:00
Aleksey Kliger 582c5d77f0 [sre] Resolve EnumBuilder tokens in managed. (Fixes #58361)
In particular, delegate to the TypeBuilder within the EnumBuilder.

Also do not register the EnumBuilder object with the runtime.  (Fixes
https://bugzilla.xamarin.com/show_bug.cgi?id=58361)
2017-07-28 11:58:51 -04:00
Marek Safar bda280c5e8 [mcs] Implements cloning for yield break. Fixes #57796 2017-07-28 11:14:42 +02:00
Aleksey Kliger 287f4303f3 [sre] Handle typeref tokens in fixup_method (Fixes #58421)
This may occur if there are two AssemblyBuilders in progress and one of them
refers to a TypeBuilder from the other.

https://bugzilla.xamarin.com/show_bug.cgi?id=58421
2017-07-27 18:07:27 -04:00
Aleksey Kliger 48d6bff3ae [test] Check that one AssemblyBuilder can refer to a TypeBuilder from another.
Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=58421
2017-07-27 18:07:26 -04:00
Aleksey Kliger ad6ef5f4bc [test] EnumBuilder regression tests for #58361
Cause the creation of a token for an EnumBuilder object.  Test both typedef
tokens (EnumBuilder from same assembly) and typeref token (EnumBuilder in another assembly)
2017-07-27 18:00:47 -04:00
Aleksey Kliger dd46212fc2 [sre] Add MonoDynamicImageTokCollision arg to mono_dynamic_image_register_token
The new argument controls what should happen when the given token is already
present.

In some situations it's expected that we either see the same object, or we
unconditionally want to replace it (for example if we previously registered a
TypeBuilder or a MethodBuilder, after the type or method is created, we will
re-register the RuntimeType or MonoMethod in its place).  In other cases (for
example when a module references a MonoMethod from a different assembly), we
may still call `mono_image_create_token()` multiple times but we expect to see
the same MonoMethod object.
2017-07-27 18:00:46 -04:00
Miguel de Icaza 41ecc70a69 [Marshal.IsComObject] Make this predicate return false instead of throwing an exception which is what the calling code expects (#5246) 2017-07-25 17:06:41 +02:00
Alexis Christoforides e9d3a69282 Update bockbuild. Fixes #57002 2017-07-25 01:27:58 -04:00
Zoltan Varga e7ce1807d7 [runtime] Fix the size calculation for CustomAttributeType coded indexes, they can only point to the MethodDef/MemberRef tables even through 3 bits are used to encode them, only 2 values are used. Fixes #58210. (#5256) 2017-07-24 23:21:08 -04:00
Zoltan Varga eb7e8d4af8 [jit] Handle OP_VCALL_MEMBASE in get_simd_vreg (). Fixes #58344. 2017-07-24 18:30:04 -04:00
Marek Safar 94651df9ed Bump roslyn to 2.3.1 2017-07-24 20:14:39 +02:00
Zoltan Varga d320c3a40a Bump bockbuild. 2017-07-24 13:53:04 -04:00
Zoltan Varga 97d59f280a Bump bockbuild. 2017-07-24 11:38:31 -04:00
Zoltan Varga 7f68119da8 [bockbuild] Avoid overwriting self.local_configure_flags in some packages, extend them instead. (#5249) 2017-07-22 02:23:36 -04:00
Bernhard Urban 9b3d1a60fc Merge pull request #5238 from lewurm/fix-aot-offset-dumper-2017-06
[2017-06][offset-tool] fix assignment for GeniOS
2017-07-19 15:40:19 +02:00
Bernhard Urban 75aeec5fb9 [offset-tool] fix assignment for GeniOS
fixes this compilation error

MonoAotOffsetsDumper.cs(279,59): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
2017-07-19 15:37:44 +02:00
Martin Baulig a625b98e26 [System.Net.Http]: Close request stream when HttpClientHandler.SendAsync() is done writing data. (#5226) (#5228)
(cherry picked from commit d1555c7c72)
2017-07-18 17:57:45 -04:00
Zoltan Varga 07ef3c251b [offsets-tool] Add a --gen-ios argument which can be used together with --targetdir= to generate ios offsets without having to specify the macos path. (#5218) 2017-07-17 18:55:22 -04:00
Alexander Köplinger fd85ac4fd1 [corlib] Preserve List<T>.ConvertAll in TypeTest (#5215)
TypeTest.GetGenericMethodDefinitionOverInflatedMethodOnGTD accesses
List<T>.ConvertAll() via reflection but doesn't use the method
elsewhere so the linker can remove it. Added some usage to avoid that.

Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=56242
(cherry picked from commit c4d38b54ad)
2017-07-16 01:49:28 +02:00
Zoltan Varga 667dcaa655 [llvm] Add support for fault clauses. Fixes #58114. (#5203) 2017-07-14 15:47:17 -04:00
Zoltan Varga d6ba1ed4fc [llvm] Reserve the proper number of got entries in the llvm got instead of 16 which used to be enough in the past. Hopefully fixes #56111. (#5207) 2017-07-14 15:46:57 -04:00
Aleksey Kliger (λgeek) 5b035af74a Merge pull request #5212 from lambdageek/bug-57691-2017-06
[metadata] Encode public key length correctly for keys longer than 128 bytes (Fixes #57691)
2017-07-14 15:08:02 -04:00
Aleksey Kliger b69e232073 [metadata] Encode public key length correctly for keys longer than 128 bytes
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=57691

For keys longer than 1024 bits, we encoded the length incorrectly as
   0x80 (length & 0xff)
instead of the correct algorithm:
  if (length < 0x80)
    length
  else if (length < 0x4000)
    0x80|(length>>8) (length & 0xff)
  else
    0xc0|(length>>24) (length>>16)&0xff (length>>8)&0xff length&0xff

which is provided by mono_metadata_encode_value.

See ECMA-335 II.24.2.4 #US and #Blob heaps

N.B.: we now always allocate the memory for the key as (keylen + 4) which
over-allocates by a couple of bytes in the cases where the key is shorter.
2017-07-14 12:23:57 -04:00
Aleksey Kliger edd2d56a32 [tests] Add regression test for InternalsVisibleTo with long PublicKey
Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=57691

We build a library that has an InternalsVisibleTo attribute that references an
executable that is signed with a long (>128bytes) public key.  Previously we
were using an incorrect method of encoding the key length.
2017-07-14 12:10:47 -04:00
Aleksey Kliger d4d81a3e02 [tests] Use test runner for test-internalsvisibleto
Also add the source files to EXTRA_DIST
2017-07-14 12:10:46 -04:00
Johan Lorensson 1d1ec7d504 Incorrect parameters passed to GetDiskFreeSpaceEx causing random memory corruption. (#5196)
The call to GetDiskFreeSpaceEx passes uninitialized pointers to GetDiskFreeSpaceEx
instead of pointers to stack variables. This will cause random memory corruption and random
crashes on Windows builds.

This is a regression caused by the refactoring work done in this PR:

https://github.com/mono/mono/pull/4255
(cherry picked from commit 46bc4f393e)
2017-07-11 23:24:18 +02:00
Johan Lorensson 5fc8e28ffa Remove partial path for ml.exe and ml64.exe in mono VS runtime builds. (#5195)
Location of ml.exe and ml64.exe is different in VS2017 compared to VS2015.
By removing the partial path from the command, the VS environment will locate
the tool depending on selected build configuration and VS version.

This should work for both VS2015 and VS2017.
(cherry picked from commit 665d8d4141)
2017-07-11 15:21:54 +02:00
Marius Ungureanu de60f3b49e Merge pull request #5185 from mono/2017-06-gtk-bump
Bump bockbuild for gtk# API compat fixes.
2017-07-07 19:50:26 +03:00
Marius Ungureanu 7f560b39c8 Bump bockbuild for gtk# API compat fixes. 2017-07-07 19:49:52 +03:00
Zoltan Varga 73c2e4322e [arm64] Really fix handler block trampolines. 2017-07-07 01:12:24 -04:00
Zoltan Varga 13166f48a8 [arm] Fix the handler block trampoline, it didn't actually call the helper function. 2017-07-07 01:12:15 -04:00
Zoltan Varga e5b06307ca [runtime] Rework process waiting. (#5175)
Instead of using fragile lockless code in the sigchld signal handler, wake up the finalizer thread and make it call back
into the process code to signal finished processes.
2017-07-06 16:23:54 -04:00
Alexander Köplinger be1b671b09 [packaging] Add Windows hostfxr.dll to MSBuild in MSI
Part of https://bugzilla.xamarin.com/show_bug.cgi?id=57930

(cherry picked from commit f7c9be4890 and 727cf39986)
2017-07-06 02:06:22 +02:00
Zoltan Varga 817a7e7bf7 [sre] Fix the signature of the create_dynamic_method () icall, make it static since the C implementation only takes two parameters, this only caused problems if the icall set the error, since it overwrite the DynamicMethod object instead. Fixes #57301. (#5081) 2017-07-05 17:20:28 -04:00
Bernhard Urban 6279df6d70 Merge pull request #5168 from lewurm/interp-cherry-pick-aot-interp-2017-06
[2017-06][interp] add --aot=interp, so we can run `mono --full-aot --interpreter`
2017-07-05 12:01:51 +02:00
Zoltan Varga cbc419bb3e [jit] Optimize ldloc+ldfld operations for valuetypes, so they don't require making a copy of the valuetype. Hopefully fixes #56452. (#5166) 2017-07-04 13:08:25 -04:00
Zoltan Varga 39a8a8f8c0 Revert "[jit] Optimize ldloc+ldfld operations for valuetypes, so they don't require making a copy of the valuetype. Hopefully fixes #56452. (#5166)"
This reverts commit 00ef078380.

Revert this as it seems to break the f# build.
2017-07-04 10:09:09 -04:00
Bernhard Urban 3c9a821c7e [interp] add --aot=interp, so we can run mono --full-aot --interpreter 2017-07-04 11:27:44 +02:00
Ankit Jain bb900edab1 Revert "[packaging/msbuild] Bump to get new changes on xplat-master (#5146)"
This reverts commit 3505d310df.
2017-07-03 21:45:44 -04:00
Zoltan Varga 36e3d93a52 [jit] Use the right type when handling shared versions of RuntimeHelpers.IsReferenceOrContainsReferences (). The previous version only worked by accident. (#5160) 2017-07-03 17:43:04 -04:00
Zoltan Varga 4b49283a9c [jit] Fix mono_debug_count () so it doesn't confuse COUNT=0 with COUNT not being used. 2017-07-03 16:57:58 -04:00
Zoltan Varga 00ef078380 [jit] Optimize ldloc+ldfld operations for valuetypes, so they don't require making a copy of the valuetype. Hopefully fixes #56452. (#5166) 2017-07-03 16:57:44 -04:00
Ludovic Henry 0a3ea22257 Remove unrefing of handles on shutdown
If one of the handle is a file handle for example, then w32file has already be cleaned up, so we cannot guarantee that the handle we are going to close is not going to call into w32file code.
2017-06-30 16:09:04 -04:00
Aleksey Kliger (λgeek) 04419ee95b Merge pull request #5157 from lambdageek/bug-57850+57851-2017-06
[sre] Deal with ResolveEventHandler returning an AssemblyBuilder (Fixes #57850, #57851)

Fix a couple of bugs in the situation where a ResolveEventHandler happens to return an AssemblyBuilder.

#57850 - if the ResolveEventHandler returns a reflection only assembly, throw a FileNotFoundException
#57851 - don't look for a ReferenceAssemblyAttribute on assemblies returned by a ResolveEventHandler if they happen to be an AssemblyBuilder. (the native code path to get there is to try and instantiate a custom attribute in some other assembly, hence the fairly convoluted test in assemblyresolve_event5 and its helper files)
2017-06-30 13:33:23 -04:00
Aleksey Kliger fc339c2777 [loader] Don't try to look for ReferenceAssemblyAttribute on dynamic assemblies (Fixes #57851)
.NETFramework seems to ignore this custom attribute and allows instantiating
types from on assembly builders.
2017-06-30 10:23:22 -04:00
Aleksey Kliger 35b2b68bdf [loader] Throw exn if ResolveEventHandler returns a refonly assembly (Fixes #57850)
(Also depends on previous commit to ensure that MonoAssembly:refonly is set
correctly for dynamic assemblies)
2017-06-30 10:23:21 -04:00
Aleksey Kliger 009d1279a2 [sre] Mark AssemblyBuilderAccess.ReflectionOnly assemblies as refonly
This will ensure they show up in AppDomain.ReflectionOnlyGetAssemblies(), and
won't be allowed to execute
2017-06-30 10:23:20 -04:00
Aleksey Kliger d8eb6c91a2 [sre] use AssemblyBuilderAccess bitmask to set MonoDynamicImage flags
In particular this makes sure that AssemblyBuilderAccess.ReflectionOnly aren't
allowed to run.  And AssemblyBuilderAccess.CollectAndRun aren't allowed to save.
2017-06-30 10:23:19 -04:00
Aleksey Kliger d451def6a5 [sre] Add MonoAssemblyBuilderAccess enum in native code
in sync with System.Reflection.Emit.AssemblyBuilderAccess
2017-06-30 10:23:18 -04:00
Aleksey Kliger f95909190c [mono-error] Add mono_error_set_file_not_found
To throw System.IO.FileNotFoundException
2017-06-30 10:23:17 -04:00
Aleksey Kliger fc65bbe329 [tests] ResolveEventHandler that returns an AssemblyBuilder shouldn't crash mono
Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=57851
2017-06-30 10:23:16 -04:00
Aleksey Kliger eb6386af15 [tests] Throw an error if ResolveEventHandler returns a reflection only AssemblyBuilder
Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=57850
2017-06-30 10:23:15 -04:00
Aleksey Kliger 8236cbe950 [tests] Add some missing files to EXTRA_DIST 2017-06-30 10:23:14 -04:00
Ankit Jain 3505d310df [packaging/msbuild] Bump to get new changes on xplat-master (#5146)
cherry-pick 7f5c2b61fcf67cc47aa8b010b34da8039276afb6
2017-06-29 09:38:46 -04:00
Alexander Köplinger c0c8d0bec4 [packaging] Remove git_branch from msbuild and mono-extensions (#5141)
We're checking out a specific commit for both now so the git branch
is no longer required.

Also fixes warnings that a 2017-06 branch doesn't exist in mono-extensions.
(cherry picked from commit 6400a71595)
2017-06-28 19:43:07 +02:00
Jo Shields 3872a400b2 Manually invoke Xvfb, don't depend on the xvfb plugin (#5132)
(cherry picked from commit a12daa47e0)
2017-06-28 19:41:50 +02:00
Aleksey Kliger (λgeek) a6612b4c64 Merge pull request #5121 from lambdageek/bug-57744-2017-06
[reflection] Convert correct MonoError to an exn in Assembly.GetTypes() (Fixes #57744)
2017-06-27 10:45:31 -04:00
Ankit Jain 4db9028cb9 [packaging/msbuild] Bump to get new changes on xplat-master (#5127) (#5128)
cherry-pick 67f753a893
2017-06-27 01:03:22 -04:00
Aleksey Kliger b6e231d521 [reflection] Convert correct MonoError to an exn in Assembly.GetTypes () (Fixes #57744)
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=57744
2017-06-26 16:24:59 -04:00
Alexander Köplinger 1ec5966c89 Bump API snapshot 2017-06-26 20:53:58 +02:00
Marius Ungureanu 9280bb5e19 [System.Core] Implement MemoryMappedFile.OpenExisting (#5118)
Reuse the existing icall infrastructure to give the same handle back.

This PR implements all OpenExisting methods (with the access rights parameter discarded) and the SafeHandle property.
In the runtime, we don't check the capacity parameter if we try to open a mmap file, and we fallthrough the handle refcount case.
2017-06-26 20:52:35 +02:00
Alexander Köplinger d470d1abbf [cil-strip] Move comment out of .sources file
I forgot that we only run gensources.sh on libraries but not
tools so the comments don't get stripped out...

(cherry picked from commit f892c7c574)
2017-06-26 19:19:41 +02:00
Alexander Köplinger 0e4d13f5b7 Revert "[cil-strip] Remove old private copy of Mono.Cecil"
(reverted from commit 4ea3122758)

(cherry picked from commit a8c53ebf16)
2017-06-26 12:36:47 +02:00
Alexander Köplinger 933ceae45c Revert "[cil-strip] Upgrade to latest Mono.Cecil API"
(reverted from commit 0c9eb70a46)

Using newer Cecil means metadata tokens will be different which
breaks AOT compilation: https://github.com/mono/mono/pull/5102#issuecomment-310801767

(cherry picked from commit f068fb6b66)
2017-06-26 12:36:43 +02:00
Ankit Jain 2f1b9e8aac [packaging/msbuild] Bump to get new changes on xplat-master (#5113) 2017-06-23 23:20:58 -04:00
Ludovic Henry f03dbfcae2 [System] Fix compilation on watchos (#5108) (#5111) 2017-06-23 19:34:34 -04:00
Alexander Köplinger d9211fcb50 [cil-strip] Remove old private copy of Mono.Cecil
No longer needed now that we're using the new Cecil.

(cherry picked from commit 4ea3122758)
2017-06-24 01:25:49 +02:00
Alexander Köplinger 153467c0c6 [cil-strip] Upgrade to latest Mono.Cecil API
This greatly simplifies the code and as a bonus also shaves off
about 300ms when stripping mscorlib.dll.

(cherry picked from commit 0c9eb70a46)
2017-06-24 01:25:46 +02:00
Vlad Brezae a1cac02732 [sgen] Performance improvement for ms_block_size computations
This reduces regressions for switching from MS_BLOCK_SIZE compile time constant
to ms_block_size variable by 85% on the tests where this was showing up. In the
future we should implement a block allocator, which would, amongst other benefits,
enable us to remove the block-size/page-size dependency.
2017-06-23 23:10:51 +03:00
Vlad Brezae 7be144c0b7 [sgen] Fix MS block size calculation.
The block size must be a multiple of the system page size. Page size simply
cannot be determined reliably at compile time, so we must obtain the page size
through a system call on startup and use it as the block size. We still enforce
a minimum block size of 16kb on systems where the page size is smaller than
that.

The old code hardcoded page sizes for certain architectures with large pages.
THe problem is that those architectures don't necessarily have to have large
pages and on systems where this wasn't the case, we'd end up with a block size
much larger than needed.

Rebase of @alexrp's work.
2017-06-23 23:10:38 +03:00
Alex Rønne Petersen 71936252fe [utils/mmap] Prefer sysconf () over getpagesize () in mono_pagesize ().
The former is async-signal-safe, while the latter makes no guarantees and also
isn't actually portable.
2017-06-23 23:10:14 +03:00
Marius Ungureanu ab0791102f Merge pull request #5105 from mono/2017-06-bump-bockbuild
Bump bockbuild
2017-06-23 19:08:19 +03:00
Marius Ungureanu be24ada60a Bump bockbuild 2017-06-23 19:06:45 +03:00
Ankit Jain 9c991786ac [packaging/msbuild] Bump to get new changes on xplat-master
cherry-picking c7b19b52fd
2017-06-23 02:20:14 -04:00
Ankit Jain 019a83f88f [packaging/msbuild] Update commit hash to point to xplat-master HEAD
cherry-pick 4f7b15520d09843c1c0668f9fa4924f3cccb7398 from master
2017-06-22 21:36:41 -04:00
Rodrigo Kumpera 33697c0568 Merge pull request #5096 from kumpera/backport-5095
[aot] Fix the name of the mono_gc_wbarrier_range_copy icall. Backport of #5095
2017-06-22 14:59:28 -07:00
Rodrigo Kumpera fbb82d3923 [aot] Fix the name of the mono_gc_wbarrier_range_copy icall. FullAOT with direct calls requires it. 2017-06-22 14:58:06 -07:00
Rodrigo Kumpera 733b51587e Merge pull request #5085 from kumpera/backport-5082
Back port of #5082 (unlink bug on RO file systems)
2017-06-21 16:34:14 -04:00
Alexander Köplinger f66e71e01b [packaging] Move Windows MSI scripts into repository
They lived in https://github.com/mono/release before, moving them
into the main repo allows us to version them more easily.

Note: I intend to do more cleanup on those scripts in the future,
this is just the first step.

(cherry picked from commit a4d6fccef9)

[packaging] Simplify Windows packaging scripts

We don't need to build in a separate checkout of mono anymore.
Also use .pkg passed in from upstream build.

(cherry picked from commit 69f8abf794)

[packaging] Fix path to wrapper.bat for Windows MSI

(cherry picked from commit 27bf99ebed)

[ci] Get rid of remaining usages of WORKSPACE env var

Most of it was already removed in ea519ada8c

(cherry picked from commit 00f7811683)

[packaging] Exit Windows packaging script on error

Also quote passed in mdk path.

(cherry picked from commit b85f34d763)

[packaging] Remove msiexec prerequisite from Windows script

We're using lessmsi now.

(cherry picked from commit 348ec2cf7a)

[packaging] Fix prerequisite in Windows script

(cherry picked from commit 7f28de8559)

[packaging] Fix wrong argument in Windows script

(cherry picked from commit acf546b1ba)

[packaging] Add missing .pc files to Windows folder

It got accidentally ignored by the root .gitignore.

(cherry picked from commit 581b46d90d)

[packaging] Add back IronLangs to Windows MSI

It was just temporarily removed from the Mac package to work around
a build break. This was fixed so we need to add iron* back.

(cherry picked from commit 6c6ab73705)

[packaging] Add a few missing msbuild files to Windows MSI

(cherry picked from commit 68130ebec9)

[packaging] Add a few more missing files to Windows MSI

Also add a safeguard so we don't accidentally leave files with
OSX paths in the package.

(cherry picked from commit dbaab5d01a)
2017-06-21 20:32:55 +02:00
Rodrigo Kumpera 262128c941 [runtime] Update comment with link to Linux Kernel fix. 2017-06-21 10:47:22 -07:00
Rodrigo Kumpera eeb68ca307 [io-layer] When deleting a file, check for EROFS and verify if the file exists. Fixes #57629.
Linux has this particular behavior of returning ENOFS when unlinking from an read only FS.
Even if the file doesn't exists! Darwin does the sane thing and return ENOENT in this case.

To workaround this, if unlink returns EROFS, we stat the file and deal with that.
2017-06-21 10:47:19 -07:00
Marek Safar 6471bbd6ef [mcs] Add missing vector cloning of definite assignment on-true. Fixes #57505 2017-06-21 15:14:39 +02:00
Marek Safar 96a2b36e82 [mcs] Fixes regression introduced by a0fc3f4dcf to consider user set values. Fixes #57242 2017-06-21 00:15:29 +02:00
Marek Safar 7a704f61c9 Bump roslyn to 2.3 beta 2 2017-06-20 23:22:10 +02:00
Bernhard Urban 39150458f0 Merge pull request #5074 from lewurm/x509-temp-file-fix-2017-06
[2017-06][bcl tests] do not attempt to delete non-existing files
2017-06-20 17:13:56 +02:00
Bernhard Urban 0b522087c2 [bcl tests] do not attempt to delete non-existing files
This fixes an issue we see on the BCL test suite when run in the context
of Xamarin Android:

```
I/mono-stdout( 2534):     Certificate1 [FAIL] : TearDown : System.UnauthorizedAccessException : Access to the path "temp.b64" is denied.
```

It seems like those files aren't generated anymore.  Not sure why this
starts to be a problem now.
2017-06-20 16:37:16 +02:00
Aleksey Kliger (λgeek) 911cc1d438 Merge pull request #5060 from lambdageek/tbt-2017-06
[2017-06][tests] Rework TypeBuilderTest SetUp/TearDown
2017-06-19 15:41:37 -04:00
Zoltan Varga e4b08aa7c9 [arm64] Remove an assert which is hit when mono_arch_get_call_target () is called with a 'b' instead of a 'bl'. 2017-06-19 14:34:53 -04:00
Aleksey Kliger 2db07ca754 [tests] Don't run SRE saved assembly in current process
Windows doesn't like deleting the file, and the original bug was a problem in
SRE, not in the AssemblyBuilder.Save ()
2017-06-19 12:04:21 -04:00
Alexander Köplinger 0d8219ea4a [MacSDK] Bump msbuild 2017-06-19 15:15:08 +02:00
Alexander Köplinger a38a8e4ad4 Bump API snapshot 2017-06-19 13:53:54 +02:00
Zoltan Varga d0b9d91817 [arm64] Fix the patching of MONO_PATCH_INFO_METHOD_JUMP so it handles thunks properly. Allocate thunk space for tail calls. Fixes asserts in the System.Numerics xunit tests. (#5026) 2017-06-18 17:34:55 -04:00
Aleksey Kliger fd6d8198f7 [tests] Rework TypeBuilderTest SetUp/TearDown
- Create a unique temporary directory for each test in TypeBuilderTest and delete
  it on TearDown.

- Change tests to use tempDir instead of Path.GetTempPath ()

- Change IsSerializable () test to how it was 11 years ago and have it write to a
  file with a simple name (but now in a directory where noone else is writing)

- Change FieldsWithSameName (), FieldsWithSameNameAndType () and
  MethodsWithSameNameAndSig () to use the default temp assembly (now in a
  unique tempDir) instead of using the CreateTempAssembly ()

- Remove CreateTempAssembly function. It is dead code.
2017-06-16 20:02:27 -04:00
Ankit Jain 54260048cc [packaging/msbuild] Update commit hash to point to xplat-master HEAD (#5046) 2017-06-15 14:04:15 -04:00
Marek Safar 34ba13146f Bump cecil 2017-06-15 19:02:56 +02:00
Bernhard Urban 00ea5f1e17 Revert "[exceptions] only do SIGSEGV related actions for SIGSEGVs in mono_handle_native_crash" (#5028)
This reverts commit a27bc024f1.

We never want the crash handler to be recursive.
2017-06-14 18:05:41 -04:00
Aleksey Kliger (λgeek) e75b24b807 Merge pull request #5033 from lambdageek/fix-strict-loader-image-cache-hit-2017-06
[2017-06][loader] If using strict strong names, recheck loaded assm before returning it.
2017-06-14 14:18:08 -04:00
Aleksey Kliger ecf65f0093 [loader] If using strict strong names, recheck loaded assm before returning it.
Suppose we have two versions of an assembly: AsmA 1.0.0.0 and AsmA 2.0.0.0 that
we want to load into the same domain at the same time (for example we want to
load AsmB and AsmC that statically reference the two versions, respectively, or
maybe we used reflection).  Suppose version 1 got loaded first (and we found it
on our MONO_PATH in "somepathdir/AsmA.dll").  Now we want to load version 2.
The problem is that if version 1 is on MONO_PATH first, we'll find a filename
that matches ("somepathdir/AsmA.dll") and try to open that image.  Then we'll
end up here in mono_assembly_open_predicate() after the mono_image_open_a_lot()
call hits the image cache.  So we get back an image and image->assembly is
version 1.

The old behavior would just return any non-NULL image->assembly.  The new
behavior is to check the predicate and reject opening the propose file if the
predicate doesn't match.  (If we're not using the strict loader, or if there's
no predicate set, return the existing image->assembly as before).
2017-06-13 19:41:36 -04:00
Aleksey Kliger 35cb8bac8a [tests] Strict assembly loading of two version of the same assm should work.
In particular, we should be able to use classes/methods that are unique to each
version.  We should not get only one version loaded.
2017-06-13 19:41:35 -04:00
Alexander Köplinger 33074493a0 [MacSDK] Remove quotes in nuget wrapper script
None of the other wrapper scripts quote the Mono path and this
broke the Windows packaging script which extracts nuget from the
Mac package.

(cherry picked from commit 258efac3c6)
2017-06-14 00:47:07 +02:00
Marius Ungureanu c5d7419186 Bump bockbuild (#5024) 2017-06-13 20:52:32 +02:00
Alexander Köplinger ccf4d32e12 Bump API snapshot 2017-06-13 02:47:59 +02:00
Alexander Köplinger 89014568b7 Fix System.Numerics xunit tests and add them to CI (#5006)
* Fix System.Numerics xunit tests and add them to CI

Xunit.Extensions.NetCore.dll is available as a net46 version now
so we can just use it instead of building it from our buildtools fork.
This also allows us to remove the fork from our submodules.

We were missing running the System.Numerics xunit tests in CI,
this adds them so we catch breaks like these earlier.

* Skip tests on Windows, they seem to fail there

(cherry picked from commit 1890aa6ec3)
2017-06-13 02:35:13 +02:00
Bernhard Urban 9161e4e5a9 Merge pull request #4999 from lewurm/marshal-string-dummy-2017-06
[2017-06][marshal] allocate dummy string always in root domain
2017-06-12 19:09:17 +02:00
Rodrigo Kumpera 6ac4a68c46 Merge pull request #5007 from kumpera/backport_56684
[corlib] Don't pass RuntimeMethodHandle across domains. Fixes #56684
2017-06-12 10:07:33 -07:00
Martin Baulig 1b5e0f7331 [System]: Correctly implement close and shutdown in SslStream. (#4969) (#5008)
* [System]: Correctly implement close and shutdown in SslStream.

* Cleanup.

* Cosmetic.

* More ReferenceSources/SR2.cs into common.sources to make it build.

(cherry picked from commit 21d5c9c346)
2017-06-12 12:59:01 -04:00
Marek Safar c8863e1d31 [mcs] C#7 type pattern matching 2017-06-12 17:06:26 +02:00
Marek Safar dd951e909a [mcs] Better detection of null operator inside conditional expression. Fixes #57232 2017-06-12 17:04:08 +02:00
Aleksey Kliger (λgeek) 3c21a0f3dd Merge pull request #5004 from lambdageek/bug-57222-2017-06
[sre] FieldBuilder:RuntimeResolve shouldn't lookup by name (Fixes #57222)
2017-06-12 10:52:01 -04:00
Rodrigo Kumpera f031c8fba3 [corlib] Don't pass RuntimeMethodHandle across domains. Fixes #56684
We can't pass RuntimeMethodHandle across AppDomains since that can lead to memory corruption.

The way this happens is that when Domain (A) passes a method handle (M) to Domain (B), (B) will get the reflection object for
which will add that MonoMethod to the per-domain reflection hashtable. This won't cause the assembly of (M) to be registered with (B).

When (A) is unloaded, it might be the only domain referencing the assembly of (M), cause it to unload resulting in (B) having a dangling
pointer to (M) on its reflection hashtable.

The fix is to serialize enough lookup data across the wire so we can do type/method lookup using reflection on the target domain.
It might be slower, but this only happens on some remoting slowpaths anyways.

Finally, we can't simply register the assembly of (M) into domain (B) as that list (MonoDomain::domain_assemblies) is used for type loading,
thus breaking the target domain in some scenarios.
2017-06-09 11:46:41 -07:00
Aleksey Kliger 442d000b6c [test] Test SRE of a class with two methods with the same name.
Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=57222

Although methods aren't affected by this bug, I added a regression test for
this case anyway in case the implementation changes.

Currently MethodBuilder.RuntimeResolve() goes through a different codepath - it
calls RuntimeType.GetMethod (MethodInfo) which calls into an icall which looks
for a method with a matching token rather than a matching name.
2017-06-09 13:15:27 -04:00
Aleksey Kliger 2cdb7e8648 [sre] FieldBuilder:RuntimeResolve shouldn't lookup by name. (Fixes #57222)
RuntimeType:GetField (FieldInfo) looks up the field by name and attributes,
which doesn't work for SRE because it is legal to create multiple fields with
the same name and type and attributes.  So lookup using the
RuntimeFieldHandle (aka MonoClassField*) instead.
2017-06-09 13:15:26 -04:00
Aleksey Kliger e72203782b [test] Test SRE of a class with two fields with same name
Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=57222
2017-06-09 13:15:25 -04:00
Bernhard Urban 00e3c897d5 [marshal] allocate dummy string always in root domain
otherwise it can happen that the dummy string is allocated in a
different domain, and when it's onloaded the GC root points to an
invalid object.
2017-06-09 12:51:02 +02:00
Bernhard Urban 52a5acbd88 Merge pull request #4992 from lewurm/interp-aot-mode-2017-06
[2017-06][interp] add MONO_AOT_MODE_INTERP
2017-06-09 12:29:40 +02:00
Bernhard Urban 778e04f2d9 [win] set HAVE_ONLINE_VES 2017-06-08 17:22:55 +02:00
Alexander Köplinger 93ecaeb2c6 [MacSDK] Bump libgdiplus to latest (#4984)
We were using a very old commit of libgdiplus. This brings in
the latest changes.
(cherry picked from commit 1d6a8ed6ea)
2017-06-08 14:22:00 +02:00
Bernhard Urban 49df11fd5f [interp] provide stub for icall_trampoline for x86 and ppc
keep the linker happy
2017-06-08 00:11:05 +02:00
Bernhard Urban c8c8b16bfd [interp] root domain must be used for AOT'd wrappers used by interpreter 2017-06-08 00:11:05 +02:00
Bernhard Urban 6f83951d1c [interp aot] documentation 2017-06-08 00:11:04 +02:00
Bernhard Urban f2ae4658f9 [marshal] some things are required in the interpreter despite DISABLE_JIT 2017-06-08 00:11:03 +02:00
Bernhard Urban faf4fe66af [configure] introduce HAVE_ONLINE_VES 2017-06-08 00:11:03 +02:00
Bernhard Urban 998759345f [interp] fix when DISABLE_JIT is set 2017-06-08 00:11:02 +02:00
Bernhard Urban c88d2cce1f [interp] add InterpMethodArguments struct to offset-tool 2017-06-08 00:11:01 +02:00
Bernhard Urban 3e589e2c39 [interp] add MONO_AOT_MODE_INTERP 2017-06-08 00:11:00 +02:00
Martin Baulig 4c944bc86e [System]: Actually disable the keychain code and SecItemImport() on XI. (#4983) (#4988)
(cherry picked from commit fff41905e9)
2017-06-07 14:32:20 -04:00
Bernhard Urban d3e6c9d17f Merge pull request #4989 from baulig/work-4987-merge
[System]: Fix possible initialization issue in MonoTlsProviderFactory. (#4987)
2017-06-07 19:37:22 +02:00
Martin Baulig 7379ac1bfb Cosmetic; remove [Category ("Martin")] from the test.
(cherry picked from commit dc58d950f2)
2017-06-07 11:55:11 -04:00
Martin Baulig 2a029615aa [System]: Fix possible initialization issue in MonoTlsProviderFactory. (#4987)
* [Mono.Security]: Add test for MonoTlsProviderFactory.GetProvider ().

* [System]: Fix possible initialization issue in MonoTlsProviderFactory.

(cherry picked from commit 83f74c4123)
2017-06-07 11:46:58 -04:00
Marek Safar 9c345b1b02 [mcs] C#7 out variable declaration 2017-06-07 16:55:13 +02:00
Alexander Köplinger 074a1228cf [MacSDK] Update version number in msbuild.py
(cherry picked from commit 9b63661c15)
2017-06-06 23:04:06 +02:00
Bernhard Urban e3596928d8 [mini] set MONO_ARCH_HAVE_INIT_LMF_EXT on architectures that implement mono_arch_init_lmf_ext
it worked before, because we relied on implicit linking
2017-06-06 21:07:18 +02:00
Bernhard Urban ac71acfd52 [mini] guard mono_arch_init_lmf_ext prototype properly 2017-06-06 19:16:05 +02:00
Bernhard Urban 8909c17d9c [arm] don't set MONO_ARCH_SOFT_DEBUG_SUPPORTED on android cross compiling
follow up fix for https://github.com/mono/mono/pull/4956

this breaks the cross compiler on windows for android:

```
  [9:07:36]                       /bin/sh ../../libtool  --tag=CC   --mode=compile /Users/builder/android-toolchain/mxe/bin/i686-w64-mingw32.static-gcc -DHAVE_CONFIG_H -I. -I/U  sers/builder/data/lanes/5000/ff452183/source/xamarin-android/external/mono/mono/mini -I../..   -DWINVER=0x0600 -D_WIN32_WINNT=0x0600 -D_WIN32_IE=0x0501 -D_UNICODE -DUNICODE -  DWIN32_THREADS -DFD_SETSIZE=1024 -g -Wall -Wunused -Wmissing-prototypes -Wmissing-declarations -Wstrict-prototypes  -Wmissing-prototypes -Wnested-externs -Wpointer-arith -Wno  -cast-qual -Wwrite-strings -Wno-switch -Wno-switch-enum -Wno-unused-value -Wno-attributes -Wno-format-zero-length -D__ARM_EABI__ -DARM_FPU_VFP=1 -DNO_UNALIGNED_ACCESS -I/User  s/builder/data/lanes/5000/ff452183/source/xamarin-android/external/mono -I/Users/builder/data/lanes/5000/ff452183/source/xamarin-android/external/mono/eglib/src -I../../eglib  /src -I/Users/builder/data/lanes/5000/ff452183/source/xamarin-android/build-tools/mono-runtimes/obj/Release//llvm/installed-win32/usr/include -DNDEBUG -D__NO_CTYPE_INLINE -D_  GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -DLLVM_API_VERSION=4 -O -I../arch/arm -fvisibility=hidden -DXAMARIN_PRODUCT_VERSION=0 -static   -static-libgcc -std=gnu99 -fno-strict-aliasing -fwrapv -DMONO_DLL_EXPORT -Wno-unused-but-set-variable -g -Wall -Wunused -Wmissing-prototypes -Wmissing-declarations -Wstrict-  prototypes  -Wmissing-prototypes -Wnested-externs -Wpointer-arith -Wno-cast-qual -Wwrite-strings -Wno-switch -Wno-switch-enum -Wno-unused-value -Wno-attributes -Wno-format-ze  ro-length -mno-tls-direct-seg-refs -Werror-implicit-function-declaration -MT libmini_la-mini-arm-gsharedvt.lo -MD -MP -MF .deps/libmini_la-mini-arm-gsharedvt.Tpo -c -o libmin  i_la-mini-arm-gsharedvt.lo `test -f 'mini-arm-gsharedvt.c' || echo '/Users/builder/data/lanes/5000/ff452183/source/xamarin-android/external/mono/mono/mini/'`mini-arm-gsharedv  t.c
  [9:07:36]                       /Users/builder/data/lanes/5000/ff452183/source/xamarin-android/external/mono/mono/mini/mini-arm.c: In function 'mono_arch_is_single_step_event  ':
  [9:07:36]                       /Users/builder/data/lanes/5000/ff452183/source/xamarin-android/external/mono/mono/mini/mini-arm.c:7242:2: error: unknown type name 'siginfo_t'
  [9:07:36]                         siginfo_t *sinfo = info;
  [9:07:36]                         ^
  [9:07:36]                       /Users/builder/data/lanes/5000/ff452183/source/xamarin-android/external/mono/mono/mini/mini-arm.c:7248:11: error: request for member 'si_addr'   in something not a structure or union
  [9:07:36]                         if (sinfo->si_addr >= ss_trigger_page && (guint8*)sinfo->si_addr <= (guint8*)ss_trigger_page + 128)
  [9:07:36]                                  ^
  [9:07:36]                       /Users/builder/data/lanes/5000/ff452183/source/xamarin-android/external/mono/mono/mini/mini-arm.c:7248:57: error: request for member 'si_addr'   in something not a structure or union
  [9:07:36]                         if (sinfo->si_addr >= ss_trigger_page && (guint8*)sinfo->si_addr <= (guint8*)ss_trigger_page + 128)
  [9:07:36]                                                                                ^
  [9:07:36]                       /Users/builder/data/lanes/5000/ff452183/source/xamarin-android/external/mono/mono/mini/mini-arm.c: In function 'mono_arch_is_breakpoint_event'  :
  [9:07:36]                       /Users/builder/data/lanes/5000/ff452183/source/xamarin-android/external/mono/mono/mini/mini-arm.c:7262:2: error: unknown type name 'siginfo_t'
  [9:07:36]                         siginfo_t *sinfo = info;
  [9:07:36]                         ^
  [9:07:36]                       /Users/builder/data/lanes/5000/ff452183/source/xamarin-android/external/mono/mono/mini/mini-arm.c:7267:11: error: request for member 'si_signo  ' in something not a structure or union
  [9:07:36]                         if (sinfo->si_signo == DBG_SIGNAL) {
  [9:07:36]                                  ^
  [9:07:36]                       /Users/builder/data/lanes/5000/ff452183/source/xamarin-android/external/mono/mono/mini/mini-arm.c:7269:12: error: request for member 'si_addr'   in something not a structure or union
  [9:07:36]                          if (sinfo->si_addr >= bp_trigger_page && (guint8*)sinfo->si_addr <= (guint8*)bp_trigger_page + 128)
  [9:07:36]                                   ^
  [9:07:36]                       /Users/builder/data/lanes/5000/ff452183/source/xamarin-android/external/mono/mono/mini/mini-arm.c:7269:58: error: request for member 'si_addr'   in something not a structure or union
  [9:07:36]                          if (sinfo->si_addr >= bp_trigger_page && (guint8*)sinfo->si_addr <= (guint8*)bp_trigger_page + 128)
```
2017-06-06 19:16:05 +02:00
Marek Safar e5d16f01fd Bump corefx 2017-06-06 16:11:32 +02:00
Marek Habersack 9874928b85 Use correct path separator for satellite assemblies in cross builds (#4976)
When creating a bundle on Windows to run on Android, macOS/iOS or Linux we need
to use the target system's path separator when storing satellite assemblies in
the bundle instead of the host system's one. Failing to do so will embed (on
Windows) the satellite assemblies with paths like

   fr_FR\myassembly.resources.dll

while at runtime Mono will try to look up the assembly by

   fr_FR/myassembly.resources.dll

and fail to find it, obviously. The `--style` parameter is now consulted to see
what path separator character should be used.

Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=55603
2017-06-06 16:07:54 +02:00
Marek Safar 9e99e20001 [mcs] Remove unwanted tests 2017-06-05 20:56:38 +02:00
Ludovic Henry b3e79ebc05 Bump to 5.4 for 2017-06 branch (#4971) 2017-06-05 14:05:27 -04:00
260 changed files with 6167 additions and 2629 deletions

No files matched your search

-3
View File
@@ -26,9 +26,6 @@
[submodule "external/nuget-buildtasks"]
path = external/nuget-buildtasks
url = git://github.com/mono/NuGet.BuildTasks
[submodule "external/buildtools"]
path = external/buildtools
url = git://github.com/mono/buildtools.git
[submodule "external/cecil-legacy"]
path = external/cecil-legacy
url = git://github.com/mono/cecil.git
+9 -4
View File
@@ -1,7 +1,7 @@
# Process this file with autoconf to produce a configure script.
#AC_PREREQ([2.62])
AC_INIT(mono, [5.3.0],
AC_INIT(mono, [5.4.0],
[http://bugzilla.xamarin.com/enter_bug.cgi?classification=Mono])
AC_CONFIG_SRCDIR([README.md])
@@ -40,8 +40,8 @@ MONO_VERSION_BUILD=`echo $VERSION | cut -d . -f 3`
# This can be reset to 0 when Mono's version number is bumped
# since it's part of the corlib version (the prefix '1' in the full
# version number is to ensure the number isn't treated as octal in C)
MONO_CORLIB_COUNTER=2
MONO_CORLIB_VERSION=`printf "1%02d%02d%02d%03d" $MONO_VERSION_MAJOR $MONO_VERSION_MINOR $MONO_VERSION_BUILD $MONO_CORLIB_COUNTER`
MONO_CORLIB_COUNTER=3
MONO_CORLIB_VERSION=`printf "1%02d%02d%02d%03d" $MONO_VERSION_MAJOR $MONO_VERSION_MINOR 0 $MONO_CORLIB_COUNTER`
AC_DEFINE_UNQUOTED(MONO_CORLIB_VERSION,$MONO_CORLIB_VERSION,[Version of the corlib-runtime interface])
AC_SUBST(MONO_CORLIB_VERSION)
@@ -3534,6 +3534,11 @@ fi
AM_CONDITIONAL(ENABLE_INTERPRETER, [test x$enable_interpreter = xyes])
if test "x$enable_interpreter" = "xyes" || test "x$mono_feature_disable_jit" != "xyes"; then
AC_DEFINE(HAVE_ONLINE_VES, 1, [Some VES is available at runtime])
fi
AM_CONDITIONAL(HAVE_ONLINE_VES, [test x$enable_interpreter = xyes] || [test x$mono_feature_disable_jit != xyes])
dnl
dnl Simple Generational checks (sgen)
@@ -4135,7 +4140,7 @@ AC_SUBST(mono_build_root)
mono_runtime=mono/mini/mono
AC_SUBST(mono_runtime)
CSC_LOCATION=`cd $srcdir && pwd`/external/roslyn-binaries/Microsoft.Net.Compilers/Microsoft.Net.Compilers.2.3.0/tools/csc.exe
CSC_LOCATION=`cd $srcdir && pwd`/external/roslyn-binaries/Microsoft.Net.Compilers/Microsoft.Net.Compilers.2.3.1/tools/csc.exe
if test $csc_compiler = mcs; then
CSC=$mcs_topdir/class/lib/build/mcs.exe
Submodule external/buildtools deleted from b5cc6e6ab5.
+1 -1
+1 -1
+1 -1
+10
View File
@@ -181,6 +181,16 @@ Gives the path for the temporary LLVM bitcode file created during AOT.
.I info
Print the architecture the AOT in this copy of Mono targets and quit.
.TP
.I interp
Generates all required wrappers, so that it is possible to run --interpreter without
any code generation at runtime. This option only makes sense with \fBmscorlib.dll\fR.
Embedders can set
.nf
mono_jit_set_aot_mode (MONO_AOT_MODE_INTERP);
.fi
.ne
.TP
.I ld-flags
Additional flags to pass to the C linker (if the current AOT mode calls for invoking it).
.TP
+5 -7
View File
@@ -20,9 +20,10 @@ TEST_RUNTIME_WRAPPERS_PATH = $(shell dirname $(RUNTIME))/_tmpinst/bin
ifndef NO_TEST
test_nunit_lib = nunitlite.dll
xunit_core := xunit.core xunit.abstractions xunit.assert
xunit_core := xunit.core xunit.abstractions xunit.assert Xunit.NetCore.Extensions
xunit_deps := System.Runtime
xunit_class_deps := Xunit.NetCore.Extensions
xunit_src := $(patsubst %,$(topdir)/../external/xunit-binaries/%,BenchmarkAttribute.cs BenchmarkDiscover.cs)
xunit_class_deps :=
xunit_libs_ref = $(patsubst %,-r:$(topdir)/../external/xunit-binaries/%.dll,$(xunit_core))
xunit_libs_ref += $(patsubst %,-r:$(topdir)/class/lib/$(PROFILE)/Facades/%.dll,$(xunit_deps))
@@ -89,9 +90,6 @@ endif
tests_CLEAN_FILES += $(topdir)/build/deps/nunit-$(PROFILE).stamp
$(topdir)/class/lib/$(PROFILE)/$(PARENT_PROFILE)Xunit.NetCore.Extensions.dll:
$(MAKE) -C $(topdir)/class/Xunit.NetCore.Extensions
endif
test_assemblies :=
@@ -222,8 +220,8 @@ run-xunit-test-lib: xunit-test-local
$$ok
@rm -f xunit.execution.desktop.dll
$(xunit_test_lib): $(the_assembly) $(xtest_response) $(xunit_libs_dep)
$(TEST_COMPILE) $(LIBRARY_FLAGS) $(XTEST_LIB_FLAGS) -target:library -out:$@ $(xtest_flags) @$(xtest_response)
$(xunit_test_lib): $(the_assembly) $(xtest_response) $(xunit_libs_dep) $(xunit_src)
$(TEST_COMPILE) $(LIBRARY_FLAGS) $(XTEST_LIB_FLAGS) -target:library -out:$@ $(xtest_flags) @$(xtest_response) $(xunit_src)
xtest_response_preprocessed = $(xtest_response)_preprocessed
@@ -86,6 +86,8 @@ namespace Mono.Security.Interface
void EndWrite (IAsyncResult asyncResult);
Task ShutdownAsync ();
TransportContext TransportContext {
get;
}
@@ -27,6 +27,7 @@ Mono.Security.Cryptography/PKCS8Test.cs
Mono.Security.Cryptography/RSAManagedTest.cs
Mono.Security.Cryptography/SHA224ManagedTest.cs
Mono.Security.Cryptography/SHA224Test.cs
Mono.Security.Interface/TestProvider.cs
Mono.Security.Protocol.Ntlm/ChallengeResponseTest.cs
Mono.Security.Protocol.Ntlm/MessageBaseTest.cs
Mono.Security.Protocol.Ntlm/Type1MessageTest.cs
@@ -0,0 +1,47 @@
//
// TestProvider.cs
//
// Author:
// Martin Baulig <[email protected]>
//
// Copyright (c) 2017 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.IO;
using System.Security.Cryptography;
using System.Text;
using Mono.Security;
using Mono.Security.Interface;
using NUnit.Framework;
namespace MonoTests.Mono.Security
{
[TestFixture]
public class TestProvider
{
[Test]
public void GetProvider ()
{
var provider = MonoTlsProviderFactory.GetProvider ();
Assert.IsNotNull (provider, "TLS Provider");
}
}
}
@@ -310,19 +310,20 @@ namespace System.IO.MemoryMappedFiles
[MonoLimitation ("Named mappings scope is process local")]
public static MemoryMappedFile OpenExisting (string mapName)
{
throw new NotImplementedException ();
return OpenExisting (mapName, MemoryMappedFileRights.ReadWrite);
}
[MonoLimitation ("Named mappings scope is process local")]
public static MemoryMappedFile OpenExisting (string mapName, MemoryMappedFileRights desiredAccessRights)
{
throw new NotImplementedException ();
return OpenExisting (mapName, desiredAccessRights, HandleInheritability.None);
}
[MonoLimitation ("Named mappings scope is process local")]
public static MemoryMappedFile OpenExisting (string mapName, MemoryMappedFileRights desiredAccessRights, HandleInheritability inheritability)
{
throw new NotImplementedException ();
// FIXME: Actually use desiredAccessRights
return CoreShmCreate (mapName, 0, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, null, inheritability, FileMode.Open);
}
public MemoryMappedViewStream CreateViewStream ()
@@ -393,10 +394,9 @@ namespace System.IO.MemoryMappedFiles
throw new NotImplementedException ();
}
[MonoTODO]
public SafeMemoryMappedFileHandle SafeMemoryMappedFileHandle {
get {
throw new NotImplementedException ();
return handle;
}
}
@@ -301,9 +301,12 @@ namespace MonoTests.System.IO.MemoryMappedFiles {
var name = MkNamedMapping ();
using (var m0 = MemoryMappedFile.CreateNew(name, 4096, MemoryMappedFileAccess.ReadWrite)) {
using (var m1 = MemoryMappedFile.CreateOrOpen (name, 4096, MemoryMappedFileAccess.ReadWrite)) {
using (MemoryMappedViewAccessor v0 = m0.CreateViewAccessor (), v1 = m1.CreateViewAccessor ()) {
v0.Write (10, 0x12345);
Assert.AreEqual (0x12345, v1.ReadInt32 (10));
using (var m2 = MemoryMappedFile.OpenExisting (name)) {
using (MemoryMappedViewAccessor v0 = m0.CreateViewAccessor (), v1 = m1.CreateViewAccessor (), v2 = m2.CreateViewAccessor ()) {
v0.Write (10, 0x12345);
Assert.AreEqual (0x12345, v1.ReadInt32 (10));
Assert.AreEqual (0x12345, v2.ReadInt32 (10));
}
}
}
}
@@ -466,5 +469,13 @@ namespace MonoTests.System.IO.MemoryMappedFiles {
}
}
}
[Test]
public void OpenExistingWithNoExistingThrows()
{
Assert.Throws<FileNotFoundException>(() => {
MemoryMappedFile.OpenExisting (MkNamedMapping ());
});
}
}
}
@@ -375,8 +375,9 @@ namespace System.Net.Http
wrequest.ResendContentFactory = content.CopyTo;
var stream = await wrequest.GetRequestStreamAsync ().ConfigureAwait (false);
await request.Content.CopyToAsync (stream).ConfigureAwait (false);
using (var stream = await wrequest.GetRequestStreamAsync ().ConfigureAwait (false)) {
await request.Content.CopyToAsync (stream).ConfigureAwait (false);
}
} else if (HttpMethod.Post.Equals (request.Method) || HttpMethod.Put.Equals (request.Method) || HttpMethod.Delete.Equals (request.Method)) {
// Explicitly set this to make sure we're sending a "Content-Length: 0" header.
// This fixes the issue that's been reported on the forums:
@@ -1,3 +1,4 @@
../../../external/corefx/src/Common/tests/System/AssertExtensions.cs
../../../external/corefx/src/Common/tests/System/PlatformDetection.cs
# ../../../external/corefx/src/System.Runtime.Numerics/tests/*.cs
@@ -58,13 +58,13 @@ namespace MonoTests.System.ServiceProcess
static ServiceInfo DISK_DRIVER_SERVICE = new ServiceInfo { ServiceName = "disk", DisplayName = "Disk Driver", ServiceType = ServiceType.KernelDriver };
static ServiceInfo ROUTING_AND_REMOTE_ACCESS_SERVICE = new ServiceInfo { ServiceName = "RemoteAccess", DisplayName = "Routing and Remote Access", DependedOn = new [] { "bfe", "http", "rasman", "rpcss" } };
static ServiceInfo SECONDARY_LOGON_SERVICE = new ServiceInfo { ServiceName = "seclogon", DisplayName = "Secondary Logon", Dependents = new [] { "te.service" } };
static ServiceInfo SECURITY_ACCOUNTS_MANAGER_SERVICE = new ServiceInfo { ServiceName = "SamSs", DisplayName = "Security Accounts Manager", Dependents = new [] { "browser", "ktmrm", "lanmanserver", "msdtc" }, DependedOn = new [] { "rpcss" } };
static ServiceInfo SECURITY_ACCOUNTS_MANAGER_SERVICE = new ServiceInfo { ServiceName = "SamSs", DisplayName = "Security Accounts Manager", Dependents = new [] { "ktmrm", "lanmanserver", "msdtc" }, DependedOn = new [] { "rpcss" } };
static ServiceInfo COMPLUS_EVENTSYSTEM_SERVICE = new ServiceInfo { ServiceName = "EventSystem", DisplayName = "COM+ Event System", ServiceType = ServiceType.Win32ShareProcess, Dependents = new [] { "comsysapp", "sens" }, DependedOn = new [] { "rpcss" } };
static ServiceInfo WINDOWS_IMAGE_ACQUISITION_SERVICE = new ServiceInfo { ServiceName = "stisvc", DisplayName = "Windows Image Acquisition (WIA)", ServiceType = ServiceType.Win32OwnProcess, DependedOn = new [] { "rpcss" } };
static ServiceInfo WINDOWS_SEARCH_SERVICE = new ServiceInfo { ServiceName = "WSearch", DisplayName = "Windows Search", ServiceType = ServiceType.Win32OwnProcess, Dependents = new [] { "wmpnetworksvc", "workfolderssvc" }, DependedOn = new [] { "rpcss" } };
static ServiceInfo WINDOWS_TIME_SERVICE = new ServiceInfo { ServiceName = "W32Time", DisplayName = "Windows Time" };
static ServiceInfo WINDOWS_UPDATE_SERVICE = new ServiceInfo { ServiceName = "wuauserv", DisplayName = "Windows Update", DependedOn = new [] { "rpcss" } };
static ServiceInfo WORKSTATION_SERVICE = new ServiceInfo { ServiceName = "LanmanWorkstation", DisplayName = "Workstation", Dependents = new [] { "browser", "netlogon", "sessionenv" }, DependedOn = new [] { "bowser", "mrxsmb20", "nsi" } };
static ServiceInfo WORKSTATION_SERVICE = new ServiceInfo { ServiceName = "LanmanWorkstation", DisplayName = "Workstation", Dependents = new [] { "netlogon", "sessionenv" }, DependedOn = new [] { "bowser", "mrxsmb20", "nsi" } };
// A service which is expected to be disabled by default on all supported Windows versions.
static ServiceInfo DISABLED_SERVICE = ROUTING_AND_REMOTE_ACCESS_SERVICE;
@@ -36,7 +36,11 @@ namespace Mono.AppleTls
*/
var certificate2 = certificate as X509Certificate2;
if (certificate2 != null)
#if MONOTOUCH
return SecIdentity.Import (certificate2);
#else
return SecImportExport.ItemImport (certificate2);
#endif
/*
* Reading Certificates from the Mac Keychain
@@ -129,28 +133,28 @@ namespace Mono.AppleTls
targetHost = targetHost.Substring (0, pos);
}
var policy = SecPolicy.CreateSslPolicy (!serverMode, targetHost);
var trust = new SecTrust (certificates, policy);
using (var policy = SecPolicy.CreateSslPolicy (!serverMode, targetHost))
using (var trust = new SecTrust (certificates, policy)) {
if (validator.Settings.TrustAnchors != null) {
var status = trust.SetAnchorCertificates (validator.Settings.TrustAnchors);
if (status != SecStatusCode.Success)
throw new InvalidOperationException (status.ToString ());
trust.SetAnchorCertificatesOnly (false);
}
if (validator.Settings.TrustAnchors != null) {
var status = trust.SetAnchorCertificates (validator.Settings.TrustAnchors);
if (status != SecStatusCode.Success)
throw new InvalidOperationException (status.ToString ());
trust.SetAnchorCertificatesOnly (false);
if (validator.Settings.CertificateValidationTime != null) {
var status = trust.SetVerifyDate (validator.Settings.CertificateValidationTime.Value);
if (status != SecStatusCode.Success)
throw new InvalidOperationException (status.ToString ());
}
var result = trust.Evaluate ();
if (result == SecTrustResult.Unspecified)
return true;
errors |= MonoSslPolicyErrors.RemoteCertificateChainErrors;
return false;
}
if (validator.Settings.CertificateValidationTime != null) {
var status = trust.SetVerifyDate (validator.Settings.CertificateValidationTime.Value);
if (status != SecStatusCode.Success)
throw new InvalidOperationException (status.ToString ());
}
var result = trust.Evaluate ();
if (result == SecTrustResult.Unspecified)
return true;
errors |= MonoSslPolicyErrors.RemoteCertificateChainErrors;
return false;
}
}
}
@@ -235,32 +235,41 @@ namespace Mono.AppleTls
*
*/
var trust = GetPeerTrust (!IsServer);
X509CertificateCollection certificates;
if (trust == null || trust.Count == 0) {
remoteCertificate = null;
if (!IsServer)
throw new TlsException (AlertDescription.CertificateUnknown);
certificates = null;
} else {
if (trust.Count > 1)
Debug ("WARNING: Got multiple certificates in SecTrust!");
certificates = new X509CertificateCollection ();
for (int i = 0; i < trust.Count; i++)
certificates.Add (trust [(IntPtr)i].ToX509Certificate ());
remoteCertificate = certificates [0];
Debug ("Got peer trust: {0}", remoteCertificate);
}
bool ok;
SecTrust trust = null;
X509CertificateCollection certificates = null;
try {
trust = GetPeerTrust (!IsServer);
if (trust == null || trust.Count == 0) {
remoteCertificate = null;
if (!IsServer)
throw new TlsException (AlertDescription.CertificateUnknown);
certificates = null;
} else {
if (trust.Count > 1)
Debug ("WARNING: Got multiple certificates in SecTrust!");
certificates = new X509CertificateCollection ();
for (int i = 0; i < trust.Count; i++)
certificates.Add (trust.GetCertificate (i));
remoteCertificate = new X509Certificate (certificates [0]);
Debug ("Got peer trust: {0}", remoteCertificate);
}
ok = ValidateCertificate (certificates);
} catch (Exception ex) {
Debug ("Certificate validation failed: {0}", ex);
throw new TlsException (AlertDescription.CertificateUnknown, "Certificate validation threw exception.");
} finally {
if (trust != null)
trust.Dispose ();
if (certificates != null) {
for (int i = 0; i < certificates.Count; i++)
certificates [i].Dispose ();
}
}
if (!ok)
@@ -665,7 +674,7 @@ namespace Mono.AppleTls
if (value == IntPtr.Zero)
throw new TlsException (AlertDescription.CertificateUnknown);
}
return (value == IntPtr.Zero) ? null : new SecTrust (value);
return (value == IntPtr.Zero) ? null : new SecTrust (value, true);
}
#endregion
@@ -848,12 +857,12 @@ namespace Mono.AppleTls
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ SslStatus SSLClose (/* SSLContextRef */ IntPtr context);
public override void Close ()
public override void Shutdown ()
{
if (Interlocked.Exchange (ref pendingIO, 1) == 1)
throw new InvalidOperationException ();
Debug ("Close");
Debug ("Shutdown");
lastException = null;
@@ -862,7 +871,7 @@ namespace Mono.AppleTls
return;
var status = SSLClose (Handle);
Debug ("Close done: {0}", status);
Debug ("Shutdown done: {0}", status);
CheckStatusAndThrow (status);
} finally {
closed = true;
@@ -38,12 +38,12 @@ namespace Mono.AppleTls
}
protected override MNS.MobileTlsContext CreateContext (
MNS.MobileAuthenticatedStream parent, bool serverMode, string targetHost,
SslProtocols enabledProtocols, X509Certificate serverCertificate,
X509CertificateCollection clientCertificates, bool askForClientCert)
bool serverMode, string targetHost, SslProtocols enabledProtocols,
X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
bool askForClientCert)
{
return new AppleTlsContext (
parent, serverMode, targetHost,
this, serverMode, targetHost,
enabledProtocols, serverCertificate,
clientCertificates, askForClientCert);
}
@@ -67,6 +67,7 @@ namespace Mono.AppleTls {
return code;
}
#if !MONOTOUCH
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static SecStatusCode SecItemImport (
/* CFDataRef */ IntPtr importedData,
@@ -217,6 +218,7 @@ namespace Mono.AppleTls {
IntPtr keyUsage;
IntPtr keyAttributes;
}
#endif
}
}
#endif
+13
View File
@@ -66,6 +66,8 @@ namespace Mono.AppleTls {
foreach (var certificate in certificates)
array [i++] = new SecCertificate (certificate);
Initialize (array, policy);
for (i = 0; i < array.Length; i++)
array [i].Dispose ();
}
void Initialize (SecCertificate[] array, SecPolicy policy)
@@ -122,6 +124,17 @@ namespace Mono.AppleTls {
}
}
internal X509Certificate GetCertificate (int index)
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecTrust");
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException ("index");
var ptr = SecTrustGetCertificateAtIndex (handle, (IntPtr)index);
return new X509Certificate (ptr);
}
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static SecStatusCode /* OSStatus */ SecTrustSetAnchorCertificates (IntPtr /* SecTrustRef */ trust, IntPtr /* CFArrayRef */ anchorCertificates);
+9 -21
View File
@@ -316,6 +316,9 @@ namespace Mono.Btls
if (status == MonoBtlsSslError.WantRead) {
wantMore = true;
return 0;
} else if (status == MonoBtlsSslError.ZeroReturn) {
wantMore = false;
return size;
} else if (status != MonoBtlsSslError.None) {
throw GetException (status);
}
@@ -358,26 +361,11 @@ namespace Mono.Btls
}
}
public override void Close ()
public override void Shutdown ()
{
Debug ("Close!");
if (ssl != null) {
ssl.Dispose ();
ssl = null;
}
if (ctx != null) {
ctx.Dispose ();
ctx = null;
}
if (bio != null) {
bio.Dispose ();
bio = null;
}
if (errbio != null) {
errbio.Dispose ();
errbio = null;
}
Debug ("Shutdown!");
// ssl.SetQuietShutdown ();
ssl.Shutdown ();
}
void Dispose<T> (ref T disposable)
@@ -397,12 +385,12 @@ namespace Mono.Btls
{
try {
if (disposing) {
Dispose (ref ssl);
Dispose (ref ctx);
Dispose (ref remoteCertificate);
Dispose (ref nativeServerCertificate);
Dispose (ref nativeClientCertificate);
Dispose (ref clientCertificate);
Dispose (ref ctx);
Dispose (ref ssl);
Dispose (ref bio);
Dispose (ref errbio);
}
@@ -102,6 +102,20 @@ namespace Mono.Btls
CheckError (ret == 1, callerName);
}
protected internal void CheckLastError ([CallerMemberName] string callerName = null)
{
var error = Interlocked.Exchange (ref lastError, null);
if (error == null)
return;
string message;
if (callerName != null)
message = string.Format ("Caught unhandled exception in {0}.{1}.", GetType ().Name, callerName);
else
message = string.Format ("Caught unhandled exception.");
throw new MonoBtlsException (message, error);
}
[DllImport (BTLS_DYLIB)]
extern static void mono_btls_free (IntPtr data);
+38 -10
View File
@@ -47,6 +47,7 @@ namespace Mono.Btls
protected override bool ReleaseHandle ()
{
mono_btls_ssl_destroy (handle);
handle = IntPtr.Zero;
return true;
}
}
@@ -78,6 +79,12 @@ namespace Mono.Btls
[DllImport (BTLS_DYLIB)]
extern static void mono_btls_ssl_close (IntPtr handle);
[DllImport (BTLS_DYLIB)]
extern static int mono_btls_ssl_shutdown (IntPtr handle);
[DllImport (BTLS_DYLIB)]
extern static void mono_btls_ssl_set_quiet_shutdown (IntPtr handle, int mode);
[DllImport (BTLS_DYLIB)]
extern static void mono_btls_ssl_set_bio (IntPtr handle, IntPtr bio);
@@ -131,6 +138,7 @@ namespace Mono.Btls
return new BoringSslHandle (handle);
}
MonoBtlsBio bio;
PrintErrorsCallbackFunc printErrorsFunc;
IntPtr printErrorsFuncPtr;
@@ -148,6 +156,7 @@ namespace Mono.Btls
public void SetBio (MonoBtlsBio bio)
{
CheckThrow ();
this.bio = bio;
mono_btls_ssl_set_bio (
Handle.DangerousGetHandle (),
bio.Handle.DangerousGetHandle ());
@@ -164,18 +173,17 @@ namespace Mono.Btls
errors = null;
}
if (errors != null) {
Console.Error.WriteLine ("ERROR: {0} failed: {1}", callerName, errors);
if (errors != null)
throw new MonoBtlsException ("{0} failed: {1}.", callerName, errors);
} else {
Console.Error.WriteLine ("ERROR: {0} failed.", callerName);
else
throw new MonoBtlsException ("{0} failed.", callerName);
}
}
MonoBtlsSslError GetError (int ret_code)
{
CheckThrow ();
bio.CheckLastError ();
var error = mono_btls_ssl_get_error (
Handle.DangerousGetHandle (), ret_code);
return (MonoBtlsSslError)error;
@@ -287,15 +295,20 @@ namespace Mono.Btls
var ret = mono_btls_ssl_read (
Handle.DangerousGetHandle (), data, dataSize);
if (ret >= 0) {
if (ret > 0) {
dataSize = ret;
return MonoBtlsSslError.None;
}
var error = mono_btls_ssl_get_error (
Handle.DangerousGetHandle (), ret);
var error = GetError (ret);
if (ret == 0 && error == MonoBtlsSslError.Syscall) {
// End-of-stream
dataSize = 0;
return MonoBtlsSslError.None;
}
dataSize = 0;
return (MonoBtlsSslError)error;
return error;
}
public MonoBtlsSslError Write (IntPtr data, ref int dataSize)
@@ -416,9 +429,24 @@ namespace Mono.Btls
return Marshal.PtrToStringAnsi (namePtr);
}
public void Shutdown ()
{
CheckThrow ();
var ret = mono_btls_ssl_shutdown (Handle.DangerousGetHandle ());
if (ret < 0)
throw ThrowError ();
}
public void SetQuietShutdown ()
{
CheckThrow ();
mono_btls_ssl_set_quiet_shutdown (Handle.DangerousGetHandle (), 1);
}
protected override void Close ()
{
mono_btls_ssl_close (Handle.DangerousGetHandle ());
if (!Handle.IsInvalid)
mono_btls_ssl_close (Handle.DangerousGetHandle ());
}
}
}
+4 -4
View File
@@ -53,12 +53,12 @@ namespace Mono.Btls
}
protected override MNS.MobileTlsContext CreateContext (
MNS.MobileAuthenticatedStream parent, bool serverMode, string targetHost,
SslProtocols enabledProtocols, X509Certificate serverCertificate,
X509CertificateCollection clientCertificates, bool askForClientCert)
bool serverMode, string targetHost, SslProtocols enabledProtocols,
X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
bool askForClientCert)
{
return new MonoBtlsContext (
parent, serverMode, targetHost,
this, serverMode, targetHost,
enabledProtocols, serverCertificate,
clientCertificates, askForClientCert);
}
@@ -11,14 +11,14 @@ using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Authentication;
using SD = System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.ExceptionServices;
namespace Mono.Net.Security
{
delegate AsyncOperationStatus AsyncOperation (AsyncProtocolRequest asyncRequest, AsyncOperationStatus status);
class BufferOffsetSize
{
public byte[] Buffer;
@@ -37,6 +37,13 @@ namespace Mono.Net.Security
public BufferOffsetSize (byte[] buffer, int offset, int size)
{
if (buffer == null)
throw new ArgumentNullException (nameof (buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException (nameof (offset));
if (size < 0 || offset + size > buffer.Length)
throw new ArgumentOutOfRangeException (nameof (size));
Buffer = buffer;
Offset = offset;
Size = size;
@@ -54,7 +61,7 @@ namespace Mono.Net.Security
public readonly int InitialSize;
public BufferOffsetSize2 (int size)
: base (new byte [size], 0, 0)
: base (new byte[size], 0, 0)
{
InitialSize = size;
}
@@ -63,7 +70,7 @@ namespace Mono.Net.Security
{
Offset = Size = 0;
TotalBytes = 0;
Buffer = new byte [InitialSize];
Buffer = new byte[InitialSize];
Complete = false;
}
@@ -74,11 +81,11 @@ namespace Mono.Net.Security
int missing = size - Remaining;
if (Offset == 0 && Size == 0) {
Buffer = new byte [size];
Buffer = new byte[size];
return;
}
var buffer = new byte [Buffer.Length + missing];
var buffer = new byte[Buffer.Length + missing];
Buffer.CopyTo (buffer, 0);
Buffer = buffer;
}
@@ -91,201 +98,296 @@ namespace Mono.Net.Security
}
}
enum AsyncOperationStatus {
NotStarted,
enum AsyncOperationStatus
{
Initialize,
Continue,
Running,
Complete,
WantRead,
WantWrite,
ReadDone,
FinishWrite
Complete
}
class AsyncProtocolRequest
class AsyncProtocolResult
{
public readonly MobileAuthenticatedStream Parent;
public readonly BufferOffsetSize UserBuffer;
int RequestedSize;
public int CurrentSize;
public int UserResult;
AsyncOperation Operation;
int Status;
public readonly int ID = ++next_id;
static int next_id;
public readonly LazyAsyncResult UserAsyncResult;
public AsyncProtocolRequest (MobileAuthenticatedStream parent, LazyAsyncResult lazyResult, BufferOffsetSize userBuffer = null)
{
Parent = parent;
UserAsyncResult = lazyResult;
UserBuffer = userBuffer;
public int UserResult {
get;
}
public ExceptionDispatchInfo Error {
get;
}
public bool CompleteWithError (Exception ex)
public AsyncProtocolResult (int result)
{
Status = (int)AsyncOperationStatus.Complete;
if (UserAsyncResult == null)
return true;
if (!UserAsyncResult.InternalPeekCompleted)
UserAsyncResult.InvokeCallback (ex);
return false;
UserResult = result;
}
public AsyncProtocolResult (ExceptionDispatchInfo error)
{
Error = error;
}
}
abstract class AsyncProtocolRequest
{
public MobileAuthenticatedStream Parent {
get;
}
public bool RunSynchronously {
get;
}
public int ID => ++next_id;
public string Name => GetType ().Name;
public int UserResult {
get;
protected set;
}
int Started;
int RequestedSize;
int WriteRequested;
readonly object locker = new object ();
static int next_id;
public AsyncProtocolRequest (MobileAuthenticatedStream parent, bool sync)
{
Parent = parent;
RunSynchronously = sync;
}
[SD.Conditional ("MARTIN_DEBUG")]
protected void Debug (string message, params object[] args)
{
Parent.Debug ("AsyncProtocolRequest({0}:{1}): {2}", Parent.ID, ID, string.Format (message, args));
Parent.Debug ("{0}({1}:{2}): {3}", Name, Parent.ID, ID, string.Format (message, args));
}
internal void RequestRead (int size)
{
var oldStatus = (AsyncOperationStatus)Interlocked.CompareExchange (ref Status, (int)AsyncOperationStatus.WantRead, (int)AsyncOperationStatus.Running);
Debug ("RequestRead: {0} {1}", oldStatus, size);
if (oldStatus == AsyncOperationStatus.Running)
RequestedSize = size;
else if (oldStatus == AsyncOperationStatus.WantRead)
lock (locker) {
RequestedSize += size;
else if (oldStatus != AsyncOperationStatus.WantWrite)
throw new InvalidOperationException ();
}
internal void ResetRead ()
{
var oldStatus = (AsyncOperationStatus)Interlocked.CompareExchange (ref Status, (int)AsyncOperationStatus.Complete, (int)AsyncOperationStatus.WantRead);
Debug ("ResetRead: {0} {1}", oldStatus, Status);
}
internal void ResetWrite ()
{
var oldStatus = (AsyncOperationStatus)Interlocked.CompareExchange (ref Status, (int)AsyncOperationStatus.Complete, (int)AsyncOperationStatus.WantWrite);
Debug ("ResetWrite: {0} {1}", oldStatus, Status);
Debug ("RequestRead: {0}", size);
}
}
internal void RequestWrite ()
{
var oldStatus = (AsyncOperationStatus)Interlocked.CompareExchange (ref Status, (int)AsyncOperationStatus.WantWrite, (int)AsyncOperationStatus.Running);
Debug ("RequestWrite: {0} {1}", oldStatus, Status);
if (oldStatus == AsyncOperationStatus.Running)
return;
else if (oldStatus != AsyncOperationStatus.WantRead && oldStatus != AsyncOperationStatus.WantWrite)
throw new InvalidOperationException ();
WriteRequested = 1;
}
internal void StartOperation (AsyncOperation operation)
internal async Task<AsyncProtocolResult> StartOperation (CancellationToken cancellationToken)
{
Debug ("Start Operation: {0} {1}", Status, operation);
if (Interlocked.CompareExchange (ref Status, (int)AsyncOperationStatus.Initialize, (int)AsyncOperationStatus.NotStarted) != (int)AsyncOperationStatus.NotStarted)
Debug ("Start Operation: {0}", this);
if (Interlocked.CompareExchange (ref Started, 1, 0) != 0)
throw new InvalidOperationException ();
Operation = operation;
if (UserAsyncResult == null) {
StartOperation ();
return;
}
ThreadPool.QueueUserWorkItem (_ => StartOperation ());
}
void StartOperation ()
{
try {
ProcessOperation ();
if (UserAsyncResult != null && !UserAsyncResult.InternalPeekCompleted)
UserAsyncResult.InvokeCallback (UserResult);
await ProcessOperation (cancellationToken).ConfigureAwait (false);
return new AsyncProtocolResult (UserResult);
} catch (Exception ex) {
if (UserAsyncResult == null)
throw;
if (!UserAsyncResult.InternalPeekCompleted)
UserAsyncResult.InvokeCallback (ex);
var info = Parent.SetException (MobileAuthenticatedStream.GetSSPIException (ex));
return new AsyncProtocolResult (info);
}
}
void ProcessOperation ()
async Task ProcessOperation (CancellationToken cancellationToken)
{
AsyncOperationStatus status;
do {
status = (AsyncOperationStatus)Interlocked.Exchange (ref Status, (int)AsyncOperationStatus.Running);
var status = AsyncOperationStatus.Initialize;
while (status != AsyncOperationStatus.Complete) {
cancellationToken.ThrowIfCancellationRequested ();
Debug ("ProcessOperation: {0}", status);
status = ProcessOperation (status);
Debug ("ProcessOperation done: {0}", status);
AsyncOperationStatus oldStatus;
if (status == AsyncOperationStatus.Complete) {
oldStatus = (AsyncOperationStatus)Interlocked.CompareExchange (ref Status, (int)AsyncOperationStatus.FinishWrite, (int)AsyncOperationStatus.WantWrite);
if (oldStatus == AsyncOperationStatus.WantWrite) {
// We are done, but still need to flush the write queue.
status = AsyncOperationStatus.FinishWrite;
continue;
var ret = await InnerRead (cancellationToken).ConfigureAwait (false);
if (ret != null) {
if (ret == 0) {
// End-of-stream
Debug ("END OF STREAM!");
status = AsyncOperationStatus.ReadDone;
} else if (ret < 0) {
// remote prematurely closed connection.
throw new IOException ("Remote prematurely closed connection.");
}
}
oldStatus = (AsyncOperationStatus)Interlocked.CompareExchange (ref Status, (int)status, (int)AsyncOperationStatus.Running);
Debug ("ProcessOperation done: {0} -> {1}", oldStatus, status);
Debug ("ProcessOperation run: {0}", status);
if (oldStatus != AsyncOperationStatus.Running) {
if (status == oldStatus || status == AsyncOperationStatus.Continue || status == AsyncOperationStatus.Complete)
status = oldStatus;
else
throw new InvalidOperationException ();
AsyncOperationStatus newStatus;
switch (status) {
case AsyncOperationStatus.Initialize:
case AsyncOperationStatus.Continue:
case AsyncOperationStatus.ReadDone:
newStatus = Run (status);
break;
default:
throw new InvalidOperationException ();
}
} while (status != AsyncOperationStatus.Complete);
if (Interlocked.Exchange (ref WriteRequested, 0) != 0) {
// Flush the write queue.
await Parent.InnerWrite (RunSynchronously, cancellationToken);
}
Debug ("ProcessOperation done: {0} -> {1}", status, newStatus);
status = newStatus;
}
}
AsyncOperationStatus ProcessOperation (AsyncOperationStatus status)
async Task<int?> InnerRead (CancellationToken cancellationToken)
{
if (status == AsyncOperationStatus.WantRead) {
if (RequestedSize < 0)
int? totalRead = null;
var requestedSize = Interlocked.Exchange (ref RequestedSize, 0);
while (requestedSize > 0) {
Debug ("ProcessOperation - read inner: {0}", requestedSize);
var ret = await Parent.InnerRead (RunSynchronously, requestedSize, cancellationToken).ConfigureAwait (false);
Debug ("ProcessOperation - read inner done: {0} - {1}", requestedSize, ret);
if (ret <= 0)
return ret;
if (ret > requestedSize)
throw new InvalidOperationException ();
else if (RequestedSize == 0)
return AsyncOperationStatus.Continue;
Debug ("ProcessOperation - read inner: {0}", RequestedSize);
var ret = Parent.InnerRead (RequestedSize);
Debug ("ProcessOperation - read inner done: {0} - {1}", RequestedSize, ret);
totalRead += ret;
requestedSize -= ret;
var newRequestedSize = Interlocked.Exchange (ref RequestedSize, 0);
requestedSize += newRequestedSize;
}
if (ret < 0)
return AsyncOperationStatus.ReadDone;
return totalRead;
}
RequestedSize -= ret;
/*
* This will operate on the internal buffers and never block.
*/
protected abstract AsyncOperationStatus Run (AsyncOperationStatus status);
if (ret == 0 || RequestedSize == 0)
return AsyncOperationStatus.Continue;
else
return AsyncOperationStatus.WantRead;
} else if (status == AsyncOperationStatus.WantWrite) {
Debug ("ProcessOperation - want write");
Parent.InnerWrite ();
Debug ("ProcessOperation - want write done");
return AsyncOperationStatus.Continue;
} else if (status == AsyncOperationStatus.Initialize || status == AsyncOperationStatus.Continue) {
Debug ("ProcessOperation - continue");
status = Operation (this, status);
Debug ("ProcessOperation - continue done: {0}", status);
return status;
} else if (status == AsyncOperationStatus.ReadDone) {
Debug ("ProcessOperation - read done");
status = Operation (this, status);
Debug ("ProcessOperation - read done: {0}", status);
return status;
} else if (status == AsyncOperationStatus.FinishWrite) {
Debug ("ProcessOperation - finish write");
Parent.InnerWrite ();
Debug ("ProcessOperation - finish write done");
public override string ToString ()
{
return string.Format ("[{0}]", Name);
}
}
class AsyncHandshakeRequest : AsyncProtocolRequest
{
public AsyncHandshakeRequest (MobileAuthenticatedStream parent, bool sync)
: base (parent, sync)
{
}
protected override AsyncOperationStatus Run (AsyncOperationStatus status)
{
return Parent.ProcessHandshake (status);
}
}
abstract class AsyncReadOrWriteRequest : AsyncProtocolRequest
{
protected BufferOffsetSize UserBuffer {
get;
}
protected int CurrentSize {
get; set;
}
public AsyncReadOrWriteRequest (MobileAuthenticatedStream parent, bool sync, byte[] buffer, int offset, int size)
: base (parent, sync)
{
UserBuffer = new BufferOffsetSize (buffer, offset, size);
}
public override string ToString ()
{
return string.Format ("[{0}: {1}]", Name, UserBuffer);
}
}
class AsyncReadRequest : AsyncReadOrWriteRequest
{
public AsyncReadRequest (MobileAuthenticatedStream parent, bool sync, byte[] buffer, int offset, int size)
: base (parent, sync, buffer, offset, size)
{
}
protected override AsyncOperationStatus Run (AsyncOperationStatus status)
{
Debug ("ProcessRead - read user: {0} {1}", this, status);
var (ret, wantMore) = Parent.ProcessRead (UserBuffer);
Debug ("ProcessRead - read user done: {0} - {1} {2}", this, ret, wantMore);
if (ret < 0) {
UserResult = -1;
return AsyncOperationStatus.Complete;
}
throw new InvalidOperationException ();
CurrentSize += ret;
UserBuffer.Offset += ret;
UserBuffer.Size -= ret;
Debug ("Process Read - read user done #1: {0} - {1} {2}", this, CurrentSize, wantMore);
if (wantMore && CurrentSize == 0)
return AsyncOperationStatus.Continue;
UserResult = CurrentSize;
return AsyncOperationStatus.Complete;
}
}
class AsyncWriteRequest : AsyncReadOrWriteRequest
{
public AsyncWriteRequest (MobileAuthenticatedStream parent, bool sync, byte[] buffer, int offset, int size)
: base (parent, sync, buffer, offset, size)
{
}
protected override AsyncOperationStatus Run (AsyncOperationStatus status)
{
Debug ("ProcessWrite - write user: {0} {1}", this, status);
if (UserBuffer.Size == 0) {
UserResult = CurrentSize;
return AsyncOperationStatus.Complete;
}
var (ret, wantMore) = Parent.ProcessWrite (UserBuffer);
Debug ("ProcessWrite - write user done: {0} - {1} {2}", this, ret, wantMore);
if (ret < 0) {
UserResult = -1;
return AsyncOperationStatus.Complete;
}
CurrentSize += ret;
UserBuffer.Offset += ret;
UserBuffer.Size -= ret;
if (wantMore)
return AsyncOperationStatus.Continue;
UserResult = CurrentSize;
return AsyncOperationStatus.Complete;
}
}
class AsyncShutdownRequest : AsyncProtocolRequest
{
public AsyncShutdownRequest (MobileAuthenticatedStream parent)
: base (parent, false)
{
}
protected override AsyncOperationStatus Run (AsyncOperationStatus status)
{
return Parent.ProcessShutdown (status);
}
}
}
#endif
@@ -575,6 +575,11 @@ namespace Mono.Net.Security.Private
#region IMonoSslStream
Task IMonoSslStream.ShutdownAsync ()
{
return Task.CompletedTask;
}
AuthenticatedStream IMonoSslStream.AuthenticatedStream {
get { return this; }
}
@@ -23,6 +23,7 @@ using System.IO;
using System.Net;
using System.Net.Security;
using System.Globalization;
using System.Security.Authentication;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
@@ -36,8 +37,13 @@ namespace Mono.Net.Security
{
abstract class MobileAuthenticatedStream : AuthenticatedStream, MSI.IMonoSslStream
{
/*
* This is intentionally called `xobileTlsContext'. It is a "dangerous" object
* that must not be touched outside the `ioLock' and we need to be very careful
* where we access it.
*/
MobileTlsContext xobileTlsContext;
Exception lastException;
ExceptionDispatchInfo lastException;
AsyncProtocolRequest asyncHandshakeRequest;
AsyncProtocolRequest asyncReadRequest;
@@ -47,11 +53,12 @@ namespace Mono.Net.Security
object ioLock = new object ();
int closeRequested;
bool shutdown;
static int uniqueNameInteger = 123;
public MobileAuthenticatedStream (Stream innerStream, bool leaveInnerStreamOpen, SslStream owner,
MSI.MonoTlsSettings settings, MSI.MonoTlsProvider provider)
MSI.MonoTlsSettings settings, MSI.MonoTlsProvider provider)
: base (innerStream, leaveInnerStreamOpen)
{
SslStream = owner;
@@ -78,42 +85,47 @@ namespace Mono.Net.Security
get { return xobileTlsContext != null; }
}
internal MobileTlsContext Context {
get {
CheckThrow (true);
return xobileTlsContext;
}
}
internal void CheckThrow (bool authSuccessCheck)
internal void CheckThrow (bool authSuccessCheck, bool shutdownCheck = false)
{
if (closeRequested != 0)
throw new InvalidOperationException ("Stream is closed.");
if (lastException != null)
throw lastException;
lastException.Throw ();
if (authSuccessCheck && !IsAuthenticated)
throw new InvalidOperationException ("Must be authenticated.");
throw new InvalidOperationException (SR.net_auth_noauth);
if (shutdownCheck && shutdown)
throw new InvalidOperationException (SR.net_ssl_io_already_shutdown);
}
Exception SetException (Exception e)
internal static Exception GetSSPIException (Exception e)
{
e = SetException_internal (e);
if (e != null && xobileTlsContext != null)
xobileTlsContext.Dispose ();
return e;
if (e is OperationCanceledException || e is IOException || e is ObjectDisposedException || e is AuthenticationException)
return e;
return new AuthenticationException (SR.net_auth_SSPI, e);
}
Exception SetException_internal (Exception e)
internal static Exception GetIOException (Exception e, string message)
{
if (lastException == null)
lastException = e;
return lastException;
if (e is OperationCanceledException || e is IOException || e is ObjectDisposedException || e is AuthenticationException)
return e;
return new IOException (message, e);
}
internal ExceptionDispatchInfo SetException (Exception e)
{
var info = ExceptionDispatchInfo.Capture (e);
var old = Interlocked.CompareExchange (ref lastException, info, null);
return old ?? info;
}
SslProtocols DefaultProtocols {
get { return SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls; }
}
enum OperationType {
Read,
Write,
Shutdown
}
public void AuthenticateAsClient (string targetHost)
{
AuthenticateAsClient (targetHost, new X509CertificateCollection (), DefaultProtocols, false);
@@ -121,8 +133,8 @@ namespace Mono.Net.Security
public void AuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
{
ValidateCreateContext (false, targetHost, enabledSslProtocols, null, clientCertificates, false);
ProcessAuthentication (null);
var task = ProcessAuthentication (true, false, targetHost, enabledSslProtocols, null, clientCertificates, false);
task.Wait ();
}
public IAsyncResult BeginAuthenticateAsClient (string targetHost, AsyncCallback asyncCallback, object asyncState)
@@ -132,15 +144,13 @@ namespace Mono.Net.Security
public IAsyncResult BeginAuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
{
ValidateCreateContext (false, targetHost, enabledSslProtocols, null, clientCertificates, false);
var result = new LazyAsyncResult (this, asyncState, asyncCallback);
ProcessAuthentication (result);
return result;
var task = ProcessAuthentication (false, false, targetHost, enabledSslProtocols, null, clientCertificates, false);
return TaskToApm.Begin (task, asyncCallback, asyncState);
}
public void EndAuthenticateAsClient (IAsyncResult asyncResult)
{
EndProcessAuthentication (asyncResult);
TaskToApm.End (asyncResult);
}
public void AuthenticateAsServer (X509Certificate serverCertificate)
@@ -150,8 +160,8 @@ namespace Mono.Net.Security
public void AuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
{
ValidateCreateContext (true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired);
ProcessAuthentication (null);
var task = ProcessAuthentication (true, true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired);
task.Wait ();
}
public IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState)
@@ -161,218 +171,214 @@ namespace Mono.Net.Security
public IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
{
ValidateCreateContext (true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired);
var result = new LazyAsyncResult (this, asyncState, asyncCallback);
ProcessAuthentication (result);
return result;
var task = ProcessAuthentication (false, true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired);
return TaskToApm.Begin (task, asyncCallback, asyncState);
}
public void EndAuthenticateAsServer (IAsyncResult asyncResult)
{
EndProcessAuthentication (asyncResult);
TaskToApm.End (asyncResult);
}
public Task AuthenticateAsClientAsync (string targetHost)
{
return Task.Factory.FromAsync (BeginAuthenticateAsClient, EndAuthenticateAsClient, targetHost, null);
return ProcessAuthentication (false, false, targetHost, DefaultProtocols, null, null, false);
}
public Task AuthenticateAsClientAsync (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
{
return Task.Factory.FromAsync ((callback, state) => BeginAuthenticateAsClient (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, callback, state), EndAuthenticateAsClient, null);
return ProcessAuthentication (false, false, targetHost, enabledSslProtocols, null, clientCertificates, false);
}
public Task AuthenticateAsServerAsync (X509Certificate serverCertificate)
{
return Task.Factory.FromAsync (BeginAuthenticateAsServer, EndAuthenticateAsServer, serverCertificate, null);
return AuthenticateAsServerAsync (serverCertificate, false, DefaultProtocols, false);
}
public Task AuthenticateAsServerAsync (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
{
return Task.Factory.FromAsync ((callback, state) => BeginAuthenticateAsServer (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, callback, state), EndAuthenticateAsServer, null);
return ProcessAuthentication (false, true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired);
}
public Task ShutdownAsync ()
{
Debug ("ShutdownAsync");
/*
* SSLClose() is a little bit tricky as it might attempt to send a close_notify alert
* and thus call our write callback.
*
* It is also not thread-safe with SSLRead() or SSLWrite(), so we need to take the I/O lock here.
*/
var asyncRequest = new AsyncShutdownRequest (this);
var task = StartOperation (OperationType.Shutdown, asyncRequest, CancellationToken.None);
return task;
}
public AuthenticatedStream AuthenticatedStream {
get { return this; }
}
internal void ProcessAuthentication (LazyAsyncResult lazyResult)
async Task ProcessAuthentication (
bool runSynchronously, bool serverMode, string targetHost, SslProtocols enabledProtocols,
X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool clientCertRequired)
{
var asyncRequest = new AsyncProtocolRequest (this, lazyResult);
if (Interlocked.CompareExchange (ref asyncHandshakeRequest, asyncRequest, null) != null)
throw new InvalidOperationException ("Invalid nested call.");
try {
if (lastException != null)
throw lastException;
if (xobileTlsContext == null)
throw new InvalidOperationException ();
readBuffer.Reset ();
writeBuffer.Reset ();
try {
asyncRequest.StartOperation (ProcessHandshake);
} catch (Exception ex) {
ExceptionDispatchInfo.Capture (SetException (ex)).Throw ();
}
} finally {
if (lazyResult == null || lastException != null) {
readBuffer.Reset ();
writeBuffer.Reset ();
asyncHandshakeRequest = null;
}
}
}
internal void EndProcessAuthentication (IAsyncResult result)
{
if (result == null)
throw new ArgumentNullException ("asyncResult");
var lazyResult = (LazyAsyncResult)result;
if (Interlocked.Exchange (ref asyncHandshakeRequest, null) == null)
throw new InvalidOperationException ("Invalid end call.");
lazyResult.InternalWaitForCompletion ();
readBuffer.Reset ();
writeBuffer.Reset ();
var e = lazyResult.Result as Exception;
if (e != null)
ExceptionDispatchInfo.Capture (SetException (e)).Throw ();
}
internal void ValidateCreateContext (bool serverMode, string targetHost, SslProtocols enabledProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool clientCertRequired)
{
if (xobileTlsContext != null)
throw new InvalidOperationException ();
if (serverMode) {
if (serverCertificate == null)
throw new ArgumentException ("serverCertificate");
} else {
throw new ArgumentException (nameof (serverCertificate));
} else {
if (targetHost == null)
throw new ArgumentException ("targetHost");
throw new ArgumentException (nameof (targetHost));
if (targetHost.Length == 0)
targetHost = "?" + Interlocked.Increment (ref uniqueNameInteger).ToString (NumberFormatInfo.InvariantInfo);
}
xobileTlsContext = CreateContext (this, serverMode, targetHost, enabledProtocols, serverCertificate, clientCertificates, clientCertRequired);
if (lastException != null)
lastException.Throw ();
var asyncRequest = new AsyncHandshakeRequest (this, runSynchronously);
if (Interlocked.CompareExchange (ref asyncHandshakeRequest, asyncRequest, null) != null)
throw new InvalidOperationException ("Invalid nested call.");
// Make sure no other async requests can be started during the handshake.
if (Interlocked.CompareExchange (ref asyncReadRequest, asyncRequest, null) != null)
throw new InvalidOperationException ("Invalid nested call.");
if (Interlocked.CompareExchange (ref asyncWriteRequest, asyncRequest, null) != null)
throw new InvalidOperationException ("Invalid nested call.");
AsyncProtocolResult result;
try {
lock (ioLock) {
if (xobileTlsContext != null)
throw new InvalidOperationException ();
readBuffer.Reset ();
writeBuffer.Reset ();
xobileTlsContext = CreateContext (
serverMode, targetHost, enabledProtocols, serverCertificate,
clientCertificates, clientCertRequired);
}
try {
result = await asyncRequest.StartOperation (CancellationToken.None).ConfigureAwait (false);
} catch (Exception ex) {
result = new AsyncProtocolResult (SetException (GetSSPIException (ex)));
}
} finally {
lock (ioLock) {
readBuffer.Reset ();
writeBuffer.Reset ();
asyncWriteRequest = null;
asyncReadRequest = null;
asyncHandshakeRequest = null;
}
}
if (result.Error != null)
result.Error.Throw ();
}
protected abstract MobileTlsContext CreateContext (
MobileAuthenticatedStream parent, bool serverMode, string targetHost,
SSA.SslProtocols enabledProtocols, X509Certificate serverCertificate,
X509CertificateCollection clientCertificates, bool askForClientCert);
bool serverMode, string targetHost, SSA.SslProtocols enabledProtocols,
X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
bool askForClientCert);
public override IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
return BeginReadOrWrite (ref asyncReadRequest, ref readBuffer, ProcessRead, new BufferOffsetSize (buffer, offset, count), asyncCallback, asyncState);
var asyncRequest = new AsyncReadRequest (this, false, buffer, offset, count);
var task = StartOperation (OperationType.Read, asyncRequest, CancellationToken.None);
return TaskToApm.Begin (task, asyncCallback, asyncState);
}
public override int EndRead (IAsyncResult asyncResult)
{
return (int)EndReadOrWrite (asyncResult, ref asyncReadRequest);
return TaskToApm.End<int> (asyncResult);
}
public override IAsyncResult BeginWrite (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
return BeginReadOrWrite (ref asyncWriteRequest, ref writeBuffer, ProcessWrite, new BufferOffsetSize (buffer, offset, count), asyncCallback, asyncState);
var asyncRequest = new AsyncWriteRequest (this, false, buffer, offset, count);
var task = StartOperation (OperationType.Write, asyncRequest, CancellationToken.None);
return TaskToApm.Begin (task, asyncCallback, asyncState);
}
public override void EndWrite (IAsyncResult asyncResult)
{
EndReadOrWrite (asyncResult, ref asyncWriteRequest);
TaskToApm.End (asyncResult);
}
public override int Read (byte[] buffer, int offset, int count)
{
return ProcessReadOrWrite (ref asyncReadRequest, ref readBuffer, ProcessRead, new BufferOffsetSize (buffer, offset, count), null);
var asyncRequest = new AsyncReadRequest (this, true, buffer, offset, count);
var task = StartOperation (OperationType.Read, asyncRequest, CancellationToken.None);
return task.Result;
}
public void Write (byte[] buffer)
{
Write (buffer, 0, buffer.Length);
}
public override void Write (byte[] buffer, int offset, int count)
{
ProcessReadOrWrite (ref asyncWriteRequest, ref writeBuffer, ProcessWrite, new BufferOffsetSize (buffer, offset, count), null);
var asyncRequest = new AsyncWriteRequest (this, true, buffer, offset, count);
var task = StartOperation (OperationType.Write, asyncRequest, CancellationToken.None);
task.Wait ();
}
IAsyncResult BeginReadOrWrite (ref AsyncProtocolRequest nestedRequest, ref BufferOffsetSize2 internalBuffer, AsyncOperation operation, BufferOffsetSize userBuffer, AsyncCallback asyncCallback, object asyncState)
public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
LazyAsyncResult lazyResult = new LazyAsyncResult (this, asyncState, asyncCallback);
ProcessReadOrWrite (ref nestedRequest, ref internalBuffer, operation, userBuffer, lazyResult);
return lazyResult;
var asyncRequest = new AsyncReadRequest (this, false, buffer, offset, count);
return StartOperation (OperationType.Read, asyncRequest, cancellationToken);
}
object EndReadOrWrite (IAsyncResult asyncResult, ref AsyncProtocolRequest nestedRequest)
public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
var asyncRequest = new AsyncWriteRequest (this, false, buffer, offset, count);
return StartOperation (OperationType.Write, asyncRequest, cancellationToken);
}
var lazyResult = (LazyAsyncResult)asyncResult;
async Task<int> StartOperation (OperationType type, AsyncProtocolRequest asyncRequest, CancellationToken cancellationToken)
{
CheckThrow (true, type != OperationType.Read);
Debug ("StartOperationAsync: {0} {1}", asyncRequest, type);
if (Interlocked.Exchange (ref nestedRequest, null) == null)
throw new InvalidOperationException ("Invalid end call.");
// No "artificial" timeouts implemented so far, InnerStream controls timeout.
lazyResult.InternalWaitForCompletion ();
Debug ("EndReadOrWrite");
var e = lazyResult.Result as Exception;
if (e != null) {
var ioEx = e as IOException;
if (ioEx != null)
throw ioEx;
throw new IOException ("read failed", e);
if (type == OperationType.Read) {
if (Interlocked.CompareExchange (ref asyncReadRequest, asyncRequest, null) != null)
throw new InvalidOperationException ("Invalid nested call.");
} else {
if (Interlocked.CompareExchange (ref asyncWriteRequest, asyncRequest, null) != null)
throw new InvalidOperationException ("Invalid nested call.");
}
return lazyResult.Result;
}
AsyncProtocolResult result;
int ProcessReadOrWrite (ref AsyncProtocolRequest nestedRequest, ref BufferOffsetSize2 internalBuffer, AsyncOperation operation, BufferOffsetSize userBuffer, LazyAsyncResult lazyResult)
{
if (userBuffer == null || userBuffer.Buffer == null)
throw new ArgumentNullException ("buffer");
if (userBuffer.Offset < 0)
throw new ArgumentOutOfRangeException ("offset");
if (userBuffer.Size < 0 || userBuffer.Offset + userBuffer.Size > userBuffer.Buffer.Length)
throw new ArgumentOutOfRangeException ("count");
CheckThrow (true);
var name = internalBuffer == readBuffer ? "read" : "write";
Debug ("ProcessReadOrWrite: {0} {1}", name, userBuffer);
var asyncRequest = new AsyncProtocolRequest (this, lazyResult, userBuffer);
return StartOperation (ref nestedRequest, ref internalBuffer, operation, asyncRequest, name);
}
int StartOperation (ref AsyncProtocolRequest nestedRequest, ref BufferOffsetSize2 internalBuffer, AsyncOperation operation, AsyncProtocolRequest asyncRequest, string name)
{
if (Interlocked.CompareExchange (ref nestedRequest, asyncRequest, null) != null)
throw new InvalidOperationException ("Invalid nested call.");
bool failed = false;
try {
internalBuffer.Reset ();
asyncRequest.StartOperation (operation);
return asyncRequest.UserResult;
lock (ioLock) {
if (type == OperationType.Read)
readBuffer.Reset ();
else
writeBuffer.Reset ();
}
result = await asyncRequest.StartOperation (cancellationToken).ConfigureAwait (false);
} catch (Exception e) {
failed = true;
if (e is IOException)
throw;
throw new IOException (name + " failed", e);
var info = SetException (GetIOException (e, asyncRequest.Name + " failed"));
result = new AsyncProtocolResult (info);
} finally {
if (asyncRequest.UserAsyncResult == null || failed) {
internalBuffer.Reset ();
nestedRequest = null;
lock (ioLock) {
if (type == OperationType.Read) {
readBuffer.Reset ();
asyncReadRequest = null;
} else {
writeBuffer.Reset ();
asyncWriteRequest = null;
}
}
}
if (result.Error != null)
result.Error.Throw ();
return result.UserResult;
}
static int nextId;
@@ -384,26 +390,31 @@ namespace Mono.Net.Security
Console.Error.WriteLine ("MobileAuthenticatedStream({0}): {1}", ID, string.Format (message, args));
}
#region Called back from native code via SslConnection
#region Called back from native code via SslConnection
/*
* Called from within SSLRead() and SSLHandshake(). We only access tha managed byte[] here.
*/
internal int InternalRead (byte[] buffer, int offset, int size, out bool wantMore)
internal int InternalRead (byte[] buffer, int offset, int size, out bool outWantMore)
{
try {
Debug ("InternalRead: {0} {1} {2} {3}", offset, size, asyncReadRequest != null, readBuffer != null);
Debug ("InternalRead: {0} {1} {2} {3} {4}", offset, size,
asyncHandshakeRequest != null ? "handshake" : "",
asyncReadRequest != null ? "async" : "",
readBuffer != null ? readBuffer.ToString () : "");
var asyncRequest = asyncHandshakeRequest ?? asyncReadRequest;
return InternalRead (asyncRequest, readBuffer, buffer, offset, size, out wantMore);
var (ret, wantMore) = InternalRead (asyncRequest, readBuffer, buffer, offset, size);
outWantMore = wantMore;
return ret;
} catch (Exception ex) {
Debug ("InternalRead failed: {0}", ex);
SetException_internal (ex);
wantMore = false;
SetException (GetIOException (ex, "InternalRead() failed"));
outWantMore = false;
return -1;
}
}
int InternalRead (AsyncProtocolRequest asyncRequest, BufferOffsetSize internalBuffer, byte[] buffer, int offset, int size, out bool wantMore)
(int, bool) InternalRead (AsyncProtocolRequest asyncRequest, BufferOffsetSize internalBuffer, byte[] buffer, int offset, int size)
{
if (asyncRequest == null)
throw new InvalidOperationException ();
@@ -422,11 +433,10 @@ namespace Mono.Net.Security
* native function again.
*/
if (internalBuffer.Size == 0 && !internalBuffer.Complete) {
Debug ("InternalRead #1: {0} {1}", internalBuffer.Offset, internalBuffer.TotalBytes);
Debug ("InternalRead #1: {0} {1} {2}", internalBuffer.Offset, internalBuffer.TotalBytes, size);
internalBuffer.Offset = internalBuffer.Size = 0;
asyncRequest.RequestRead (size);
wantMore = true;
return 0;
return (0, true);
}
/*
@@ -441,8 +451,7 @@ namespace Mono.Net.Security
Buffer.BlockCopy (internalBuffer.Buffer, internalBuffer.Offset, buffer, offset, len);
internalBuffer.Offset += len;
internalBuffer.Size -= len;
wantMore = !internalBuffer.Complete && len < size;
return len;
return (len, !internalBuffer.Complete && len < size);
}
/*
@@ -456,7 +465,7 @@ namespace Mono.Net.Security
return InternalWrite (asyncRequest, writeBuffer, buffer, offset, size);
} catch (Exception ex) {
Debug ("InternalWrite failed: {0}", ex);
SetException_internal (ex);
SetException (GetIOException (ex, "InternalWrite() failed"));
return false;
}
}
@@ -511,22 +520,30 @@ namespace Mono.Net.Security
return true;
}
#endregion
#endregion
#region Inner Stream
#region Inner Stream
/*
* Read / write data from the inner stream; we're only called from managed code and only manipulate
* the internal buffers.
*/
internal int InnerRead (int requestedSize)
internal async Task<int> InnerRead (bool sync, int requestedSize, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested ();
Debug ("InnerRead: {0} {1} {2} {3}", readBuffer.Offset, readBuffer.Size, readBuffer.Remaining, requestedSize);
var len = System.Math.Min (readBuffer.Remaining, requestedSize);
if (len == 0)
throw new InvalidOperationException ();
var ret = InnerStream.Read (readBuffer.Buffer, readBuffer.EndOffset, len);
Task<int> task;
if (sync)
task = Task.Run (() => InnerStream.Read (readBuffer.Buffer, readBuffer.EndOffset, len));
else
task = InnerStream.ReadAsync (readBuffer.Buffer, readBuffer.EndOffset, len, cancellationToken);
var ret = await task.ConfigureAwait (false);
Debug ("InnerRead done: {0} {1} - {2}", readBuffer.Remaining, len, ret);
if (ret >= 0) {
@@ -549,165 +566,126 @@ namespace Mono.Net.Security
return ret;
}
internal void InnerWrite ()
internal async Task InnerWrite (bool sync, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested ();
Debug ("InnerWrite: {0} {1}", writeBuffer.Offset, writeBuffer.Size);
InnerFlush ();
if (writeBuffer.Size == 0)
return;
Task task;
if (sync)
task = Task.Run (() => InnerStream.Write (writeBuffer.Buffer, writeBuffer.Offset, writeBuffer.Size));
else
task = InnerStream.WriteAsync (writeBuffer.Buffer, writeBuffer.Offset, writeBuffer.Size);
await task.ConfigureAwait (false);
writeBuffer.TotalBytes += writeBuffer.Size;
writeBuffer.Offset = writeBuffer.Size = 0;
}
internal void InnerFlush ()
{
if (writeBuffer.Size > 0) {
InnerStream.Write (writeBuffer.Buffer, writeBuffer.Offset, writeBuffer.Size);
writeBuffer.TotalBytes += writeBuffer.Size;
writeBuffer.Offset = writeBuffer.Size = 0;
}
}
#endregion
#endregion
#region Main async I/O loop
#region Main async I/O loop
AsyncOperationStatus ProcessHandshake (AsyncProtocolRequest asyncRequest, AsyncOperationStatus status)
internal AsyncOperationStatus ProcessHandshake (AsyncOperationStatus status)
{
Debug ("ProcessHandshake: {0}", status);
/*
* The first time we're called (AsyncOperationStatus.Initialize), we need to setup the SslContext and
* start the handshake.
*/
if (status == AsyncOperationStatus.Initialize) {
xobileTlsContext.StartHandshake ();
return AsyncOperationStatus.Continue;
} else if (status == AsyncOperationStatus.ReadDone) {
// remote prematurely closed connection.
throw new IOException ("Remote prematurely closed connection.");
} else if (status != AsyncOperationStatus.Continue) {
throw new InvalidOperationException ();
}
/*
* SSLHandshake() will return repeatedly with 'SslStatus.WouldBlock', we then need
* to take care of I/O and call it again.
*/
if (!xobileTlsContext.ProcessHandshake ()) {
lock (ioLock) {
/*
* Flush the internal write buffer.
*/
InnerFlush ();
return AsyncOperationStatus.Continue;
}
* The first time we're called (AsyncOperationStatus.Initialize), we need to setup the SslContext and
* start the handshake.
*/
if (status == AsyncOperationStatus.Initialize) {
xobileTlsContext.StartHandshake ();
return AsyncOperationStatus.Continue;
} else if (status == AsyncOperationStatus.ReadDone) {
throw new IOException (SR.net_auth_eof);
} else if (status != AsyncOperationStatus.Continue) {
throw new InvalidOperationException ();
}
xobileTlsContext.FinishHandshake ();
return AsyncOperationStatus.Complete;
}
AsyncOperationStatus ProcessRead (AsyncProtocolRequest asyncRequest, AsyncOperationStatus status)
{
Debug ("ProcessRead - read user: {0} {1}", status, asyncRequest.UserBuffer);
int ret;
bool wantMore;
lock (ioLock) {
ret = Context.Read (asyncRequest.UserBuffer.Buffer, asyncRequest.UserBuffer.Offset, asyncRequest.UserBuffer.Size, out wantMore);
}
Debug ("ProcessRead - read user done: {0} - {1} {2}", asyncRequest.UserBuffer, ret, wantMore);
if (ret < 0) {
asyncRequest.UserResult = -1;
return AsyncOperationStatus.Complete;
}
asyncRequest.CurrentSize += ret;
asyncRequest.UserBuffer.Offset += ret;
asyncRequest.UserBuffer.Size -= ret;
Debug ("Process Read - read user done #1: {0} - {1} {2}", asyncRequest.UserBuffer, asyncRequest.CurrentSize, wantMore);
if (wantMore && asyncRequest.CurrentSize == 0)
return AsyncOperationStatus.WantRead;
asyncRequest.ResetRead ();
asyncRequest.UserResult = asyncRequest.CurrentSize;
return AsyncOperationStatus.Complete;
}
AsyncOperationStatus ProcessWrite (AsyncProtocolRequest asyncRequest, AsyncOperationStatus status)
{
Debug ("ProcessWrite - write user: {0} {1}", status, asyncRequest.UserBuffer);
if (asyncRequest.UserBuffer.Size == 0) {
asyncRequest.UserResult = asyncRequest.CurrentSize;
return AsyncOperationStatus.Complete;
}
int ret;
bool wantMore;
lock (ioLock) {
ret = Context.Write (asyncRequest.UserBuffer.Buffer, asyncRequest.UserBuffer.Offset, asyncRequest.UserBuffer.Size, out wantMore);
}
Debug ("ProcessWrite - write user done: {0} - {1} {2}", asyncRequest.UserBuffer, ret, wantMore);
if (ret < 0) {
asyncRequest.UserResult = -1;
return AsyncOperationStatus.Complete;
}
asyncRequest.CurrentSize += ret;
asyncRequest.UserBuffer.Offset += ret;
asyncRequest.UserBuffer.Size -= ret;
if (wantMore || writeBuffer.Size > 0)
return AsyncOperationStatus.WantWrite;
asyncRequest.ResetWrite ();
asyncRequest.UserResult = asyncRequest.CurrentSize;
return AsyncOperationStatus.Complete;
}
AsyncOperationStatus ProcessClose (AsyncProtocolRequest asyncRequest, AsyncOperationStatus status)
{
Debug ("ProcessClose: {0}", status);
lock (ioLock) {
if (xobileTlsContext == null)
/*
* SSLHandshake() will return repeatedly with 'SslStatus.WouldBlock', we then need
* to take care of I/O and call it again.
*/
if (xobileTlsContext.ProcessHandshake ()) {
xobileTlsContext.FinishHandshake ();
return AsyncOperationStatus.Complete;
xobileTlsContext.Close ();
xobileTlsContext = null;
}
return AsyncOperationStatus.Continue;
}
}
AsyncOperationStatus ProcessFlush (AsyncProtocolRequest asyncRequest, AsyncOperationStatus status)
internal (int, bool) ProcessRead (BufferOffsetSize userBuffer)
{
Debug ("ProcessFlush: {0}", status);
return AsyncOperationStatus.Complete;
lock (ioLock) {
// This operates on the internal buffer and will never block.
var ret = xobileTlsContext.Read (userBuffer.Buffer, userBuffer.Offset, userBuffer.Size, out bool wantMore);
return (ret, wantMore);
}
}
#endregion
internal (int, bool) ProcessWrite (BufferOffsetSize userBuffer)
{
lock (ioLock) {
// This operates on the internal buffer and will never block.
var ret = xobileTlsContext.Write (userBuffer.Buffer, userBuffer.Offset, userBuffer.Size, out bool wantMore);
return (ret, wantMore);
}
}
internal AsyncOperationStatus ProcessShutdown (AsyncOperationStatus status)
{
Debug ("ProcessShutdown: {0}", status);
lock (ioLock) {
xobileTlsContext.Shutdown ();
shutdown = true;
return AsyncOperationStatus.Complete;
}
}
#endregion
public override bool IsServer {
get { return xobileTlsContext != null && xobileTlsContext.IsServer; }
get {
CheckThrow (false);
return xobileTlsContext != null && xobileTlsContext.IsServer;
}
}
public override bool IsAuthenticated {
get { return xobileTlsContext != null && lastException == null && xobileTlsContext.IsAuthenticated; }
get {
lock (ioLock) {
// Don't use CheckThrow(), we want to return false if we're not authenticated.
return xobileTlsContext != null && lastException == null && xobileTlsContext.IsAuthenticated;
}
}
}
public override bool IsMutuallyAuthenticated {
get {
return IsAuthenticated &&
(Context.IsServer? Context.LocalServerCertificate: Context.LocalClientCertificate) != null &&
Context.IsRemoteCertificateAvailable;
lock (ioLock) {
// Don't use CheckThrow() here.
if (!IsAuthenticated)
return false;
if ((xobileTlsContext.IsServer ? xobileTlsContext.LocalServerCertificate : xobileTlsContext.LocalClientCertificate) == null)
return false;
return xobileTlsContext.IsRemoteCertificateAvailable;
}
}
}
protected override void Dispose (bool disposing)
{
try {
lastException = new ObjectDisposedException ("MobileAuthenticatedStream");
lock (ioLock) {
Debug ("Dispose: {0}", xobileTlsContext != null);
lastException = ExceptionDispatchInfo.Capture (new ObjectDisposedException ("MobileAuthenticatedStream"));
if (xobileTlsContext != null) {
xobileTlsContext.Dispose ();
xobileTlsContext = null;
@@ -720,26 +698,53 @@ namespace Mono.Net.Security
public override void Flush ()
{
CheckThrow (true);
var asyncRequest = new AsyncProtocolRequest (this, null);
StartOperation (ref asyncWriteRequest, ref writeBuffer, ProcessFlush, asyncRequest, "flush");
// Write() automatically flushes the underlying stream.
}
public override void Close ()
{
/*
* SSLClose() is a little bit tricky as it might attempt to send a close_notify alert
* and thus call our write callback.
*
* It is also not thread-safe with SSLRead() or SSLWrite(), so we need to take the I/O lock here.
*/
if (Interlocked.Exchange (ref closeRequested, 1) == 1)
return;
if (xobileTlsContext == null)
return;
public SslProtocols SslProtocol {
get {
lock (ioLock) {
CheckThrow (true);
return (SslProtocols)xobileTlsContext.NegotiatedProtocol;
}
}
}
var asyncRequest = new AsyncProtocolRequest (this, null);
StartOperation (ref asyncWriteRequest, ref writeBuffer, ProcessClose, asyncRequest, "close");
public X509Certificate RemoteCertificate {
get {
lock (ioLock) {
CheckThrow (true);
return xobileTlsContext.RemoteCertificate;
}
}
}
public X509Certificate LocalCertificate {
get {
lock (ioLock) {
CheckThrow (true);
return InternalLocalCertificate;
}
}
}
public X509Certificate InternalLocalCertificate {
get {
lock (ioLock) {
CheckThrow (false);
if (xobileTlsContext == null)
return null;
return xobileTlsContext.IsServer ? xobileTlsContext.LocalServerCertificate : xobileTlsContext.LocalClientCertificate;
}
}
}
public MSI.MonoTlsConnectionInfo GetConnectionInfo ()
{
lock (ioLock) {
CheckThrow (true);
return xobileTlsContext.ConnectionInfo;
}
}
//
@@ -769,7 +774,7 @@ namespace Mono.Net.Security
}
public override bool CanWrite {
get { return IsAuthenticated & InnerStream.CanWrite; }
get { return IsAuthenticated & InnerStream.CanWrite && !shutdown; }
}
public override bool CanSeek {
@@ -803,46 +808,10 @@ namespace Mono.Net.Security
set { InnerStream.WriteTimeout = value; }
}
public SslProtocols SslProtocol {
get {
CheckThrow (true);
return (SslProtocols)Context.NegotiatedProtocol;
}
}
public X509Certificate RemoteCertificate {
get {
CheckThrow (true);
return Context.RemoteCertificate;
}
}
public X509Certificate LocalCertificate {
get {
CheckThrow (true);
return InternalLocalCertificate;
}
}
public X509Certificate InternalLocalCertificate {
get {
CheckThrow (false);
if (!HasContext)
return null;
return Context.IsServer ? Context.LocalServerCertificate : Context.LocalClientCertificate;
}
}
public MSI.MonoTlsConnectionInfo GetConnectionInfo ()
{
CheckThrow (true);
return Context.ConnectionInfo;
}
public SSA.CipherAlgorithmType CipherAlgorithm {
get {
CheckThrow (true);
var info = Context.ConnectionInfo;
var info = GetConnectionInfo ();
if (info == null)
return SSA.CipherAlgorithmType.None;
switch (info.CipherAlgorithmType) {
@@ -861,7 +830,7 @@ namespace Mono.Net.Security
public SSA.HashAlgorithmType HashAlgorithm {
get {
CheckThrow (true);
var info = Context.ConnectionInfo;
var info = GetConnectionInfo ();
if (info == null)
return SSA.HashAlgorithmType.None;
switch (info.HashAlgorithmType) {
@@ -883,7 +852,7 @@ namespace Mono.Net.Security
public SSA.ExchangeAlgorithmType KeyExchangeAlgorithm {
get {
CheckThrow (true);
var info = Context.ConnectionInfo;
var info = GetConnectionInfo ();
if (info == null)
return SSA.ExchangeAlgorithmType.None;
switch (info.ExchangeAlgorithmType) {
@@ -898,7 +867,7 @@ namespace Mono.Net.Security
}
}
#region Need to Implement
#region Need to Implement
public int CipherStrength {
get {
throw new NotImplementedException ();
@@ -920,7 +889,7 @@ namespace Mono.Net.Security
}
}
#endregion
#endregion
}
}
#endif
@@ -169,7 +169,7 @@ namespace Mono.Net.Security
public abstract int Write (byte[] buffer, int offset, int count, out bool wantMore);
public abstract void Close ();
public abstract void Shutdown ();
protected bool ValidateCertificate (X509Certificate leaf, X509Chain chain)
{
@@ -83,6 +83,8 @@ namespace Mono.Net.Security
if (initialized)
return;
InitializeProviderRegistration ();
MSI.MonoTlsProvider provider;
try {
provider = CreateDefaultProviderImpl ();
+2
View File
@@ -9,6 +9,8 @@ partial class SR
{
public const string mono_net_io_shutdown = "mono_net_io_shutdown";
public const string mono_net_io_renegotiate = "mono_net_io_renegotiate";
public const string net_ssl_io_already_shutdown = "Write operations are not allowed after the channel was shutdown.";
public const string net_log_set_socketoption_reuseport_default_on = "net_log_set_socketoption_reuseport_default_on";
public const string net_log_set_socketoption_reuseport_not_supported = "net_log_set_socketoption_reuseport_not_supported";
@@ -46,6 +46,7 @@ namespace System.ComponentModel
case 32: /* ERROR_SHARING_VIOLATION */ return "Sharing violation";
case 33: /* ERROR_LOCK_VIOLATION */ return "Lock violation";
case 50: /* ERROR_NOT_SUPPORTED */ return "Operation not supported";
case 55: /* ERROR_DEV_NOT_EXIST */ return "Device does not exist";
case 87: /* ERROR_INVALID_PARAMETER */ return "Invalid parameter";
case 120: /* ERROR_CALL_NOT_IMPLEMENTED */ return "Call not implemented";
case 123: /* ERROR_INVALID_NAME */ return "Invalid name";
@@ -142,7 +143,6 @@ namespace System.ComponentModel
case 52: /* ERROR_DUP_NAME */ return "Duplicate name";
case 53: /* ERROR_BAD_NETPATH */ return "Bad netpath";
case 54: /* ERROR_NETWORK_BUSY */ return "Network busy";
case 55: /* ERROR_DEV_NOT_EXIST */ return "Device does not exist";
case 56: /* ERROR_TOO_MANY_CMDS */ return "Too many commands";
case 57: /* ERROR_ADAP_HDW_ERR */ return "ADAP HDW error";
case 58: /* ERROR_BAD_NET_RESP */ return "Bad net response";
@@ -223,6 +223,11 @@ namespace System.Net.Security
return Impl.AuthenticateAsServerAsync (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation);
}
public virtual Task ShutdownAsync ()
{
return Impl.ShutdownAsync ();
}
public override bool IsAuthenticated {
get { return Impl.IsAuthenticated; }
}
@@ -152,6 +152,11 @@ namespace System.Net.Security
throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
}
public virtual Task ShutdownAsync ()
{
throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
}
public override bool IsAuthenticated {
get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
}
@@ -24,11 +24,12 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System.Security.Principal;
namespace System.Net {
public class HttpListenerBasicIdentity {
internal const string EXCEPTION_MESSAGE = "System.Net.HttpListenerBasicIdentity is not supported on the current platform.";
public class HttpListenerBasicIdentity : GenericIdentity {
const string EXCEPTION_MESSAGE = "System.Net.HttpListenerBasicIdentity is not supported on the current platform.";
public HttpListenerBasicIdentity (string username, string password)
public HttpListenerBasicIdentity (string username, string password) : base (username, "Basic")
{
throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
}
@@ -56,7 +56,6 @@ namespace System.Net
object socketLock = new object ();
IWebConnectionState state;
WebExceptionStatus status;
WaitCallback initConn;
bool keepAlive;
byte [] buffer;
EventHandler abortHandler;
@@ -37,12 +37,18 @@ namespace MonoTests.System.Net {
[ExpectedException (typeof (ArgumentNullException))]
public void Basic1 ()
{
#if MONOTOUCH_WATCH || __WATCHOS__
Assert.Ignore ("HttpListenerBasicIdentity is not supported on watchOS");
#endif
HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity (null, null);
}
[Test]
public void Basic2 ()
{
#if MONOTOUCH_WATCH || __WATCHOS__
Assert.Ignore ("HttpListenerBasicIdentity is not supported on watchOS");
#endif
HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity ("", null);
Assert.AreEqual ("Basic", bi.AuthenticationType, "#01");
Assert.AreEqual ("", bi.Name, "#02");
@@ -53,6 +59,9 @@ namespace MonoTests.System.Net {
[Test]
public void Basic3 ()
{
#if MONOTOUCH_WATCH || __WATCHOS__
Assert.Ignore ("HttpListenerBasicIdentity is not supported on watchOS");
#endif
HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity ("hey", null);
Assert.AreEqual ("Basic", bi.AuthenticationType, "#01");
Assert.AreEqual ("hey", bi.Name, "#02");
@@ -63,6 +72,9 @@ namespace MonoTests.System.Net {
[Test]
public void Basic4 ()
{
#if MONOTOUCH_WATCH || __WATCHOS__
Assert.Ignore ("HttpListenerBasicIdentity is not supported on watchOS");
#endif
HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity ("hey", "pass");
Assert.AreEqual ("Basic", bi.AuthenticationType, "#01");
Assert.AreEqual ("hey", bi.Name, "#02");
+1
View File
@@ -276,6 +276,7 @@ ReferenceSources/SettingsSectionInternal.cs
ReferenceSources/SecureStringHelper.cs
ReferenceSources/Socket.cs
ReferenceSources/SR.cs
ReferenceSources/SR2.cs
ReferenceSources/SRCategoryAttribute.cs
ReferenceSources/Win32Exception.cs
@@ -245,7 +245,6 @@ Mono.Net.Dns/ResolverError.cs
Mono.Net.Dns/SimpleResolverEventArgs.cs
ReferenceSources/BinaryCompatibility.cs
ReferenceSources/ConfigurationManagerInternalFactory.cs
ReferenceSources/SR2.cs
../referencesource/System/misc/PrivilegedConfigurationManager.cs
@@ -1,17 +0,0 @@
thisdir = class/Xunit.NetCore.Extensions
SUBDIRS =
include ../../build/rules.make
XUNIT_LIBS := xunit.core xunit.abstractions xunit.execution.desktop xunit.assert
LIBRARY = Xunit.NetCore.Extensions.dll
LIB_REFS = System System.Core Facades/System.Runtime.InteropServices.RuntimeInformation Facades/System.Runtime Facades/System.Threading.Tasks
LIB_MCS_FLAGS = $(patsubst %,-r:$(topdir)/../external/xunit-binaries/%.dll,$(XUNIT_LIBS))
EXTRA_DISTFILES =
NO_TEST = yes
NO_INSTALL = yes
NO_SIGN_ASSEMBLY = yes
include ../../build/library.make
@@ -1,13 +0,0 @@
using System;
using Xunit;
using Xunit.Sdk;
namespace Microsoft.Xunit.Performance
{
[TraitDiscoverer("Microsoft.Xunit.Performance.BenchmarkDiscoverer", "Xunit.NetCore.Extensions")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class BenchmarkAttribute : Attribute, ITraitAttribute
{
public long InnerIterationCount { get; set; }
}
}
@@ -1,14 +0,0 @@
using System.Collections.Generic;
using Xunit.Sdk;
using Xunit.Abstractions;
namespace Xunit.NetCore.Extensions
{
public class BenchmarkDiscoverer : ITraitDiscoverer
{
public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute)
{
yield return new KeyValuePair<string, string>("Benchmark", "True");
}
}
}
@@ -1,6 +0,0 @@
../../../external/buildtools/src/xunit.netcore.extensions/*.cs
../../../external/buildtools/src/xunit.netcore.extensions/Attributes/*.cs
../../../external/buildtools/src/xunit.netcore.extensions/Discoverers/*.cs
Microsoft.Xunit.Performance/BenchmarkAttribute.cs
Microsoft.Xunit.Performance/BenchmarkDiscover.cs
@@ -35,6 +35,7 @@ namespace System.Reflection.Emit
[ComVisible (true)]
[Serializable]
[Flags]
#region Sync with sre-internals.h
public enum AssemblyBuilderAccess {
Run = 1,
Save = 2,
@@ -42,4 +43,5 @@ namespace System.Reflection.Emit
ReflectionOnly = 6,
RunAndCollect = 9
}
#endregion
}
@@ -131,7 +131,7 @@ namespace System.Reflection.Emit {
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void create_dynamic_method (DynamicMethod m);
private static extern void create_dynamic_method (DynamicMethod m);
private void CreateDynMethod () {
if (mhandle.Value == IntPtr.Zero) {
@@ -71,6 +71,9 @@ namespace System.Reflection.Emit {
return _tb.InternalResolve ();
}
internal override Type RuntimeResolve () {
return _tb.RuntimeResolve ();
}
public override Assembly Assembly {
get {
@@ -229,7 +229,9 @@ namespace System.Reflection.Emit {
}
internal FieldInfo RuntimeResolve () {
return typeb.CreateType ().GetField (this);
// typeb.CreateType() populates this.handle
var type_handle = new RuntimeTypeHandle (typeb.CreateType () as RuntimeType);
return FieldInfo.GetFieldFromHandle (handle, type_handle);
}
public override Module Module {
@@ -87,7 +87,7 @@ namespace System.Reflection.Emit
internal override Type InternalResolve ()
{
if (mbuilder != null)
return MethodBase.GetMethodFromHandle (mbuilder.MethodHandleInternal).GetGenericArguments () [index];
return MethodBase.GetMethodFromHandle (mbuilder.MethodHandleInternal, mbuilder.TypeBuilder.InternalResolve ().TypeHandle).GetGenericArguments () [index];
return tbuilder.InternalResolve ().GetGenericArguments () [index];
}
@@ -814,7 +814,7 @@ namespace System.Reflection.Emit {
make_room (6);
ll_emit (opcode);
int token = token_gen.GetToken (cls, opcode != OpCodes.Ldtoken);
if (cls is TypeBuilderInstantiation || cls is SymbolType || cls is TypeBuilder || cls is GenericTypeParameterBuilder)
if (cls is TypeBuilderInstantiation || cls is SymbolType || cls is TypeBuilder || cls is GenericTypeParameterBuilder || cls is EnumBuilder)
add_token_fixup (cls);
emit_int (token);
}
@@ -749,6 +749,14 @@ namespace System.Reflection.Emit {
token = typedef_tokengen --;
else
token = typeref_tokengen --;
} else if (member is EnumBuilder) {
token = GetPseudoToken ((member as EnumBuilder).GetTypeBuilder(), create_open_instance);
if (create_open_instance)
inst_tokens_open[member] = token;
else
inst_tokens[member] = token;
// n.b. don't register with the runtime, the TypeBuilder already did it.
return token;
} else if (member is ConstructorBuilder) {
if (member.Module == this && !(member as ConstructorBuilder).TypeBuilder.ContainsGenericParameters)
token = methoddef_tokengen --;
@@ -779,7 +787,8 @@ namespace System.Reflection.Emit {
}
internal int GetToken (MemberInfo member, bool create_open_instance) {
if (member is TypeBuilderInstantiation || member is FieldOnTypeBuilderInst || member is ConstructorOnTypeBuilderInst || member is MethodOnTypeBuilderInst || member is SymbolType || member is FieldBuilder || member is TypeBuilder || member is ConstructorBuilder || member is MethodBuilder || member is GenericTypeParameterBuilder)
if (member is TypeBuilderInstantiation || member is FieldOnTypeBuilderInst || member is ConstructorOnTypeBuilderInst || member is MethodOnTypeBuilderInst || member is SymbolType || member is FieldBuilder || member is TypeBuilder || member is ConstructorBuilder || member is MethodBuilder || member is GenericTypeParameterBuilder ||
member is EnumBuilder)
return GetPseudoToken (member, create_open_instance);
return getToken (this, member, create_open_instance);
}
@@ -872,6 +881,8 @@ namespace System.Reflection.Emit {
finished = (member as FieldBuilder).RuntimeResolve ();
} else if (member is TypeBuilder) {
finished = (member as TypeBuilder).RuntimeResolve ();
} else if (member is EnumBuilder) {
finished = (member as EnumBuilder).RuntimeResolve ();
} else if (member is ConstructorBuilder) {
finished = (member as ConstructorBuilder).RuntimeResolve ();
} else if (member is MethodBuilder) {
@@ -741,7 +741,7 @@ namespace System.Runtime.InteropServices
#else
public static bool IsComObject (object o)
{
throw new PlatformNotSupportedException ();
return false;
}
#endif
@@ -73,19 +73,59 @@ namespace System.Runtime.Remoting.Messaging {
[Serializable]
internal class CADMethodRef
{
internal string FullTypeName;
internal IntPtr MethodHandlePtr;
Type[] GetTypes (string[] typeArray)
{
Type[] res = new Type [typeArray.Length];
for (int i = 0; i < typeArray.Length; ++i)
res [i] = Type.GetType (typeArray [i], true);
return res;
}
public RuntimeMethodHandle MethodHandle {
get {
return new RuntimeMethodHandle (MethodHandlePtr);
}
bool ctor;
string typeName;
string methodName;
string[] param_names;
string[] generic_arg_names;
public MethodBase Resolve ()
{
Type type = Type.GetType (typeName, true);
MethodBase sig_cand = null;
Type[] param_types = GetTypes (param_names);
if (ctor)
sig_cand = type.GetConstructor (BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance, null, param_types, null);
else
sig_cand = type.GetMethod (methodName, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance, null, param_types, null);
if (sig_cand != null && generic_arg_names != null)
sig_cand = ((MethodInfo)sig_cand).MakeGenericMethod (GetTypes (generic_arg_names));
if (sig_cand == null)
throw new RemotingException ($"Method '{methodName}' not found in type '{typeName}'");
return sig_cand;
}
public CADMethodRef (IMethodMessage msg)
{
MethodHandlePtr = msg.MethodBase.MethodHandle.Value;
FullTypeName = msg.MethodBase.DeclaringType.AssemblyQualifiedName;
MethodBase method = msg.MethodBase;
typeName = method.DeclaringType.AssemblyQualifiedName;
ctor = method.IsConstructor;
methodName = method.Name;
if (!ctor && method.IsGenericMethod) {
var ga = method.GetGenericArguments ();
generic_arg_names = new string [ga.Length];
for (int i = 0; i < ga.Length; ++i)
generic_arg_names [i] = ga [i].AssemblyQualifiedName;
method = ((MethodInfo)method).GetGenericMethodDefinition ();
}
var param_types = method.GetParameters ();
param_names = new string [param_types.Length];
for (int i = 0; i < param_types.Length; ++i)
param_names [i] = param_types [i].ParameterType.AssemblyQualifiedName;
}
}
@@ -102,62 +142,11 @@ namespace System.Runtime.Remoting.Messaging {
serializedMethod = CADSerializer.SerializeObject (methodRef).GetBuffer ();
}
internal MethodBase method {
get { return GetMethod (); }
}
internal MethodBase GetMethod ()
{
CADMethodRef methRef = (CADMethodRef)CADSerializer.DeserializeObjectSafe (serializedMethod);
MethodBase _method;
Type tt = Type.GetType (methRef.FullTypeName, true);
if (tt.IsGenericType || tt.IsGenericTypeDefinition) {
_method = MethodBase.GetMethodFromHandleNoGenericCheck (methRef.MethodHandle);
} else {
_method = MethodBase.GetMethodFromHandle (methRef.MethodHandle);
}
if (tt != _method.DeclaringType) {
// The target domain has loaded the type from a different assembly.
// We need to locate the correct type and get the method from it
Type [] signature = GetSignature (_method, true);
if (_method.IsGenericMethod) {
MethodBase [] methods = tt.GetMethods (BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
Type [] base_args = _method.GetGenericArguments ();
foreach (MethodBase method in methods) {
if (!method.IsGenericMethod || method.Name != _method.Name)
continue;
Type [] method_args = method.GetGenericArguments ();
if (base_args.Length != method_args.Length)
continue;
MethodInfo method_instance = ((MethodInfo) method).MakeGenericMethod (base_args);
Type [] base_sig = GetSignature (method_instance, false);
if (base_sig.Length != signature.Length) {
continue;
}
bool dont = false;
for (int i = base_sig.Length - 1; i >= 0; i--) {
if (base_sig [i] != signature [i]) {
dont = true;
break;
}
}
if (dont)
continue;
return method_instance;
}
return _method;
}
MethodBase mb = tt.GetMethod (_method.Name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance, null, signature, null);
if (mb == null)
throw new RemotingException ("Method '" + _method.Name + "' not found in type '" + tt + "'");
return mb;
}
return _method;
return methRef.Resolve ();
}
static protected Type [] GetSignature (MethodBase methodBase, bool load)
@@ -174,6 +163,7 @@ namespace System.Runtime.Remoting.Messaging {
}
return signature;
}
// Helper to marshal properties
internal static int MarshalProperties (IDictionary dict, ref ArrayList args) {
IDictionary serDict = dict;
@@ -457,7 +447,7 @@ namespace System.Runtime.Remoting.Messaging {
_returnValue = MarshalArgument ( retMsg.ReturnValue, ref serializeList);
_args = MarshalArguments ( retMsg.Args, ref serializeList);
_sig = GetSignature (method, true);
_sig = GetSignature (GetMethod (), true);
if (null != retMsg.Exception) {
if (null == serializeList)
+5 -2
View File
@@ -495,8 +495,11 @@ namespace System
public override int GetHashCode ()
{
/* same implementation as CoreCLR */
return GetType ().GetHashCode ();
MethodInfo m;
m = Method;
return (m != null ? m.GetHashCode () : GetType ().GetHashCode ()) ^ RuntimeHelpers.GetHashCode (m_target);
}
protected virtual MethodInfo GetMethodImpl ()
@@ -1844,5 +1844,68 @@ public class AssemblyBuilderTest
} catch (NotSupportedException e) {
}
}
class AssemblyBuilderResolver {
private Assembly mock;
private ResolveEventHandler d;
private string theName;
public AssemblyBuilderResolver (string theName) {
mock = CreateMock (theName);
d = new ResolveEventHandler (HandleResolveEvent);
this.theName = theName;
}
public void StartHandling () {
AppDomain.CurrentDomain.AssemblyResolve += d;
}
public void StopHandling () {
AppDomain.CurrentDomain.AssemblyResolve -= d;
}
public Assembly HandleResolveEvent (Object sender, ResolveEventArgs args) {
if (args.Name.StartsWith (theName))
return mock;
else
return null;
}
private static Assembly CreateMock (string name) {
var an = new AssemblyName (name);
var ab = AssemblyBuilder.DefineDynamicAssembly (an, AssemblyBuilderAccess.ReflectionOnly);
var mb = ab.DefineDynamicModule (an.Name);
// Just make some content for the assembly
var tb = mb.DefineType ("Foo", TypeAttributes.Public);
tb.DefineDefaultConstructor (MethodAttributes.Public);
tb.CreateType ();
return ab;
}
}
[Test]
public void ResolveEventHandlerReflectionOnlyError ()
{
// Regression test for 57850.
// If a ResolveEventHandler returns a reflection-only
// AssemblyBuilder, we should throw a FileNotFoundException.
var s = "ResolveEventHandlerReflectionOnlyErrorAssembly";
var h = new AssemblyBuilderResolver (s);
Assert.Throws<FileNotFoundException>(() => {
h.StartHandling ();
var aName = new AssemblyName (s);
try {
AppDomain.CurrentDomain.Load (aName);
} finally {
h.StopHandling ();
}
});
}
}
}
@@ -328,6 +328,61 @@ namespace MonoTests.System.Reflection.Emit
Assert.Fail ("Expected CreateInstance of a broken type to throw TLE");
}
[Test]
public void TestEnumBuilderTokenUsable () {
// Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=58361
// Create an EnumBuilder and use it in an ILGenerator that consumes its token.
var modBuilder = GenerateModule ();
EnumBuilder enumBuilder = GenerateEnum (modBuilder);
var tb = modBuilder.DefineType ("Foo", TypeAttributes.Public);
var cb = tb.DefineConstructor (MethodAttributes.Public, CallingConventions.Standard,
Type.EmptyTypes);
var ilg = cb.GetILGenerator ();
ilg.Emit (OpCodes.Ldtoken, enumBuilder);
ilg.Emit (OpCodes.Pop);
ilg.Emit (OpCodes.Ret);
var t = tb.CreateType ();
enumBuilder.CreateType ();
var ci = t.GetConstructor (Type.EmptyTypes);
var x = ci.Invoke (null);
Assert.IsNotNull (x);
}
[Test]
public void TestEnumBuilderTokenUsableCrossAssembly () {
// Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=58361
// Create an EnumBuilder and use it in an ILGenerator that consumes its token in a different assembly.
var modBuilder = GenerateModule ();
var modBuilder2 = GenerateModule ();
EnumBuilder enumBuilder = GenerateEnum (modBuilder2);
// N.B. "tb" is in modBuilder but enumBuilder is in modBuilder2
var tb = modBuilder.DefineType ("Foo", TypeAttributes.Public);
var cb = tb.DefineConstructor (MethodAttributes.Public, CallingConventions.Standard,
Type.EmptyTypes);
var ilg = cb.GetILGenerator ();
ilg.Emit (OpCodes.Ldtoken, enumBuilder);
ilg.Emit (OpCodes.Pop);
ilg.Emit (OpCodes.Ret);
var t = tb.CreateType ();
enumBuilder.CreateType ();
var ci = t.GetConstructor (Type.EmptyTypes);
var x = ci.Invoke (null);
Assert.IsNotNull (x);
}
private static void VerifyType (Type type)
{
Assert.IsNotNull (type.Assembly, "#V1");
@@ -353,5 +353,60 @@ namespace MonoTests.System.Reflection.Emit
Assert.AreEqual (TypeAttributes.Public, gparam.Attributes, "#1");
}
[Test]
public void ActionConstructorInfoTest ()
{
// Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=58454
//
// Need to check that GenericTypeParameterBuilderTest:InternalResolve() passes the declaring type to GetMethodFromHandle()
//
/* Want to generate:
public class Store<TState> {
public Action<TSelection> Subscribe<TSelection> (TState state) {
return new Action<TSelection> (Foo<TSelection>);
}
public static void Foo<X> (X x) { }
}
... and then: new Store<string>().Subscribe<int>("x");
*/
SetUp (AssemblyBuilderAccess.Run);
var tb = module.DefineType ("Store");
var tparsStore = tb.DefineGenericParameters ("TState");
tb.DefineDefaultConstructor (MethodAttributes.Public);
var methFoo = tb.DefineMethod ("Foo", MethodAttributes.Public | MethodAttributes.Static);
var tparsFoo = methFoo.DefineGenericParameters ("X");
methFoo.SetReturnType (typeof(void));
methFoo.SetParameters (tparsFoo[0]);
methFoo.GetILGenerator().Emit (OpCodes.Ret);
var methSub = tb.DefineMethod ("Subscribe", MethodAttributes.Public | MethodAttributes.Static);
var tparsSub = methSub.DefineGenericParameters ("TSelection");
var actOfSel = typeof(Action<>).MakeGenericType (tparsSub[0]); // Action<TSelection>
methSub.SetReturnType (actOfSel);
methSub.SetParameters (tparsStore[0]); // TState
var ilg = methSub.GetILGenerator ();
ilg.Emit (OpCodes.Ldnull); // instance == null
ilg.Emit (OpCodes.Ldftn, methFoo.MakeGenericMethod (tparsSub[0])); // ldftn void class Store`1<!TState>::Foo<!!0> (!!0)
var aaa = TypeBuilder.GetConstructor (actOfSel, typeof(Action<>).GetConstructors()[0]);
ilg.Emit (OpCodes.Newobj, aaa); // new Action<TSelection> (Foo<TSelection>);
ilg.Emit (OpCodes.Ret);
var tgen = tb.CreateType (); // TState`1
var t = tgen.MakeGenericType(typeof(string));
var x = t.GetConstructor(Type.EmptyTypes).Invoke (null); // x = new Store<string> ()
var mgen = t.GetMethod("Subscribe");
var m = mgen.MakeGenericMethod (typeof (int)); // Action<int> Store<string>.Subscribe<int> (string)
var y = m.Invoke (x, new object[] {"hello"}); // x.Subscribte<int> ("hello")
Assert.IsNotNull (y);
}
}
}
@@ -100,21 +100,41 @@ namespace MonoTests.System.Reflection.Emit
private ModuleBuilder module;
string tempDir = Path.Combine (Path.GetTempPath (), typeof (TypeBuilderTest).FullName);
static string ASSEMBLY_NAME = "MonoTests.System.Reflection.Emit.TypeBuilderTest";
[SetUp]
protected void SetUp ()
{
Random AutoRand = new Random ();
string basePath = tempDir;
while (Directory.Exists (tempDir))
tempDir = Path.Combine (basePath, AutoRand.Next ().ToString ());
Directory.CreateDirectory (tempDir);
AssemblyName assemblyName = new AssemblyName ();
assemblyName.Name = ASSEMBLY_NAME;
assembly =
Thread.GetDomain ().DefineDynamicAssembly (
assemblyName, AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
assemblyName, AssemblyBuilderAccess.RunAndSave, tempDir);
module = assembly.DefineDynamicModule (ASSEMBLY_NAME, ASSEMBLY_NAME + ".dll");
}
[TearDown]
protected void TearDown ()
{
try {
Directory.Delete (tempDir, true);
} catch (DirectoryNotFoundException) {
} catch (IOException) {
// Can happen on Windows if assemblies from this dir are still used
}
}
static int typeIndexer = 0;
// Return a unique type name
@@ -738,30 +758,6 @@ namespace MonoTests.System.Reflection.Emit
Assert.IsTrue (tb2.IsSealed, "#2");
}
static string CreateTempAssembly ()
{
FileStream f = null;
string path;
Random rnd;
int num = 0;
rnd = new Random ();
do {
num = rnd.Next ();
num++;
path = Path.Combine (Path.GetTempPath (), "tmp" + num.ToString ("x") + ".dll");
try {
f = new FileStream (path, FileMode.CreateNew);
} catch { }
} while (f == null);
f.Close ();
return "tmp" + num.ToString ("x") + ".dll";
}
[Test]
public void IsSerializable ()
{
@@ -774,10 +770,10 @@ namespace MonoTests.System.Reflection.Emit
tb.SetCustomAttribute (new CustomAttributeBuilder (ctors [0], new object [0]));
Type createdType = tb.CreateType ();
string an = CreateTempAssembly ();
string an = "IsSerializableTestAssembly.dll";
assembly.Save (an);
Assert.IsTrue (createdType.IsSerializable, "#3");
File.Delete (Path.Combine (Path.GetTempPath (), an));
File.Delete (Path.Combine (tempDir, an));
}
[Test]
@@ -2054,7 +2050,7 @@ namespace MonoTests.System.Reflection.Emit
assembly =
Thread.GetDomain ().DefineDynamicAssembly (
assemblyName, AssemblyBuilderAccess.RunAndSave | (AssemblyBuilderAccess)0x800, Path.GetTempPath ());
assemblyName, AssemblyBuilderAccess.RunAndSave | (AssemblyBuilderAccess)0x800, tempDir);
module = assembly.DefineDynamicModule ("module1");
@@ -9706,7 +9702,7 @@ namespace MonoTests.System.Reflection.Emit
[Test] //bug #399047
public void FieldOnTypeBuilderInstDontInflateWhenEncoded () {
assembly = Thread.GetDomain ().DefineDynamicAssembly (new AssemblyName (ASSEMBLY_NAME), AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
assembly = Thread.GetDomain ().DefineDynamicAssembly (new AssemblyName (ASSEMBLY_NAME), AssemblyBuilderAccess.RunAndSave, tempDir);
module = assembly.DefineDynamicModule ("Instance.exe");
@@ -9743,10 +9739,11 @@ namespace MonoTests.System.Reflection.Emit
assembly.SetEntryPoint (main);
G.CreateType ();
P.CreateType ();
var PCreated = P.CreateType ();
assembly.Save ("Instance.exe");
Thread.GetDomain ().ExecuteAssembly(Path.GetTempPath () + Path.DirectorySeparatorChar + "Instance.exe");
PCreated.InvokeMember ("Main", BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, null);
}
[Test]
@@ -9756,7 +9753,7 @@ namespace MonoTests.System.Reflection.Emit
FieldBuilder fb = tb.DefineInitializedData ("Foo", new byte [] {1,2,3,4}, FieldAttributes.Static|FieldAttributes.Public);
tb.CreateType ();
assembly = Thread.GetDomain ().DefineDynamicAssembly (new AssemblyName (ASSEMBLY_NAME+"2"), AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
assembly = Thread.GetDomain ().DefineDynamicAssembly (new AssemblyName (ASSEMBLY_NAME+"2"), AssemblyBuilderAccess.RunAndSave, tempDir);
module = assembly.DefineDynamicModule ("Instance.exe");
TypeBuilder tb2 = module.DefineType ("Type2", TypeAttributes.Public);
@@ -9783,7 +9780,7 @@ namespace MonoTests.System.Reflection.Emit
FieldBuilder fb = tb.DefineInitializedData ("Foo", new byte [] {1,2,3,4}, FieldAttributes.Static|FieldAttributes.Public);
tb.CreateType ();
assembly = Thread.GetDomain ().DefineDynamicAssembly (new AssemblyName (ASSEMBLY_NAME+"2"), AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
assembly = Thread.GetDomain ().DefineDynamicAssembly (new AssemblyName (ASSEMBLY_NAME+"2"), AssemblyBuilderAccess.RunAndSave, tempDir);
module = assembly.DefineDynamicModule ("Instance.exe");
TypeBuilder tb2 = module.DefineType ("Type2", TypeAttributes.Public);
@@ -11306,5 +11303,110 @@ namespace MonoTests.System.Reflection.Emit
Assert.AreSame (buildX, defX);
}
[Test]
public void FieldsWithSameName () {
// Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=57222
var typeBuilder = module.DefineType ("type1", TypeAttributes.Public | TypeAttributes.Class);
var mainMethod = typeBuilder.DefineMethod ("Main", MethodAttributes.Public | MethodAttributes.Static, typeof (int), new Type[0]);
var mainMethodIl = mainMethod.GetILGenerator ();
var f1 = typeBuilder.DefineField ("x", typeof (byte), FieldAttributes.Private | FieldAttributes.Static);
var f2 = typeBuilder.DefineField ("x", typeof (sbyte), FieldAttributes.Private | FieldAttributes.Static);
mainMethodIl.Emit (OpCodes.Ldsflda, f1);
mainMethodIl.Emit (OpCodes.Ldsflda, f2);
mainMethodIl.Emit (OpCodes.Pop);
mainMethodIl.Emit (OpCodes.Pop);
mainMethodIl.Emit (OpCodes.Ldc_I4_0);
mainMethodIl.Emit (OpCodes.Ret);
typeBuilder.CreateType ();
assembly.SetEntryPoint (mainMethod);
assembly.Save (ASSEMBLY_NAME + ".dll");
}
[Test]
public void FieldsWithSameNameAndType () {
// https://bugzilla.xamarin.com/show_bug.cgi?id=57222
var typeBuilder = module.DefineType ("type1", TypeAttributes.Public | TypeAttributes.Class);
var mainMethod = typeBuilder.DefineMethod ("Main", MethodAttributes.Public | MethodAttributes.Static, typeof (int), new Type[0]);
var mainMethodIl = mainMethod.GetILGenerator ();
var f1 = typeBuilder.DefineField ("x", typeof (sbyte), FieldAttributes.Private | FieldAttributes.Static);
var f2 = typeBuilder.DefineField ("x", typeof (sbyte), FieldAttributes.Private | FieldAttributes.Static);
mainMethodIl.Emit (OpCodes.Ldsflda, f1);
mainMethodIl.Emit (OpCodes.Ldsflda, f2);
mainMethodIl.Emit (OpCodes.Pop);
mainMethodIl.Emit (OpCodes.Pop);
mainMethodIl.Emit (OpCodes.Ldc_I4_0);
mainMethodIl.Emit (OpCodes.Ret);
typeBuilder.CreateType ();
assembly.SetEntryPoint (mainMethod);
assembly.Save (ASSEMBLY_NAME + ".dll");
}
[Test]
public void MethodsWithSameNameAndSig () {
// https://bugzilla.xamarin.com/show_bug.cgi?id=57222
var typeBuilder = module.DefineType ("type1", TypeAttributes.Public | TypeAttributes.Class);
var mainMethod = typeBuilder.DefineMethod ("Main", MethodAttributes.Public | MethodAttributes.Static, typeof (int), new Type[0]);
var mainMethodIl = mainMethod.GetILGenerator ();
var m1 = typeBuilder.DefineMethod ("X", MethodAttributes.Private | MethodAttributes.Static, typeof (void), new Type [0]);
var m2 = typeBuilder.DefineMethod ("X", MethodAttributes.Private | MethodAttributes.Static, typeof (void), new Type [0]);
m1.GetILGenerator ().Emit (OpCodes.Ret);
m2.GetILGenerator ().Emit (OpCodes.Ret);
mainMethodIl.Emit (OpCodes.Call, m1);
mainMethodIl.Emit (OpCodes.Call, m2);
mainMethodIl.Emit (OpCodes.Ldc_I4_0);
mainMethodIl.Emit (OpCodes.Ret);
typeBuilder.CreateType ();
assembly.SetEntryPoint (mainMethod);
assembly.Save (ASSEMBLY_NAME + ".dll");
}
[Test]
public void TwoAssembliesMidFlightTest () {
// Check that one AssemblyBuilder can refer to a TypeBuilder from another AssemblyBuilder.
// Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=58421
var name2 = "MonoTests.System.Reflection.Emit.TypeBuilderTest2";
var assemblyName2 = new AssemblyName (name2);
var assembly2 =
Thread.GetDomain ().DefineDynamicAssembly (
assemblyName2, AssemblyBuilderAccess.RunAndSave, tempDir);
var module2 = assembly2.DefineDynamicModule (name2, name2 + ".dll");
var tb = module.DefineType ("Foo", TypeAttributes.Public);
var tb2 = module2.DefineType ("Foo2", TypeAttributes.Public);
var cb = tb.DefineConstructor (MethodAttributes.Public, CallingConventions.Standard,
Type.EmptyTypes);
var ilg = cb.GetILGenerator ();
ilg.Emit (OpCodes.Ldtoken, tb2); // N.B. type from the other AssemblyBuilder
ilg.Emit (OpCodes.Pop);
ilg.Emit (OpCodes.Ret);
var t = tb.CreateType ();
tb2.CreateType ();
var ci = t.GetConstructor (Type.EmptyTypes);
var x = ci.Invoke (null);
assembly.Save (ASSEMBLY_NAME + ".dll");
assembly2.Save (name2 + ".dll");
}
}
}
@@ -0,0 +1,76 @@
//
// MonoTests.System.Runtime.Remoting.Proxies.RealProxyTest.cs
//
//
using System;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using NUnit.Framework;
namespace MonoTests.System.Runtime.Remoting.Proxies {
[TestFixture]
public class RealProxyTest {
public class ExampleInterfaceProxy : RealProxy {
public bool Called;
public ExampleInterfaceProxy () : base (typeof(IComparable))
{
Called = false;
}
public override IMessage Invoke (IMessage msg)
{
Called = true;
return new ReturnMessage (typeof(IComparable), null, 0, null, null);
}
}
[Test]
public void InterfaceProxyGetTypeOkay ()
{
// Regression test for #17325
// Check that GetType () for a proxy of an interface
// returns the interface.
var prox = new ExampleInterfaceProxy ();
var tprox = prox.GetTransparentProxy ();
Assert.IsNotNull (tprox, "#1");
var tproxType = tprox.GetType ();
Assert.IsFalse (prox.Called, "#2"); // this is true on .NET Framework, but false on Mono.
Assert.IsNotNull (tproxType, "#3");
Assert.IsTrue (tproxType.IsAssignableFrom (typeof(IComparable)), "#4");
}
[Test]
public void InterfaceProxyGetTypeViaReflectionOkay ()
{
// Regression test for #17325
// Check that GetType () for a proxy of an interface
// returns the interface.
//
// This versions calls GetType using reflection, which
// avoids the fast path in the JIT.
var prox = new ExampleInterfaceProxy ();
var tprox = prox.GetTransparentProxy ();
Assert.IsNotNull (tprox, "#1");
var m = typeof(object).GetMethod ("GetType");
var tproxType = m.Invoke (tprox, null);
Assert.IsTrue (prox.Called, "#2");
Assert.IsNotNull (tproxType, "#3");
Assert.IsTrue (tproxType is Type, "#4");
Assert.IsTrue ((tproxType as Type).IsAssignableFrom (typeof(IComparable)), "#5");
}
}
}
@@ -341,7 +341,7 @@ namespace MonoTests.System.Runtime.Remoting
Thread tr = new Thread (new ThreadStart (CallbackThread));
tr.Start();
bool terminated = tr.Join(2000);
bool terminated = tr.Join(10000);
Assert.IsTrue(terminated, "Thread didn't get lock of context bound object.");
Assert.IsTrue (!otResult, "Concurrency detected in CallbackThread");
@@ -68,8 +68,6 @@ namespace MonoTests.System.Security.Cryptography.X509Certificates {
public void TearDown ()
{
Thread.CurrentThread.CurrentCulture = oldcult;
File.Delete("temp.cer");
File.Delete("temp.b64");
}
#if !MOBILE && !MONOMAC
@@ -37,7 +37,6 @@ public void SetUp () {
[TearDown]
public void TearDown () {
Thread.CurrentThread.CurrentCulture = oldcult;
File.Delete("temp.b64");
try {
File.Delete (temp_certificate_filename);
} catch {
@@ -1258,7 +1258,7 @@ namespace MonoTests.System.Threading.Tasks
{
var t = Task.Delay (300);
Assert.IsTrue (TaskStatus.WaitingForActivation == t.Status || TaskStatus.Running == t.Status, "#1");
Assert.IsTrue (t.Wait (400), "#2");
Assert.IsTrue (t.Wait (1200), "#2");
}
[Test]
+3
View File
@@ -2261,11 +2261,14 @@ namespace MonoTests.System
[Test]
public void GetGenericMethodDefinitionOverInflatedMethodOnGTD () {
var s = new List<int> () { 1, 2, 3 }.ConvertAll ( i => i.ToString () );
Assert.AreEqual (3, s.Count);
var l = typeof (List<>);
var m = l.GetMethod ("ConvertAll");
var infl = m.MakeGenericMethod (typeof (int));
var res = m.GetGenericMethodDefinition ();
Assert.AreEqual (m, res, "#1");
Assert.AreEqual (1, infl.GetGenericArguments().Length, "#2");
}
[Test]
+1
View File
@@ -203,6 +203,7 @@ System.Runtime.Remoting.Channels/ChannelServicesTest.cs
System.Runtime.Remoting.Contexts/SynchronizationAttributeTest.cs
System.Runtime.Remoting.Messaging/CallContextTest.cs
System.Runtime.Remoting.Metadata.W3cXsd2001/SoapHexBinaryTest.cs
System.Runtime.Remoting.Proxies/RealProxyTest.cs
System.Runtime.Serialization/FormatterServicesTests.cs
System.Runtime.Serialization/ObjectIDGeneratorTests.cs
System.Runtime.Serialization/SerializationBinderTest.cs
@@ -39,6 +39,7 @@ System.Runtime.Remoting.Channels/ChannelServicesTest.cs
System.Runtime.Remoting.Contexts/SynchronizationAttributeTest.cs
System.Runtime.Remoting.Messaging/CallContextTest.cs
System.Runtime.Remoting.Metadata.W3cXsd2001/SoapHexBinaryTest.cs
System.Runtime.Remoting.Proxies/RealProxyTest.cs
System.Security.AccessControl/AuthorizationRuleTest.cs
System.Security.AccessControl/CommonAceTest.cs
System.Security.AccessControl/CommonAclTest.cs
+16
View File
@@ -0,0 +1,16 @@
// CS0128: A local variable named `x' is already defined in this scope
// Line: 9
class X
{
public static void Main ()
{
Foo (out int x);
Foo (out int x);
}
static void Foo (out int arg)
{
arg = 2;
}
}
+13
View File
@@ -0,0 +1,13 @@
// CS0128: A local variable named `s' is already defined in this scope
// Line: 12
class C
{
public static void Main ()
{
object o = null;
var x1 = o is string s;
var x2 = o is string s;
}
}
+13
View File
@@ -0,0 +1,13 @@
// CS0136: A local variable named `s' cannot be declared in this scope because it would give a different meaning to `s', which is already used in a `parent or current' scope to denote something else
// Line: 10
internal class Program
{
public static void Main ()
{
object o = null;
if (o is string s) {
int s = 1;
}
}
}
+14
View File
@@ -0,0 +1,14 @@
// CS0165: Use of unassigned local variable `s'
// Line: 12
class X
{
static string Foo (object arg)
{
if (arg is string s) {
}
return s;
}
}
+54
View File
@@ -0,0 +1,54 @@
// CS0165: Use of unassigned local variable `v'
// Line: 52
struct Vector3
{
int field1, field2, field3;
}
public class C
{
void Update ()
{
int v1 = 0;
int v2 = 0;
int v3 = 0;
int v4 = 0;
int v5 = 0;
int v6 = 0;
int v7 = 0;
int v8 = 0;
int v9 = 0;
int v10 = 0;
int v11 = 0;
int v12 = 0;
int v13 = 0;
int v14 = 0;
int v15 = 0;
int v16 = 0;
int v17 = 0;
int v18 = 0;
int v19 = 0;
int v20 = 0;
int v21 = 0;
int v22 = 0;
int v23 = 0;
int v24 = 0;
int v25 = 0;
int v26 = 0;
int v27 = 0;
int v29;
Vector3 v;
if (v1 == 0)
{
v = new Vector3 ();
}
else if (v2 >= 0.5)
{
v = new Vector3 ();
}
System.GC.KeepAlive (v);
}
}
+49
View File
@@ -0,0 +1,49 @@
// CS0165: Use of unassigned local variable `v'
// Line: 52
struct Vector3
{
int field1, field2, field3;
}
public class C
{
void Update ()
{
int v1 = 0;
int v2 = 0;
int v3 = 0;
int v4 = 0;
int v5 = 0;
int v6 = 0;
int v7 = 0;
int v8 = 0;
int v9 = 0;
int v10 = 0;
int v11 = 0;
int v12 = 0;
int v13 = 0;
int v14 = 0;
int v15 = 0;
int v16 = 0;
int v17 = 0;
int v18 = 0;
int v19 = 0;
int v20 = 0;
int v21 = 0;
int v22 = 0;
int v23 = 0;
int v24 = 0;
int v25 = 0;
int v26 = 0;
int v27 = 0;
int v29;
Vector3 v;
while (v8 != 0) {
v = new Vector3 ();
}
System.GC.KeepAlive (v);
}
}
-16
View File
@@ -1,16 +0,0 @@
// CS0815: An implicitly typed local variable declaration cannot be initialized with `void'
// Line: 8
// Compiler options: -langversion:experimental
class X
{
public static void Main ()
{
Foo (out var x = Main ());
}
static void Foo (out int i)
{
i = 0;
}
}
-18
View File
@@ -1,18 +0,0 @@
// CS1061: No overload for method `Call' takes `0' arguments
// Line: 11
using System;
class Program
{
static void Main ()
{
Action<dynamic, object> action = delegate { };
Foo (action).NoDynamicBinding ();
}
static T Foo<T>(Action<T, T> x)
{
throw new NotImplementedException ();
}
}
-15
View File
@@ -1,15 +0,0 @@
// CS1501: Argument `#1' cannot convert `ref string' expression to type `ref int'
// Line: 8
// Compiler options: -langversion:experimental
class C
{
public static void Main ()
{
Foo (ref var x = "");
}
static void Foo (ref int i)
{
}
}
+21
View File
@@ -0,0 +1,21 @@
// CS1621: The yield statement cannot be used inside anonymous method blocks
// Line: 12
using System;
using System.Collections;
public class Test
{
public IEnumerator Foo ()
{
Call (() => {
yield break;
});
yield break;
}
void Call (Action a)
{
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
// CS1644: Feature `declaration expression' cannot be used because it is not part of the C# 5.0 language specification
// Line: 12
// CS1644: Feature `out variable declaration' cannot be used because it is not part of the C# 5.0 language specification
// Line: 9
// Compiler options: -langversion:5
class C
+13
View File
@@ -0,0 +1,13 @@
// CS1644: Feature `pattern matching' cannot be used because it is not part of the C# 6.0 language specification
// Line: 9
// Compiler options: -langversion:6
class Class
{
static void Foo (object arg)
{
if (arg is Type v) {
return;
}
}
}
-12
View File
@@ -1,12 +0,0 @@
// CS4001: Cannot await `void' expression
// Line: 10
using System;
class A
{
static async void Test ()
{
await Console.WriteLine;
}
}
+13
View File
@@ -0,0 +1,13 @@
// CS8116: The nullable type `byte?' pattern matching is not allowed. Consider using underlying type `byte'
// Line: 11
using System;
class C
{
public static void Main ()
{
object o2 = null;
bool r2 = o2 is Nullable<byte> t3;
}
}
+10
View File
@@ -0,0 +1,10 @@
// CS8117: Cannot use null as pattern matching operand
// Line: 8
class C
{
static object Test ()
{
return null is object res;
}
}
+14
View File
@@ -0,0 +1,14 @@
// CS8122: An expression tree cannot contain a pattern matching operator
// Line: 12
using System;
using System.Linq.Expressions;
class X
{
public static void Main ()
{
object o = 1;
Expression<Func<bool>> e = () => o is int y;
}
}
+16
View File
@@ -0,0 +1,16 @@
// CS8196: Reference to an implicitly typed out variable `x1' is not permitted in the same argument list
// Line: 8
public class C
{
public static void Main ()
{
Test (out var x1, out x1);
}
static void Test (out int x, out int x2)
{
x = 1;
x2 = 2;
}
}
+16
View File
@@ -0,0 +1,16 @@
// CS8196: Reference to an implicitly typed out variable `x1' is not permitted in the same argument list
// Line: 8
public class C
{
public static void Main ()
{
Test (out var x1, out x1);
}
static void Test (out int x, out int x2)
{
x = 1;
x2 = 2;
}
}
@@ -1,6 +1,5 @@
// CS8047: Declaration expression cannot be used in this context
// Line: 8
// Compiler options: -langversion:experimental
// CS8197: Cannot infer the type of implicitly-typed out variable `y'
// Line: 9
public class C
{
@@ -1,6 +1,5 @@
// CS8046: An expression tree cannot contain a declaration expression
// CS8198: An expression tree cannot contain out variable declaration
// Line: 11
// Compiler options: -langversion:experimental
using System;
using System.Linq.Expressions;
+13
View File
@@ -0,0 +1,13 @@
// CS8200: Out variable and pattern variable declarations are not allowed within constructor initializers, field initializers, or property initializers
// Line: 6
public class C
{
bool res = Foo (out int arg);
static bool Foo (out int arg)
{
arg = 2;
return false;
}
}
+13
View File
@@ -0,0 +1,13 @@
// CS8200: Out variable and pattern variable declarations are not allowed within constructor initializers, field initializers, or property initializers
// Line: 11
public class C
{
bool Prop { get; } = Foo (out int arg);
static bool Foo (out int arg)
{
arg = 2;
return false;
}
}
+15
View File
@@ -0,0 +1,15 @@
// CS8200: Out variable and pattern variable declarations are not allowed within constructor initializers, field initializers, or property initializers
// Line: 8
using System;
public class C
{
event Action H = Foo (out var res);
static Action Foo (out int arg)
{
arg = 2;
return null;
}
}
+12
View File
@@ -0,0 +1,12 @@
// CS8200: Out variable and pattern variable declarations are not allowed within constructor initializers, field initializers, or property initializers
// Line: 6
public class C
{
bool res = Foo () is string s;
static object Foo ()
{
return null;
}
}
+12
View File
@@ -0,0 +1,12 @@
// CS8200: Out variable and pattern variable declarations are not allowed within constructor initializers, field initializers, or property initializers
// Line: 6
class X
{
public static bool Test { get; } = Foo () is bool x;
static object Foo ()
{
return false;
}
}
+20
View File
@@ -0,0 +1,20 @@
// CS8200: Out variable and pattern variable declarations are not allowed within constructor initializers, field initializers, or property initializers
// Line: 11
public class C
{
public C (bool value)
{
}
public C ()
: this (Foo (out int arg))
{
}
static bool Foo (out int arg)
{
arg = 2;
return false;
}
}
+15
View File
@@ -0,0 +1,15 @@
// CS8201: Out variable and pattern variable declarations are not allowed within a query clause
// Line: 11
using System.Linq;
class Program
{
public static void Main ()
{
var a = "abcdef";
var res = from x in a from y in M (a, out var z) select x;
}
public static T M<T>(T x, out T z) => z = x;
}
+12
View File
@@ -0,0 +1,12 @@
// CS8208: The type `dynamic' pattern matching is not allowed
// Line: 9
static class Program
{
public static void Main ()
{
object o = null;
if (o is dynamic res) {
}
}
}
+25 -3
View File
@@ -651,13 +651,35 @@ namespace Mono.CSharp
//
// Returns dynamic when at least one argument is of dynamic type
//
public void Resolve (ResolveContext ec, out bool dynamic)
public void Resolve (ResolveContext rc, out bool dynamic)
{
dynamic = false;
List<LocalVariable> var_locals = null;
foreach (Argument a in args) {
a.Resolve (ec);
if (a.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && !a.IsByRef)
a.Resolve (rc);
if (a.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && !a.IsByRef) {
dynamic = true;
continue;
}
if (a.Type == InternalType.VarOutType) {
var de = a.Expr as DeclarationExpression;
if (de != null) {
if (var_locals == null)
var_locals = new List<LocalVariable> ();
var_locals.Add (de.Variable);
continue;
}
var lvr = a.Expr as LocalVariableReference;
if (lvr != null && var_locals != null && var_locals.Contains (lvr.local_info)) {
rc.Report.Error (8196, lvr.Location, "Reference to an implicitly typed out variable `{0}' is not permitted in the same argument list", lvr.Name);
lvr.Type = InternalType.ErrorType;
}
}
}
}
+1 -1
View File
@@ -2227,7 +2227,7 @@ namespace Mono.CSharp
Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (TypeBuilder);
#if STATIC
if (Kind == MemberKind.Struct && HasInstanceField) {
if (Kind == MemberKind.Struct && !HasStructLayout && HasInstanceField) {
TypeBuilder.__SetLayout (0, 0);
}
Loaded 100 of 260 files, more files were not shown because too many files have changed in this diff. Show more