Compare commits

...
Author SHA1 Message Date
Alexander Köplinger 5077205a44 [pdb2mdb] Dispose Cecil AssemblyDefinition on pdb2mdb (#4899)
Context: https://bugzilla.xamarin.com/show_bug.cgi?id=56275

Recent Cecil 0.10 changed to not reading the assembly in memory but
instead reads directly from the underlying stream [0]. This however
means that the file handle is not freed until the AssemblyDefinition
is disposed.

Xamarin.Android is using the pdb2mdb source as part of
Xamarin.Android.Build.Tasks.dll and hit an issue where the file
would be locked inside of VS.

[0] http://cecil.pe/post/149243207656/mono-cecil-010-beta-1
2017-05-18 15:41:08 -04:00
Jo Shields 0d6f6f8f40 Bump version, following 5.0.0.x release 2017-05-18 17:02:34 +01:00
Zoltan Varga d6c24517f4 [runtime] Make RuntimeHelpers:SufficientExecutionStack () a no-op on android for now. Fixes #56240. (#4889) 2017-05-17 12:34:11 -04:00
Rodrigo Kumpera 0f5c24054c Merge pull request #4885 from kumpera/backport_56177
[runtime] Fix pedump. Fixes bug #56177.
2017-05-16 23:48:14 -04:00
Zoltan Varga 3511ffcb2d [runtime] Fix pedump. 2017-05-16 16:20:15 -07:00
Alexander Köplinger 188c235ca4 [xbuild] Add web targets for 15.0 (#4868) (#4876)
(cherry picked from commit 8077ff5da7)
2017-05-16 19:46:57 +02:00
Aleksey Kliger 25ac18a9b7 [sre] Don't leak coop handles in mono_dynimage_encode_typedef_or_ref_full
This function calls mono_class_get_ref_info which allocates a coop handle.
However it is called from an icall that wasn't converted to use coop handles
yet, so nothing was saving/restoring the handle stack mark, and consequently
the handles leak.
2017-05-15 15:03:07 -04:00
Jonathan Chambers d95d7d30fe Use handle macros to avoid leaking result of mono_type_get_object_handle 2017-05-15 15:03:07 -04:00
Marek Safar 82d42e61b1 [runtime] Remove System.ValueTuple from denied assemblies. It's not needed
anymore because we have reference assemblies and it didn't work for mobile tools (e.g. linker)
2017-05-13 16:22:31 +02:00
Marek Safar 4c98dc2006 Revert "[runtime] Remove System.ValueTuple from denied assemblies. It's not needed"
This reverts commit 4dc09dc922.
2017-05-13 10:35:52 +02:00
Marek Safar 4dc09dc922 [runtime] Remove System.ValueTuple from denied assemblies. It's not needed
anymore because we have reference assemblies and it didn't work for mobile tools (e.g. linker)
2017-05-13 10:32:23 +02:00
Martin Baulig d27287c77b [System]: Cherry-pick GZipStream.BeginRead() fix from corefx. Bug #56260. (#4844)
https://github.com/dotnet/corefx/commit/a6c7e23421701870c1eb855eae95e4605e5b04b3.
2017-05-12 15:39:55 -04:00
Zoltan Varga 1298269b88 [arm] Disable the usage of lmf_ir_mono_lmf. Fixes #55087. (#4819) 2017-05-10 10:58:13 -04:00
Martin Baulig 2ce82742e8 Revert "[System]: Fix bug #52508 in HttpListener when doing multiple Https request."
This reverts commit 81da99eb76.
2017-05-08 15:05:33 -04:00
Martin Baulig 81da99eb76 [System]: Fix bug #52508 in HttpListener when doing multiple Https request.
Move the call to SslStream.AuthenticateAsServer() into the constructor because
we don't want to call it again when Init() is called from Close().

(cherry picked from commit 5e08742b5c)
(cherry picked from commit abfb9a00a7)
2017-05-08 15:01:45 -04:00
Martin Baulig 9667aa6485 [System]: Fix default TLS provider. (#4797) 2017-05-05 13:40:11 +02:00
Ankit Jain 1e856f02ff Empty commit to trigger a build on wrench 2017-05-03 19:58:19 -04:00
Vlad Brezae 6ab979c9df [sgen] Fix accidental triggering of degraded mode
We trigger degraded mode when we are unable to properly build the nursery fragments due to excessive nursery pinning. This is done by initializing degraded_mode at the end of a minor. alloc_degraded is used to do allocation to major heap either as part of mature allocation or as part of degraded mode (when we bump the degraded_mode so we can detect when the next minor should be triggered).

When failing to allocate from the nursery after doing a minor (because the other threads might have already consumed the nursery) we need to do a mature allocation (as a fallback) instead of a degraded mode allocation so we don't uselessly enable the mode.
2017-05-03 22:48:54 +03:00
Ankit Jain 02b6c24e5d Empty commit to trigger a build on wrench 2017-05-03 01:59:45 -04:00
Ankit Jain 87ad2c3690 Empty commit to trigger a build on wrench 2017-05-03 00:27:57 -04:00
Ankit Jain 3cde98344e Empty commit to trigger a build on wrench 2017-05-02 21:05:53 -04:00
Aleksey Kliger (λgeek) 1d0445bfc7 Merge pull request #4769 from lambdageek/bug-55681-2017-02
[sre-save] Handle ConstructorBuilder custom attribute constructors
2017-04-28 17:45:37 -04:00
Ankit Jain 1d389ea02c Empty commit to trigger a build on wrench 2017-04-28 11:56:06 -04:00
Aleksey Kliger ad60bf18b7 [sre-save] Handle ConstructorBuilder custom attribute constructors.
The code expected that a custom attribute was specified as a MonoCMethod and
was calling mono_image_create_token().  However that function expects to be
called from the managed S.R.E.ModuleBuilder:GetToken (MemberInfo) which handles
all the builders in managed code.  Consequently mono_image_create_token () was
asserting.

So now we encode the token for a ConstructorBuilder in place.
2017-04-28 11:46:47 -04:00
Aleksey Kliger c20c0b3b81 [sre] Make mono_image_get_methodref_token non-static in sre-internals.h 2017-04-28 11:46:46 -04:00
Aleksey Kliger d33f7f6de9 [test] Regression tests for ConstructorBuilder custom attributes
Regression tests for https://bugzilla.xamarin.com/show_bug.cgi?id=55681
2017-04-28 11:46:45 -04:00
nosami c8c005f137 Bump msbuild for F#. Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=55626 2017-04-28 09:28:36 +01:00
Ankit Jain 1aa58e9a46 Empty commit to trigger a build on wrench 2017-04-27 15:01:51 -04:00
Rodrigo Kumpera 5673411799 Merge pull request #4742 from kumpera/2017-02-backport-4682
2017 02 backport 4682
2017-04-26 00:00:11 -04:00
Zoltan Varga 1434f9c879 [jit] Remove some debug spew. 2017-04-25 05:11:19 -04:00
Rodrigo Kumpera 3598a4ab55 [bcl] Check the compact switch for whether cancelation token throws when disposed. 2017-04-24 14:14:20 -07:00
Rodrigo Kumpera 72cdd51acb [corlib] Change SwitchThrowExceptionIfDisposedCancellationTokenSource to false as this is the default 4.6.0 behavior. 2017-04-24 13:26:46 -07:00
Rodrigo Kumpera ea3996571a [bcl] Make our AppContextDefaultValues more compatible with RS and make them non toggle-able on mobile.
We change AppContextSwitches to hardcode values on mobile and use the full stack on desktop.

We still have all strings in AppContextDefaultValues as this reduces the ifdef mess in AppContextSwitches.
It's only used on desktop, where an extra kb is not the end of the world.
2017-04-24 13:26:19 -07:00
Vlad Brezae bdf17346a6 [metadata] Lock around special static fields hash access
If a type is loaded in another thread, the fields hash can get resized, leading to failure.
2017-04-24 23:25:25 +03:00
Rodrigo Kumpera 37f8c76e38 [corlib] Use AppContextSwitches implementation from RS. Fixes #54448
This change makes AppContextSwitches usable which allow backwards incompatible settings to be actually toggled.
2017-04-24 12:41:59 -07:00
Zoltan Varga cda97d6fc1 [cil-stripper] Mark stripped methods as noinline to prevent the JIT from trying to inline them. Fixes #55041. (#4732) 2017-04-24 13:42:55 -04:00
Alexander Köplinger 198ff835e9 [Facades] Use Open.snk for netstandard.dll
We were using the wrong key since dotnet/standard switched to using the new Open key.

(cherry picked from commit 27fd8e5ad8)
2017-04-24 16:28:10 +02:00
Ankit Jain ba317ed4e6 Empty commit to trigger Wrench build 2017-04-22 18:24:41 -04:00
Alexis Christoforides 450d4d7a9e Trigger package CI build 2017-04-21 18:09:33 -04:00
nosami 5da5fa26fb Bump bockbuild for F# jit tracking patch 2017-04-21 18:14:44 +01:00
Alexis Christoforides bee954cff2 Trigger package CI build 2017-04-21 11:10:27 -04:00
Alexander Köplinger 762430b83e [Facades] Allow passing $(EXTRA_LIB_MCS_FLAGS) to netstandard build 2017-04-21 17:01:34 +02:00
Zoltan Varga d717e1b1ea [runtime] Shadow copy the .pdb files as well. Fixes #55095. (#4715) 2017-04-20 09:49:16 -04:00
Ankit Jain 5a3893de5c Empty commit to trigger Wrench build 2017-04-20 08:52:51 -04:00
Alexis Christoforides 6dc5ddd3d9 Trigger package CI build 2017-04-19 12:28:50 -04:00
Marek Safar 6f6232707c Bump cecil 2017-04-19 12:01:31 +02:00
Mikayla Hutchinson 64a055b079 [Sockets] Fix RemoteEndpoint with async+DualMode (#4702) 2017-04-19 11:49:24 +02:00
Ankit Jain 34a69b5e81 Update NuGet.BuildTasks to dev15.1 from usptream (#4706)
* Update nuget-buildtasks from upstream's `dev15.1` branch

dev15.1 branch + fixup import paths

This was prompted by needing to support nuget restore for projects with
`PackageReference`.

* [nuget] Bump reference to NuGet.BuildTasks to pick up a build fix

* Bump nuget-buildtasks
2017-04-18 21:27:50 +02:00
Zoltan Varga b8c96604c5 [jit] Disable handler block trampolines+aot support on ios, it does an async stack walk, and the eh info for llvm compiled methods cannot be loaded in async context currently. Works around #54658. (#4713) 2017-04-18 14:04:30 -04:00
Alexander Kyte 440fff5aee Merge pull request #4681 from alexanderkyte/circular_type_memo
[runtime] Handle circular references in SRE types
2017-04-18 11:24:09 -04:00
Alexander Köplinger 502a6a5e1b Empty commit to trigger Wrench build 2017-04-18 14:26:24 +02:00
Mikayla Hutchinson 02f0d6ee9d Add System.Net.Http 4.3.1 to blacklist 2017-04-18 10:53:49 +02:00
Zoltan Varga 4242008df5 [arm] Fix a gsharedvt assertion which happens with gsharedvt methods with a lot of arguments. Fixes #54976. 2017-04-17 14:49:29 -04:00
Ankit Jain 12f8ebafed Empty commit to force a wrench build 2017-04-14 23:46:43 -04:00
Ludovic Henry e6a3b54b37 [WebConnection] Fix race condition between Close and BeginWrite (#4694) 2017-04-14 15:17:20 -04:00
Martin Baulig b6255d35cd [appletls]: Disable the new keychain code on XI. (#4695) 2017-04-14 14:50:36 -04:00
Alexander Kyte ff7a2e46e7 [runtime] Handle circular references in SRE types
We previously recursed through the entire directed cyclic graph
of the type passed to SRE. When given a (legal) circular type reference,
we encountered stack overflows. This was particularly easy to trigger
with fsharpi and with FAKE.

By creating everything about the type before searching for the parent,
and by defering all type hierarchy establishment until the type must be
surfaced to manage code, we tease out the data dependencies caught up in
the cycle.

Note the bounded lifetime of the unmanaged object hidden in the SRE
module, which acts as a global reference for all types reachable from
the TypeBuilder passed to the runtime through the icall.
2017-04-14 11:28:59 -04:00
David Karlaš b83bdfd396 Merge pull request #4688 from mono/bug55148
Bug 55148 - Debugger checks type which is possibly never used
2017-04-14 09:51:52 +02:00
Alexander Kyte c686827dba [runtime] Test circular references in SRE 2017-04-13 21:00:31 -04:00
Martin Baulig b9b2d23f1a [appletls]: Use SecIdentityCreate() to avoid using the Mac keychain. (#4671) (#4677)
* [appletls]: Use SecIdentityCreate() to avoid using the Mac keychain. (#4671)

Reading Certificates from the Mac Keychain
==========================================

Reading the private key from the keychain is a new feature introduced with
AppleTls on XamMac and iOS. On Desktop Mono, this new feature has several
known issues and it also did not received any testing yet. We go back to the old
way of doing things, which is to explicitly provide an X509Certificate2 with a
private key.

Keychain Dialog Popups
======================

When using Xamarin.Mac or Xamarin.iOS, we try to search the keychain
for the certificate and private key.

On Xamarin.iOS, this is easy because each app has its own keychain.

On Xamarin.Mac, the .app package needs to be trusted via code-sign
to get permission to access the user's keychain. [FIXME: I still have to
research how to actually do that.] Without this, you will get a popup
message each time, asking you whether you want to allow the app to access
the keychain, but you can make these go away by selecting "Trust always".

On Desktop Mono, this is problematic because selecting "Trust always"
give the 'mono' binary (and thus everything you'll ever run with Mono)
permission to retrieve the private key from the keychain.

This code would also trigger constant keychain popup messages,
which could only be suppressed by granting full trust. It also makes it
impossible to run Mono in headless mode.

SecIdentityCreate
=================

To avoid these problems, we are currently using an undocumented API
called SecIdentityRef() to avoid using the Mac keychain whenever a
X509Certificate2 with a private key is used.

On iOS and XamMac, you can still provide the X509Certificate without
a private key - in this case, a keychain search will be performed (and you
may get a popup message on XamMac).
2017-04-13 18:24:43 -04:00
David Karlaš d845201db4 Bug 55148 - Debugger checks type which is possibly never used 2017-04-13 20:34:01 +02:00
Zoltan Varga 10fe0e89c0 [ppdb] Fix a crash if mono_ppdb_get_seq_points () is only passed a 'source_file' argument. 2017-04-12 16:35:05 -04:00
nosami 83ca242114 Bump F# to 4.1.8 2017-04-11 12:27:35 +01:00
nosami 5309190d7d Bump F# to 4.1.8 2017-04-11 09:40:17 +01:00
nosami 98e0d8c486 Bump F# to 4.1.8 2017-04-11 07:10:42 +01:00
nosami a9d142eeb2 Bump F# to 4.1.8 2017-04-11 05:17:59 +01:00
nosami 6149b5d569 Bump F# to 4.1.8 2017-04-10 23:42:56 +01:00
Alexis Christoforides 851b6c7654 Bump for package change 2017-04-07 10:52:36 -04:00
Alexander Köplinger 6462e3fc8e Make sure .sources files end with newline
It confuses the build on Linux otherwise.

(cherry picked from commit 47ca0c0ae8)
2017-04-07 14:55:23 +02:00
Alexander Köplinger 2eced64a82 Bring in the new reference assemblies (#4619) (#4647)
This bumps the reference assemblies submodule so we can install
the new assemblies which are built from source.
(cherry picked from commit feff7ee306)
2017-04-06 01:55:39 +02:00
Vlad Brezae e6c0a86e70 [sgen] Lock around worker start, not only finishing
If we don't take the finished_lock when starting workers, the workers that we started could have already finished the work and switch to non-parallel context before we are even able to signal all of them.
2017-04-05 19:24:14 +03:00
Marek Safar ad88c52d8e Bump cecil 2017-04-05 15:59:52 +02:00
Alexander Köplinger 7e2f9aa7e8 [tests] Fix the mcs-compileall target in runtime/ (#4637)
It is used as the "verify" step on Jenkins/Wrench and I noticed
it didn't run recently.

Looks like it was broken a while ago by 695e8f53ae.
Moving the verifiable_files variable at the top is wrong since
the $$profile variable is only defined inside the for loop and
so we'd get an empty list.

When that was fixed it still didn't work as piping to `echo`
doesn't work. Replaced it with a Makefile solution instead.
(cherry picked from commit 3bfff911dd)
2017-04-05 03:36:37 +02:00
Martin Baulig dda961cf9a [appletls]: Make CFObject.dlsym() private and fix CFBoolean. (#4640) (#4641)
This fixes a native crash when attempting to use appletls.
(cherry picked from commit 989aefce37)
2017-04-04 15:47:22 -04:00
Marek Safar 55a698e07d Bump cecil 2017-04-04 11:54:40 +02:00
Marek Safar 67489264b7 [System.Core] Linker friendly test update 2017-04-04 11:03:45 +02:00
Marek Safar f23dca66a7 Bump cecil 2017-04-04 09:10:22 +02:00
Alexis Christoforides 590080c39e Bump for packaging change 2017-04-03 18:48:21 -04:00
Ankit Jain 452f94286b Empty commit to force a wrench build 2017-04-03 17:12:09 -04:00
Zoltan Varga f342dae059 [jit] Fix a regression caused by 399f6e2425. Avoid a crash if MONO_VERBOS_METHOD is used. 2017-04-03 15:01:50 -04:00
Alexander Köplinger 8fafb67859 Make monolite profile directory versioned (#4631)
If you're building with monolite currently the build system
checks for the existence of mcs/class/lib/monolite and just
uses it in that case.

It becomes a problem when bumping corlib version since if you
pull the update and try to build it'll use the old monolite
and you'll hit the "corlib version not in sync" error.

By making the monolite directory include the version this can
be avoided and everything works out of the box.

Also removed the confusing "You need Mono version 4.8 or better"
message since we actually require a newer version in
basic-profile-check.cs now and keeping them in sync is error prone.
(cherry picked from commit 500765a5d3)
2017-04-01 18:55:53 +02:00
Mikayla Hutchinson 71cc0a16c9 [System.Web] Implement HostingEnvironment.QueueBackgroundWorkItem
From reference source.

This is required for the Azure Functions Host to run unmodified.
2017-03-31 12:11:39 +02:00
Alexander Köplinger 78c2486dcb Fix Windows build
(cherry picked from commit 6f1d247060)
2017-03-31 04:18:10 +02:00
Andi McClure f47f6a1dab Merge pull request #4629 from alexanderkyte/2017-02-env
[runtime] Switch getenv to use heap memory
2017-03-30 22:12:53 -04:00
Alexander Kyte 052d1c2867 [runtime] Switch getenv to use heap memory
Getenv doesn't use heap memory, it uses static memory.
Mono's usage is consistent with a view of getenv memory contents
that are durable and can be stored and manipulated.

In a multithreaded context, getenv calls can race and corrupt
string buffers as they are read. In a single threaded context,
subsequent calls to getenv will lead to overwriting the memory
that pointers to previous calls point to.

In order to bring memory safety back, we duplicate memory and
manage it at each call-site.

Note: this changes the API semantics of g_getenv. This is necessary
because the locking around the getenv buffer is safest when confined to
the function in eglib.
2017-03-30 18:11:48 -04:00
Marek Safar bdc6fd7f03 Bump cecil 2017-03-30 17:42:46 +02:00
Marek Safar 90faddac77 Bump cecil 2017-03-30 17:29:15 +02:00
nosami 809fa3a3a8 Bump F# to 4.1.5 2017-03-30 11:08:07 +01:00
nosami 7ce4e861df Bump F# to 4.1.5 2017-03-30 10:53:29 +01:00
Zoltan Varga 4e11ba5c8b [jit] Disable SIMD support for System.Numerics, its has too many problems. 2017-03-29 19:52:15 -04:00
nosami 9dafa35db6 Bump F# to 4.1.5 2017-03-29 21:16:04 +01:00
Alexis Christoforides 51f9a82ecd Bump for F# upgrade in package 2017-03-29 12:22:50 -04:00
Marek Safar 5a3b524b60 Bump cecil 2017-03-29 10:28:17 +02:00
Zoltan Varga d4df2e7aa9 [bcl] Avoid waiting for events inside a finalizer in Process.WaitForExit () because it can hang if the thread which sets the event is aborted during shutdown. Fixes #53843. (#4609) 2017-03-28 20:38:51 -04:00
Andi McClure 4d40922fde Remove 'experimental' label from full/hybrid AOT in manpage 2017-03-28 14:14:47 -04:00
Andi McClure 082289cc15 Correctly document --aot options in man page
- Ensure all AOT options are both documented and listed in
  alphabetical order in both the manpage and --help line
- Ensure all exceptoins are commented in the aot-compiler.c source
  with "intentionally udnocumented"
2017-03-28 14:14:43 -04:00
Rolf Bjarne Kvinge ef4352cde5 [corlib] Add back X509 support for watchOS.
Otherwise we'd be regressing existing (and working) behavior.
2017-03-28 11:16:55 +02:00
Chris Hamons 9ed0907eea Disable a few x509 tests that fail on older macOS
- Handles https://bugzilla.xamarin.com/show_bug.cgi?id=53958
- https://bugzilla.xamarin.com/show_bug.cgi?id=53689 is filed to turn them
  back on later with a better version check
- SecCertificateCreateWithData handles invalid arguments differently based on
  macOS version
2017-03-28 00:01:55 +02:00
Ludovic Henry 339c5249a7 [process] Disable tests that do not work on mobile (#4598) 2017-03-27 15:21:15 -04:00
Andi McClure df9df437ae Merge pull request #4592 from lambdageek/bug-53890-2017-02
2017-02 [remoting] Pass correct object to invoke of IRemotingTypeInfo.CanCastTo
2017-03-27 15:14:54 -04:00
Ludovic Henry d15985c4af [threadpool] Fix #53481 (2nd attempt) (#4597)
This will leak on shutdown, and it is to prevent https://bugzilla.xamarin.com/show_bug.cgi?id=53481
2017-03-27 13:37:42 -04:00
Ludovic Henry 98a9c23d70 [threadpool] Fix #53481 (#4593) 2017-03-25 23:52:59 -04:00
Aleksey Kliger 4b82d60bbc [remoting] Pass correct object to invoke of IRemotingTypeInfo.CanCastTo
Pass the payload of the coop handle as the 'this' object, not the handle
itself.

Add asserts in ves_icall_Remoting_RealProxy_InternalGetProxyType that
remote_class and the proxy_class are non-NULL.

Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=53890
2017-03-24 18:53:04 -04:00
Ludovic Henry c3452996bd [threadpool-io] Ensure selector thread is running before waiting on it (#4582)
This could result in a unecessary wait on shutdown where the selector thread would have exited, and the finalizer thread would try to dispose a Socket, which would try to remove the socket from the IOSelector. This removal operation would wait on the selector thread to acknowledge the removal, but because the selector thread would have alreday exited, we would wait on an event that would never happen.
2017-03-24 15:57:40 -04:00
Andi McClure 65d1d7cdae Improve "Could not resolve type with token" exception message 2017-03-24 14:43:17 -04:00
Andi McClure d424096c05 Empty commit to kick builders 2017-03-24 12:28:23 -04:00
Vlad Brezae 6d11ff42da [runtime] Don't reset abort exception in invoke wrapper
It leads to missing self aborts on full-aot.
2017-03-24 16:26:15 +02:00
Vlad Brezae 1c7614193f [runtime] Improve debugging of thread interruptions 2017-03-24 16:25:52 +02:00
Vlad Brezae be6441b30d [runtime] Defer async requests during abort protected blocks
We avoid unnecessary checks for each interruption checkpoint.
2017-03-24 16:25:38 +02:00
Vlad Brezae 66f8f1aa53 [runtime] Fix detecting abort at end of abort protected block
If we have a pending abort then we know we will have the thread_state set and the thread_interruption_requested bumped. We used to consume this request and set the MonoError with the exception. The problems with this is that not all callsites handle the passed MonoError and handling it means converting it back to a pending exception anyway. We just leave the interruption request untouched now.

If the cctor self aborts it means that we consumed the abort exception so we do need to call mono_thread_resume_interruption to reactivate it. We need to make sure that we still don't throw a TypeInitializationException if we had a self abort.
2017-03-24 16:25:26 +02:00
Vlad Brezae a5c496fd46 [runtime] Fix missing abort during abort protected regions
When aborting a thread we set the thread's interruption request and we also increment the global interruption request. If we were trying to abort a thread when it is in an abort protected region, it will just set an interruption deferred and not do anything else (in async_abort_critical). When the thread exited the abort protected region, it was missing the abort request since we didn't increment the global interruption request.

Refactor thread_interruption_requested modifications, making sure we always bump it when requesting an interruption and decrease it when we clear an interruption.
2017-03-24 16:25:12 +02:00
Vlad Brezae b92bdff265 [runtime] Rework abort deferring
The problem with previous implementation was that we were not able to account for two pending exceptions at the same time, since when we execute an interruption request we clear all the state and there is no clear way to account for two exceptions at the same time. This means that, if we have a pending abort in a cctor, all exception handling inside the cctor will be broken (for the provided test case we were only throwing the cctor internal exception outside of it).

In order to fix this, we split into two types of interruptions SYNC and ASYNC (in order to separate mainly between abort and pending exceptions). Sync interruptions are interruptions requested by the thread itself (pending exceptions and self aborts) and they are processed as soon as possible. Async interruptions are requested by other threads (abort, interrupt, suspend) and we defer them as we were doing before (we have a deferred interruption if we have an async exception and abort block count is non zero).
2017-03-24 16:24:56 +02:00
Vlad Brezae d27cc030bb [runtime] Fix interruption deferring
We were accidentally clearing the interruption deferred flag when exiting from nested abort protected regions.
2017-03-24 16:24:42 +02:00
Zoltan Varga 5f5f25f58a [bcl] Add a finalizer to MemoryMappedFile. 2017-03-24 09:37:40 -04:00
Martin Baulig 0d0be3e704 [AppleTls]: Use correct definition of SecTrustResult. (#4586)
* [AppleTls]: Use correct definition of `SecTrustResult`.

We need all the values in this enum because `SecTrustResult.Unspecified`
means success - which currently has an integer value of 4, not 0.

* Oops, make it build.

* Don't make it public.

* Revert whitespace change.

(cherry picked from commit 4638c98ba0)
2017-03-23 17:04:31 -04:00
Andi McClure 414feeffc7 Bump version to 5.0.0 2017-03-23 16:23:59 -04:00
Aleksey Kliger 06060e290d [reflection] Set correct reflected type in MonoMethod.get_base_method
It can be the case that we have two different System.MonoMethod objects that both
point to the same native MonoMethod* but have two different reflected types.
(For example if we call derivedType.GetMethod("f") where f is virtual and
derivedType corresponds to a class that did not override a base definition.  In
that case, the MonoMethod* corresponds to the parent type's f method, but the
reflected type is derivedType)

In this case, GetBaseDefinition will return the same MonoMethod* but the
reflected type of the result should be the base type, not the derived type.
2017-03-23 10:32:05 -04:00
Aleksey Kliger 37a593df33 [tests] Additional tests of System.Reflection.MethodInfo.GetBaseDefinition 2017-03-23 10:32:05 -04:00
Aaron Bockover c34e267b4c csharp: support command line arguments for scripts
This adds a command line argument preprocessor that splits command line
arguments into two groups, delimited by the "standard" `--` "stop
processing" argument, or by the `-s` argument which can be used with
Unix shebang syntax (where the path of the file being executed will
be appended to the command line specified on the shebang line).

- anything before `--` or `-s` will be passed to mcs/csharp as usual
- anything after `--` or `-s` will _not_ be processed by mcs/csharp,
  and will be made available in an `Args` builtin, like `csi`

This _finally_ (after almost 10 years) allows `csharp` to be used for
proper script authoring!

Document the new arguments in the man page. Also remove references to
'gsharp' from the man page.
2017-03-23 10:18:47 +01:00
Chris Hamons 582b140f7d AppleTls Support (#4470)
(cherry picked from commit 4d1e45d76a)
2017-03-23 00:10:39 +01:00
Marek Safar 16c75ce329 [xbuild] Copy csc/mcs GC settings to xbuild script 2017-03-22 23:14:39 +01:00
Zoltan Varga 72eabfe658 [ppdb] Avoid asserting on ppdb images without a guid heap. 2017-03-22 12:12:06 +01:00
Marek Safar c8e14aa2ea Bump cecil 2017-03-22 10:12:38 +01:00
Zoltan Varga ffcc54965d [runtime] Fix another typo in get_errno_from_g_file_error (). 2017-03-22 04:21:59 -04:00
Zoltan Varga 2d56aa09df [runtime] Fix a typo causing an assert in get_errno_from_g_file_error (). Fixes #53684. 2017-03-22 04:21:53 -04:00
Marek Safar ac26b00ca4 Fixes build 2017-03-21 01:30:46 +01:00
Marek Safar f77c835faf [System] Fix Process tests on watch 2017-03-20 23:58:18 +01:00
Marek Safar e319507866 [System.Core] Update mobile test 2017-03-20 23:09:47 +01:00
Rodrigo Kumpera cd5d8a9d1b Merge pull request #4553 from kumpera/backport-block-rebind-of-banned-assemblies
Backport of the rebind bans
2017-03-20 16:27:58 -04:00
Zoltan Varga 5eae4df2ee [arm64] Fix the DISABLE_JIT build. 2017-03-20 07:47:00 -04:00
Alexander Köplinger 9ecfd9f23a [WinForms] Fix test build 2017-03-18 03:17:31 +01:00
Zoltan Varga 37de1b5b0d [arm] Fix the DISABLE_JIT build. 2017-03-17 19:05:59 -04:00
Rodrigo Kumpera 68392d0c90 [runtime] Remove debug spew. 2017-03-17 13:31:47 -07:00
Rodrigo Kumpera 715991f427 [runtime] Remove debug leftover and have mono_assembly_is_problematic_version actually work. 2017-03-17 13:31:43 -07:00
Ankit Jain 503f379a22 Handle windows paths in ResXFileRef, for conversion to string case
- convert the path a little earlier to handle the case for conversion to
  string
- Fixes earlier commit a3195b79f6
- And enable the corresponding test
2017-03-17 15:22:32 -04:00
Ankit Jain a36202bfea Handle a file ref, with backslashes, in a .resx, on a non-windows system
File ref of the form:

```xml
  <data name="foo" type="System.Resources.ResXFileRef, System.Windows.Forms">
    <value>..\Resources\foo.json;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </data>
```
2017-03-17 15:22:23 -04:00
Rodrigo Kumpera bbf84b172e [tools] Dep check the downloads to avoid the mistake fixed by the previous commit. 2017-03-17 11:46:48 -07:00
Rodrigo Kumpera 62a0e75dd8 [runtime] Update the banned version list to include SRDP and SVT. 2017-03-17 11:46:47 -07:00
Rodrigo Kumpera 80e1e3a964 [tools] Update nuget-hash-extractor to spew the new ban table. 2017-03-17 11:46:43 -07:00
Rodrigo Kumpera 303981e264 [runtime] Reject rebinds that target one of the banned assemblies.
The matching is done by name and version. We don't check pubkey or MVID.
2017-03-17 11:45:59 -07:00
Marek Safar 05ff99fc73 [System] Add back empty MonoTouch namespace 2017-03-17 14:09:44 +01:00
Zoltan Varga 24e82a5385 [x86] Disable the usage of mono_lmf on android as a workaround. 2017-03-16 19:06:52 -04:00
Zoltan Varga cd2579f7ce [x86] Remove some incorrect code from method prologs which clobbers the return value. 2017-03-16 18:57:17 -04:00
Alexander Köplinger 760ac86dd9 Move target for creating monolite package to Mono
(cherry picked from commit 622840da56)
2017-03-16 21:49:18 +01:00
Alexander Köplinger 2b14612b1c Include Mono version in corlib version
This makes it possible to version the runtime<->corlib interface
for each version branch independently and fixes the problem
of monolite getting overwritten by changes in different branches
when corlib version is still the same.

We're moving definition of the corlib version into configure.ac
so we can more easily bake the Mono version into it.

(cherry picked from commit c0dd559ee4)
2017-03-16 21:49:12 +01:00
Alexander Köplinger 94ced23f9a Revert "Include Mono version in corlib version"
This reverts commit b600314281.

A better version is coming in the next commit.
2017-03-16 21:46:47 +01:00
Vlad Brezae 66905636c1 [sgen] Fix xmm scanning on mac x86 (#4521)
The MonoContext (which sgen scans) did not have its fpregs populated, even though we were fetching the fpstate.
2017-03-16 01:07:09 +02:00
Jon Purdy 2fb26892dc Fix XMM scanning on Mac x86.
MONO_CONTEXT_GET_CURRENT needed to be updated.
2017-03-16 01:07:04 +02:00
Zoltan Varga 4b62516d17 [simd] Fix some problems exposed by the corefx test suite. (#4531) 2017-03-15 05:13:16 -04:00
Zoltan Varga d78c35091b [jit] Add parameter type checks to the SIMD intrinsics to make sure we are handling the proper methods. Fixes #53278. (#4520) 2017-03-15 05:13:10 -04:00
Zoltan Varga 836896684c [arm64] Fix the saving/restoring of fp regs in exception filters, we were saving/restoring them from the incorrect position in MonoContext.fregs. (#4499) 2017-03-15 05:12:52 -04:00
Alexander Köplinger 9528721b39 [tools] Don't install mdb2ppdb by default (#4526)
(cherry picked from commit 294148d27d)
2017-03-14 19:41:37 +01:00
Andi McClure eff6063589 Move RunningOnUnix symbol outside #if MONO_FEATURE_PROCESS_START in test
Fixes build on Android
2017-03-14 11:17:31 -04:00
Alexander Köplinger b600314281 Include Mono version in corlib version
This makes it possible to version the runtime<->corlib interface
for each version branch independently and fixes the problem
of monolite getting overwritten by changes in different branches
when corlib version is still the same.
2017-03-14 02:19:17 +01:00
Marek Safar a5808f9c71 [corlib] FileStream::Name needs to include fully qualified normalized name. Fixes #53231 2017-03-12 10:00:22 +01:00
Marek Safar 785c82b5d1 [corlib][Mono.Posix] Remove NunitHelpers.cs reference 2017-03-10 14:52:07 -05:00
Rodrigo Kumpera dcc3c6090b Merge pull request #4498 from kumpera/backport-android-fix
[runtime] Make sure we use lower numbered signals on Android.
2017-03-09 14:13:01 -08:00
Rodrigo Kumpera 08f150b1d9 [runtime] Make sure we use lower numbered signals on Android.
Android on 32bits arm shipped broken headers that made sigset_t be 32 bits instead of 64.

This means that it's not possible to use signals whose value are >= 32. The default implementation
uses RT signals when available (and they are on Android). But RT signals don't work as expected
as their value is >= 32.

This fix hardcodes some safe signals on Android and add asserts about their values to avoid regressions.

See 5005c6f3fb for more details.
2017-03-09 13:19:23 -08:00
Zoltan Varga a417e02c2d [arm] Implement aot support for handler block trampolines. 2017-03-09 15:37:32 -05:00
Zoltan Varga 1a1d71d808 [arm64] Implement aot support for handler block trampolines. 2017-03-09 15:37:28 -05:00
Marek Habersack 152e22549b [mkbundle] Encode directory separator character on Windows (#4493)
When storing satellite assemblies, mkbundle prefixes their names with a
directory name derived from the language/locale of the assembly. It uses the
platform's default directory separator character which on Windows defaults to
'\' and that causes problems when building such a bundle on Windows since \ is
an escape sequence prefix inside strings and not escaping it with another \
leads to gcc errors when building the genrated source.

This commit fixes the problem by quoting the directory separator character
properly on Windows.

Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=52845
2017-03-09 10:32:43 -05:00
Ludovic Henry ae2e60c61c [process] Allocate a handle even for non-child processes (#4393) 2017-03-08 21:07:19 -05:00
Ludovic Henry 9f78eca1af [threads] Fix async call in coop (#4423)
We would observe crashes like the following:

```
 * Assertion at mono-threads.c:1009, condition `mono_thread_info_run_state (info) == STATE_ASYNC_SUSPENDED' not met

 Debug info from gdb:

 [New LWP 26793]
 [New LWP 26792]
 [Thread debugging using libthread_db enabled]
 Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
 0x00002b0ff3481ee9 in waitpid () from /lib/x86_64-linux-gnu/libpthread.so.0
   Id   Target Id         Frame
   3    Thread 0x2b0ff3e6c700 (LWP 26792) "SGen worker" 0x00002b0ff347e414 in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/x86_64-linux-gnu/libpthread.so.0
   2    Thread 0x2b0ff633e700 (LWP 26793) "Finalizer" 0x00002b0ff347e414 in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/x86_64-linux-gnu/libpthread.so.0
 * 1    Thread 0x2b0ff2b67c40 (LWP 26780) "mono" 0x00002b0ff3481ee9 in waitpid () from /lib/x86_64-linux-gnu/libpthread.so.0

 Thread 3 (Thread 0x2b0ff3e6c700 (LWP 26792)):
 #0  0x00002b0ff347e414 in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/x86_64-linux-gnu/libpthread.so.0
 #1  0x0000000000661bdf in mono_os_cond_wait (mutex=0x9dee40 <lock>, cond=0x9dee00 <work_cond>) at ../../mono/utils/mono-os-mutex.h:146
 #2  thread_func (thread_data=0x2b0ff2bcb008) at sgen-thread-pool.c:129
 #3  0x00002b0ff347a182 in start_thread () from /lib/x86_64-linux-gnu/libpthread.so.0
 #4  0x00002b0ff39a130d in clone () from /lib/x86_64-linux-gnu/libc.so.6

 Thread 2 (Thread 0x2b0ff633e700 (LWP 26793)):
 #0  0x00002b0ff347e414 in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/x86_64-linux-gnu/libpthread.so.0
 #1  0x00000000005caff3 in mono_os_cond_wait (mutex=<optimized out>, cond=<optimized out>) at ../../mono/utils/mono-os-mutex.h:146
 #2  mono_coop_cond_wait (mutex=<optimized out>, cond=<optimized out>) at ../../mono/utils/mono-coop-mutex.h:87
 #3  mono_threadpool_io_remove_socket (fd=134239440) at threadpool-io.c:628
 #4  0x00000000005ae4f4 in ves_icall_System_Net_Sockets_Socket_Close_internal (sock=42, werror=<optimized out>) at w32socket.c:708
 #5  0x0000000041e8101f in ?? ()
 #6  0x00002b1014abe070 in ?? ()
 #7  0x0000000001615860 in ?? ()
 #8  0x0000000001615860 in ?? ()
 #9  0x0000000000000000 in ?? ()

 Thread 1 (Thread 0x2b0ff2b67c40 (LWP 26780)):
 #0  0x00002b0ff3481ee9 in waitpid () from /lib/x86_64-linux-gnu/libpthread.so.0
 #1  0x00000000004ac5e6 in mono_handle_native_crash (signal=<optimized out>, ctx=<optimized out>, info=<optimized out>) at mini-exceptions.c:2557
 #2  <signal handler called>
 #3  0x00002b0ff38dcf79 in raise () from /lib/x86_64-linux-gnu/libc.so.6
 #4  0x00002b0ff38e0388 in abort () from /lib/x86_64-linux-gnu/libc.so.6
 #5  0x000000000066b459 in mono_log_write_logfile (log_domain=<optimized out>, level=<optimized out>, hdr=<optimized out>, message=<optimized out>) at mono-log-common.c:137
 #6  0x00000000006805e0 in monoeg_g_logv (log_domain=log_domain@entry=0x0, log_level=log_level@entry=G_LOG_LEVEL_ERROR, format=<optimized out>, args=args@entry=0x7ffc7324ea78) at goutput.c:115
 #7  0x0000000000680736 in monoeg_assertion_message (format=<optimized out>) at goutput.c:135
 #8  0x00000000006759b8 in mono_thread_info_setup_async_call (info=info@entry=0x2b0ff80008c0, target_func=target_func@entry=0x5bac20 <suspend_for_shutdown_async_call>, user_data=user_data@entry=0x0) at mono-threads.c:1009
 #9  0x00000000005bad50 in suspend_for_shutdown_critical (info=info@entry=0x2b0ff80008c0, unused=unused@entry=0x0) at threads.c:5019
 #10 0x00000000006763ae in mono_thread_info_safe_suspend_and_run (id=47347555100416, interrupt_kernel=interrupt_kernel@entry=0, callback=callback@entry=0x5bad40 <suspend_for_shutdown_critical>, user_data=user_data@entry=0x0) at mono-threads.c:979
 #11 0x00000000005c2e71 in mono_thread_internal_suspend_for_shutdown (thread=<optimized out>) at threads.c:5028
 #12 0x00000000005e9100 in mono_gc_cleanup () at gc.c:1015
 #13 0x00000000005e108e in mono_runtime_cleanup (domain=domain@entry=0x1615860) at appdomain.c:423
 #14 0x00000000004228cb in mini_cleanup (domain=0x1615860) at mini-runtime.c:4111
 #15 0x000000000047b99f in mono_main (argc=10, argv=<optimized out>) at driver.c:2167
 #16 0x00000000004200db in mono_main_with_options (argv=0x7ffc7324ef68, argc=10) at main.c:45
 #17 main (argc=10, argv=0x7ffc7324ef68) at main.c:338

 =================================================================
 Got a SIGABRT while executing native code. This usually indicates
 a fatal error in the mono runtime or one of the native libraries
 used by your application.
 =================================================================
```
2017-03-08 21:07:19 -05:00
Ludovic Henry 8cbef676c3 [threads] Ensure we have balanced appdomain push/pop when attaching the thread on shutdown (#4416) 2017-03-08 21:07:19 -05:00
Ludovic Henry 724c7df79c [threadpool] Do not swallow exception in RegisterWaitForSingleObject callback (#4408) 2017-03-08 21:07:19 -05:00
Ludovic Henry 15e53eba9b [socket] Fix bad parameter passed to select (#4390)
If fd is equals to FD_SETSIZE, then we pass (FD_SETSIZE + 1) as first parameter to select, making it return EINVAL.
2017-03-08 21:07:19 -05:00
Ludovic Henry 7323343a64 [socket] Fix race on SocketAsyncResult (#4389)
It might be possible that the callback modifies the current SocketAsyncResult via the Init method. We observe it with AcceptAsync with a ReceiveAsync in the callback.
2017-03-08 21:07:19 -05:00
Ludovic Henry c69dae3bcb [finalizer] Suspend finalizer thread on after shutdown timeout (#4363)
Fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=52429
2017-03-08 21:07:19 -05:00
Ludovic Henry 661495317c [threads] Make OSEvent alertable to fix bug #51653 (#4347) 2017-03-08 21:07:19 -05:00
Ludovic Henry 2415374524 [threads] Allow resetting the name of a threadpool thread (#4350)
Fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=47221
2017-03-08 21:07:19 -05:00
Zoltan Varga fa1030da6f [offsets-tool] Remove dependencies on android directory layout by adding a --targetdir=dir argument argument which points to the mono build directory corresponding to the target abi. Only allow one --abi= argument on android. (#4487) 2017-03-08 12:05:20 -05:00
Rodrigo Kumpera a17a84caee [loader] When loading the parent of a GTD fails. We must disable gclass recording for it.
mono_class_create_from_typedef: When loading a GTD, we track what ginsts' of it were loaded in the meanwhile
so we can fix some information that will be wrong (such as if it's a VT or not).

Were not stopping the recording when a GTD type failed to load its parent. This would result in *A LOT* of ginsts
being captured and would cause issues during domain unload.
2017-03-07 15:01:10 -08:00
Zoltan Varga 44560f1e67 [arm64] Fix the passing of small arguments on the stack in the gsharedvt trampoline, the calculation of their stack offset was incorrect in two places. Fixes #52866. 2017-03-07 01:54:09 -05:00
Zoltan Varga c52c4bd713 [jit] Remove an #ifdef ENABLE_LLVM from mini-os.h, the cross-compile genmdesc.pl can't handle it. 2017-03-06 15:56:21 -05:00
Zoltan Varga c8ca5929c7 [linker] Update the mscorlib descriptor with missing generic interfaces. 2017-03-06 15:56:21 -05:00
Zoltan Varga d60a36ee80 [ssa] Fix an assertion if the buffer used to keep renaming history gets full. 2017-03-06 15:56:21 -05:00
Zoltan Varga cee57b3c78 [runtime] Fix the reflected type of Delegate.Method if the method is an inherited virtual method. Fixes #39444. (#4353) 2017-03-06 15:56:21 -05:00
Zoltan Varga fe75a6ee2f [lldb] Avoid a crash with the mono_tramp_info_register () call in load_aot_module (). 2017-03-06 15:56:21 -05:00
Zoltan Varga 65956a952d [arm] Use TARGET_IOS instead of __APPLE__ so we don't use the ios abi when cross compiling from osx to android. 2017-03-06 15:56:21 -05:00
Andi McClure b6b7ce3eff Bump mono to 4.9.3 to force builders to pick up csc fixes 2017-03-06 13:06:31 -05:00
Alexander Köplinger e6409c5953 [cert-sync] Don't import into BTLS store if BTLS is not available (#4475)
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=53015
(cherry picked from commit fb4d198131)
2017-03-06 12:07:20 +01:00
Zoltan Varga 2cc99a1681 [jit] Fix an assert in mono_unwind_ops_encode_full () caused by an off-by-one error. Fixes #53066. 2017-03-06 02:33:17 -05:00
Zoltan Varga d8b4f5d2ab [runtime] Add fastpaths to the stelem wrappers for the case when the array element type and the value type are the same. (#4427) 2017-03-06 02:33:09 -05:00
Zoltan Varga 0c315e92b0 [runtime] Speed up mono_icall_start()/mono_icall_end() a bit by using inline versions of the MonoError functions. (#4424) 2017-03-06 02:33:09 -05:00
Zoltan Varga 5d7e4c9cf6 [runtime] Use mono_debug_method_lookup_location () instead of mono_debug_symfile_lookup_location (), the latter doesn't support portable pdb files. Use mono_debug_free_source_location () for freeing. Fixes #52899. (#4457)
(cherry picked from commit 4d7109cceb)
2017-03-05 00:15:26 +01:00
Vincent Povirk 23fb3fe800 [metadata] Fix a possible crash when looking up a p/invoke function. (#4471)
It's possible for two threads to modify the same MonoMethodPInvoke.addr
in mono_lookup_pinvoke_call, with one thread setting it to NULL inside the
loop, and the other thread having completed the loop and expecting it to
be non-NULL.

Use an intermediate variable to prevent addr becoming non-NULL.
2017-03-04 16:55:01 -05:00
Rodrigo Kumpera 679777b17b Merge pull request #4464 from kumpera/backport-4454-2017-02
Backport of #4454 to 2017-02
2017-03-02 21:10:14 -05:00
Zoltan Varga f0c0314e4d [runtime] Fix an infinite loop in the runtime class init code. (#4455)
The following can happen:
* Thread T1 starts initialization of C1
* Thread T2 starts initialization of C2
* T2 starts initialization of C1, it gets blocked on T1.
* T1 finishes initializing C1.
* T1 starts initialization of C3.
* T1 starts initialization of C2. It sees that T2 is
  still blocked on T1, but its not actually blocked, since
  C1 is finished. Still, we record that T1 is blocked.
* T3 starts initialization of C2, it gets into an infinite
  loop in the while loop, since the blocked_thread_hash
  now indicates that T1 and T2 are blocked on each other.

The solution is to not mark a thread as blocked, if its waiting
for a thread which is waiting on a finished lock. Fixes hangs
when running csc.
2017-03-02 17:02:28 -05:00
Rodrigo Kumpera 10ee1bafc9 [loader] Revert allowing SIOC 4.3. This is fine for now as we support LoadFrom as a work-around. 2017-03-02 11:48:07 -08:00
Rodrigo Kumpera bceca5b359 [loader] Pass LoadFrom down to image loading so we can make decisions based on that. 2017-03-02 11:47:29 -08:00
Rodrigo Kumpera 4560d3c57f Pass LoadFrom info down to assembly loading. 2017-03-02 11:47:29 -08:00
Rodrigo Kumpera 1c41089315 [runtime] SIOC 4.3.0 has a managed impl that works under mono. Don't ignore it. 2017-03-02 11:47:28 -08:00
Rodrigo Kumpera cb922c0fa6 Merge pull request #4442 from kumpera/fix-assembly-remapping-2017-02
Backport of #4440
2017-02-28 12:23:08 -08:00
Rodrigo Kumpera fe9c5ebe97 [runtime] Fix assembly remapping by using a hashtable. Fixes #52846 and #52743
In multiple occasions we had bugs due to framework_assemblies not being correctly sorted.

Instead of just fixing the ordering again, I'm moving it a hashtable so future generations won't have to fix this for System.SpaceTravel.dll.
2017-02-27 17:09:29 -08:00
Andi McClure 51403d818e Fix monodis
monodis was not calling the mono_tls_init_runtime_keys function, which
was causing it to crash the first time it attempted to access the
current domain (ie almost immediately).
2017-02-27 15:54:05 -05:00
Rodrigo Kumpera 459d47bb9b [jit] Fix LMF codegen on android arm64.
Android doesn't have fast tls either, so we must use the jit_tls variant.
2017-02-27 12:47:55 -08:00
Vlad Brezae 63dde6cce0 [threads] Don't ignore abort requests in abort protected blocks
Either interrupt or set the interrupt_deferred flag, so the thread can handle the request later in the future. Otherwise we are left with a thread that has an AbortRequested set on its state that it is never processed and future abort requests are ignored due to the presence of this flag.
2017-02-27 22:07:04 +02:00
Vlad Brezae 640d5a03e4 [sgen] Throw OOM also from the managed allocator
Allocation functions from object.c correctly throw OOM when sgen allocation returns NULL. When allocating with the managed allocator we invoke sgen directly (as a fallback) and we didn't handle the NULL return case.

Fixes #52437
2017-02-24 22:19:18 +02:00
Vlad Brezae 19b866517a [sgen] Rename confusing variable 2017-02-24 22:19:16 +02:00
Marek Safar 8953abc7d3 Fixes windows po/ build
(cherry picked from commit 8e7cae914b)
2017-02-24 16:35:45 +01:00
Marek Safar b78f4f6e5f [Mono.Data.Sqlite] Change default datetime convert format to excluded datetime kind. Fixes #46929 2017-02-24 16:19:49 +01:00
Alexander Köplinger 9bd54596bb Force LF line endings for .sources and Makefiles too
This should fix the Windows build.

(cherry picked from commit a7bed9a7fc)
2017-02-24 11:20:34 +01:00
Alexander Köplinger 74d31d88ef Fix Windows build due to line ending changes in sed
The recent sed update in cygwin [1] changed the way sed handles
carriage returns. This meant that every .in file we processed
still contained CR, which doesn't work for .sh files.

Force LF line endings for those files (and also other shell scripts).

[1] https://cygwin.com/ml/cygwin-announce/2017-02/msg00036.html

(cherry picked from commit 8d0e921d8b)
2017-02-24 11:20:26 +01:00
Zoltan Varga d66823b37b [runtime] Avoid holding the init lock while calling the cctor in mono_runtime_class_init (), its not needed any more. (#4361) 2017-02-23 17:57:03 -05:00
Zoltan Varga f01f6476b5 [arm] Fix the passing of structs with 8 byte alignment with llvm on armeabi, they need to be passed as an int64 array to let llvm know that it might need to insert a dummy argument so they are passed in a even register pair. Fixes #52548. 2017-02-22 15:09:23 -05:00
Zoltan Varga bcf75c0b8c [runtime] Use TARGET_WIN32 instead of HOST_WIN32 when setting calling conventions, so cross compilers running on windows do the right thing. (#4412) 2017-02-22 12:49:27 -05:00
Zoltan Varga 84b7173fcb [runtime] Fix mono_bitset_count () so it works on win64 as well. (#4413) 2017-02-22 12:48:11 -05:00
Marek Safar 2b673c3022 [System] Test fix for watch 2017-02-22 10:39:27 +01:00
Andi McClure ff9ce3b7ff Bump version number to 4.9.2 because of msbuild/xbuild compatibility changes. 2017-02-21 14:07:19 -05:00
Marek Safar 97056ba86a Bump cecil 2017-02-21 17:41:09 +01:00
Zoltan Varga ceaa04d0b8 [jit] Fix support for gsharedvt constrained calls which return enums. Fixes #52600. 2017-02-18 16:37:59 -05:00
Ankit Jain 87a92c89c2 [xbuild] Show the deprecation notice with logo, and so hide it with
`/nologo`. It is not controlled by logging levels now.
But we also show the deprecation notice if we couldn't parse
the arguments, which would be more likely to be noticed by a user.
2017-02-17 13:22:47 -05:00
Andi McClure de1a4a0229 Back out 6fbe05fe9, we will decide on version number format changes later 2017-02-17 11:58:00 -05:00
Ankit Jain 2f1bfa9788 [xbuild] Don't show the deprecation notice for minimal or quiet logging
.. levels. This is useful for scripts that might depend on minimal/quiet
levels, to parse output of a specific target execution, eg.
Xamarin.Android .
2017-02-16 17:08:06 -05:00
Ludovic Henry 6caddcd9d1 [socket] Add EPROTOTYPE error case (#4391)
Fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=52549
2017-02-16 14:07:49 +01:00
Rodrigo Kumpera 8a3e2b11e1 Merge pull request #4376 from kumpera/test-hardneing
Disable some flaky tests and harden another one.
2017-02-16 11:06:26 +01:00
Alexander Köplinger e2fa30543b [System] Fix failing ClientWebSocket test
The wrong part of the ifdef was deleted in a4df7d4923,
we need to InvalidOperationException instead of PNSE.

(cherry picked from commit ed685e8b76)
2017-02-16 03:57:33 +01:00
Marek Safar 8a113e88b3 [System] Fixes failing tests on mobile 2017-02-16 00:04:52 +01:00
Marek Safar d8e522c16c Revert "[Facades] Update netstandard facade to latest"
This reverts commit 171ba52158.
2017-02-15 17:45:50 +01:00
Alexander Köplinger e476b1ac33 [man] Remove outdated version numbers (#4382)
We haven't been consistent in keeping those version numbers
up to date as we bump Mono's version so it's less confusing
to not show them in the manual pages.

`mono --version` is and has been the source of truth.
(cherry picked from commit b117a53b8f)
2017-02-15 17:01:54 +01:00
Marek Safar 6fbe05fe9a Update version number 2017-02-15 13:19:47 +01:00
Marek Safar 440cd5475c [Mono.CodeContracts] Read debug symbols only when they are going to be used 2017-02-15 13:05:21 +01:00
Marek Safar dc34ec682c Cecil update 2017-02-15 13:04:49 +01:00
Alexander Köplinger 9deeb95816 [System.ServiceModel.Internals] Use the mobile sources for testing_aot_full and orbis profile (#4378)
(cherry picked from commit 17c5a00c59)
2017-02-14 22:14:10 +01:00
Alexander Köplinger 171ba52158 [Facades] Update netstandard facade to latest
Includes latest changes from dotnet/standard repo.

(cherry picked from commit 4e54ac3d4b)
2017-02-14 03:43:30 +01:00
Marek Safar 4393b68452 [System.Net.Http] Allow re-sending StreamContent. Fixes #52448 2017-02-13 22:39:10 +01:00
Zoltan Varga 76da2e9ed8 [jit] Disable llvm for overly complex methods, to avoid compilation slowdowns. Fixes #52475. 2017-02-13 14:46:37 -05:00
Marek Safar 5006bcc901 [System] Fixes failing tests on watch 2017-02-13 12:50:48 +01:00
Martin Baulig 50c26943d4 [btls]: Partial merge of #4318 and #4337. (#4345)
* [btls]: Partial merge of #4318 and #4337.

Partially merged commits 4ecb683 and 4c6c6f0 from master without adding
'MonoTlsSettings.CertificateSearchPath'.

* Add MonoBtlsProvider.SetupCertificateStore(MonoBtlsX509Store,MonoTlsSettings,bool)
  overload, which adds 'settings.TrustAnchors' if applicable.

* MonoBtlsContext: call it instead of having our own custom implementation.

* [btls]: Fix MonoBtlsX509Store.cs.AddTrustedRoots(). (#4340)

This internal method is only called from Mono.Btls.Interface.BtlsStore
and used by the web-tests.

Call MonoBtlsProvider.SetupCertificateStore(store) to make its
behavior consistent with the internal implementation.
(cherry picked from commit 8b18c84289)

* [btls]: Partial merge of #4318, #4337 and #4340.

Partially merged commits 4ecb683, 4c6c6f0 and 8b18c84 from master
(without adding 'MonoTlsSettings.CertificateSearchPath').

* Add MonoBtlsProvider.SetupCertificateStore(MonoBtlsX509Store,MonoTlsSettings,bool)
  overload, which adds 'settings.TrustAnchors' if applicable.

* MonoBtlsContext: call it instead of having our own custom implementation.

* Fix MonoBtlsX509Store.cs.AddTrustedRoots(). (#4340)

  This internal method is only called from Mono.Btls.Interface.BtlsStore
  and used by the web-tests. Call MonoBtlsProvider.SetupCertificateStore(store)
  to make its behavior consistent with the internal implementation.
2017-02-13 11:25:02 +01:00
Marek Safar 5596255efe Bump roslyn to rc4 2017-02-13 09:24:18 +01:00
Alexander Köplinger a41069ad76 [tools] Install pdb files for security tools (#4364)
We don't use the global executable.make install logic for the tools
in security so we missed updating this to copy .pdb's as well.
(cherry picked from commit b17ddc5c15)
2017-02-10 20:56:38 +01:00
Alexander Köplinger f70bda0c06 [Mono.Security] Check NewLocalMachinePath too for deciding if store is machine store (#4357)
The code in X509Store only checked the legacy X509StoreManager.LocalMachinePath
when deciding whether CspProviderFlags.UseMachineKeyStore should be
set when dealing with private keys.

However, with BTLS we now also have X509StoreManager.NewLocalMachinePath.

This caused an issue/regression in the recent 4.8 builds that
started importing into the BTLS cert store when using cert-sync:
https://github.com/mono/mono/commit/968c60a0f32c7a4c92568c3feda7503f99b98c94

Because cert-sync is ran at package installation time as root
on Linux we would erroneously not pass UseMachineKeyStore (because
the paths between legacy and BTLS store are different), which in turn
causes KeyPairPersistence to look into the user directory, e.g.
~/.config/.mono/keypairs. Since on a clean machine that directory
hierarchy doesn't exist, it goes on and creates it -> we now have
the ~/.config directory owned by root which means a normal user
application can't write to it anymore (like NuGet) and crashes.

The fix is to check for the BTLS store path as well so KeyPairPersistence
uses the machine path and ~/.config is not created on package installation.

See e.g. https://github.com/travis-ci/travis-ci/issues/7271
(cherry picked from commit 12b44a0e94)
2017-02-09 18:31:30 +01:00
Alexander Köplinger 3ed19e6630 [ci] Temporarily use http url to download server until cert is fixed
(cherry picked from commit 9281d4a7e6)
2017-02-09 18:29:33 +01:00
Ludovic Henry f404e04d6d [process] Fix Process.GetProcessesByName (#4351)
To get a process by name, we need to access the other process ProcessName, but it can fails on non-win32 platforms. This failure wouldn't be caught in the referencesource implementation trigerring this bug.

The exception we would observe would be:
 Unhandled Exception:
 System.InvalidOperationException: Process has exited, so the requested information is not available.
   at System.Diagnostics.Process.get_ProcessName () [0x0002d] in /Users/alexander/dev/mono/mcs/class/System/System.Diagnostics/Process.cs:336
   at (wrapper remoting-invoke-with-check) System.Diagnostics.Process:get_ProcessName ()
   at Program.Main (System.String[] args) [0x0003b] in <9c838a66cdc44c81b38c974edcc9c029>:0
 [ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidOperationException: Process has exited, so the requested information is not available.
   at System.Diagnostics.Process.get_ProcessName () [0x0002d] in /Users/alexander/dev/mono/mcs/class/System/System.Diagnostics/Process.cs:336
   at (wrapper remoting-invoke-with-check) System.Diagnostics.Process:get_ProcessName ()
   at Program.Main (System.String[] args) [0x0003b] in <9c838a66cdc44c81b38c974edcc9c029>:0

Fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=52345
2017-02-09 11:45:10 +01:00
Marek Safar 6019eeb483 [xbuild] Add deprecation warning 2017-02-07 23:29:40 +01:00
Martin Baulig e37d7a2ce9 [btls]: MonoBtlsError.GetError(out string, out int) returns 0, not null. (#4338)
(cherry picked from commit d3aa5f9504)
2017-02-07 22:28:16 +01:00
Zoltan Varga 2440b14865 [runtime] Add a workaround for #50529 by locking around pthread_create()/pthread_join () calls so they can't happen at the same time. (#4332) 2017-02-07 16:14:32 -05:00
Ludovic Henry 4f4cb919cf [threadpool] Fix hang on threadpool cleanup (#4331)
Waiting for the threadpool threads to exit on shutdown triggers a hand. The simplest solution is to not wait for them, and let the general runtime shutdown mechanism wait for them (see `mono_thread_manage`).
2017-02-07 15:13:12 -05:00
Marek Safar 42a5eeb95a Bump cecil 2017-02-07 17:53:26 +01:00
Marek Safar b65e5ee577 [corlib] Update TimeZoneTest ios simulator check 2017-02-07 10:23:02 +01:00
Vlad Brezae 672282c892 [sgen] Don't assert when suspending detaching thread (#4292)
This means that the thread will be part of the stw (not skipped), so if the stack pointer is not between the expected ranges we dont scan the thread. In other parts of the runtime, suspending here is handled by the suspend_can_continue flag.
2017-02-06 21:25:22 +02:00
274 changed files with 6805 additions and 1378 deletions

No files matched your search

+3 -4
View File
@@ -4,6 +4,9 @@ config.rpath crlf=input
configure.host crlf=input
mkinstalldirs crlf=input
*.sh crlf=input
*.sources crlf=input
.gitattributes crlf=input
*akefile* crlf=input
# ensure native line endings on checkout
*.c crlf
@@ -11,10 +14,6 @@ mkinstalldirs crlf=input
*.cs crlf
*.il crlf
.gitattributes crlf
*akefile* crlf
*.sources crlf
# don't do anything to line-endings. Let CRLFs go into the repo, and CRLF on checkout
*.bat -crlf
*.sln -crlf
+1
View File
@@ -7,6 +7,7 @@
[submodule "external/cecil"]
path = external/cecil
url = git://github.com/mono/cecil.git
branch = mono-2017-02
[submodule "external/rx"]
path = external/rx
url = git://github.com/mono/rx.git
+5 -13
View File
@@ -44,10 +44,6 @@ dist-hook:
rm -rf `find $(top_distdir)/external -path '*\.git'`
rm -f `find $(top_distdir)/external -path '*\.exe' -not -path '*/roslyn-binaries/*'`
rm -f `find $(top_distdir)/external -path '*\.dll' -not -path '*/binary-reference-assemblies/*' -not -path '*/roslyn-binaries/*'`
cp mcs/class/lib/basic/System.Configuration.dll mcs/class/lib/monolite/
cp mcs/class/lib/basic/System.Security.dll mcs/class/lib/monolite/
# Disable this for now because it is very slow and causes wrench to timeout:
# test ! -d $(GIT_DIR) || ./scripts/commits-to-changelog.py --root=$(distdir) last-commit-with-compulsory-changelog-entry
mac-sdk-package:
external/bockbuild/bb MacSDK --package
@@ -58,17 +54,13 @@ DISTCLEANFILES= mono-uninstalled.pc
# building with monolite
mcslib = $(mcs_topdir)/class/lib
monolite = $(mcslib)/monolite
mono_corlib_version = $(shell sed -n "s/\#define MONO_CORLIB_VERSION //p" $(srcdir)/mono/metadata/appdomain.c)
monolite_url = http://download.mono-project.com/monolite/monolite-$(mono_corlib_version)-latest.tar.gz
monolite_url = https://download.mono-project.com/monolite/monolite-$(MONO_CORLIB_VERSION)-latest.tar.gz
.PHONY: get-monolite-latest
get-monolite-latest:
-rm -fr $(mcslib)/monolite-*
-mkdir -p $(mcslib)
test ! -d $(monolite) || test ! -d $(monolite).old || rm -fr $(monolite).old
test ! -d $(monolite) || mv -f $(monolite) $(monolite).old
cd $(mcslib) && { (wget -O- $(monolite_url) || curl $(monolite_url)) | gzip -d | tar xf - ; }
cd $(mcslib) && mv -f monolite-* monolite
-rm -fr $(mcslib)/monolite/$(MONO_CORLIB_VERSION)
-mkdir -p $(mcslib)/monolite
cd $(mcslib) && { (wget -O- $(monolite_url) || curl -L $(monolite_url)) | gzip -d | tar xf - ; }
cd $(mcslib) && mv -f monolite-* monolite/$(MONO_CORLIB_VERSION)
if BITCODE
BITCODE_CHECK=yes
+20 -2
View File
@@ -1,8 +1,7 @@
# Process this file with autoconf to produce a configure script.
#AC_PREREQ([2.62])
# when bumping version number below, keep it in sync with man/mono.1 too
AC_INIT(mono, [4.9.0],
AC_INIT(mono, [5.0.1],
[http://bugzilla.xamarin.com/enter_bug.cgi?classification=Mono])
AC_CONFIG_SRCDIR([README.md])
@@ -29,6 +28,24 @@ AC_PROG_LN_S
m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])
MONO_VERSION_MAJOR=`echo $VERSION | cut -d . -f 1`
MONO_VERSION_MINOR=`echo $VERSION | cut -d . -f 2`
MONO_VERSION_BUILD=`echo $VERSION | cut -d . -f 3`
# This is the version number of the corlib-runtime interface. When
# making changes to this interface (by changing the layout
# of classes the runtime knows about, changing icall signature or
# semantics etc), increment this variable.
#
# 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=0
MONO_CORLIB_VERSION=`printf "1%02d%02d%02d%03d" $MONO_VERSION_MAJOR $MONO_VERSION_MINOR $MONO_VERSION_BUILD $MONO_CORLIB_COUNTER`
AC_DEFINE_UNQUOTED(MONO_CORLIB_VERSION,$MONO_CORLIB_VERSION,[Version of the corlib-runtime interface])
AC_SUBST(MONO_CORLIB_VERSION)
case $host_os in
*cygwin* )
echo "Run configure using ./configure --host=i686-pc-mingw32"
@@ -4504,6 +4521,7 @@ fi
}')]
echo "MONO_VERSION = $myver" >> $mcs_topdir/build/config.make
echo "MONO_CORLIB_VERSION = $MONO_CORLIB_VERSION" >> $mcs_topdir/build/config.make
if test x$host_darwin = xyes; then
echo "PLATFORM = darwin" >> $mcs_topdir/build/config.make
+3
View File
@@ -0,0 +1,3 @@
check-coverage crlf=input
check-exports crlf=input
produce-lists crlf=input
+2 -1
View File
@@ -160,7 +160,8 @@ typedef struct _GMemChunk GMemChunk;
* Misc.
*/
const gchar * g_getenv(const gchar *variable);
gboolean g_hasenv(const gchar *variable);
gchar * g_getenv(const gchar *variable);
gboolean g_setenv(const gchar *variable, const gchar *value, gboolean overwrite);
void g_unsetenv(const gchar *variable);
+50 -4
View File
@@ -39,23 +39,69 @@
#include <unistd.h>
#endif
static pthread_mutex_t env_lock = PTHREAD_MUTEX_INITIALIZER;
const gchar *
g_getenv(const gchar *variable)
/* MONO Comment
*
* As per the UNIX spec,
* "The return value from getenv() may point to static data which may be overwritten by subsequent calls to getenv(), setenv(), or unsetenv()."
* Source: Unix Manual Pages for getenv, IEEE Std 1003.1
*
* This means that using pointers returned from getenv may (and does) lead to many
* pointers which refer to the same piece of memory. When one is freed, all will be freed.
*
* This is unsafe and an ergonomics risk to fix in the callers. While the caller could lock,
* this introduces the risk for looping or exiting while inside of a lock. For this reason,
* g_getenv does not mimic the behavior of POSIX getenv anymore.
*
* The memory address returned will be unique to the invocaton, and must be freed.
* */
gchar *
g_getenv (const gchar *variable)
{
return getenv(variable);
gchar *ret = NULL;
pthread_mutex_lock (&env_lock);
gchar *res = getenv(variable);
if (res)
ret = g_strdup(res);
pthread_mutex_unlock (&env_lock);
return ret;
}
/*
* This function checks if the given variable is non-NULL
* in the environment. It's useful because it removes memory
* freeing requirements.
*
*/
gboolean
g_hasenv (const gchar *variable)
{
pthread_mutex_lock (&env_lock);
gchar *res = getenv(variable);
gboolean not_null = (res != NULL);
pthread_mutex_unlock (&env_lock);
return not_null;
}
gboolean
g_setenv(const gchar *variable, const gchar *value, gboolean overwrite)
{
return setenv(variable, value, overwrite) == 0;
gboolean res;
pthread_mutex_lock (&env_lock);
res = (setenv(variable, value, overwrite) == 0);
pthread_mutex_unlock (&env_lock);
return res;
}
void
g_unsetenv(const gchar *variable)
{
pthread_mutex_lock (&env_lock);
unsetenv(variable);
pthread_mutex_unlock (&env_lock);
}
gchar*
+7 -1
View File
@@ -39,7 +39,13 @@
#include <io.h>
#include <assert.h>
const gchar *
gboolean
g_hasenv (const gchar *variable)
{
return g_getenv (variable) != NULL;
}
gchar *
g_getenv(const gchar *variable)
{
gunichar2 *var, *buffer;
+1 -1
+1 -1
+57 -18
View File
@@ -2,31 +2,22 @@
.if t .sp .5v
.if n .sp
..
.TH csharp 1 "4 September 2008"
.TH csharp 1 "22 March 2017"
.SH NAME
csharp, gsharp \- Interactive C# Shell
csharp \- Interactive C# Shell and Scripting
.SH SYNOPSIS
.B csharp [--attach PID] [-e EXPRESSION] [file1 [file2]]
[options]
.P
.B gsharp [file1 [file2]]
[compiler-options] [--|-s script-options]
.SH DESCRIPTION
The
.I csharp
is an interactive C# shell that allows the user to enter and evaluate
C# statements and expressions from the command line. The regular
command is an interactive C# shell and scripting host that allows
the user to enter and evaluate C# statements and expressions from
the command line or execute C# scripts.
The regular
.I mcs
command line options can be used in this version of the compiler.
.PP
The
.I gsharp
command is a GUI version of the C# interpreter that uses Gtk# and
provides an area to attach widgets as well. This version can be
attached to other Gtk# applications in a safe way as it injects itself
into the main loop of a Gtk# application, avoiding any problems
arising from the multi-threaded nature of injecting itself into a
target process.
.PP
Files specified in the command line will be loaded and executed as
scripts.
.PP
@@ -35,9 +26,31 @@ Starting with Mono 2.10, the
command can be used as an interpreter executed by executables flagged
with the Unix execute attribute. To do this, make the first line of
your C# source code look like this:
.PP
.nf
"#!/usr/bin/csharp"
Console.WriteLine ("Hello, World");
#!/usr/bin/csharp
Console.WriteLine ("Hello, World");
.fi
.PP
Starting with Mono 5.0, command line arguments may now be passed
to the
.I csharp
command by specifying either the
.I -s
or
.I --
(script) options.
.PP
The
.I -s
option is ideal for interpreting executable scripts that utilize
shebang syntax (introduced in Mono 2.10). This allows command line
arguments to be passed to and consumed cleanly by the script:
.PP
.nf
#!/usr/bin/csharp -s
foreach (var arg in Args)
Console.WriteLine ($"script argument: {arg}");
.fi
.SH OPTIONS
The commands accept all of the commands that are available to the
@@ -45,6 +58,23 @@ The commands accept all of the commands that are available to the
command, so you can reference assemblies, specify paths, language
level and so on from the command line. In addition, the following
command line options are supported:
.TP
.I "\-s" SCRIPT_FILE
This option is ideal for authoring executable scripts that utilize
the Unix shebang feature. Unix will implicitly append as an argument
the path of the script to execute. When the executable is invoked,
any arguments then passed to it will be available in the
.I Args
global. Example:
.I "#!/usr/bin/env csharp -s"
.TP
.I "\-\-"
Any arguments that follow will not be passed to the compiler driver,
and instead will be made available in the
.I Args
global. Example:
.I csharp -- a b c
will result in Args = { "a", "b", "c" } in the interactive shell.
.TP
.I "\-\-attach"
This is an advanced option and should only be used if you have a deep
@@ -290,6 +320,15 @@ statements and expressions are executed are static, they can be
invoked directly from the shell. These are the available properties
and methods:
.TP
.I Args
An easy to consume array of any arguments specified after either
.I -s
or
.I --
on the command line. Ideal for self-executing scripts utilizing the
.I -s
option.
.TP
.I void LoadAssembly(string assembly)
Loads the given assembly. This is equivalent to passing the compiler
the -r: flag with the specified string.
+1 -1
View File
@@ -8,7 +8,7 @@
.if t .sp .5v
.if n .sp
..
.TH gacutil "Mono 1.0"
.TH Mono "gacutil"
.SH NAME
gacutil \- Global Assembly Cache management utility.
.SH SYNOPSIS
+1 -1
View File
@@ -9,7 +9,7 @@
.if t .sp .5v
.if n .sp
..
.TH lc "Mono 2.6"
.TH Mono "lc"
.SH NAME
lc \- Mono License Compiler
.SH SYNOPSIS
+1 -1
View File
@@ -8,7 +8,7 @@
.if t .sp .5v
.if n .sp
..
.TH macpack "Mono 1.0"
.TH Mono "macpack"
.SH NAME
macpack \- Macintosh OS X Packager for managed gui assemblies
.SH SYNOPSIS
+2 -2
View File
@@ -1,8 +1,8 @@
.\"
.\" mono manual page.
.\" mdb2ppdb manual page.
.\" Copyright 2017 Microsoft
.\"
.TH Mono "Mono 4.8.0"
.TH Mono "mdb2ppdb"
.SH NAME
mdb2ppdb \- Convert Mono's debug file format (MDB) to Portable Program
Database (PPDB) file formatn
+1 -1
View File
@@ -8,7 +8,7 @@
.if t .sp .5v
.if n .sp
..
.TH mkbundle "mkbundle 1.0"
.TH Mono "mkbundle"
.SH NAME
mkbundle, mkbundle2 \- Creates a bundled executable.
.SH SYNOPSIS
+1 -1
View File
@@ -5,7 +5,7 @@
.\" Miguel de Icaza ([email protected])
.\" Paolo Molaro ([email protected])
.\"
.TH Mono "Mono 1.0"
.TH Mono "mono-config"
.SH NAME
mono-config \- Mono runtime file format configuration
.SH DESCRIPTION
+1 -1
View File
@@ -8,7 +8,7 @@
.if t .sp .5v
.if n .sp
..
.TH Mono "Mono 1.0"
.TH Mono "mono-service"
.SH NAME
mono-service, mono-service2 \- Mono ServiceProcess host
.SH SYNOPSIS
+1 -1
View File
@@ -9,7 +9,7 @@
.if t .sp .5v
.if n .sp
..
.TH mono-xmltool "Mono 1.0"
.TH Mono "mono-xmltool"
.SH NAME
mono-xmltool \- Mono XML validation and transformation tool.
.SH SYNOPSIS
+95 -27
View File
@@ -7,7 +7,7 @@
.\" Author:
.\" Miguel de Icaza ([email protected])
.\"
.TH Mono "Mono 4.7.0"
.TH Mono "mono"
.SH NAME
mono \- Mono's ECMA-CLI native code generator (Just-in-Time and Ahead-of-Time)
.SH SYNOPSIS
@@ -104,11 +104,6 @@ than one can be specified:
.RS
.ne 8
.TP
.I autoreg
The AOT compiler will emit a (ELF only) library initializer to automatically
register the aot compiled module with the runtime. This is only useful in static
mode
.TP
.I asmonly
Instructs the AOT compiler to output assembly code instead of an
object file.
@@ -118,11 +113,6 @@ object file.
If specified, forces the generated AOT files to be bound to the
runtime version of the compiling Mono. This will prevent the AOT
files from being consumed by a different Mono runtime.
.I full
.Sp
This is currently an experimental feature as it is not complete.
This instructs Mono to precompile code that has historically not been
precompiled with AOT.
.TP
.I data-outfile=FILE.dll.aotdata
.Sp
@@ -134,10 +124,59 @@ on demand by using the
.I mono_install_load_aot_data_hook
method.
.TP
.I direct-icalls
.Sp
When this option is specified, icalls (internal calls made from the
standard library into the mono runtime code) are invoked directly
instead of going through the operating system symbol lookup operation.
This requires use of the
.I static
option.
.TP
.I direct-pinvoke
.Sp
When this option is specified, P/Invoke methods are invoked directly
instead of going through the operating system symbol lookup operation.
This requires use of the
.I static
option.
.TP
.I dwarfdebug
Instructs the AOT compiler to emit DWARF debugging information. When
used together with the nodebug option, only DWARF debugging
information is emitted, but not the information that can be used at
runtime.
.TP
.I full
.Sp
This creates binaries which can be used with the --full-aot option.
.TP
.I hybrid
.Sp
This creates binaries which can be used with the --hybrid-aot option.
.TP
.I llvm
AOT will be performed with the LLVM backend instead of the Mono backend where possible. This will be slower to compile but most likely result in a performance improvement.
.TP
.I llvmonly
AOT will be performed with the LLVM backend exclusively and the Mono backend will not be used. The only output in this mode will be the bitcode file normally specified with the
.I llvm-outfile
option. Use of
.I llvmonly
automatically enables the
.I full
and
.I llvm
options. This feature is experimental.
.TP
.I llvm-outfile=[filename]
Gives the path for the temporary LLVM bitcode file created during AOT.
.TP
.I info
Print the architecture the AOT in this copy of Mono targets and quit.
.TP
.I ld-flags
Additional flags to pass to the C linker (if the current AOT mode calls for invoking it).
.TP
.I llvm-path=<PREFIX>
Same for the llvm tools 'opt' and 'llc'.
@@ -156,7 +195,12 @@ llc compiler.
.I nimt-trampolines=[number]
When compiling in full aot mode, the IMT trampolines must be precreated
in the AOT image. You can add additional method trampolines with this argument.
Defaults to 128.
Defaults to 512.
.TP
.I ngsharedvt-trampolines=[number]
When compiling in full aot mode, the value type generic sharing trampolines must be precreated
in the AOT image. You can add additional method trampolines with this argument.
Defaults to 512.
.TP
.I nodebug
Instructs the AOT compiler to not output any debugging information.
@@ -166,23 +210,22 @@ This prevents the AOT compiler from generating a direct calls to a
method. The AOT compiler usually generates direct calls for certain
methods that do not require going through the PLT (for example,
methods that are known to not require a hook like a static
constructor) or call into simple internal calls.
.TP
.I dwarfdebug
Instructs the AOT compiler to emit DWARF debugging information. When
used together with the nodebug option, only DWARF debugging
information is emitted, but not the information that can be used at
runtime.
constructor) or call into simple internal calls.
.TP
.I nrgctx-trampolines=[number]
When compiling in full aot mode, the generic sharing trampolines must be precreated
in the AOT image. You can add additional method trampolines with this argument.
Defaults to 1024.
Defaults to 4096.
.TP
.I nrgctx-fetch-trampolines=[number]
When compiling in full aot mode, the generic sharing fetch trampolines must be precreated
in the AOT image. You can add additional method trampolines with this argument.
Defaults to 128.
.TP
.I ntrampolines=[number]
When compiling in full aot mode, the method trampolines must be precreated
in the AOT image. You can add additional method trampolines with this argument.
Defaults to 1024.
Defaults to 4096.
.TP
.I outfile=[filename]
Instructs the AOT compiler to save the output to the specified file.
@@ -191,6 +234,16 @@ Instructs the AOT compiler to save the output to the specified file.
If the AOT compiler cannot compile a method for any reason, enabling this flag
will output the skipped methods to the console.
.TP
.I profile=[file]
Specify a file to use for profile-guided optimization. See the "AOT PROFILING" section. To specify multiple files, include the
.I profile
option multiple times.
.TP
.I profile-only
AOT *only* the methods described in the files specified with the
.I profile
option. See the "AOT PROFILING" section.
.TP
.I readonly-value=namespace.typename.fieldname=type/value
Override the value of a static readonly field. Usually, during JIT
compilation, the static constructor is ran eagerly, so the value of
@@ -203,7 +256,6 @@ Note that signed/unsigned numbers do not matter here, just the storage size.
This option can be specified multiple times and it doesn't prevent the static
constructor for the type defining the field to execute with the usual rules
at runtime (hence possibly computing a different value for the field).
.TP
.I save-temps,keep-temps
Instructs the AOT compiler to keep temporary files.
@@ -232,6 +284,9 @@ mono_aot_register_module (mono_aot_module_hello_info);
.I stats
Print various stats collected during AOT compilation.
.TP
.I temp_path=[path]
Explicitly specify path to store temporary files created during AOT compilation.
.TP
.I threads=[number]
This is an experimental option for the AOT compiler to use multiple threads
when compiling the methods.
@@ -241,8 +296,11 @@ Prepends <PREFIX> to the name of tools ran by the AOT compiler, i.e. 'as'/'ld'.
example, --tool=prefix=arm-linux-gnueabi- will make the AOT compiler run
'arm-linux-gnueabi-as' instead of 'as'.
.TP
.I write-symbols
Instructs the AOT compiler to emit debug symbol information.
.I verbose
Prints additional information about type loading failures.
.TP
.I write-symbols,no-write-symbols
Instructs the AOT compiler to emit (or not emit) debug symbol information.
.PP
For more information about AOT, see: http://www.mono-project.com/docs/advanced/aot/
.RE
@@ -318,10 +376,12 @@ the heap as much as possible at the expense of slowing down garbage
collection a bit.
.TP
\fB--full-aot\fR
This is an experimental flag that instructs the Mono runtime to not
This flag instructs the Mono runtime to not
generate any code at runtime and depend exclusively on the code
generated from using mono --aot=full previously. This is useful for
platforms that do not permit dynamic code generation.
generated from using mono --aot=full previously. This is useful for
platforms that do not permit dynamic code generation, or if you need
to run assemblies that have been stripped of IL (for example using
mono-cil-strip).
.Sp
Notice that this feature will abort execution at runtime if a codepath
in your program, or Mono's class libraries attempts to generate code
@@ -351,6 +411,14 @@ will switch to '/bin/mono64' iff '/bin/mono' is a 32-bit build).
\fB--help\fR, \fB-h\fR
Displays usage instructions.
.TP
\fB--hybrid-aot\fR
This flag allows the Mono runtime to run assemblies
that have been stripped of IL, for example using mono-cil-strip. For this to
work, the assembly must have been AOT compiled with --aot=hybrid.
This flag is similar to --full-aot, but it does not disable the JIT. This means
you can use dynamic features such as System.Reflection.Emit.
.TP
\fB--llvm\fR
If the Mono runtime has been compiled with LLVM support (not available
in all configurations), Mono will use the LLVM optimization and code
+1 -1
View File
@@ -8,7 +8,7 @@
.if t .sp .5v
.if n .sp
..
.TH resgen "resgen 1.0"
.TH Mono "resgen"
.SH NAME
resgen, resgen2 \- Mono/CLI Resource Generator
.SH SYNOPSIS
+1
View File
@@ -1,2 +1,3 @@
/LICENSE.MSPL -crlf
/ScalableMonoIcon.svg -crlf
/winexe.in crlf=input
+2 -1
View File
@@ -12,7 +12,8 @@ clean-local:
common/Consts.cs: common/Consts.cs.in $(wildcard config.make)
test -n '$(MONO_VERSION)'
sed -e 's,@''MONO_VERSION@,$(MONO_VERSION),' $< > $@
test -n '$(MONO_CORLIB_VERSION)'
sed -e 's,@''MONO_VERSION@,$(MONO_VERSION),' -e 's,@''MONO_CORLIB_VERSION@,$(MONO_CORLIB_VERSION),' $< > $@
PLATFORMS = darwin linux win32
PROFILES = \
+1
View File
@@ -38,6 +38,7 @@ static class Consts
public const string MonoCompany = "Mono development team";
public const string MonoProduct = "Mono Common Language Infrastructure";
public const string MonoCopyright = "(c) Various Mono authors";
public const int MonoCorlibVersion = @MONO_CORLIB_VERSION@;
#if MOBILE
// Versions of .NET Framework for Silverlight 4.0
+2 -2
View File
@@ -1,12 +1,12 @@
# -*- makefile -*-
#
# Platform-specific makefile rules. This one's for linux.
# Platform-specific makefile rules. This one's for macOS.
#
PLATFORM_MCS_FLAGS =
PLATFORM_RUNTIME = $(RUNTIME)
PLATFORM_CORLIB = mscorlib.dll
PLATFORM_TEST_HARNESS_EXCLUDES = NotOnMac,
PLATFORM_TEST_HARNESS_EXCLUDES = NotOnMac,MacNotWorking,
EXTERNAL_MCS = mcs
EXTERNAL_MBAS = mbas
+9 -8
View File
@@ -1,15 +1,17 @@
# -*- makefile -*-
with_mono_path_monolite = MONO_PATH="$(topdir)/class/lib/monolite$(PLATFORM_PATH_SEPARATOR)$(topdir)/class/lib/monolite/Facades$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH"
monolite_path := $(topdir)/class/lib/monolite/$(MONO_CORLIB_VERSION)
with_mono_path_monolite = MONO_PATH="$(monolite_path)$(PLATFORM_PATH_SEPARATOR)$(monolite_path)/Facades$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH"
monolite_flag := $(depsdir)/use-monolite
use_monolite := $(wildcard $(monolite_flag))
MONOLITE_MSCORLIB = $(topdir)/class/lib/monolite/mscorlib.dll
MONOLITE_MSCORLIB = $(monolite_path)/mscorlib.dll
ifdef use_monolite
ifdef MCS_MODE
CSC_LOCATION = $(topdir)/class/lib/monolite/mcs.exe
CSC_LOCATION = $(monolite_path)/mcs.exe
endif
PROFILE_RUNTIME = $(with_mono_path_monolite) $(RUNTIME)
@@ -79,8 +81,7 @@ do-profile-check: $(depsdir)/.stamp
$(MAKE) $(MAKE_Q) do-profile-check-monolite ; \
else \
echo "*** The runtime '$(PROFILE_RUNTIME)' doesn't appear to be usable." 1>&2; \
echo "*** You need Mono version 4.8 or better installed to build MCS" 1>&2 ; \
echo "*** Check mono README for information on how to bootstrap a Mono installation." 1>&2 ; \
echo "*** Check README for information on how to bootstrap a Mono installation." 1>&2 ; \
exit 1; fi; fi
@@ -89,7 +90,7 @@ ifdef use_monolite
do-get-monolite:
do-profile-check-monolite:
@echo "*** The contents of your 'monolite' directory may be out-of-date" 1>&2
@echo "*** The contents of your 'monolite/$(MONO_CORLIB_VERSION)' directory may be out-of-date" 1>&2
@echo "*** You may want to try 'make get-monolite-latest'" 1>&2
rm -f $(monolite_flag)
exit 1
@@ -97,12 +98,12 @@ do-profile-check-monolite:
else
do-get-monolite:
@echo "*** Downloading bootstrap required 'monolite'" 1>&2
@echo "*** Downloading bootstrap required 'monolite/$(MONO_CORLIB_VERSION)'" 1>&2
$(MAKE) $(MAKE_Q) -C $(mono_build_root) get-monolite-latest
do-profile-check-monolite: $(depsdir)/.stamp
@echo "*** The runtime '$(PROFILE_RUNTIME)' doesn't appear to be usable." 1>&2
@echo "*** Trying the 'monolite' directory." 1>&2
@echo "*** Trying the 'monolite/$(MONO_CORLIB_VERSION)' directory." 1>&2
@echo dummy > $(monolite_flag)
$(MAKE) do-profile-check
@@ -43,3 +43,5 @@ MOBILE_PROFILE = yes
NO_CONSOLE = yes
PROFILE_DISABLE_BTLS=1
MONO_FEATURE_APPLETLS=1
ONLY_APPLETLS=1
+3
View File
@@ -9,3 +9,6 @@ NO_THREAD_SUSPEND_RESUME=1
NO_MULTIPLE_APPDOMAINS=1
NO_PROCESS_START=1
NO_MONO_SECURITY=1
MONO_FEATURE_APPLETLS=
ONLY_APPLETLS=
MONO_FEATURE_APPLE_X509=1
@@ -10,3 +10,6 @@ NO_THREAD_SUSPEND_RESUME=1
# so we need a System.dll that can do that.
#NO_PROCESS_START=1
NO_MONO_SECURITY=1
MONO_FEATURE_APPLETLS=
ONLY_APPLETLS=
MONO_FEATURE_APPLE_X509=1
+1
View File
@@ -15,3 +15,4 @@ PROFILE_MCS_FLAGS = -d:NET_4_0 -d:NET_4_5 -d:NET_4_6 -d:MONO -d:WIN_PLATFORM -no
FRAMEWORK_VERSION = 4.5
XBUILD_VERSION = 4.0
MONO_FEATURE_APPLETLS=1
+2
View File
@@ -39,3 +39,5 @@ MOBILE_PROFILE = yes
NO_CONSOLE = yes
PROFILE_DISABLE_BTLS=1
MONO_FEATURE_APPLETLS=1
ONLY_APPLETLS=1
+2 -1
View File
@@ -18,5 +18,6 @@ NO_SYSTEM_DRAWING_DEPENDENCY=1
NO_SYSTEM_SERVICEMODEL_ACTIVATION_DEPENDENCY=1
NO_SYSTEM_DESIGN_DEPENDENCY=1
NO_SYSTEM_DIRECTORY_SERVICES_DEPENDENCY=1
PROFILE_DISABLE_BTLS=1
MONO_FEATURE_APPLETLS=1
ONLY_APPLETLS=1
+1 -1
View File
@@ -33,7 +33,7 @@ USE_MCS_FLAGS = /codepage:$(CODEPAGE) /nologo /noconfig /deterministic $(LOCAL_M
USE_MBAS_FLAGS = /codepage:$(CODEPAGE) $(LOCAL_MBAS_FLAGS) $(PLATFORM_MBAS_FLAGS) $(PROFILE_MBAS_FLAGS) $(MBAS_FLAGS)
USE_CFLAGS = $(LOCAL_CFLAGS) $(CFLAGS) $(CPPFLAGS)
CSCOMPILE = $(Q_MCS) $(MCS) $(USE_MCS_FLAGS)
CSC_RUNTIME_FLAGS = --aot-path=$(topdir)/class/lib/$(BUILD_TOOLS_PROFILE) --gc-params=nursery-size=64m
CSC_RUNTIME_FLAGS = --aot-path=$(abspath $(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)) --gc-params=nursery-size=64m
BASCOMPILE = $(MBAS) $(USE_MBAS_FLAGS)
CCOMPILE = $(CC) $(USE_CFLAGS)
BOOT_COMPILE = $(Q_MCS) $(BOOTSTRAP_MCS) $(USE_MCS_FLAGS)
+1
View File
@@ -1,2 +1,3 @@
/lib
/compat/
monolite-*.tar.gz
@@ -1,4 +1,4 @@
TypeForwarders.cs
AssemblyInfo.cs
SR.cs
../../../../external/corefx/src/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/IncrementalHash.net46.cs
../../../../external/corefx/src/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/IncrementalHash.net46.cs
+3 -2
View File
@@ -9,7 +9,8 @@ LIBRARY_INSTALL_DIR = $(mono_libdir)/mono/$(FRAMEWORK_VERSION)/Facades
LIBRARY = netstandard.dll
KEY_FILE = ../../msfinal.pub
KEY_FILE = ../../Open.snk
LIBRARY_SNK = $(KEY_FILE)
SIGN_FLAGS = /delaysign /keyfile:$(KEY_FILE) /nowarn:1616,1699 /nowarn:618
LIB_REFS = System System.Xml System.Xml.Linq System.Runtime.Serialization System.Core System.Numerics System.Net.Http System.Transactions \
System.IO.Compression System.Data System.ComponentModel.Composition System.IO.Compression.FileSystem \
@@ -21,7 +22,7 @@ else
LIB_REFS += System.Web System.Drawing
endif
LIB_MCS_FLAGS = $(SIGN_FLAGS)
LIB_MCS_FLAGS = $(SIGN_FLAGS) $(EXTRA_LIB_MCS_FLAGS)
PLATFORM_DEBUG_FLAGS =
+14 -3
View File
@@ -2,6 +2,12 @@ thisdir = class
pcl_facade_dirs := Facades
-include ../build/config.make
ifdef MCS_MODE
MCS_MODE_dirs := Mono.Cecil.Mdb
endif
# The minimal set of csc dependencies
basic_SUBDIRS := \
corlib \
@@ -14,6 +20,7 @@ basic_SUBDIRS := \
System.Xml.Linq \
System.Runtime.InteropServices.RuntimeInformation \
Mono.Cecil \
$(MCS_MODE_dirs) \
../tools/cil-stringreplacer
# resgen is corlib specific so we need to wait until corlib is build
@@ -33,12 +40,11 @@ build_SUBDIRS := \
System.Runtime.InteropServices.RuntimeInformation \
System.IO.Compression \
Mono.Cecil \
$(MCS_MODE_dirs) \
Mono.CompilerServices.SymbolWriter \
PEAPI \
../tools/cil-stringreplacer
-include ../build/config.make
ifdef MCS_MODE
basic_PARALLEL_SUBDIRS := ../mcs
build_PARALLEL_SUBDIRS := ../mcs
@@ -384,7 +390,7 @@ all-local $(STD_TARGETS:=-local):
all-local-aot:
monolite_dir := monolite
monolite_dir := monolite/$(MONO_CORLIB_VERSION)
# Files needed to bootstrap C# compiler
build_files = mscorlib.dll System.dll System.Xml.dll Mono.Security.dll System.Core.dll System.Security.dll System.Configuration.dll \
@@ -419,6 +425,11 @@ $(build_files:%=lib/build/%):
dist-monolite: $(monolite_files) lib/$(monolite_dir)/mcs.exe
package-monolite-latest:
MONOLITE=monolite-$(MONO_CORLIB_VERSION)-latest; \
$(MAKE) dist-monolite monolite_dir=$$MONOLITE; \
tar zcvpf $$MONOLITE.tar.gz --directory=lib $$MONOLITE/
dist-default: dist-monolite
dist-local: dist-default
@@ -64,7 +64,7 @@ namespace Mono.CodeContracts.Rewrite {
var readerParameters = new ReaderParameters ();
if (options.Debug)
if (options.Debug && options.WritePdbFile)
readerParameters.ReadSymbols = true;
var assembly = this.options.Assembly.IsFilename ?
@@ -221,7 +221,7 @@ namespace Mono.Data.Sqlite
case SQLiteDateFormats.UnixEpoch:
return ((long)(dateValue.Subtract(UnixEpoch).Ticks / TimeSpan.TicksPerSecond)).ToString();
default:
return dateValue.ToString(_datetimeFormats[5], CultureInfo.InvariantCulture);
return dateValue.ToString(_datetimeFormats[19], CultureInfo.InvariantCulture);
}
}
@@ -1,4 +1,3 @@
../../test-helpers/NunitHelpers.cs
Mono.Unix/ReadlinkTest.cs
Mono.Unix/StdioFileStreamTest.cs
Mono.Unix/UnixEncodingTest.cs
@@ -173,7 +173,7 @@ namespace MonoTests.Mono.Unix
long r = Syscall.readlink (link, buf);
if (r < 0)
UnixMarshal.ThrowExceptionForLastError ();
AssertHelper.GreaterOrEqual (buf.Length, r);
Assert.That(buf.Length, Is.GreaterThanOrEqualTo(r));
if (r == buf.Length)
buf = new byte[checked (buf.Length * 2)];
else
@@ -199,7 +199,7 @@ namespace MonoTests.Mono.Unix
long r = Syscall.readlinkat (TempFD, "link", buf);
if (r < 0)
UnixMarshal.ThrowExceptionForLastError ();
AssertHelper.GreaterOrEqual (buf.Length, r);
Assert.That(buf.Length, Is.GreaterThanOrEqualTo(r));
if (r == buf.Length)
buf = new byte[checked (buf.Length * 2)];
else
@@ -226,7 +226,7 @@ namespace MonoTests.Mono.Unix
if (r < 0)
UnixMarshal.ThrowExceptionForLastError ();
Assert.AreEqual (r, sb.Length);
AssertHelper.GreaterOrEqual (sb.Capacity, r);
Assert.That(sb.Capacity, Is.GreaterThanOrEqualTo(r));
if (r == sb.Capacity)
checked { sb.Capacity *= 2; }
else
@@ -255,7 +255,7 @@ namespace MonoTests.Mono.Unix
if (r < 0)
UnixMarshal.ThrowExceptionForLastError ();
Assert.AreEqual (r, sb.Length);
AssertHelper.GreaterOrEqual (sb.Capacity, r);
Assert.That(sb.Capacity, Is.GreaterThanOrEqualTo(r));
if (r == sb.Capacity)
checked { sb.Capacity *= 2; }
else
@@ -1,9 +0,0 @@
namespace Mono.Security.Interface
{
delegate MonoTlsProvider MonoTlsProviderFactoryDelegate ();
static partial class MonoTlsProviderFactory
{
internal static MonoTlsProviderFactoryDelegate _PrivateFactoryDelegate;
}
}
@@ -163,7 +163,7 @@ namespace Mono.Security.X509 {
cspParams.KeyContainerName = CryptoConvert.ToHex (certificate.Hash);
// Right now this seems to be the best way to know if we should use LM store.. ;)
if (_storePath.StartsWith (X509StoreManager.LocalMachinePath))
if (_storePath.StartsWith (X509StoreManager.LocalMachinePath) || _storePath.StartsWith(X509StoreManager.NewLocalMachinePath))
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
ImportPrivateKey (certificate, cspParams);
@@ -338,7 +338,7 @@ namespace Mono.Security.X509 {
// If privateKey it's available, load it too..
CspParameters cspParams = new CspParameters ();
cspParams.KeyContainerName = CryptoConvert.ToHex (cert.Hash);
if (_storePath.StartsWith (X509StoreManager.LocalMachinePath))
if (_storePath.StartsWith (X509StoreManager.LocalMachinePath) || _storePath.StartsWith(X509StoreManager.NewLocalMachinePath))
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
KeyPairPersistence kpp = new KeyPairPersistence (cspParams);
@@ -1,4 +1,3 @@
#include Mono.Security.dll.sources
../corlib/CommonCrypto/CommonCrypto.cs
../corlib/CommonCrypto/RC4CommonCrypto.cs
Mono.Security.Interface/MonoTlsProviderFactory.Apple.cs
@@ -1,5 +1,5 @@
Novell.Directory.Ldap/AssemblyInfo.cs
../../build/common/Consts.cs.in
../../build/common/Consts.cs
Novell.Directory.Ldap/SupportClass.cs
Novell.Directory.Ldap.Utilclass/Base64.cs
Novell.Directory.Ldap.Utilclass/DN.cs
@@ -31,6 +31,7 @@ using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Permissions;
using System.Security.Principal;
using System.IO.MemoryMappedFiles;
namespace Microsoft.Win32.SafeHandles
{
@@ -42,10 +43,11 @@ namespace Microsoft.Win32.SafeHandles
handle = preexistingHandle;
}
[MonoTODO]
protected override bool ReleaseHandle ()
{
throw new NotImplementedException ();
MemoryMapImpl.CloseMapping (handle);
handle = IntPtr.Zero;
return true;
}
}
}
@@ -33,7 +33,6 @@ using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace System.IO.MemoryMappedFiles
{
internal static class MemoryMapImpl {
@@ -113,7 +112,6 @@ namespace System.IO.MemoryMappedFiles
}
}
public class MemoryMappedFile : IDisposable {
// MemoryMappedFileAccess fileAccess;
// string name;
@@ -127,7 +125,7 @@ namespace System.IO.MemoryMappedFiles
//
FileStream stream;
bool keepOpen;
IntPtr handle;
SafeMemoryMappedFileHandle handle;
public static MemoryMappedFile CreateFromFile (string path)
{
@@ -147,7 +145,7 @@ namespace System.IO.MemoryMappedFiles
IntPtr handle = MemoryMapImpl.OpenFile (path, mode, null, out capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None);
return new MemoryMappedFile () {
handle = handle,
handle = new SafeMemoryMappedFileHandle (handle, true),
// fileAccess = MemoryMappedFileAccess.ReadWrite,
// fileCapacity = capacity
};
@@ -179,7 +177,7 @@ namespace System.IO.MemoryMappedFiles
IntPtr handle = MemoryMapImpl.OpenFile (path, mode, mapName, out capacity, access, MemoryMappedFileOptions.None);
return new MemoryMappedFile () {
handle = handle,
handle = new SafeMemoryMappedFileHandle (handle, true),
// fileAccess = access,
// name = mapName,
// fileCapacity = capacity
@@ -202,7 +200,7 @@ namespace System.IO.MemoryMappedFiles
MemoryMapImpl.ConfigureHandleInheritability (handle, inheritability);
return new MemoryMappedFile () {
handle = handle,
handle = new SafeMemoryMappedFileHandle (handle, true),
// fileAccess = access,
// name = mapName,
// fileCapacity = capacity,
@@ -229,7 +227,7 @@ namespace System.IO.MemoryMappedFiles
MemoryMapImpl.ConfigureHandleInheritability (handle, inheritability);
return new MemoryMappedFile () {
handle = handle,
handle = new SafeMemoryMappedFileHandle (handle, true),
// fileAccess = access,
// name = mapName,
// fileCapacity = capacity,
@@ -252,7 +250,7 @@ namespace System.IO.MemoryMappedFiles
IntPtr handle = MemoryMapImpl.OpenFile (null, mode, mapName, out capacity, access, options);
return new MemoryMappedFile () {
handle = handle,
handle = new SafeMemoryMappedFileHandle (handle, true),
// fileAccess = access,
// name = mapName,
// fileCapacity = capacity
@@ -339,7 +337,7 @@ namespace System.IO.MemoryMappedFiles
public MemoryMappedViewStream CreateViewStream (long offset, long size, MemoryMappedFileAccess access)
{
var view = MemoryMappedView.Create (handle, offset, size, access);
var view = MemoryMappedView.Create (handle.DangerousGetHandle (), offset, size, access);
return new MemoryMappedViewStream (view);
}
@@ -355,7 +353,7 @@ namespace System.IO.MemoryMappedFiles
public MemoryMappedViewAccessor CreateViewAccessor (long offset, long size, MemoryMappedFileAccess access)
{
var view = MemoryMappedView.Create (handle, offset, size, access);
var view = MemoryMappedView.Create (handle.DangerousGetHandle (), offset, size, access);
return new MemoryMappedViewAccessor (view);
}
@@ -370,16 +368,16 @@ namespace System.IO.MemoryMappedFiles
protected virtual void Dispose (bool disposing)
{
if (disposing){
if (stream != null){
if (disposing) {
if (stream != null) {
if (keepOpen == false)
stream.Close ();
stream = null;
}
if (handle != IntPtr.Zero) {
MemoryMapImpl.CloseMapping (handle);
handle = IntPtr.Zero;
}
}
if (handle != null) {
handle.Dispose ();
handle = null;
}
}
@@ -511,6 +511,11 @@ namespace MonoTests.System.Linq.Expressions {
[Test]
public void CallNullableGetValueOrDefault () // #568989
{
#if MOBILE
// ensure that int?.GetValueOrDefault won't be removed by the linker
Assert.AreEqual (0, ((int?)0).GetValueOrDefault (3));
#endif
var value = Expression.Parameter (typeof (int?), "value");
var default_parameter = Expression.Parameter (typeof (int), "default");
@@ -36,46 +36,50 @@ using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions {
[TestFixture]
public class ExpressionTest_Loop {
public class ExpressionTest_Loop
{
public static void Print (int arg)
{
}
[Test]
public void ComplexTest ()
{
var breakLabel = Expression.Label ("LoopBreak");
var counter = Expression.Variable (typeof (int), "counter");
var breakLabel = Expression.Label ("LoopBreak");
var counter = Expression.Variable (typeof (int), "counter");
var l = Expression.Block (new[] { counter },
Expression.Assign (counter, Expression.Constant (-1)),
Expression.Loop (
Expression.Block (Expression.IfThenElse (
Expression.Equal (Expression.Assign (counter, Expression.Add (counter, Expression.Constant (1))), Expression.Constant (1000)),
Expression.Block (Expression.Break (breakLabel)),
Expression.Call (null, typeof (Console).GetMethod ("WriteLine", new Type[] { typeof (int) }), counter)
)),
breakLabel)
);
var l = Expression.Block (new[] { counter },
Expression.Assign (counter, Expression.Constant (-1)),
Expression.Loop (
Expression.Block (Expression.IfThenElse (
Expression.Equal (Expression.Assign (counter, Expression.Add (counter, Expression.Constant (1))), Expression.Constant (1000)),
Expression.Block (Expression.Break (breakLabel)),
Expression.Call (null, typeof (ExpressionTest_Loop).GetMethod ("Print", new Type[] { typeof (int) }), counter)
)),
breakLabel)
);
var res = Expression.Lambda<Action> (l).Compile ();
}
var res = Expression.Lambda<Action> (l).Compile ();
}
[Test]
public void ComplexTest_2 ()
{
var breakLabel = Expression.Label ("LoopBreak");
var counter = Expression.Variable (typeof (int), "counter");
var breakLabel = Expression.Label ("LoopBreak");
var counter = Expression.Variable (typeof (int), "counter");
var l = Expression.Block (new[] { counter },
Expression.Assign (counter, Expression.Constant(-1)),
Expression.Loop (
Expression.IfThenElse (
Expression.Equal (Expression.Assign (counter, Expression.Add (counter, Expression.Constant (1))), Expression.Constant (1000)),
Expression.Break (breakLabel),
Expression.Call (null, typeof (Console).GetMethod ("WriteLine", new Type[] { typeof (int) }), counter)
),
breakLabel)
);
var l = Expression.Block (new[] { counter },
Expression.Assign (counter, Expression.Constant(-1)),
Expression.Loop (
Expression.IfThenElse (
Expression.Equal (Expression.Assign (counter, Expression.Add (counter, Expression.Constant (1))), Expression.Constant (1000)),
Expression.Break (breakLabel),
Expression.Call (null, typeof (ExpressionTest_Loop).GetMethod ("Print", new Type[] { typeof (int) }), counter)
),
breakLabel)
);
var res = Expression.Lambda<Action> (l).Compile ();
var res = Expression.Lambda<Action> (l).Compile ();
}
}
}
+1 -1
View File
@@ -289,4 +289,4 @@
../referencesource/System.Data/System/Data/SqlClient/SqlUtil.cs
../referencesource/System.Data/System/Data/SqlClient/TdsEnums.cs
../referencesource/System.Data/System/Data/SqlClient/TdsParserStaticMethods.cs
../referencesource/System.Data/System/Data/DataSet.cs
../referencesource/System.Data/System/Data/DataSet.cs
@@ -1,5 +1,5 @@
Assembly/AssemblyInfo.cs
../../build/common/Consts.cs.in
../../build/common/Consts.cs
../../build/common/Locale.cs
../../build/common/SR.cs
../../build/common/MonoTODOAttribute.cs
@@ -1,5 +1,5 @@
Assembly/AssemblyInfo.cs
../../build/common/Consts.cs.in
../../build/common/Consts.cs
../../build/common/Locale.cs
System.DirectoryServices/ActiveDirectoryAccessRule.cs
System.DirectoryServices/ActiveDirectoryAuditRule.cs
@@ -1,3 +1,3 @@
Assembly/AssemblyInfo.cs
../../build/common/Consts.cs
#include netstandard.sources
#include netstandard.sources
@@ -11,4 +11,4 @@ corefx/SR.cs
../../../external/corefx/src/System.Buffers/src/System/Buffers/ArrayPoolEventSource.cs
../../../external/corefx/src/System.Buffers/src/System/Buffers/DefaultArrayPool.cs
../../../external/corefx/src/System.Buffers/src/System/Buffers/DefaultArrayPoolBucket.cs
../../../external/corefx/src/System.Buffers/src/System/Buffers/Utilities.cs
../../../external/corefx/src/System.Buffers/src/System/Buffers/Utilities.cs
@@ -37,6 +37,8 @@ namespace System.Net.Http
readonly Stream content;
readonly int bufferSize;
readonly CancellationToken cancellationToken;
readonly long startPosition;
bool contentCopied;
public StreamContent (Stream content)
: this (content, 16 * 1024)
@@ -53,6 +55,10 @@ namespace System.Net.Http
this.content = content;
this.bufferSize = bufferSize;
if (content.CanSeek) {
startPosition = content.Position;
}
}
//
@@ -83,6 +89,16 @@ namespace System.Net.Http
protected internal override Task SerializeToStreamAsync (Stream stream, TransportContext context)
{
if (contentCopied) {
if (!content.CanSeek) {
throw new InvalidOperationException ("The stream was already consumed. It cannot be read again.");
}
content.Seek (startPosition, SeekOrigin.Begin);
} else {
contentCopied = true;
}
return content.CopyToAsync (stream, bufferSize, cancellationToken);
}
@@ -92,7 +108,7 @@ namespace System.Net.Http
length = 0;
return false;
}
length = content.Length;
length = content.Length - startPosition;
return true;
}
}
@@ -149,8 +149,8 @@ namespace MonoTests.System.Net.Http
/*
sc = new StreamContent (new ExceptionStream ());
try {
sc.CopyToAsync (m).Wait ();
Assert.Fail ("#2");
sc.CopyToAsync (m).Wait ();
Assert.Fail ("#2");
} catch (AggregateException) {
}
*/
@@ -190,6 +190,32 @@ namespace MonoTests.System.Net.Http
Assert.IsTrue (hit, "#10");
}
[Test]
public void CopyToAsync_Twice ()
{
var ms = new MemoryStream();
ms.WriteByte(4);
ms.WriteByte(12);
ms.WriteByte(7);
ms.Seek(1, SeekOrigin.Begin);
var sc = new StreamContent(ms);
var dest = new MemoryStream();
var task = sc.CopyToAsync(dest);
Assert.True(task.Wait(3000), "#0");
Assert.AreEqual(2, dest.Length, "#1");
dest.Seek(0, SeekOrigin.Begin);
Assert.AreEqual(12, dest.ReadByte(), "#2");
dest = new MemoryStream();
task = sc.CopyToAsync(dest);
Assert.True(task.Wait(3000), "#10");
Assert.AreEqual(2, dest.Length, "#11");
dest.Seek(0, SeekOrigin.Begin);
Assert.AreEqual(12, dest.ReadByte(), "#12");
}
[Test]
public void CopyToAsync_ClosedInput ()
{
@@ -0,0 +1 @@
#include mobile_System.ServiceModel.Internals.dll.sources
@@ -0,0 +1 @@
#include mobile_System.ServiceModel.Internals.dll.sources
@@ -31,9 +31,12 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Permissions;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Configuration;
using System.Web.Caching;
using System.Web.Util;
@@ -53,6 +56,8 @@ namespace System.Web.Hosting {
static VirtualPathProvider vpath_provider = (HttpRuntime.AppDomainAppVirtualPath == null) ? null :
new DefaultVirtualPathProvider ();
static int busy_count;
static BackgroundWorkScheduler _backgroundWorkScheduler = null; // created on demand
static readonly Task<object> _completedTask = Task.FromResult<object>(null);
internal static bool HaveCustomVPP {
get;
@@ -212,6 +217,73 @@ namespace System.Web.Hosting {
if (Host != null)
Host.UnregisterObject (obj);
}
// Schedules a task which can run in the background, independent of any request.
// This differs from a normal ThreadPool work item in that ASP.NET can keep track
// of how many work items registered through this API are currently running, and
// the ASP.NET runtime will try not to delay AppDomain shutdown until these work
// items have finished executing.
//
// Usage notes:
// - This API cannot be called outside of an ASP.NET-managed AppDomain.
// - The caller's ExecutionContext is not flowed to the work item.
// - Scheduled work items are not guaranteed to ever execute, e.g., when AppDomain
// shutdown has already started by the time this API was called.
// - The provided CancellationToken will be signaled when the application is
// shutting down. The work item should make every effort to honor this token.
// If a work item does not honor this token and continues executing it will
// eventually be considered rogue, and the ASP.NET runtime will rudely unload
// the AppDomain without waiting for the work item to finish.
//
// This overload of QueueBackgroundWorkItem takes a void-returning callback; the
// work item will be considered finished when the callback returns.
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
public static void QueueBackgroundWorkItem(Action<CancellationToken> workItem) {
if (workItem == null) {
throw new ArgumentNullException("workItem");
}
QueueBackgroundWorkItem(ct => { workItem(ct); return _completedTask; });
}
// See documentation on the other overload for a general API overview.
//
// This overload of QueueBackgroundWorkItem takes a Task-returning callback; the
// work item will be considered finished when the returned Task transitions to a
// terminal state.
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
public static void QueueBackgroundWorkItem(Func<CancellationToken, Task> workItem) {
if (workItem == null) {
throw new ArgumentNullException("workItem");
}
if (Host == null) {
throw new InvalidOperationException(); // can only be called within an ASP.NET AppDomain
}
QueueBackgroundWorkItemInternal(workItem);
}
static void QueueBackgroundWorkItemInternal(Func<CancellationToken, Task> workItem) {
Debug.Assert(workItem != null);
BackgroundWorkScheduler scheduler = Volatile.Read(ref _backgroundWorkScheduler);
// If the scheduler doesn't exist, lazily create it, but only allow one instance to ever be published to the backing field
if (scheduler == null) {
BackgroundWorkScheduler newlyCreatedScheduler = new BackgroundWorkScheduler(UnregisterObject, WriteUnhandledException);
scheduler = Interlocked.CompareExchange(ref _backgroundWorkScheduler, newlyCreatedScheduler, null) ?? newlyCreatedScheduler;
if (scheduler == newlyCreatedScheduler) {
RegisterObject(scheduler); // Only call RegisterObject if we just created the "winning" one
}
}
scheduler.ScheduleWorkItem(workItem);
}
static void WriteUnhandledException (AppDomain appDomain, Exception exception)
{
Console.Error.WriteLine ("Error in background work item: " + exception);
}
}
}
@@ -290,6 +290,7 @@ System.Web.Hosting/AppManagerAppDomainFactory.cs
System.Web.Hosting/ApplicationInfo.cs
System.Web.Hosting/ApplicationHost.cs
System.Web.Hosting/ApplicationManager.cs
../referencesource/System.Web/Hosting/BackgroundWorkScheduler.cs
System.Web.Hosting/BareApplicationHost.cs
System.Web.Hosting/DefaultVirtualDirectory.cs
System.Web.Hosting/DefaultVirtualFile.cs
@@ -1199,6 +1200,7 @@ System.Web.UI/XhtmlMobileDocType.cs
System.Web.UI/XhtmlTextWriter.cs
System.Web.UI/XPathBinder.cs
System.Web.Util/AltSerialization.cs
../referencesource/System.Web/Util/CancellationTokenHelper.cs
System.Web.Util/DataSourceHelper.cs
System.Web.Util/DataSourceResolver.cs
System.Web.Util/FileUtils.cs
@@ -68,6 +68,10 @@ namespace System.Resources {
if (parts.Length == 1)
throw new ArgumentException ("value");
string filename = parts [0];
if (Path.DirectorySeparatorChar == '/')
filename = filename.Replace ("\\", "/");
Type type = Type.GetType (parts [1]);
if (type == typeof(string)) {
Encoding encoding;
@@ -77,12 +81,12 @@ namespace System.Resources {
encoding = Encoding.Default;
}
using (TextReader reader = new StreamReader(parts [0], encoding)) {
using (TextReader reader = new StreamReader(filename, encoding)) {
return reader.ReadToEnd();
}
}
using (FileStream file = new FileStream (parts [0], FileMode.Open, FileAccess.Read, FileShare.Read)) {
using (FileStream file = new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
buffer = new byte [file.Length];
file.Read(buffer, 0, (int) file.Length);
}
@@ -90,7 +94,7 @@ namespace System.Resources {
if (type == typeof(System.Byte[]))
return buffer;
if (type == typeof (Bitmap) && Path.GetExtension (parts [0]) == ".ico") {
if (type == typeof (Bitmap) && Path.GetExtension (filename) == ".ico") {
MemoryStream ms = new MemoryStream (buffer);
return new Icon (ms).ToBitmap ();
}
@@ -229,6 +229,26 @@ namespace MonoTests.System.Resources
}
}
[Test]
public void ConvertFrom_Type_String_FilePathWithBackslashes ()
{
if (Path.DirectorySeparatorChar == '\\')
// non-windows test
return;
string fileContents = "foobar";
string fileName = "foo.txt";
string filePath = Path.Combine (_tempDirectory, fileName);
File.WriteAllText (filePath, fileContents);
filePath = _tempDirectory + "\\.\\" + fileName;
string fileRef = filePath + ";" + typeof (string).AssemblyQualifiedName;
string result = _converter.ConvertFrom (fileRef) as string;
Assert.IsNotNull (result, "#A1");
Assert.AreEqual (result, fileContents, "#A2");
}
[Test]
public void ConvertFrom_Type_StreamReader ()
{
+15 -1
View File
@@ -31,7 +31,13 @@ LIB_MCS_FLAGS += -d:INSIDE_SYSTEM
endif
ifndef MOBILE_PROFILE
TEST_LIB_REFS = System.Drawing $(MONO_SECURITY) System.Data System.Xml System.Core System.Configuration
LIB_MCS_FLAGS += -d:CODEDOM
TEST_LIB_REFS = $(MONO_SECURITY) System.Data System.Xml System.Core System.Configuration
ifndef NO_SYSTEM_DRAWING_DEPENDENCY
TEST_LIB_REFS += System.Drawing
endif
else
LIB_MCS_FLAGS += -nowarn:618
TEST_LIB_REFS = $(MONO_SECURITY) System.Data System.Xml System.Core
@@ -48,6 +54,14 @@ REFERENCE_SOURCES_FLAGS += -d:MONO_FEATURE_PROCESS_START
TEST_MCS_FLAGS += -d:MONO_FEATURE_PROCESS_START
endif
ifdef MONO_FEATURE_APPLETLS
LIB_MCS_FLAGS += -d:MONO_FEATURE_APPLETLS
endif
ifdef ONLY_APPLETLS
LIB_MCS_FLAGS += -d:ONLY_APPLETLS
endif
ifndef PROFILE_DISABLE_BTLS
ifdef HAVE_BTLS
@@ -0,0 +1,155 @@
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
//
// AppleCertificateHelper.cs
//
// Author:
// Martin Baulig <[email protected]>
//
// Copyright (c) 2015 Xamarin, Inc.
//
#if MONO_SECURITY_ALIAS
extern alias MonoSecurity;
#endif
using System;
using System.Collections;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
#if MONO_SECURITY_ALIAS
using MonoSecurity::Mono.Security.Interface;
#else
using Mono.Security.Interface;
#endif
namespace Mono.AppleTls
{
static class AppleCertificateHelper
{
public static SecIdentity GetIdentity (X509Certificate certificate)
{
/*
* If we got an 'X509Certificate2', then we require it to have a private key
* and import it.
*/
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
* ==========================================
*
* Reading the private key from the keychain is a new feature introduced with
* AppleTls on XamMac and iOS. On Desktop Mono, this new feature has several
* known issues and it also did not received any testing yet. We go back to the old
* way of doing things, which is to explicitly provide an X509Certificate2 with a
* private key.
*
* Keychain Dialog Popups
* ======================
*
* When using Xamarin.Mac or Xamarin.iOS, we try to search the keychain
* for the certificate and private key.
*
* On Xamarin.iOS, this is easy because each app has its own keychain.
*
* On Xamarin.Mac, the .app package needs to be trusted via code-sign
* to get permission to access the user's keychain. [FIXME: I still have to
* research how to actually do that.] Without this, you will get a popup
* message each time, asking you whether you want to allow the app to access
* the keychain, but you can make these go away by selecting "Trust always".
*
* On Desktop Mono, this is problematic because selecting "Trust always"
* give the 'mono' binary (and thus everything you'll ever run with Mono)
* permission to retrieve the private key from the keychain.
*
* This code would also trigger constant keychain popup messages,
* which could only be suppressed by granting full trust. It also makes it
* impossible to run Mono in headless mode.
*
* SecIdentityCreate
* =================
*
* To avoid these problems, we are currently using an undocumented API
* called SecIdentityRef() to avoid using the Mac keychain whenever a
* X509Certificate2 with a private key is used.
*
* On iOS and XamMac, you can still provide the X509Certificate without
* a private key - in this case, a keychain search will be performed (and you
* may get a popup message on XamMac).
*/
#if MOBILE
using (var secCert = new SecCertificate (certificate)) {
return SecKeyChain.FindIdentity (secCert, true);
}
#else
return null;
#endif
}
public static SecIdentity GetIdentity (X509Certificate certificate, out SecCertificate[] intermediateCerts)
{
var identity = GetIdentity (certificate);
var impl2 = certificate.Impl as X509Certificate2Impl;
if (impl2 == null || impl2.IntermediateCertificates == null) {
intermediateCerts = new SecCertificate [0];
return identity;
}
try {
intermediateCerts = new SecCertificate [impl2.IntermediateCertificates.Count];
for (int i = 0; i < intermediateCerts.Length; i++)
intermediateCerts [i] = new SecCertificate (impl2.IntermediateCertificates [i]);
return identity;
} catch {
identity.Dispose ();
throw;
}
}
public static bool InvokeSystemCertificateValidator (
ICertificateValidator2 validator, string targetHost, bool serverMode,
X509CertificateCollection certificates,
ref MonoSslPolicyErrors errors, ref int status11)
{
if (certificates == null) {
errors |= MonoSslPolicyErrors.RemoteCertificateNotAvailable;
return false;
}
if (!string.IsNullOrEmpty (targetHost)) {
var pos = targetHost.IndexOf (':');
if (pos > 0)
targetHost = targetHost.Substring (0, pos);
}
var policy = SecPolicy.CreateSslPolicy (!serverMode, targetHost);
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);
}
var result = trust.Evaluate ();
if (result == SecTrustResult.Unspecified)
return true;
errors |= MonoSslPolicyErrors.RemoteCertificateChainErrors;
return false;
}
}
}
#endif
@@ -0,0 +1,907 @@
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
//
// AppleTlsContext.cs
//
// Author:
// Martin Baulig <[email protected]>
//
// Copyright (c) 2015 Xamarin, Inc.
//
#if MONO_SECURITY_ALIAS
extern alias MonoSecurity;
#endif
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using SSA = System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
#if MONO_SECURITY_ALIAS
using MonoSecurity::Mono.Security.Interface;
#else
using Mono.Security.Interface;
#endif
using Mono.Net;
using Mono.Net.Security;
using Mono.Util;
using ObjCRuntime;
namespace Mono.AppleTls
{
class AppleTlsContext : MobileTlsContext
{
public const string SecurityLibrary = "/System/Library/Frameworks/Security.framework/Security";
GCHandle handle;
IntPtr context;
IntPtr connectionId;
SslReadFunc readFunc;
SslWriteFunc writeFunc;
SecIdentity serverIdentity;
SecIdentity clientIdentity;
X509Certificate remoteCertificate;
X509Certificate localClientCertificate;
MonoTlsConnectionInfo connectionInfo;
bool havePeerTrust;
bool isAuthenticated;
bool handshakeFinished;
int handshakeStarted;
bool closed;
bool disposed;
bool closedGraceful;
int pendingIO;
Exception lastException;
public AppleTlsContext (
MobileAuthenticatedStream parent, bool serverMode, string targetHost,
SSA.SslProtocols enabledProtocols, X509Certificate serverCertificate,
X509CertificateCollection clientCertificates, bool askForClientCert)
: base (parent, serverMode, targetHost, enabledProtocols,
serverCertificate, clientCertificates, askForClientCert)
{
handle = GCHandle.Alloc (this);
connectionId = GCHandle.ToIntPtr (handle);
readFunc = NativeReadCallback;
writeFunc = NativeWriteCallback;
if (IsServer) {
if (serverCertificate == null)
throw new ArgumentNullException ("serverCertificate");
}
}
public IntPtr Handle {
get {
if (!HasContext)
throw new ObjectDisposedException ("AppleTlsContext");
return context;
}
}
public override bool HasContext {
get { return !disposed && context != IntPtr.Zero; }
}
[System.Diagnostics.Conditional ("APPLE_TLS_DEBUG")]
protected new void Debug (string message, params object[] args)
{
Console.Error.WriteLine ("MobileTlsStream({0}): {1}", Parent.ID, string.Format (message, args));
}
void CheckStatusAndThrow (SslStatus status, params SslStatus[] acceptable)
{
var last = Interlocked.Exchange (ref lastException, null);
if (last != null)
throw last;
if (status == SslStatus.Success || Array.IndexOf (acceptable, status) > -1)
return;
switch (status) {
case SslStatus.ClosedAbort:
throw new IOException ("Connection closed.");
case SslStatus.BadCert:
throw new TlsException (AlertDescription.BadCertificate);
case SslStatus.UnknownRootCert:
case SslStatus.NoRootCert:
case SslStatus.XCertChainInvalid:
throw new TlsException (AlertDescription.CertificateUnknown, status.ToString ());
case SslStatus.CertExpired:
case SslStatus.CertNotYetValid:
throw new TlsException (AlertDescription.CertificateExpired);
case SslStatus.Protocol:
throw new TlsException (AlertDescription.ProtocolVersion);
default:
throw new TlsException (AlertDescription.InternalError, "Unknown Secure Transport error `{0}'.", status);
}
}
#region Handshake
public override bool IsAuthenticated {
get { return isAuthenticated; }
}
public override void StartHandshake ()
{
Debug ("StartHandshake: {0}", IsServer);
if (Interlocked.CompareExchange (ref handshakeStarted, 1, 1) != 0)
throw new InvalidOperationException ();
InitializeConnection ();
SetSessionOption (SslSessionOption.BreakOnCertRequested, true);
SetSessionOption (SslSessionOption.BreakOnClientAuth, true);
SetSessionOption (SslSessionOption.BreakOnServerAuth, true);
if (IsServer) {
SecCertificate[] intermediateCerts;
serverIdentity = AppleCertificateHelper.GetIdentity (LocalServerCertificate, out intermediateCerts);
if (serverIdentity == null)
throw new SSA.AuthenticationException ("Unable to get server certificate from keychain.");
SetCertificate (serverIdentity, intermediateCerts);
for (int i = 0; i < intermediateCerts.Length; i++)
intermediateCerts [i].Dispose ();
}
}
public override void FinishHandshake ()
{
InitializeSession ();
isAuthenticated = true;
}
public override void Flush ()
{
}
public override bool ProcessHandshake ()
{
if (handshakeFinished)
throw new NotSupportedException ("Handshake already finished.");
while (true) {
lastException = null;
var status = SSLHandshake (Handle);
Debug ("Handshake: {0} - {0:x}", status);
CheckStatusAndThrow (status, SslStatus.WouldBlock, SslStatus.PeerAuthCompleted, SslStatus.PeerClientCertRequested);
if (status == SslStatus.PeerAuthCompleted) {
RequirePeerTrust ();
} else if (status == SslStatus.PeerClientCertRequested) {
RequirePeerTrust ();
if (remoteCertificate == null)
throw new TlsException (AlertDescription.InternalError, "Cannot request client certificate before receiving one from the server.");
localClientCertificate = SelectClientCertificate (remoteCertificate, null);
if (localClientCertificate == null)
continue;
clientIdentity = AppleCertificateHelper.GetIdentity (localClientCertificate);
if (clientIdentity == null)
throw new TlsException (AlertDescription.CertificateUnknown);
SetCertificate (clientIdentity, new SecCertificate [0]);
} else if (status == SslStatus.WouldBlock) {
return false;
} else if (status == SslStatus.Success) {
handshakeFinished = true;
return true;
}
}
}
void RequirePeerTrust ()
{
if (!havePeerTrust) {
EvaluateTrust ();
havePeerTrust = true;
}
}
void EvaluateTrust ()
{
InitializeSession ();
/*
* We're using .NET's SslStream semantics here.
*
* A server must always provide a valid certificate.
*
* However, in server mode, "ask for client certificate" means that
* we ask the client to provide a certificate, then invoke the client
* certificate validator - passing 'null' if the client didn't provide
* any.
*
*/
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;
try {
ok = ValidateCertificate (certificates);
} catch (Exception ex) {
Debug ("Certificate validation failed: {0}", ex);
throw new TlsException (AlertDescription.CertificateUnknown, "Certificate validation threw exception.");
}
if (!ok)
throw new TlsException (AlertDescription.CertificateUnknown);
}
void InitializeConnection ()
{
context = SSLCreateContext (IntPtr.Zero, IsServer ? SslProtocolSide.Server : SslProtocolSide.Client, SslConnectionType.Stream);
var result = SSLSetIOFuncs (Handle, readFunc, writeFunc);
CheckStatusAndThrow (result);
result = SSLSetConnection (Handle, connectionId);
CheckStatusAndThrow (result);
if ((EnabledProtocols & SSA.SslProtocols.Tls) != 0)
MinProtocol = SslProtocol.Tls_1_0;
else if ((EnabledProtocols & SSA.SslProtocols.Tls11) != 0)
MinProtocol = SslProtocol.Tls_1_1;
else
MinProtocol = SslProtocol.Tls_1_2;
if ((EnabledProtocols & SSA.SslProtocols.Tls12) != 0)
MaxProtocol = SslProtocol.Tls_1_2;
else if ((EnabledProtocols & SSA.SslProtocols.Tls11) != 0)
MaxProtocol = SslProtocol.Tls_1_1;
else
MaxProtocol = SslProtocol.Tls_1_0;
#if APPLE_TLS_DEBUG
foreach (var c in GetSupportedCiphers ())
Debug (" {0} SslCipherSuite.{1} {2:x} {3}", IsServer ? "Server" : "Client", c, (int)c, (CipherSuiteCode)c);
#endif
if (Settings != null && Settings.EnabledCiphers != null) {
SslCipherSuite [] ciphers = new SslCipherSuite [Settings.EnabledCiphers.Length];
for (int i = 0 ; i < Settings.EnabledCiphers.Length; ++i)
ciphers [i] = (SslCipherSuite)Settings.EnabledCiphers[i];
SetEnabledCiphers (ciphers);
}
if (AskForClientCertificate)
SetClientSideAuthenticate (SslAuthenticate.Try);
IPAddress address;
if (!IsServer && !string.IsNullOrEmpty (TargetHost) &&
!IPAddress.TryParse (TargetHost, out address)) {
PeerDomainName = ServerName;
}
}
void InitializeSession ()
{
if (connectionInfo != null)
return;
var cipher = NegotiatedCipher;
var protocol = GetNegotiatedProtocolVersion ();
Debug ("GET CONNECTION INFO: {0:x}:{0} {1:x}:{1} {2}", cipher, protocol, (TlsProtocolCode)protocol);
connectionInfo = new MonoTlsConnectionInfo {
CipherSuiteCode = (CipherSuiteCode)cipher,
ProtocolVersion = GetProtocol (protocol),
PeerDomainName = PeerDomainName
};
}
static TlsProtocols GetProtocol (SslProtocol protocol)
{
switch (protocol) {
case SslProtocol.Tls_1_0:
return TlsProtocols.Tls10;
case SslProtocol.Tls_1_1:
return TlsProtocols.Tls11;
case SslProtocol.Tls_1_2:
return TlsProtocols.Tls12;
default:
throw new NotSupportedException ();
}
}
public override MonoTlsConnectionInfo ConnectionInfo {
get { return connectionInfo; }
}
internal override bool IsRemoteCertificateAvailable {
get { return remoteCertificate != null; }
}
internal override X509Certificate LocalClientCertificate {
get { return localClientCertificate; }
}
public override X509Certificate RemoteCertificate {
get { return remoteCertificate; }
}
public override TlsProtocols NegotiatedProtocol {
get { return connectionInfo.ProtocolVersion; }
}
#endregion
#region General P/Invokes
[DllImport (SecurityLibrary )]
extern static /* OSStatus */ SslStatus SSLGetProtocolVersionMax (/* SSLContextRef */ IntPtr context, out SslProtocol maxVersion);
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ SslStatus SSLSetProtocolVersionMax (/* SSLContextRef */ IntPtr context, SslProtocol maxVersion);
public SslProtocol MaxProtocol {
get {
SslProtocol value;
var result = SSLGetProtocolVersionMax (Handle, out value);
CheckStatusAndThrow (result);
return value;
}
set {
var result = SSLSetProtocolVersionMax (Handle, value);
CheckStatusAndThrow (result);
}
}
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ SslStatus SSLGetProtocolVersionMin (/* SSLContextRef */ IntPtr context, out SslProtocol minVersion);
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ SslStatus SSLSetProtocolVersionMin (/* SSLContextRef */ IntPtr context, SslProtocol minVersion);
public SslProtocol MinProtocol {
get {
SslProtocol value;
var result = SSLGetProtocolVersionMin (Handle, out value);
CheckStatusAndThrow (result);
return value;
}
set {
var result = SSLSetProtocolVersionMin (Handle, value);
CheckStatusAndThrow (result);
}
}
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ SslStatus SSLGetNegotiatedProtocolVersion (/* SSLContextRef */ IntPtr context, out SslProtocol protocol);
public SslProtocol GetNegotiatedProtocolVersion ()
{
SslProtocol value;
var result = SSLGetNegotiatedProtocolVersion (Handle, out value);
CheckStatusAndThrow (result);
return value;
}
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ SslStatus SSLGetSessionOption (/* SSLContextRef */ IntPtr context, SslSessionOption option, out bool value);
public bool GetSessionOption (SslSessionOption option)
{
bool value;
var result = SSLGetSessionOption (Handle, option, out value);
CheckStatusAndThrow (result);
return value;
}
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ SslStatus SSLSetSessionOption (/* SSLContextRef */ IntPtr context, SslSessionOption option, bool value);
public void SetSessionOption (SslSessionOption option, bool value)
{
var result = SSLSetSessionOption (Handle, option, value);
CheckStatusAndThrow (result);
}
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ SslStatus SSLSetClientSideAuthenticate (/* SSLContextRef */ IntPtr context, SslAuthenticate auth);
public void SetClientSideAuthenticate (SslAuthenticate auth)
{
var result = SSLSetClientSideAuthenticate (Handle, auth);
CheckStatusAndThrow (result);
}
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ SslStatus SSLHandshake (/* SSLContextRef */ IntPtr context);
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ SslStatus SSLGetSessionState (/* SSLContextRef */ IntPtr context, ref SslSessionState state);
public SslSessionState SessionState {
get {
var value = SslSessionState.Invalid;
var result = SSLGetSessionState (Handle, ref value);
CheckStatusAndThrow (result);
return value;
}
}
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLGetPeerID (/* SSLContextRef */ IntPtr context, /* const void** */ out IntPtr peerID, /* size_t* */ out IntPtr peerIDLen);
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLSetPeerID (/* SSLContextRef */ IntPtr context, /* const void* */ byte* peerID, /* size_t */ IntPtr peerIDLen);
public unsafe byte[] PeerId {
get {
IntPtr length;
IntPtr id;
var result = SSLGetPeerID (Handle, out id, out length);
CheckStatusAndThrow (result);
if ((result != SslStatus.Success) || ((int)length == 0))
return null;
var data = new byte [(int)length];
Marshal.Copy (id, data, 0, (int) length);
return data;
}
set {
SslStatus result;
IntPtr length = (value == null) ? IntPtr.Zero : (IntPtr)value.Length;
fixed (byte *p = value) {
result = SSLSetPeerID (Handle, p, length);
}
CheckStatusAndThrow (result);
}
}
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLGetBufferedReadSize (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr bufSize);
public IntPtr BufferedReadSize {
get {
IntPtr value;
var result = SSLGetBufferedReadSize (Handle, out value);
CheckStatusAndThrow (result);
return value;
}
}
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLGetNumberSupportedCiphers (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr numCiphers);
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLGetSupportedCiphers (/* SSLContextRef */ IntPtr context, SslCipherSuite *ciphers, /* size_t* */ ref IntPtr numCiphers);
public unsafe IList<SslCipherSuite> GetSupportedCiphers ()
{
IntPtr n;
var result = SSLGetNumberSupportedCiphers (Handle, out n);
CheckStatusAndThrow (result);
if ((result != SslStatus.Success) || ((int)n <= 0))
return null;
var ciphers = new SslCipherSuite [(int)n];
fixed (SslCipherSuite *p = ciphers) {
result = SSLGetSupportedCiphers (Handle, p, ref n);
}
CheckStatusAndThrow (result);
return ciphers;
}
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLGetNumberEnabledCiphers (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr numCiphers);
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLGetEnabledCiphers (/* SSLContextRef */ IntPtr context, SslCipherSuite *ciphers, /* size_t* */ ref IntPtr numCiphers);
public unsafe IList<SslCipherSuite> GetEnabledCiphers ()
{
IntPtr n;
var result = SSLGetNumberEnabledCiphers (Handle, out n);
CheckStatusAndThrow (result);
if ((result != SslStatus.Success) || ((int)n <= 0))
return null;
var ciphers = new SslCipherSuite [(int)n];
fixed (SslCipherSuite *p = ciphers) {
result = SSLGetEnabledCiphers (Handle, p, ref n);
}
CheckStatusAndThrow (result);
return ciphers;
}
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLSetEnabledCiphers (/* SSLContextRef */ IntPtr context, SslCipherSuite *ciphers, /* size_t */ IntPtr numCiphers);
public unsafe void SetEnabledCiphers (SslCipherSuite [] ciphers)
{
if (ciphers == null)
throw new ArgumentNullException ("ciphers");
SslStatus result;
fixed (SslCipherSuite *p = ciphers)
result = SSLSetEnabledCiphers (Handle, p, (IntPtr)ciphers.Length);
CheckStatusAndThrow (result);
}
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLGetNegotiatedCipher (/* SSLContextRef */ IntPtr context, /* SslCipherSuite* */ out SslCipherSuite cipherSuite);
public SslCipherSuite NegotiatedCipher {
get {
SslCipherSuite value;
var result = SSLGetNegotiatedCipher (Handle, out value);
CheckStatusAndThrow (result);
return value;
}
}
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLGetPeerDomainNameLength (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr peerNameLen);
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLGetPeerDomainName (/* SSLContextRef */ IntPtr context, /* char* */ byte[] peerName, /* size_t */ ref IntPtr peerNameLen);
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLSetPeerDomainName (/* SSLContextRef */ IntPtr context, /* char* */ byte[] peerName, /* size_t */ IntPtr peerNameLen);
public string PeerDomainName {
get {
IntPtr length;
var result = SSLGetPeerDomainNameLength (Handle, out length);
CheckStatusAndThrow (result);
if (result != SslStatus.Success || (int)length == 0)
return String.Empty;
var bytes = new byte [(int)length];
result = SSLGetPeerDomainName (Handle, bytes, ref length);
CheckStatusAndThrow (result);
int peerDomainLength = (int)length;
if (result != SslStatus.Success)
return string.Empty;
if (peerDomainLength > 0 && bytes [peerDomainLength-1] == 0)
peerDomainLength = peerDomainLength - 1;
return Encoding.UTF8.GetString (bytes, 0, peerDomainLength);
}
set {
SslStatus result;
if (value == null) {
result = SSLSetPeerDomainName (Handle, null, (IntPtr)0);
} else {
var bytes = Encoding.UTF8.GetBytes (value);
result = SSLSetPeerDomainName (Handle, bytes, (IntPtr)bytes.Length);
}
CheckStatusAndThrow (result);
}
}
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLSetCertificate (/* SSLContextRef */ IntPtr context, /* CFArrayRef */ IntPtr certRefs);
CFArray Bundle (SecIdentity identity, IEnumerable<SecCertificate> certificates)
{
if (identity == null)
throw new ArgumentNullException ("identity");
int i = 0;
int n = 0;
if (certificates != null) {
foreach (var obj in certificates)
n++;
}
var ptrs = new IntPtr [n + 1];
ptrs [0] = identity.Handle;
foreach (var certificate in certificates)
ptrs [++i] = certificate.Handle;
return CFArray.CreateArray (ptrs);
}
public void SetCertificate (SecIdentity identify, IEnumerable<SecCertificate> certificates)
{
using (var array = Bundle (identify, certificates)) {
var result = SSLSetCertificate (Handle, array.Handle);
CheckStatusAndThrow (result);
}
}
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLGetClientCertificateState (/* SSLContextRef */ IntPtr context, out SslClientCertificateState clientState);
public SslClientCertificateState ClientCertificateState {
get {
SslClientCertificateState value;
var result = SSLGetClientCertificateState (Handle, out value);
CheckStatusAndThrow (result);
return value;
}
}
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLCopyPeerTrust (/* SSLContextRef */ IntPtr context, /* SecTrustRef */ out IntPtr trust);
public SecTrust GetPeerTrust (bool requireTrust)
{
IntPtr value;
var result = SSLCopyPeerTrust (Handle, out value);
if (requireTrust) {
CheckStatusAndThrow (result);
if (value == IntPtr.Zero)
throw new TlsException (AlertDescription.CertificateUnknown);
}
return (value == IntPtr.Zero) ? null : new SecTrust (value);
}
#endregion
#region IO Functions
[DllImport (SecurityLibrary)]
extern static /* SSLContextRef */ IntPtr SSLCreateContext (/* CFAllocatorRef */ IntPtr alloc, SslProtocolSide protocolSide, SslConnectionType connectionType);
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ SslStatus SSLSetConnection (/* SSLContextRef */ IntPtr context, /* SSLConnectionRef */ IntPtr connection);
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ SslStatus SSLSetIOFuncs (/* SSLContextRef */ IntPtr context, /* SSLReadFunc */ SslReadFunc readFunc, /* SSLWriteFunc */ SslWriteFunc writeFunc);
[MonoPInvokeCallback (typeof (SslReadFunc))]
static SslStatus NativeReadCallback (IntPtr ptr, IntPtr data, ref IntPtr dataLength)
{
var handle = GCHandle.FromIntPtr (ptr);
if (!handle.IsAllocated)
return SslStatus.Internal;
var context = (AppleTlsContext) handle.Target;
if (context.disposed)
return SslStatus.ClosedAbort;
try {
return context.NativeReadCallback (data, ref dataLength);
} catch (Exception ex) {
if (context.lastException == null)
context.lastException = ex;
return SslStatus.Internal;
}
}
[MonoPInvokeCallback (typeof (SslWriteFunc))]
static SslStatus NativeWriteCallback (IntPtr ptr, IntPtr data, ref IntPtr dataLength)
{
var handle = GCHandle.FromIntPtr (ptr);
if (!handle.IsAllocated)
return SslStatus.Internal;
var context = (AppleTlsContext) handle.Target;
if (context.disposed)
return SslStatus.ClosedAbort;
try {
return context.NativeWriteCallback (data, ref dataLength);
} catch (Exception ex) {
if (context.lastException == null)
context.lastException = ex;
return SslStatus.Internal;
}
}
SslStatus NativeReadCallback (IntPtr data, ref IntPtr dataLength)
{
if (closed || disposed || Parent == null)
return SslStatus.ClosedAbort;
var len = (int)dataLength;
var readBuffer = new byte [len];
Debug ("NativeReadCallback: {0} {1}", dataLength, len);
bool wantMore;
var ret = Parent.InternalRead (readBuffer, 0, len, out wantMore);
dataLength = (IntPtr)ret;
Debug ("NativeReadCallback #1: {0} - {1} {2}", len, ret, wantMore);
if (ret < 0)
return SslStatus.ClosedAbort;
Marshal.Copy (readBuffer, 0, data, ret);
if (ret > 0)
return SslStatus.Success;
else if (wantMore)
return SslStatus.WouldBlock;
else if (ret == 0) {
closedGraceful = true;
return SslStatus.ClosedGraceful;
} else {
return SslStatus.Success;
}
}
SslStatus NativeWriteCallback (IntPtr data, ref IntPtr dataLength)
{
if (closed || disposed || Parent == null)
return SslStatus.ClosedAbort;
var len = (int)dataLength;
var writeBuffer = new byte [len];
Marshal.Copy (data, writeBuffer, 0, len);
Debug ("NativeWriteCallback: {0}", len);
var ok = Parent.InternalWrite (writeBuffer, 0, len);
Debug ("NativeWriteCallback done: {0} {1}", len, ok);
return ok ? SslStatus.Success : SslStatus.ClosedAbort;
}
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLRead (/* SSLContextRef */ IntPtr context, /* const void* */ byte* data, /* size_t */ IntPtr dataLength, /* size_t* */ out IntPtr processed);
public override unsafe int Read (byte[] buffer, int offset, int count, out bool wantMore)
{
if (Interlocked.Exchange (ref pendingIO, 1) == 1)
throw new InvalidOperationException ();
Debug ("Read: {0},{1}", offset, count);
lastException = null;
try {
IntPtr processed;
SslStatus status;
fixed (byte *d = &buffer [offset])
status = SSLRead (Handle, d, (IntPtr)count, out processed);
Debug ("Read done: {0} {1} {2}", status, count, processed);
if (closedGraceful && (status == SslStatus.ClosedAbort || status == SslStatus.ClosedGraceful)) {
/*
* This is really ugly, but unfortunately SSLRead() also returns 'SslStatus.ClosedAbort'
* when the first inner Read() returns 0. MobileAuthenticatedStream.InnerRead() attempts
* to distinguish between a graceful close and abnormal termination of connection.
*/
wantMore = false;
return 0;
}
CheckStatusAndThrow (status, SslStatus.WouldBlock, SslStatus.ClosedGraceful);
wantMore = status == SslStatus.WouldBlock;
return (int)processed;
} catch (Exception ex) {
Debug ("Read error: {0}", ex);
throw;
} finally {
pendingIO = 0;
}
}
[DllImport (SecurityLibrary)]
extern unsafe static /* OSStatus */ SslStatus SSLWrite (/* SSLContextRef */ IntPtr context, /* const void* */ byte* data, /* size_t */ IntPtr dataLength, /* size_t* */ out IntPtr processed);
public override unsafe int Write (byte[] buffer, int offset, int count, out bool wantMore)
{
if (Interlocked.Exchange (ref pendingIO, 1) == 1)
throw new InvalidOperationException ();
Debug ("Write: {0},{1}", offset, count);
lastException = null;
try {
SslStatus status = SslStatus.ClosedAbort;
IntPtr processed = (IntPtr)(-1);
fixed (byte *d = &buffer [offset])
status = SSLWrite (Handle, d, (IntPtr)count, out processed);
Debug ("Write done: {0} {1}", status, processed);
CheckStatusAndThrow (status, SslStatus.WouldBlock);
wantMore = status == SslStatus.WouldBlock;
return (int)processed;
} finally {
pendingIO = 0;
}
}
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ SslStatus SSLClose (/* SSLContextRef */ IntPtr context);
public override void Close ()
{
if (Interlocked.Exchange (ref pendingIO, 1) == 1)
throw new InvalidOperationException ();
Debug ("Close");
lastException = null;
try {
if (closed || disposed)
return;
var status = SSLClose (Handle);
Debug ("Close done: {0}", status);
CheckStatusAndThrow (status);
} finally {
closed = true;
pendingIO = 0;
}
}
#endregion
protected override void Dispose (bool disposing)
{
try {
if (disposed)
return;
if (disposing) {
disposed = true;
if (serverIdentity != null) {
serverIdentity.Dispose ();
serverIdentity = null;
}
if (clientIdentity != null) {
clientIdentity.Dispose ();
clientIdentity = null;
}
if (remoteCertificate != null) {
remoteCertificate.Dispose ();
remoteCertificate = null;
}
}
} finally {
disposed = true;
if (context != IntPtr.Zero) {
CFObject.CFRelease (context);
context = IntPtr.Zero;
}
base.Dispose (disposing);
}
}
}
}
#endif
@@ -0,0 +1,77 @@
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
//
// AppleTlsProvider.cs
//
// Author:
// Martin Baulig <[email protected]>
//
// Copyright (c) 2015 Xamarin, Inc.
//
#if MONO_SECURITY_ALIAS
extern alias MonoSecurity;
#endif
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using MNS = Mono.Net.Security;
#if MONO_SECURITY_ALIAS
using MonoSecurity::Mono.Security.Interface;
#else
using Mono.Security.Interface;
#endif
namespace Mono.AppleTls
{
class AppleTlsProvider : MonoTlsProvider
{
static readonly Guid id = new Guid ("981af8af-a3a3-419a-9f01-a518e3a17c1c");
public override string Name {
get { return "apple-tls"; }
}
public override Guid ID {
get { return id; }
}
public override IMonoSslStream CreateSslStream (
Stream innerStream, bool leaveInnerStreamOpen,
MonoTlsSettings settings = null)
{
return new AppleTlsStream (innerStream, leaveInnerStreamOpen, settings, this);
}
public override bool SupportsSslStream {
get { return true; }
}
public override bool SupportsMonoExtensions {
get { return true; }
}
public override bool SupportsConnectionInfo {
get { return true; }
}
public override SslProtocols SupportedProtocols {
get { return SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls; }
}
internal override bool ValidateCertificate (
ICertificateValidator2 validator, string targetHost, bool serverMode,
X509CertificateCollection certificates, bool wantsChain, ref X509Chain chain,
ref MonoSslPolicyErrors errors, ref int status11)
{
if (wantsChain)
chain = MNS.SystemCertificateValidator.CreateX509Chain (certificates);
return AppleCertificateHelper.InvokeSystemCertificateValidator (validator, targetHost, serverMode, certificates, ref errors, ref status11);
}
}
}
#endif
@@ -0,0 +1,50 @@
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
//
// AppleTlsStream.cs
//
// Author:
// Martin Baulig <[email protected]>
//
// Copyright (c) 2016 Xamarin, Inc.
//
#if MONO_SECURITY_ALIAS
extern alias MonoSecurity;
#endif
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using MNS = Mono.Net.Security;
#if MONO_SECURITY_ALIAS
using MonoSecurity::Mono.Security.Interface;
#else
using Mono.Security.Interface;
#endif
namespace Mono.AppleTls
{
class AppleTlsStream : MNS.MobileAuthenticatedStream
{
public AppleTlsStream (Stream innerStream, bool leaveInnerStreamOpen, MonoTlsSettings settings, MonoTlsProvider provider)
: base (innerStream, leaveInnerStreamOpen, settings, provider)
{
}
protected override MNS.MobileTlsContext CreateContext (
MNS.MobileAuthenticatedStream parent, bool serverMode, string targetHost,
SslProtocols enabledProtocols, X509Certificate serverCertificate,
X509CertificateCollection clientCertificates, bool askForClientCert)
{
return new AppleTlsContext (
parent, serverMode, targetHost,
enabledProtocols, serverCertificate,
clientCertificates, askForClientCert);
}
}
}
#endif
@@ -0,0 +1,450 @@
//
// Certificate.cs: Implements the managed SecCertificate wrapper.
//
// Authors:
// Miguel de Icaza
// Sebastien Pouliot <[email protected]>
//
// Copyright 2010 Novell, Inc
// Copyright 2012-2013 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.
//
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using Mono.Net;
using ObjCRuntime;
namespace Mono.AppleTls {
partial class SecCertificate : INativeObject, IDisposable {
internal IntPtr handle;
internal SecCertificate (IntPtr handle, bool owns = false)
{
if (handle == IntPtr.Zero)
throw new Exception ("Invalid handle");
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
[DllImport (AppleTlsContext.SecurityLibrary, EntryPoint="SecCertificateGetTypeID")]
public extern static IntPtr GetTypeID ();
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static IntPtr SecCertificateCreateWithData (IntPtr allocator, IntPtr cfData);
public SecCertificate (X509Certificate certificate)
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
handle = certificate.Impl.GetNativeAppleCertificate ();
if (handle != IntPtr.Zero) {
CFObject.CFRetain (handle);
return;
}
using (CFData cert = CFData.FromData (certificate.GetRawCertData ())) {
Initialize (cert);
}
}
internal SecCertificate (X509CertificateImpl impl)
{
handle = impl.GetNativeAppleCertificate ();
if (handle != IntPtr.Zero) {
CFObject.CFRetain (handle);
return;
}
using (CFData cert = CFData.FromData (impl.GetRawCertData ())) {
Initialize (cert);
}
}
void Initialize (CFData data)
{
handle = SecCertificateCreateWithData (IntPtr.Zero, data.Handle);
if (handle == IntPtr.Zero)
throw new ArgumentException ("Not a valid DER-encoded X.509 certificate");
}
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static IntPtr SecCertificateCopySubjectSummary (IntPtr cert);
public string SubjectSummary {
get {
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecCertificate");
IntPtr subjectSummaryHandle = IntPtr.Zero;
try {
subjectSummaryHandle = SecCertificateCopySubjectSummary (handle);
CFString subjectSummary = CFString.AsString (subjectSummaryHandle);
return subjectSummary;
}
finally {
if (subjectSummaryHandle != IntPtr.Zero)
CFObject.CFRelease (subjectSummaryHandle);
}
}
}
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static /* CFDataRef */ IntPtr SecCertificateCopyData (/* SecCertificateRef */ IntPtr cert);
public CFData DerData {
get {
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecCertificate");
IntPtr data = SecCertificateCopyData (handle);
if (data == IntPtr.Zero)
throw new ArgumentException ("Not a valid certificate");
return new CFData (data, true);
}
}
public X509Certificate ToX509Certificate ()
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecCertificate");
return new X509Certificate (handle);
}
internal static bool Equals (SecCertificate first, SecCertificate second)
{
/*
* This is a little bit expensive, but unfortunately there is no better API to compare two
* SecCertificateRef's for equality.
*/
if (first == null)
throw new ArgumentNullException ("first");
if (second == null)
throw new ArgumentNullException ("second");
if (first.Handle == second.Handle)
return true;
using (var firstData = first.DerData)
using (var secondData = second.DerData) {
if (firstData.Handle == secondData.Handle)
return true;
if (firstData.Length != secondData.Length)
return false;
IntPtr length = (IntPtr)firstData.Length;
for (long i = 0; i < (long)length; i++) {
if (firstData [i] != secondData [i])
return false;
}
return true;
}
}
~SecCertificate ()
{
Dispose (false);
}
public IntPtr Handle {
get {
return handle;
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
}
partial class SecIdentity : INativeObject, IDisposable {
static readonly CFString ImportExportPassphase;
static readonly CFString ImportItemIdentity;
static readonly CFString ImportExportAccess;
static readonly CFString ImportExportKeychain;
static SecIdentity ()
{
var handle = CFObject.dlopen (AppleTlsContext.SecurityLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
ImportExportPassphase = CFObject.GetStringConstant (handle, "kSecImportExportPassphrase");
ImportItemIdentity = CFObject.GetStringConstant (handle, "kSecImportItemIdentity");
ImportExportAccess = CFObject.GetStringConstant (handle, "kSecImportExportAccess");
ImportExportKeychain = CFObject.GetStringConstant (handle, "kSecImportExportKeychain");
} finally {
CFObject.dlclose (handle);
}
}
internal IntPtr handle;
internal SecIdentity (IntPtr handle, bool owns = false)
{
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
[DllImport (AppleTlsContext.SecurityLibrary, EntryPoint="SecIdentityGetTypeID")]
public extern static IntPtr GetTypeID ();
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static /* OSStatus */ SecStatusCode SecIdentityCopyCertificate (/* SecIdentityRef */ IntPtr identityRef, /* SecCertificateRef* */ out IntPtr certificateRef);
public SecCertificate Certificate {
get {
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecIdentity");
IntPtr cert;
SecStatusCode result = SecIdentityCopyCertificate (handle, out cert);
if (result != SecStatusCode.Success)
throw new InvalidOperationException (result.ToString ());
return new SecCertificate (cert, true);
}
}
internal class ImportOptions
{
#if !MONOTOUCH
public SecAccess Access {
get; set;
}
public SecKeyChain KeyChain {
get; set;
}
#endif
}
static CFDictionary CreateImportOptions (CFString password, ImportOptions options = null)
{
if (options == null)
return CFDictionary.FromObjectAndKey (password.Handle, ImportExportPassphase.Handle);
var items = new List<Tuple<IntPtr, IntPtr>> ();
items.Add (new Tuple<IntPtr, IntPtr> (ImportExportPassphase.Handle, password.Handle));
#if !MONOTOUCH
if (options.KeyChain != null)
items.Add (new Tuple<IntPtr, IntPtr> (ImportExportKeychain.Handle, options.KeyChain.Handle));
if (options.Access != null)
items.Add (new Tuple<IntPtr, IntPtr> (ImportExportAccess.Handle, options.Access.Handle));
#endif
return CFDictionary.FromKeysAndObjects (items);
}
public static SecIdentity Import (byte[] data, string password, ImportOptions options = null)
{
if (data == null)
throw new ArgumentNullException ("data");
if (string.IsNullOrEmpty (password)) // SecPKCS12Import() doesn't allow empty passwords.
throw new ArgumentException ("password");
using (var pwstring = CFString.Create (password))
using (var optionDict = CreateImportOptions (pwstring, options)) {
CFDictionary [] array;
SecStatusCode result = SecImportExport.ImportPkcs12 (data, optionDict, out array);
if (result != SecStatusCode.Success)
throw new InvalidOperationException (result.ToString ());
return new SecIdentity (array [0].GetValue (ImportItemIdentity.Handle));
}
}
public static SecIdentity Import (X509Certificate2 certificate, ImportOptions options = null)
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
if (!certificate.HasPrivateKey)
throw new InvalidOperationException ("Need X509Certificate2 with a private key.");
/*
* SecPSK12Import does not allow any empty passwords, so let's generate
* a semi-random one here.
*/
var password = Guid.NewGuid ().ToString ();
var pkcs12 = certificate.Export (X509ContentType.Pfx, password);
return Import (pkcs12, password, options);
}
~SecIdentity ()
{
Dispose (false);
}
public IntPtr Handle {
get {
return handle;
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
}
partial class SecKey : INativeObject, IDisposable {
internal IntPtr handle;
internal IntPtr owner;
public SecKey (IntPtr handle, bool owns = false)
{
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
/*
* SecItemImport() returns a SecArrayRef. We need to free the array, not the items inside it.
*
*/
internal SecKey (IntPtr handle, IntPtr owner)
{
this.handle = handle;
this.owner = owner;
CFObject.CFRetain (owner);
}
[DllImport (AppleTlsContext.SecurityLibrary, EntryPoint="SecKeyGetTypeID")]
public extern static IntPtr GetTypeID ();
~SecKey ()
{
Dispose (false);
}
public IntPtr Handle {
get {
return handle;
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (owner != IntPtr.Zero) {
CFObject.CFRelease (owner);
owner = handle = IntPtr.Zero;
} else if (handle != IntPtr.Zero) {
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
}
#if !MONOTOUCH
class SecAccess : INativeObject, IDisposable {
internal IntPtr handle;
public SecAccess (IntPtr handle, bool owns = false)
{
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
~SecAccess ()
{
Dispose (false);
}
public IntPtr Handle {
get {
return handle;
}
}
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static /* OSStatus */ SecStatusCode SecAccessCreate (/* CFStringRef */ IntPtr descriptor, /* CFArrayRef */ IntPtr trustedList, /* SecAccessRef _Nullable * */ out IntPtr accessRef);
public static SecAccess Create (string descriptor)
{
var descriptorHandle = CFString.Create (descriptor);
if (descriptorHandle == null)
throw new InvalidOperationException ();
try {
IntPtr accessRef;
var result = SecAccessCreate (descriptorHandle.Handle, IntPtr.Zero, out accessRef);
if (result != SecStatusCode.Success)
throw new InvalidOperationException (result.ToString ());
return new SecAccess (accessRef, true);
} finally {
descriptorHandle.Dispose ();
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero) {
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
}
#endif
}
#endif
+408
View File
@@ -0,0 +1,408 @@
#if MONO_FEATURE_APPLETLS
// Copyright 2011-2015 Xamarin Inc. All rights reserved.
using ObjCRuntime;
namespace Mono.AppleTls {
// this is a subset of OSStatus -> SInt32 -> signed int - see CoreFoundation.framework/Headers/CFBase.h
// values are defined in Security.framework/Headers/SecBase.h
enum SecStatusCode {
Success = 0,
Unimplemented = -4,
DiskFull = -34,
IO = -36,
OpWr = -49,
Param = -50,
WritePermissions = -61,
Allocate = -108,
UserCanceled = -128,
BadReq = -909,
InternalComponent = -2070,
CoreFoundationUnknown = -4960,
NotAvailable = -25291,
ReadOnly = -25292,
AuthFailed = -25293,
NoSuchKeyChain = -25294,
InvalidKeyChain = -25295,
DuplicateKeyChain = -25296,
DuplicateItem = -25299,
ItemNotFound = -25300,
InteractionNotAllowed = -25308,
Decode = -26275,
DuplicateCallback = -25297,
InvalidCallback = -25298,
BufferTooSmall = -25301,
DataTooLarge = -25302,
NoSuchAttribute = -25303,
InvalidItemRef = -25304,
InvalidSearchRef = -25305,
NoSuchClass = -25306,
NoDefaultKeychain = -25307,
ReadOnlyAttribute = -25309,
WrongSecVersion = -25310,
KeySizeNotAllowed = -25311,
NoStorageModule = -25312,
NoCertificateModule = -25313,
NoPolicyModule = -25314,
InteractionRequired = -25315,
DataNotAvailable = -25316,
DataNotModifiable = -25317,
CreateChainFailed = -25318,
InvalidPrefsDomain = -25319,
InDarkWake = -25320,
ACLNotSimple = -25240,
PolicyNotFound = -25241,
InvalidTrustSetting = -25242,
NoAccessForItem = -25243,
InvalidOwnerEdit = -25244,
TrustNotAvailable = -25245,
UnsupportedFormat = -25256,
UnknownFormat = -25257,
KeyIsSensitive = -25258,
MultiplePrivateKeys = -25259,
PassphraseRequired = -25260,
InvalidPasswordRef = -25261,
InvalidTrustSettings = -25262,
NoTrustSettings = -25263,
Pkcs12VerifyFailure = -25264,
NotSigner = -26267,
ServiceNotAvailable = -67585,
InsufficientClientID = -67586,
DeviceReset = -67587,
DeviceFailed = -67588,
AppleAddAppACLSubject = -67589,
ApplePublicKeyIncomplete = -67590,
AppleSignatureMismatch = -67591,
AppleInvalidKeyStartDate = -67592,
AppleInvalidKeyEndDate = -67593,
ConversionError = -67594,
AppleSSLv2Rollback = -67595,
QuotaExceeded = -67596,
FileTooBig = -67597,
InvalidDatabaseBlob = -67598,
InvalidKeyBlob = -67599,
IncompatibleDatabaseBlob = -67600,
IncompatibleKeyBlob = -67601,
HostNameMismatch = -67602,
UnknownCriticalExtensionFlag = -67603,
NoBasicConstraints = -67604,
NoBasicConstraintsCA = -67605,
InvalidAuthorityKeyID = -67606,
InvalidSubjectKeyID = -67607, /* The subject key ID is not valid. */
InvalidKeyUsageForPolicy = -67608, /* The key usage is not valid for the specified policy. */
InvalidExtendedKeyUsage = -67609, /* The extended key usage is not valid. */
InvalidIDLinkage = -67610, /* The ID linkage is not valid. */
PathLengthConstraintExceeded = -67611, /* The path length constraint was exceeded. */
InvalidRoot = -67612, /* The root or anchor certificate is not valid. */
CRLExpired = -67613, /* The CRL has expired. */
CRLNotValidYet = -67614, /* The CRL is not yet valid. */
CRLNotFound = -67615, /* The CRL was not found. */
CRLServerDown = -67616, /* The CRL server is down. */
CRLBadURI = -67617, /* The CRL has a bad Uniform Resource Identifier. */
UnknownCertExtension = -67618, /* An unknown certificate extension was encountered. */
UnknownCRLExtension = -67619, /* An unknown CRL extension was encountered. */
CRLNotTrusted = -67620, /* The CRL is not trusted. */
CRLPolicyFailed = -67621, /* The CRL policy failed. */
IDPFailure = -67622, /* The issuing distribution point was not valid. */
SMIMEEmailAddressesNotFound = -67623, /* An email address mismatch was encountered. */
SMIMEBadExtendedKeyUsage = -67624, /* The appropriate extended key usage for SMIME was not found. */
SMIMEBadKeyUsage = -67625, /* The key usage is not compatible with SMIME. */
SMIMEKeyUsageNotCritical = -67626, /* The key usage extension is not marked as critical. */
SMIMENoEmailAddress = -67627, /* No email address was found in the certificate. */
SMIMESubjAltNameNotCritical = -67628, /* The subject alternative name extension is not marked as critical. */
SSLBadExtendedKeyUsage = -67629, /* The appropriate extended key usage for SSL was not found. */
OCSPBadResponse = -67630, /* The OCSP response was incorrect or could not be parsed. */
OCSPBadRequest = -67631, /* The OCSP request was incorrect or could not be parsed. */
OCSPUnavailable = -67632, /* OCSP service is unavailable. */
OCSPStatusUnrecognized = -67633, /* The OCSP server did not recognize this certificate. */
EndOfData = -67634, /* An end-of-data was detected. */
IncompleteCertRevocationCheck = -67635, /* An incomplete certificate revocation check occurred. */
NetworkFailure = -67636, /* A network failure occurred. */
OCSPNotTrustedToAnchor = -67637, /* The OCSP response was not trusted to a root or anchor certificate. */
RecordModified = -67638, /* The record was modified. */
OCSPSignatureError = -67639, /* The OCSP response had an invalid signature. */
OCSPNoSigner = -67640, /* The OCSP response had no signer. */
OCSPResponderMalformedReq = -67641, /* The OCSP responder was given a malformed request. */
OCSPResponderInternalError = -67642, /* The OCSP responder encountered an internal error. */
OCSPResponderTryLater = -67643, /* The OCSP responder is busy, try again later. */
OCSPResponderSignatureRequired = -67644, /* The OCSP responder requires a signature. */
OCSPResponderUnauthorized = -67645, /* The OCSP responder rejected this request as unauthorized. */
OCSPResponseNonceMismatch = -67646, /* The OCSP response nonce did not match the request. */
CodeSigningBadCertChainLength = -67647, /* Code signing encountered an incorrect certificate chain length. */
CodeSigningNoBasicConstraints = -67648, /* Code signing found no basic constraints. */
CodeSigningBadPathLengthConstraint = -67649, /* Code signing encountered an incorrect path length constraint. */
CodeSigningNoExtendedKeyUsage = -67650, /* Code signing found no extended key usage. */
CodeSigningDevelopment = -67651, /* Code signing indicated use of a development-only certificate. */
ResourceSignBadCertChainLength = -67652, /* Resource signing has encountered an incorrect certificate chain length. */
ResourceSignBadExtKeyUsage = -67653, /* Resource signing has encountered an error in the extended key usage. */
TrustSettingDeny = -67654, /* The trust setting for this policy was set to Deny. */
InvalidSubjectName = -67655, /* An invalid certificate subject name was encountered. */
UnknownQualifiedCertStatement = -67656, /* An unknown qualified certificate statement was encountered. */
MobileMeRequestQueued = -67657, /* The MobileMe request will be sent during the next connection. */
MobileMeRequestRedirected = -67658, /* The MobileMe request was redirected. */
MobileMeServerError = -67659, /* A MobileMe server error occurred. */
MobileMeServerNotAvailable = -67660, /* The MobileMe server is not available. */
MobileMeServerAlreadyExists = -67661, /* The MobileMe server reported that the item already exists. */
MobileMeServerServiceErr = -67662, /* A MobileMe service error has occurred. */
MobileMeRequestAlreadyPending = -67663, /* A MobileMe request is already pending. */
MobileMeNoRequestPending = -67664, /* MobileMe has no request pending. */
MobileMeCSRVerifyFailure = -67665, /* A MobileMe CSR verification failure has occurred. */
MobileMeFailedConsistencyCheck = -67666, /* MobileMe has found a failed consistency check. */
NotInitialized = -67667, /* A function was called without initializing CSSM. */
InvalidHandleUsage = -67668, /* The CSSM handle does not match with the service type. */
PVCReferentNotFound = -67669, /* A reference to the calling module was not found in the list of authorized callers. */
FunctionIntegrityFail = -67670, /* A function address was not within the verified module. */
InternalError = -67671, /* An internal error has occurred. */
MemoryError = -67672, /* A memory error has occurred. */
InvalidData = -67673, /* Invalid data was encountered. */
MDSError = -67674, /* A Module Directory Service error has occurred. */
InvalidPointer = -67675, /* An invalid pointer was encountered. */
SelfCheckFailed = -67676, /* Self-check has failed. */
FunctionFailed = -67677, /* A function has failed. */
ModuleManifestVerifyFailed = -67678, /* A module manifest verification failure has occurred. */
InvalidGUID = -67679, /* An invalid GUID was encountered. */
InvalidHandle = -67680, /* An invalid handle was encountered. */
InvalidDBList = -67681, /* An invalid DB list was encountered. */
InvalidPassthroughID = -67682, /* An invalid passthrough ID was encountered. */
InvalidNetworkAddress = -67683, /* An invalid network address was encountered. */
CRLAlreadySigned = -67684, /* The certificate revocation list is already signed. */
InvalidNumberOfFields = -67685, /* An invalid number of fields were encountered. */
VerificationFailure = -67686, /* A verification failure occurred. */
UnknownTag = -67687, /* An unknown tag was encountered. */
InvalidSignature = -67688, /* An invalid signature was encountered. */
InvalidName = -67689, /* An invalid name was encountered. */
InvalidCertificateRef = -67690, /* An invalid certificate reference was encountered. */
InvalidCertificateGroup = -67691, /* An invalid certificate group was encountered. */
TagNotFound = -67692, /* The specified tag was not found. */
InvalidQuery = -67693, /* The specified query was not valid. */
InvalidValue = -67694, /* An invalid value was detected. */
CallbackFailed = -67695, /* A callback has failed. */
ACLDeleteFailed = -67696, /* An ACL delete operation has failed. */
ACLReplaceFailed = -67697, /* An ACL replace operation has failed. */
ACLAddFailed = -67698, /* An ACL add operation has failed. */
ACLChangeFailed = -67699, /* An ACL change operation has failed. */
InvalidAccessCredentials = -67700, /* Invalid access credentials were encountered. */
InvalidRecord = -67701, /* An invalid record was encountered. */
InvalidACL = -67702, /* An invalid ACL was encountered. */
InvalidSampleValue = -67703, /* An invalid sample value was encountered. */
IncompatibleVersion = -67704, /* An incompatible version was encountered. */
PrivilegeNotGranted = -67705, /* The privilege was not granted. */
InvalidScope = -67706, /* An invalid scope was encountered. */
PVCAlreadyConfigured = -67707, /* The PVC is already configured. */
InvalidPVC = -67708, /* An invalid PVC was encountered. */
EMMLoadFailed = -67709, /* The EMM load has failed. */
EMMUnloadFailed = -67710, /* The EMM unload has failed. */
AddinLoadFailed = -67711, /* The add-in load operation has failed. */
InvalidKeyRef = -67712, /* An invalid key was encountered. */
InvalidKeyHierarchy = -67713, /* An invalid key hierarchy was encountered. */
AddinUnloadFailed = -67714, /* The add-in unload operation has failed. */
LibraryReferenceNotFound = -67715, /* A library reference was not found. */
InvalidAddinFunctionTable = -67716, /* An invalid add-in function table was encountered. */
InvalidServiceMask = -67717, /* An invalid service mask was encountered. */
ModuleNotLoaded = -67718, /* A module was not loaded. */
InvalidSubServiceID = -67719, /* An invalid subservice ID was encountered. */
AttributeNotInContext = -67720, /* An attribute was not in the context. */
ModuleManagerInitializeFailed = -67721, /* A module failed to initialize. */
ModuleManagerNotFound = -67722, /* A module was not found. */
EventNotificationCallbackNotFound = -67723, /* An event notification callback was not found. */
InputLengthError = -67724, /* An input length error was encountered. */
OutputLengthError = -67725, /* An output length error was encountered. */
PrivilegeNotSupported = -67726, /* The privilege is not supported. */
DeviceError = -67727, /* A device error was encountered. */
AttachHandleBusy = -67728, /* The CSP handle was busy. */
NotLoggedIn = -67729, /* You are not logged in. */
AlgorithmMismatch = -67730, /* An algorithm mismatch was encountered. */
KeyUsageIncorrect = -67731, /* The key usage is incorrect. */
KeyBlobTypeIncorrect = -67732, /* The key blob type is incorrect. */
KeyHeaderInconsistent = -67733, /* The key header is inconsistent. */
UnsupportedKeyFormat = -67734, /* The key header format is not supported. */
UnsupportedKeySize = -67735, /* The key size is not supported. */
InvalidKeyUsageMask = -67736, /* The key usage mask is not valid. */
UnsupportedKeyUsageMask = -67737, /* The key usage mask is not supported. */
InvalidKeyAttributeMask = -67738, /* The key attribute mask is not valid. */
UnsupportedKeyAttributeMask = -67739, /* The key attribute mask is not supported. */
InvalidKeyLabel = -67740, /* The key label is not valid. */
UnsupportedKeyLabel = -67741, /* The key label is not supported. */
InvalidKeyFormat = -67742, /* The key format is not valid. */
UnsupportedVectorOfBuffers = -67743, /* The vector of buffers is not supported. */
InvalidInputVector = -67744, /* The input vector is not valid. */
InvalidOutputVector = -67745, /* The output vector is not valid. */
InvalidContext = -67746, /* An invalid context was encountered. */
InvalidAlgorithm = -67747, /* An invalid algorithm was encountered. */
InvalidAttributeKey = -67748, /* A key attribute was not valid. */
MissingAttributeKey = -67749, /* A key attribute was missing. */
InvalidAttributeInitVector = -67750, /* An init vector attribute was not valid. */
MissingAttributeInitVector = -67751, /* An init vector attribute was missing. */
InvalidAttributeSalt = -67752, /* A salt attribute was not valid. */
MissingAttributeSalt = -67753, /* A salt attribute was missing. */
InvalidAttributePadding = -67754, /* A padding attribute was not valid. */
MissingAttributePadding = -67755, /* A padding attribute was missing. */
InvalidAttributeRandom = -67756, /* A random number attribute was not valid. */
MissingAttributeRandom = -67757, /* A random number attribute was missing. */
InvalidAttributeSeed = -67758, /* A seed attribute was not valid. */
MissingAttributeSeed = -67759, /* A seed attribute was missing. */
InvalidAttributePassphrase = -67760, /* A passphrase attribute was not valid. */
MissingAttributePassphrase = -67761, /* A passphrase attribute was missing. */
InvalidAttributeKeyLength = -67762, /* A key length attribute was not valid. */
MissingAttributeKeyLength = -67763, /* A key length attribute was missing. */
InvalidAttributeBlockSize = -67764, /* A block size attribute was not valid. */
MissingAttributeBlockSize = -67765, /* A block size attribute was missing. */
InvalidAttributeOutputSize = -67766, /* An output size attribute was not valid. */
MissingAttributeOutputSize = -67767, /* An output size attribute was missing. */
InvalidAttributeRounds = -67768, /* The number of rounds attribute was not valid. */
MissingAttributeRounds = -67769, /* The number of rounds attribute was missing. */
InvalidAlgorithmParms = -67770, /* An algorithm parameters attribute was not valid. */
MissingAlgorithmParms = -67771, /* An algorithm parameters attribute was missing. */
InvalidAttributeLabel = -67772, /* A label attribute was not valid. */
MissingAttributeLabel = -67773, /* A label attribute was missing. */
InvalidAttributeKeyType = -67774, /* A key type attribute was not valid. */
MissingAttributeKeyType = -67775, /* A key type attribute was missing. */
InvalidAttributeMode = -67776, /* A mode attribute was not valid. */
MissingAttributeMode = -67777, /* A mode attribute was missing. */
InvalidAttributeEffectiveBits = -67778, /* An effective bits attribute was not valid. */
MissingAttributeEffectiveBits = -67779, /* An effective bits attribute was missing. */
InvalidAttributeStartDate = -67780, /* A start date attribute was not valid. */
MissingAttributeStartDate = -67781, /* A start date attribute was missing. */
InvalidAttributeEndDate = -67782, /* An end date attribute was not valid. */
MissingAttributeEndDate = -67783, /* An end date attribute was missing. */
InvalidAttributeVersion = -67784, /* A version attribute was not valid. */
MissingAttributeVersion = -67785, /* A version attribute was missing. */
InvalidAttributePrime = -67786, /* A prime attribute was not valid. */
MissingAttributePrime = -67787, /* A prime attribute was missing. */
InvalidAttributeBase = -67788, /* A base attribute was not valid. */
MissingAttributeBase = -67789, /* A base attribute was missing. */
InvalidAttributeSubprime = -67790, /* A subprime attribute was not valid. */
MissingAttributeSubprime = -67791, /* A subprime attribute was missing. */
InvalidAttributeIterationCount = -67792, /* An iteration count attribute was not valid. */
MissingAttributeIterationCount = -67793, /* An iteration count attribute was missing. */
InvalidAttributeDLDBHandle = -67794, /* A database handle attribute was not valid. */
MissingAttributeDLDBHandle = -67795, /* A database handle attribute was missing. */
InvalidAttributeAccessCredentials = -67796, /* An access credentials attribute was not valid. */
MissingAttributeAccessCredentials = -67797, /* An access credentials attribute was missing. */
InvalidAttributePublicKeyFormat = -67798, /* A public key format attribute was not valid. */
MissingAttributePublicKeyFormat = -67799, /* A public key format attribute was missing. */
InvalidAttributePrivateKeyFormat = -67800, /* A private key format attribute was not valid. */
MissingAttributePrivateKeyFormat = -67801, /* A private key format attribute was missing. */
InvalidAttributeSymmetricKeyFormat = -67802, /* A symmetric key format attribute was not valid. */
MissingAttributeSymmetricKeyFormat = -67803, /* A symmetric key format attribute was missing. */
InvalidAttributeWrappedKeyFormat = -67804, /* A wrapped key format attribute was not valid. */
MissingAttributeWrappedKeyFormat = -67805, /* A wrapped key format attribute was missing. */
StagedOperationInProgress = -67806, /* A staged operation is in progress. */
StagedOperationNotStarted = -67807, /* A staged operation was not started. */
VerifyFailed = -67808, /* A cryptographic verification failure has occurred. */
QuerySizeUnknown = -67809, /* The query size is unknown. */
BlockSizeMismatch = -67810, /* A block size mismatch occurred. */
PublicKeyInconsistent = -67811, /* The public key was inconsistent. */
DeviceVerifyFailed = -67812, /* A device verification failure has occurred. */
InvalidLoginName = -67813, /* An invalid login name was detected. */
AlreadyLoggedIn = -67814, /* The user is already logged in. */
InvalidDigestAlgorithm = -67815, /* An invalid digest algorithm was detected. */
InvalidCRLGroup = -67816, /* An invalid CRL group was detected. */
CertificateCannotOperate = -67817, /* The certificate cannot operate. */
CertificateExpired = -67818, /* An expired certificate was detected. */
CertificateNotValidYet = -67819, /* The certificate is not yet valid. */
CertificateRevoked = -67820, /* The certificate was revoked. */
CertificateSuspended = -67821, /* The certificate was suspended. */
InsufficientCredentials = -67822, /* Insufficient credentials were detected. */
InvalidAction = -67823, /* The action was not valid. */
InvalidAuthority = -67824, /* The authority was not valid. */
VerifyActionFailed = -67825, /* A verify action has failed. */
InvalidCertAuthority = -67826, /* The certificate authority was not valid. */
InvalidCRLAuthority = -67827, /* The CRL authority was not valid. */
#if MONOMAC
[Obsolete ("Use InvalidCRLAuthority")]
InvaldCRLAuthority = InvalidCRLAuthority,
#endif
InvalidCRLEncoding = -67828, /* The CRL encoding was not valid. */
InvalidCRLType = -67829, /* The CRL type was not valid. */
InvalidCRL = -67830, /* The CRL was not valid. */
InvalidFormType = -67831, /* The form type was not valid. */
InvalidID = -67832, /* The ID was not valid. */
InvalidIdentifier = -67833, /* The identifier was not valid. */
InvalidIndex = -67834, /* The index was not valid. */
InvalidPolicyIdentifiers = -67835, /* The policy identifiers are not valid. */
InvalidTimeString = -67836, /* The time specified was not valid. */
InvalidReason = -67837, /* The trust policy reason was not valid. */
InvalidRequestInputs = -67838, /* The request inputs are not valid. */
InvalidResponseVector = -67839, /* The response vector was not valid. */
InvalidStopOnPolicy = -67840, /* The stop-on policy was not valid. */
InvalidTuple = -67841, /* The tuple was not valid. */
MultipleValuesUnsupported = -67842, /* Multiple values are not supported. */
NotTrusted = -67843, /* The trust policy was not trusted. */
NoDefaultAuthority = -67844, /* No default authority was detected. */
RejectedForm = -67845, /* The trust policy had a rejected form. */
RequestLost = -67846, /* The request was lost. */
RequestRejected = -67847, /* The request was rejected. */
UnsupportedAddressType = -67848, /* The address type is not supported. */
UnsupportedService = -67849, /* The service is not supported. */
InvalidTupleGroup = -67850, /* The tuple group was not valid. */
InvalidBaseACLs = -67851, /* The base ACLs are not valid. */
InvalidTupleCredentials = -67852, /* The tuple credentials are not valid. */
#if MONOMAC
[Obsolete ("Use InvalidTupleCredentials")]
InvalidTupleCredendtials = InvalidTupleCredentials,
#endif
InvalidEncoding = -67853, /* The encoding was not valid. */
InvalidValidityPeriod = -67854, /* The validity period was not valid. */
InvalidRequestor = -67855, /* The requestor was not valid. */
RequestDescriptor = -67856, /* The request descriptor was not valid. */
InvalidBundleInfo = -67857, /* The bundle information was not valid. */
InvalidCRLIndex = -67858, /* The CRL index was not valid. */
NoFieldValues = -67859, /* No field values were detected. */
UnsupportedFieldFormat = -67860, /* The field format is not supported. */
UnsupportedIndexInfo = -67861, /* The index information is not supported. */
UnsupportedLocality = -67862, /* The locality is not supported. */
UnsupportedNumAttributes = -67863, /* The number of attributes is not supported. */
UnsupportedNumIndexes = -67864, /* The number of indexes is not supported. */
UnsupportedNumRecordTypes = -67865, /* The number of record types is not supported. */
FieldSpecifiedMultiple = -67866, /* Too many fields were specified. */
IncompatibleFieldFormat = -67867, /* The field format was incompatible. */
InvalidParsingModule = -67868, /* The parsing module was not valid. */
DatabaseLocked = -67869, /* The database is locked. */
DatastoreIsOpen = -67870, /* The data store is open. */
MissingValue = -67871, /* A missing value was detected. */
UnsupportedQueryLimits = -67872, /* The query limits are not supported. */
UnsupportedNumSelectionPreds = -67873, /* The number of selection predicates is not supported. */
UnsupportedOperator = -67874, /* The operator is not supported. */
InvalidDBLocation = -67875, /* The database location is not valid. */
InvalidAccessRequest = -67876, /* The access request is not valid. */
InvalidIndexInfo = -67877, /* The index information is not valid. */
InvalidNewOwner = -67878, /* The new owner is not valid. */
InvalidModifyMode = -67879, /* The modify mode is not valid. */
MissingRequiredExtension = -67880, /* A required certificate extension is missing. */
ExtendedKeyUsageNotCritical = -67881, /* The extended key usage extension was not marked critical. */
TimestampMissing = -67882, /* A timestamp was expected but was not found. */
TimestampInvalid = -67883, /* The timestamp was not valid. */
TimestampNotTrusted = -67884, /* The timestamp was not trusted. */
TimestampServiceNotAvailable = -67885, /* The timestamp service is not available. */
TimestampBadAlg = -67886, /* An unrecognized or unsupported Algorithm Identifier in timestamp. */
TimestampBadRequest = -67887, /* The timestamp transaction is not permitted or supported. */
TimestampBadDataFormat = -67888, /* The timestamp data submitted has the wrong format. */
TimestampTimeNotAvailable = -67889, /* The time source for the Timestamp Authority is not available. */
TimestampUnacceptedPolicy = -67890, /* The requested policy is not supported by the Timestamp Authority. */
TimestampUnacceptedExtension = -67891, /* The requested extension is not supported by the Timestamp Authority. */
TimestampAddInfoNotAvailable = -67892, /* The additional information requested is not available. */
TimestampSystemFailure = -67893, /* The timestamp request cannot be handled due to system failure. */
SigningTimeMissing = -67894, /* A signing time was expected but was not found. */
TimestampRejection = -67895, /* A timestamp transaction was rejected. */
TimestampWaiting = -67896, /* A timestamp transaction is waiting. */
TimestampRevocationWarning = -67897, /* A timestamp authority revocation warning was issued. */
TimestampRevocationNotification = -67898, /* A timestamp authority revocation notification was issued. */
}
// typedef uint32_t SecTrustResultType;
// values are defined in Security.framework/Headers/SecTrust.h
enum SecTrustResult {
Invalid,
Proceed,
Confirm,
Deny,
Unspecified,
RecoverableTrustFailure,
FatalTrustFailure,
ResultOtherError,
}
}
#endif
@@ -0,0 +1,21 @@
using System;
namespace ObjCRuntime {
internal interface INativeObject {
IntPtr Handle {
get;
}
}
static class NativeObjectHelper {
// help to avoid the (too common pattern)
// var p = x == null ? IntPtr.Zero : x.Handle;
static public IntPtr GetHandle (this INativeObject self)
{
return self == null ? IntPtr.Zero : self.Handle;
}
}
}
@@ -0,0 +1,224 @@
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
//
// ImportExport.cs
//
// Authors:
// Sebastien Pouliot <[email protected]>
//
// Copyright 2011-2014 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using ObjCRuntime;
using Mono.Net;
#if MONO_FEATURE_BTLS
using Mono.Btls;
#else
using Mono.Security.Cryptography;
#endif
namespace Mono.AppleTls {
internal partial class SecImportExport {
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static SecStatusCode SecPKCS12Import (IntPtr pkcs12_data, IntPtr options, out IntPtr items);
static public SecStatusCode ImportPkcs12 (byte[] buffer, CFDictionary options, out CFDictionary[] array)
{
using (CFData data = CFData.FromData (buffer)) {
return ImportPkcs12 (data, options, out array);
}
}
static public SecStatusCode ImportPkcs12 (CFData data, CFDictionary options, out CFDictionary [] array)
{
if (options == null)
throw new ArgumentNullException ("options");
IntPtr handle;
SecStatusCode code = SecPKCS12Import (data.Handle, options.Handle, out handle);
array = CFArray.ArrayFromHandle <CFDictionary> (handle, h => new CFDictionary (h, false));
if (handle != IntPtr.Zero)
CFObject.CFRelease (handle);
return code;
}
#if !MONOTOUCH
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static SecStatusCode SecItemImport (
/* CFDataRef */ IntPtr importedData,
/* CFStringRef */ IntPtr fileNameOrExtension, // optional
/* SecExternalFormat* */ ref SecExternalFormat inputFormat, // optional, IN/OUT
/* SecExternalItemType* */ ref SecExternalItemType itemType, // optional, IN/OUT
/* SecItemImportExportFlags */ SecItemImportExportFlags flags,
/* const SecItemImportExportKeyParameters* */ IntPtr keyParams, // optional
/* SecKeychainRef */ IntPtr importKeychain, // optional
/* CFArrayRef* */ out IntPtr outItems);
static public CFArray ItemImport (byte[] buffer, string password)
{
using (var data = CFData.FromData (buffer))
using (var pwstring = CFString.Create (password)) {
SecItemImportExportKeyParameters keyParams = new SecItemImportExportKeyParameters ();
keyParams.passphrase = pwstring.Handle;
return ItemImport (data, SecExternalFormat.PKCS12, SecExternalItemType.Aggregate, SecItemImportExportFlags.None, keyParams);
}
}
static CFArray ItemImport (CFData data, SecExternalFormat format, SecExternalItemType itemType,
SecItemImportExportFlags flags = SecItemImportExportFlags.None,
SecItemImportExportKeyParameters? keyParams = null)
{
return ItemImport (data, ref format, ref itemType, flags, keyParams);
}
static CFArray ItemImport (CFData data, ref SecExternalFormat format, ref SecExternalItemType itemType,
SecItemImportExportFlags flags = SecItemImportExportFlags.None,
SecItemImportExportKeyParameters? keyParams = null)
{
IntPtr keyParamsPtr = IntPtr.Zero;
if (keyParams != null) {
keyParamsPtr = Marshal.AllocHGlobal (Marshal.SizeOf (keyParams.Value));
if (keyParamsPtr == IntPtr.Zero)
throw new OutOfMemoryException ();
Marshal.StructureToPtr (keyParams.Value, keyParamsPtr, false);
}
IntPtr result;
var status = SecItemImport (data.Handle, IntPtr.Zero, ref format, ref itemType, flags, keyParamsPtr, IntPtr.Zero, out result);
if (keyParamsPtr != IntPtr.Zero)
Marshal.FreeHGlobal (keyParamsPtr);
if (status != SecStatusCode.Success)
throw new NotSupportedException (status.ToString ());
return new CFArray (result, true);
}
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static /* SecIdentityRef */ IntPtr SecIdentityCreate (
/* CFAllocatorRef */ IntPtr allocator,
/* SecCertificateRef */ IntPtr certificate,
/* SecKeyRef */ IntPtr privateKey);
static public SecIdentity ItemImport (X509Certificate2 certificate)
{
if (!certificate.HasPrivateKey)
throw new NotSupportedException ();
using (var key = ImportPrivateKey (certificate))
using (var cert = new SecCertificate (certificate)) {
var identity = SecIdentityCreate (IntPtr.Zero, cert.Handle, key.Handle);
if (CFType.GetTypeID (identity) != SecIdentity.GetTypeID ())
throw new InvalidOperationException ();
return new SecIdentity (identity, true);
}
}
static byte[] ExportKey (RSA key)
{
#if MONO_FEATURE_BTLS
using (var btlsKey = MonoBtlsKey.CreateFromRSAPrivateKey (key))
return btlsKey.GetBytes (true);
#else
return PKCS8.PrivateKeyInfo.Encode (key);
#endif
}
static SecKey ImportPrivateKey (X509Certificate2 certificate)
{
if (!certificate.HasPrivateKey)
throw new NotSupportedException ();
CFArray items;
using (var data = CFData.FromData (ExportKey ((RSA)certificate.PrivateKey)))
items = ItemImport (data, SecExternalFormat.OpenSSL, SecExternalItemType.PrivateKey);
try {
if (items.Count != 1)
throw new InvalidOperationException ("Private key import failed.");
var imported = items[0];
if (CFType.GetTypeID (imported) != SecKey.GetTypeID ())
throw new InvalidOperationException ("Private key import doesn't return SecKey.");
return new SecKey (imported, items.Handle);
} finally {
items.Dispose ();
}
}
const int SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION = 0;
// Native enum; don't change.
enum SecExternalFormat : int {
Unknown = 0,
OpenSSL = 1,
X509Cert = 9,
PEMSequence = 10,
PKCS7 = 11,
PKCS12 = 12
}
// Native enum; don't change.
enum SecExternalItemType : int {
Unknown = 0,
PrivateKey = 1,
PublicKey = 2,
SessionKey = 3,
Certificate = 4,
Aggregate = 5
}
// Native enum; don't change
enum SecItemImportExportFlags : int {
None,
PemArmour = 0x00000001, /* exported blob is PEM formatted */
}
// Native struct; don't change
[StructLayout (LayoutKind.Sequential)]
struct SecItemImportExportKeyParameters {
public int version; /* SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION */
public int flags; /* SecKeyImportExportFlags bits */
public IntPtr passphrase; /* SecExternalFormat.PKCS12 only. Legal types are CFStringRef and CFDataRef. */
IntPtr alertTitle;
IntPtr alertPrompt;
public IntPtr accessRef; /* SecAccessRef */
IntPtr keyUsage;
IntPtr keyAttributes;
}
#endif
}
}
#endif
+356
View File
@@ -0,0 +1,356 @@
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
//
// Items.cs: Implements the KeyChain query access APIs
//
// We use strong types and a helper SecQuery class to simplify the
// creation of the dictionary used to query the Keychain
//
// Authors:
// Miguel de Icaza
// Sebastien Pouliot
//
// Copyright 2010 Novell, Inc
// Copyright 2011-2016 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.Collections;
using System.Runtime.InteropServices;
using ObjCRuntime;
using Mono.Net;
namespace Mono.AppleTls {
enum SecKind {
Identity,
Certificate
}
#if MONOTOUCH
static class SecKeyChain {
#else
class SecKeyChain : INativeObject, IDisposable {
#endif
internal static readonly IntPtr MatchLimitAll;
internal static readonly IntPtr MatchLimitOne;
internal static readonly IntPtr MatchLimit;
#if !MONOTOUCH
IntPtr handle;
internal SecKeyChain (IntPtr handle, bool owns = false)
{
if (handle == IntPtr.Zero)
throw new ArgumentException ("Invalid handle");
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
#endif
static SecKeyChain ()
{
var handle = CFObject.dlopen (AppleTlsContext.SecurityLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
MatchLimit = CFObject.GetIntPtr (handle, "kSecMatchLimit");
MatchLimitAll = CFObject.GetIntPtr (handle, "kSecMatchLimitAll");
MatchLimitOne = CFObject.GetIntPtr (handle, "kSecMatchLimitOne");
} finally {
CFObject.dlclose (handle);
}
}
public static SecIdentity FindIdentity (SecCertificate certificate, bool throwOnError = false)
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
var identity = FindIdentity (cert => SecCertificate.Equals (certificate, cert));
if (!throwOnError || identity != null)
return identity;
throw new InvalidOperationException (string.Format ("Could not find SecIdentity for certificate '{0}' in keychain.", certificate.SubjectSummary));
}
static SecIdentity FindIdentity (Predicate<SecCertificate> filter)
{
/*
* Unfortunately, SecItemCopyMatching() does not allow any search
* filters when looking up an identity.
*
* The following lookup will return all identities from the keychain -
* we then need need to find the right one.
*/
using (var record = new SecRecord (SecKind.Identity)) {
SecStatusCode status;
var result = SecKeyChain.QueryAsReference (record, -1, out status);
if (status != SecStatusCode.Success || result == null)
return null;
for (int i = 0; i < result.Length; i++) {
var identity = (SecIdentity)result [i];
if (filter (identity.Certificate))
return identity;
}
}
return null;
}
static INativeObject [] QueryAsReference (SecRecord query, int max, out SecStatusCode result)
{
if (query == null) {
result = SecStatusCode.Param;
return null;
}
using (var copy = query.QueryDict.MutableCopy ()) {
copy.SetValue (CFBoolean.True.Handle, SecItem.ReturnRef);
SetLimit (copy, max);
return QueryAsReference (copy, out result);
}
}
static INativeObject [] QueryAsReference (CFDictionary query, out SecStatusCode result)
{
if (query == null) {
result = SecStatusCode.Param;
return null;
}
IntPtr ptr;
result = SecItem.SecItemCopyMatching (query.Handle, out ptr);
if (result == SecStatusCode.Success && ptr != IntPtr.Zero) {
var array = CFArray.ArrayFromHandle<INativeObject> (ptr, p => {
IntPtr cfType = CFType.GetTypeID (p);
if (cfType == SecCertificate.GetTypeID ())
return new SecCertificate (p, true);
if (cfType == SecKey.GetTypeID ())
return new SecKey (p, true);
if (cfType == SecIdentity.GetTypeID ())
return new SecIdentity (p, true);
throw new Exception (String.Format ("Unexpected type: 0x{0:x}", cfType));
});
return array;
}
return null;
}
internal static CFNumber SetLimit (CFMutableDictionary dict, int max)
{
CFNumber n = null;
IntPtr val;
if (max == -1)
val = MatchLimitAll;
else if (max == 1)
val = MatchLimitOne;
else {
n = CFNumber.FromInt32 (max);
val = n.Handle;
}
dict.SetValue (val, SecKeyChain.MatchLimit);
return n;
}
#if !MONOTOUCH
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static /* OSStatus */ SecStatusCode SecKeychainCreate (/* const char * */ IntPtr pathName, uint passwordLength, /* const void * */ IntPtr password,
bool promptUser, /* SecAccessRef */ IntPtr initialAccess,
/* SecKeychainRef _Nullable * */ out IntPtr keychain);
internal static SecKeyChain Create (string pathName, string password)
{
IntPtr handle;
var pathNamePtr = Marshal.StringToHGlobalAnsi (pathName);
var passwordPtr = Marshal.StringToHGlobalAnsi (password);
var result = SecKeychainCreate (pathNamePtr, (uint)password.Length, passwordPtr, false, IntPtr.Zero, out handle);
if (result != SecStatusCode.Success)
throw new InvalidOperationException (result.ToString ());
return new SecKeyChain (handle, true);
}
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static /* OSStatus */ SecStatusCode SecKeychainOpen (/* const char * */ IntPtr pathName, /* SecKeychainRef _Nullable * */ out IntPtr keychain);
internal static SecKeyChain Open (string pathName)
{
IntPtr handle;
IntPtr pathNamePtr = IntPtr.Zero;
try {
pathNamePtr = Marshal.StringToHGlobalAnsi (pathName);
var result = SecKeychainOpen (pathNamePtr, out handle);
if (result != SecStatusCode.Success)
throw new InvalidOperationException (result.ToString ());
return new SecKeyChain (handle, true);
} finally {
if (pathNamePtr != IntPtr.Zero)
Marshal.FreeHGlobal (pathNamePtr);
}
}
internal static SecKeyChain OpenSystemRootCertificates ()
{
return Open ("/System/Library/Keychains/SystemRootCertificates.keychain");
}
~SecKeyChain ()
{
Dispose (false);
}
public IntPtr Handle {
get {
return handle;
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero) {
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
#endif
}
class SecRecord : IDisposable {
internal static readonly IntPtr SecClassKey;
static SecRecord ()
{
var handle = CFObject.dlopen (AppleTlsContext.SecurityLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
SecClassKey = CFObject.GetIntPtr (handle, "kSecClass");
} finally {
CFObject.dlclose (handle);
}
}
CFMutableDictionary _queryDict;
internal CFMutableDictionary QueryDict {
get {
return _queryDict;
}
}
internal void SetValue (IntPtr key, IntPtr value)
{
_queryDict.SetValue (key, value);
}
public SecRecord (SecKind secKind)
{
var kind = SecClass.FromSecKind (secKind);
_queryDict = CFMutableDictionary.Create ();
_queryDict.SetValue (SecClassKey, kind);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (_queryDict != null){
if (disposing){
_queryDict.Dispose ();
_queryDict = null;
}
}
}
~SecRecord ()
{
Dispose (false);
}
}
partial class SecItem {
public static readonly IntPtr ReturnRef;
public static readonly IntPtr MatchSearchList;
static SecItem ()
{
var handle = CFObject.dlopen (AppleTlsContext.SecurityLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
ReturnRef = CFObject.GetIntPtr (handle, "kSecReturnRef");
MatchSearchList = CFObject.GetIntPtr (handle, "kSecMatchSearchList");
} finally {
CFObject.dlclose (handle);
}
}
[DllImport (AppleTlsContext.SecurityLibrary)]
internal extern static SecStatusCode SecItemCopyMatching (/* CFDictionaryRef */ IntPtr query, /* CFTypeRef* */ out IntPtr result);
}
static partial class SecClass {
public static readonly IntPtr Identity;
public static readonly IntPtr Certificate;
static SecClass ()
{
var handle = CFObject.dlopen (AppleTlsContext.SecurityLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Identity = CFObject.GetIntPtr (handle, "kSecClassIdentity");
Certificate = CFObject.GetIntPtr (handle, "kSecClassCertificate");
} finally {
CFObject.dlclose (handle);
}
}
public static IntPtr FromSecKind (SecKind secKind)
{
switch (secKind){
case SecKind.Identity:
return Identity;
case SecKind.Certificate:
return Certificate;
default:
throw new ArgumentException ("secKind");
}
}
}
}
#endif
+87
View File
@@ -0,0 +1,87 @@
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
//
// Policy.cs: Implements the managed SecPolicy wrapper.
//
// Authors:
// Miguel de Icaza
// Sebastien Pouliot <[email protected]>
//
// Copyright 2010 Novell, Inc
// Copyright 2012-2014 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.InteropServices;
using ObjCRuntime;
using Mono.Net;
namespace Mono.AppleTls {
partial class SecPolicy : INativeObject, IDisposable {
IntPtr handle;
internal SecPolicy (IntPtr handle, bool owns = false)
{
if (handle == IntPtr.Zero)
throw new Exception ("Invalid handle");
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static IntPtr /* SecPolicyRef */ SecPolicyCreateSSL (bool server, IntPtr /* CFStringRef */ hostname);
static public SecPolicy CreateSslPolicy (bool server, string hostName)
{
CFString host = hostName == null ? null : CFString.Create (hostName);
IntPtr handle = host == null ? IntPtr.Zero : host.Handle;
SecPolicy policy = new SecPolicy (SecPolicyCreateSSL (server, handle), true);
if (host != null)
host.Dispose ();
return policy;
}
~SecPolicy ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public IntPtr Handle {
get { return handle; }
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
}
}
#endif
@@ -0,0 +1,251 @@
#if MONO_FEATURE_APPLETLS
// Copyright 2014 Xamarin Inc. All rights reserved.
namespace Mono.AppleTls {
// Security.framework/Headers/SecureTransport.h
// untyped enum
enum SslProtocol {
Unknown = 0,
// Ssl_3_0 = 2,
Tls_1_0 = 4,
Tls_1_1 = 7,
Tls_1_2 = 8,
// Dtls_1_0 = 9,
/* Obsolete on iOS */
// Ssl_2_0 = 1,
// Ssl_3_0_only = 3,
// Tls_1_0_only = 5,
// All = 6,
}
// subset of OSStatus (int)
enum SslStatus {
Success = 0, // errSecSuccess in SecBase.h
Protocol = -9800,
Negotiation = -9801,
FatalAlert = -9802,
WouldBlock = -9803,
SessionNotFound = -9804,
ClosedGraceful = -9805,
ClosedAbort = -9806,
XCertChainInvalid = -9807,
BadCert = -9808,
Crypto = -9809,
Internal = -9810,
ModuleAttach = -9811,
UnknownRootCert = -9812,
NoRootCert = -9813,
CertExpired = -9814,
CertNotYetValid = -9815,
ClosedNotNotified = -9816,
BufferOverflow = -9817,
BadCipherSuite = -9818,
PeerUnexpectedMsg = -9819,
PeerBadRecordMac = -9820,
PeerDecryptionFail = -9821,
PeerRecordOverflow = -9822,
PeerDecompressFail = -9823,
PeerHandshakeFail = -9824,
PeerBadCert = -9825,
PeerUnsupportedCert = -9826,
PeerCertRevoked = -9827,
PeerCertExpired = -9828,
PeerCertUnknown = -9829,
IllegalParam = -9830,
PeerUnknownCA = -9831,
PeerAccessDenied = -9832,
PeerDecodeError = -9833,
PeerDecryptError = -9834,
PeerExportRestriction = -9835,
PeerProtocolVersion = -9836,
PeerInsufficientSecurity = -9837,
PeerInternalError = -9838,
PeerUserCancelled = -9839,
PeerNoRenegotiation = -9840,
PeerAuthCompleted = -9841, // non fatal
PeerClientCertRequested = -9842, // non fatal
HostNameMismatch = -9843,
ConnectionRefused = -9844,
DecryptionFail = -9845,
BadRecordMac = -9846,
RecordOverflow = -9847,
BadConfiguration = -9848,
UnexpectedRecord = -9849,
SSLWeakPeerEphemeralDHKey = -9850,
SSLClientHelloReceived = -9851 // non falta
}
// Security.framework/Headers/SecureTransport.h
// untyped enum
enum SslSessionOption {
BreakOnServerAuth,
BreakOnCertRequested,
BreakOnClientAuth,
// FalseStart,
// SendOneByteRecord,
// AllowServerIdentityChange = 5,
// Fallback = 6,
// BreakOnClientHello = 7,
// AllowRenegotiation = 8,
}
// Security.framework/Headers/SecureTransport.h
// untyped enum
enum SslAuthenticate {
// Never,
// Always,
Try = 2,
}
// Security.framework/Headers/SecureTransport.h
// untyped enum
enum SslProtocolSide {
Server,
Client,
}
// Security.framework/Headers/SecureTransport.h
// untyped enum
enum SslConnectionType {
Stream,
// Datagram
}
// Security.framework/Headers/SecureTransport.h
// untyped enum
enum SslSessionState {
Invalid = -1,
// Idle,
// Handshake,
// Connected,
// Closed,
// Aborted
}
// Security.framework/Headers/SecureTransport.h
// untyped enum
enum SslClientCertificateState {
None,
Requested,
Sent,
Rejected
}
// Security.framework/Headers/CipherSuite.h
// 32 bits (uint32_t) on OSX, 16 bits (uint16_t) on iOS
#if XAMMAC || XAMMAC_4_5
enum SslCipherSuite : uint {
#else
enum SslCipherSuite : ushort {
#endif
// DO NOT RENAME VALUES - they don't look good but we need them to keep compatibility with our System.dll code
// it's how it's defined across most SSL/TLS implementation (from RFC)
SSL_NULL_WITH_NULL_NULL = 0x0000, // value used before (not after) negotiation
TLS_NULL_WITH_NULL_NULL = 0x0000,
// Not the whole list (too much unneeed metadata) but only what's supported
// FIXME needs to be expended with OSX 10.9
SSL_RSA_WITH_NULL_MD5 = 0x0001,
SSL_RSA_WITH_NULL_SHA = 0x0002,
SSL_RSA_EXPORT_WITH_RC4_40_MD5 = 0x0003, // iOS 5.1 only
SSL_RSA_WITH_RC4_128_MD5 = 0x0004,
SSL_RSA_WITH_RC4_128_SHA = 0x0005,
SSL_RSA_WITH_3DES_EDE_CBC_SHA = 0x000A,
SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x0016,
SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 = 0x0017, // iOS 5.1 only
SSL_DH_anon_WITH_RC4_128_MD5 = 0x0018,
SSL_DH_anon_WITH_3DES_EDE_CBC_SHA = 0x001B,
// TLS - identical values to SSL (above)
TLS_RSA_WITH_NULL_MD5 = 0x0001,
TLS_RSA_WITH_NULL_SHA = 0x0002,
TLS_RSA_WITH_RC4_128_MD5 = 0x0004,
TLS_RSA_WITH_RC4_128_SHA = 0x0005,
TLS_RSA_WITH_3DES_EDE_CBC_SHA = 0x000A,
TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x0016,
TLS_DH_anon_WITH_RC4_128_MD5 = 0x0018,
TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = 0x001B,
// TLS specific
TLS_PSK_WITH_NULL_SHA = 0x002C,
TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F,
TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033,
TLS_DH_anon_WITH_AES_128_CBC_SHA = 0x0034,
TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035,
TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039,
TLS_DH_anon_WITH_AES_256_CBC_SHA = 0x003A,
TLS_RSA_WITH_NULL_SHA256 = 0x003B,
TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C,
TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D,
TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067,
TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B,
TLS_DH_anon_WITH_AES_128_CBC_SHA256 = 0x006C,
TLS_DH_anon_WITH_AES_256_CBC_SHA256 = 0x006D,
TLS_PSK_WITH_RC4_128_SHA = 0x008A,
TLS_PSK_WITH_3DES_EDE_CBC_SHA = 0x008B,
TLS_PSK_WITH_AES_128_CBC_SHA = 0x008C,
TLS_PSK_WITH_AES_256_CBC_SHA = 0x008D,
TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C, // iOS 9+
TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D, // iOS 9+
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E, // iOS 9+
TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F, // iOS 9+
TLS_DH_anon_WITH_AES_128_GCM_SHA256 = 0x00A6, // iOS 5.1 only
TLS_DH_anon_WITH_AES_256_GCM_SHA384 = 0x00A7, // iOS 5.1 only
TLS_PSK_WITH_AES_128_CBC_SHA256 = 0x00AE,
TLS_PSK_WITH_AES_256_CBC_SHA384 = 0x00AF,
TLS_PSK_WITH_NULL_SHA256 = 0x00B0,
TLS_PSK_WITH_NULL_SHA384 = 0x00B1,
TLS_ECDH_ECDSA_WITH_NULL_SHA = 0xC001,
TLS_ECDH_ECDSA_WITH_RC4_128_SHA = 0xC002,
TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = 0xC003,
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA = 0xC004,
TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA = 0xC005,
TLS_ECDHE_ECDSA_WITH_NULL_SHA = 0xC006,
TLS_ECDHE_ECDSA_WITH_RC4_128_SHA = 0xC007,
TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = 0xC008,
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009,
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A,
TLS_ECDH_RSA_WITH_NULL_SHA = 0xC00B,
TLS_ECDH_RSA_WITH_RC4_128_SHA = 0xC00C,
TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA = 0xC00D,
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA = 0xC00E,
TLS_ECDH_RSA_WITH_AES_256_CBC_SHA = 0xC00F,
TLS_ECDHE_RSA_WITH_NULL_SHA = 0xC010,
TLS_ECDHE_RSA_WITH_RC4_128_SHA = 0xC011,
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA = 0xC012,
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013,
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014,
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023,
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024,
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC025,
TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC026,
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027,
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028,
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 = 0xC029,
TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 = 0xC02A,
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B, // iOS 9+
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C, // iOS 9+
TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02D, // iOS 9+
TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02E, // iOS 9+
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F, // iOS 9+
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030, // iOS 9+
TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 = 0xC031, // iOS 9+
TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 = 0xC032, // iOS 9+
}
}
#endif
@@ -0,0 +1,18 @@
#if MONO_FEATURE_APPLETLS
//
// SslConnection
//
// Authors:
// Sebastien Pouliot <[email protected]>
//
// Copyright 2014 Xamarin Inc.
//
using System;
namespace Mono.AppleTls
{
delegate SslStatus SslReadFunc (IntPtr connection, IntPtr data, /* size_t* */ ref IntPtr dataLength);
delegate SslStatus SslWriteFunc (IntPtr connection, IntPtr data, /* size_t* */ ref IntPtr dataLength);
}
#endif
+186
View File
@@ -0,0 +1,186 @@
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
//
// Trust.cs: Implements the managed SecTrust wrapper.
//
// Authors:
// Miguel de Icaza
// Sebastien Pouliot <[email protected]>
//
// Copyright 2010 Novell, Inc
// Copyright 2012-2014 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using ObjCRuntime;
using Mono.Net;
namespace Mono.AppleTls {
partial class SecTrust : INativeObject, IDisposable {
IntPtr handle;
internal SecTrust (IntPtr handle, bool owns = false)
{
if (handle == IntPtr.Zero)
throw new Exception ("Invalid handle");
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static SecStatusCode SecTrustCreateWithCertificates (
/* CFTypeRef */ IntPtr certOrCertArray,
/* CFTypeRef __nullable */ IntPtr policies,
/* SecTrustRef *__nonull */ out IntPtr sectrustref);
public SecTrust (X509CertificateCollection certificates, SecPolicy policy)
{
if (certificates == null)
throw new ArgumentNullException ("certificates");
SecCertificate[] array = new SecCertificate [certificates.Count];
int i = 0;
foreach (var certificate in certificates)
array [i++] = new SecCertificate (certificate);
Initialize (array, policy);
}
void Initialize (SecCertificate[] array, SecPolicy policy)
{
using (var certs = CFArray.CreateArray (array)) {
Initialize (certs.Handle, policy);
}
}
void Initialize (IntPtr certHandle, SecPolicy policy)
{
SecStatusCode result = SecTrustCreateWithCertificates (certHandle, policy == null ? IntPtr.Zero : policy.Handle, out handle);
if (result != SecStatusCode.Success)
throw new ArgumentException (result.ToString ());
}
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static SecStatusCode /* OSStatus */ SecTrustEvaluate (IntPtr /* SecTrustRef */ trust, out /* SecTrustResultType */ SecTrustResult result);
public SecTrustResult Evaluate ()
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecTrust");
SecTrustResult trust;
SecStatusCode result = SecTrustEvaluate (handle, out trust);
if (result != SecStatusCode.Success)
throw new InvalidOperationException (result.ToString ());
return trust;
}
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static IntPtr /* CFIndex */ SecTrustGetCertificateCount (IntPtr /* SecTrustRef */ trust);
public int Count {
get {
if (handle == IntPtr.Zero)
return 0;
return (int) SecTrustGetCertificateCount (handle);
}
}
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static IntPtr /* SecCertificateRef */ SecTrustGetCertificateAtIndex (IntPtr /* SecTrustRef */ trust, IntPtr /* CFIndex */ ix);
public SecCertificate this [IntPtr index] {
get {
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecTrust");
if (((long)index < 0) || ((long)index >= Count))
throw new ArgumentOutOfRangeException ("index");
return new SecCertificate (SecTrustGetCertificateAtIndex (handle, index));
}
}
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static SecStatusCode /* OSStatus */ SecTrustSetAnchorCertificates (IntPtr /* SecTrustRef */ trust, IntPtr /* CFArrayRef */ anchorCertificates);
public SecStatusCode SetAnchorCertificates (X509CertificateCollection certificates)
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecTrust");
if (certificates == null)
return SecTrustSetAnchorCertificates (handle, IntPtr.Zero);
SecCertificate[] array = new SecCertificate [certificates.Count];
int i = 0;
foreach (var certificate in certificates)
array [i++] = new SecCertificate (certificate);
return SetAnchorCertificates (array);
}
public SecStatusCode SetAnchorCertificates (SecCertificate[] array)
{
if (array == null)
return SecTrustSetAnchorCertificates (handle, IntPtr.Zero);
using (var certs = CFArray.FromNativeObjects (array)) {
return SecTrustSetAnchorCertificates (handle, certs.Handle);
}
}
[DllImport (AppleTlsContext.SecurityLibrary)]
extern static SecStatusCode /* OSStatus */ SecTrustSetAnchorCertificatesOnly (IntPtr /* SecTrustRef */ trust, bool anchorCertificatesOnly);
public SecStatusCode SetAnchorCertificatesOnly (bool anchorCertificatesOnly)
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecTrust");
return SecTrustSetAnchorCertificatesOnly (handle, anchorCertificatesOnly);
}
~SecTrust ()
{
Dispose (false);
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero) {
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public IntPtr Handle {
get { return handle; }
}
}
}
#endif
+2 -12
View File
@@ -159,7 +159,7 @@ namespace Mono.Btls
string file;
int line;
var error = MonoBtlsError.GetError (out file, out line);
if (error == null)
if (error == 0)
return new MonoBtlsException (status);
var text = MonoBtlsError.GetErrorString (error);
@@ -218,16 +218,6 @@ namespace Mono.Btls
isAuthenticated = true;
}
void SetupCertificateStore ()
{
MonoBtlsProvider.SetupCertificateStore (ctx.CertificateStore);
if (Settings != null && Settings.TrustAnchors != null) {
var trust = IsServer ? MonoBtlsX509TrustKind.TRUST_CLIENT : MonoBtlsX509TrustKind.TRUST_SERVER;
ctx.CertificateStore.AddCollection (Settings.TrustAnchors, trust);
}
}
void InitializeConnection ()
{
ctx = new MonoBtlsSslCtx ();
@@ -237,7 +227,7 @@ namespace Mono.Btls
ctx.SetDebugBio (errbio);
#endif
SetupCertificateStore ();
MonoBtlsProvider.SetupCertificateStore (ctx.CertificateStore, Settings, IsServer);
if (!IsServer || AskForClientCertificate)
ctx.SetVerifyCallback (VerifyCallback, false);
+27 -1
View File
@@ -150,7 +150,7 @@ namespace Mono.Btls
using (var nativeChain = MonoBtlsProvider.GetNativeChain (certificates))
using (var param = GetVerifyParam (targetHost, serverMode))
using (var storeCtx = new MonoBtlsX509StoreCtx ()) {
SetupCertificateStore (store);
SetupCertificateStore (store, validator.Settings, serverMode);
storeCtx.Initialize (store, nativeChain);
@@ -201,19 +201,45 @@ namespace Mono.Btls
}
}
internal static void SetupCertificateStore (MonoBtlsX509Store store, MonoTlsSettings settings, bool server)
{
AddTrustedRoots (store, settings, server);
SetupCertificateStore (store);
}
internal static void SetupCertificateStore (MonoBtlsX509Store store)
{
#if MONODROID
store.SetDefaultPaths ();
store.AddAndroidLookup ();
#else
AddUserStore (store);
AddMachineStore (store);
#endif
}
#if !MONODROID
static void AddUserStore (MonoBtlsX509Store store)
{
var userPath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.UserTrustedRoots);
if (Directory.Exists (userPath))
store.AddDirectoryLookup (userPath, MonoBtlsX509FileType.PEM);
}
static void AddMachineStore (MonoBtlsX509Store store)
{
var machinePath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.MachineTrustedRoots);
if (Directory.Exists (machinePath))
store.AddDirectoryLookup (machinePath, MonoBtlsX509FileType.PEM);
}
#endif
static void AddTrustedRoots (MonoBtlsX509Store store, MonoTlsSettings settings, bool server)
{
if (settings?.TrustAnchors == null)
return;
var trust = server ? MonoBtlsX509TrustKind.TRUST_CLIENT : MonoBtlsX509TrustKind.TRUST_SERVER;
store.AddCollection (settings.TrustAnchors, trust);
}
public static string GetSystemStoreLocation ()
@@ -159,8 +159,7 @@ namespace Mono.Btls
internal void AddTrustedRoots ()
{
var systemRoot = MonoBtlsProvider.GetSystemStoreLocation ();
LoadLocations (null, systemRoot);
MonoBtlsProvider.SetupCertificateStore (this);
}
public MonoBtlsX509Lookup AddLookup (MonoBtlsX509LookupType type)
@@ -1,24 +1,146 @@
// Copyright 2015 Xamarin Inc. All rights reserved.
//
// MonoTlsProviderFactory.cs
//
// Author:
// Chris Hamons <[email protected]>
// Martin Baulig <[email protected]>
//
// Copyright (c) 2015 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.
#if !ONLY_APPLETLS
#error Use MonoTlsProviderFactory.cs instead
#endif
#if SECURITY_DEP
#if MONO_SECURITY_ALIAS
extern alias MonoSecurity;
using MSI = MonoSecurity::Mono.Security.Interface;
using MX = MonoSecurity::Mono.Security.X509;
#else
using MSI = Mono.Security.Interface;
using MX = Mono.Security.X509;
#endif
using System.Security.Cryptography.X509Certificates;
using Mono.AppleTls;
#endif
using System;
using System.Net;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace Mono.Net.Security
{
/*
* Keep in sync with Mono.Security/Mono.Security.Interface/MonoTlsProvider.cs.
* Simple implementation that does hard codes only a single provider
*/
static partial class MonoTlsProviderFactory
{
static MSI.MonoTlsProvider CreateDefaultProviderImpl ()
#region Internal API
/*
* APIs in this section are for consumption within System.dll only - do not access via
* reflection or from friend assemblies.
*
* @IMonoTlsProvider is defined as empty interface outside 'SECURITY_DEP', so we don't need
* this conditional here.
*/
internal static IMonoTlsProvider GetProviderInternal ()
{
MSI.MonoTlsProvider provider = null;
if (MSI.MonoTlsProviderFactory._PrivateFactoryDelegate != null)
provider = MSI.MonoTlsProviderFactory._PrivateFactoryDelegate ();
return provider;
#if SECURITY_DEP
return GetTlsProvider ();
#else
throw new NotSupportedException ("TLS Support not available.");
#endif
}
#endregion
#if SECURITY_DEP
static object locker = new object ();
static IMonoTlsProvider provider;
static IMonoTlsProvider GetTlsProvider ()
{
lock (locker) {
if (provider == null)
provider = new Private.MonoTlsProviderWrapper (new AppleTlsProvider ());
return provider;
}
}
#region Mono.Security visible API
/*
* "Public" section, intended to be consumed via reflection.
*
* Mono.Security.dll provides a public wrapper around these.
*/
internal static MSI.MonoTlsProvider GetProvider ()
{
return GetTlsProvider ().Provider;
}
internal static bool IsProviderSupported (string name)
{
return true;
}
internal static MSI.MonoTlsProvider GetProvider (string name)
{
return GetTlsProvider ().Provider;
}
internal static bool IsInitialized => true;
internal static void Initialize ()
{
}
internal static void Initialize (string provider)
{
}
internal static HttpWebRequest CreateHttpsRequest (Uri requestUri, MSI.MonoTlsProvider provider, MSI.MonoTlsSettings settings)
{
lock (locker) {
var internalProvider = provider != null ? new Private.MonoTlsProviderWrapper (provider) : null;
return new HttpWebRequest (requestUri, internalProvider, settings);
}
}
internal static HttpListener CreateHttpListener (X509Certificate certificate, MSI.MonoTlsProvider provider, MSI.MonoTlsSettings settings)
{
lock (locker) {
var internalProvider = provider != null ? new Private.MonoTlsProviderWrapper (provider) : null;
return new HttpListener (certificate, internalProvider, settings);
}
}
#endregion
#endif
}
}
#endif
@@ -24,6 +24,8 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if !ONLY_APPLETLS // ONLY_APPLETLS uses MonoTlsProviderFactory.Apple.cs instead
#if SECURITY_DEP
#if MONO_SECURITY_ALIAS
extern alias MonoSecurity;
@@ -159,10 +161,28 @@ namespace Mono.Net.Security
if (providerRegistration != null)
return;
providerRegistration = new Dictionary<string,string> ();
providerRegistration.Add ("legacy", "Mono.Net.Security.LegacyTlsProvider");
providerRegistration.Add ("default", "Mono.Net.Security.LegacyTlsProvider");
if (IsBtlsSupported ())
providerRegistration.Add ("btls", "Mono.Btls.MonoBtlsProvider");
string legacyProvider = "Mono.Net.Security.LegacyTlsProvider";
providerRegistration.Add ("legacy", legacyProvider);
string defaultProvider = null;
if (IsBtlsSupported ()) {
var btlsProvider = "Mono.Btls.MonoBtlsProvider";
providerRegistration.Add ("btls", btlsProvider);
defaultProvider = btlsProvider;
}
if (Platform.IsMacOS) {
var appleProvider = "Mono.AppleTls.AppleTlsProvider";
providerRegistration.Add ("apple", appleProvider);
defaultProvider = appleProvider;
}
if (defaultProvider == null)
defaultProvider = legacyProvider;
providerRegistration.Add ("default", defaultProvider);
X509Helper2.Initialize ();
}
}
@@ -261,4 +281,4 @@ namespace Mono.Net.Security
}
}
#endif
+16
View File
@@ -0,0 +1,16 @@
#if MONOTOUCH
namespace MonoTouch
{
// Exists only not to break existing source code due to broken C# namespace rules
// which allow using for empty namespace
sealed class Dummy
{
private Dummy ()
{
}
}
}
#endif
@@ -485,6 +485,34 @@ namespace System.Diagnostics
return (new Process (new SafeProcessHandle (proc, false), processId));
}
public static Process[] GetProcessesByName(string processName, string machineName)
{
if (machineName == null)
throw new ArgumentNullException ("machineName");
if (!IsLocalMachine (machineName))
throw new NotImplementedException ();
Process[] processes = GetProcesses ();
if (processes.Length == 0)
return processes;
int size = 0;
for (int i = 0; i < processes.Length; i++) {
try {
if (String.Compare (processName, processes[i].ProcessName, true) == 0)
processes [size++] = processes[i];
} catch (SystemException) {
/* The process might exit between GetProcesses_internal and GetProcessById */
}
}
Array.Resize<Process> (ref processes, size);
return processes;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static int[] GetProcesses_internal();
@@ -901,12 +901,11 @@ namespace System.Net.Sockets
SocketAsyncResult ares;
if (!GetCheckedIPs (e, out addresses)) {
e.socket_async_result.EndPoint = e.RemoteEndPoint;
//NOTE: DualMode may cause Socket's RemoteEndpoint to differ in AddressFamily from the
// SocketAsyncEventArgs, but the SocketAsyncEventArgs itself is not changed
ares = (SocketAsyncResult) BeginConnect (e.RemoteEndPoint, ConnectAsyncCallback, e);
} else {
DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
e.socket_async_result.Addresses = addresses;
e.socket_async_result.Port = dep.Port;
DnsEndPoint dep = (DnsEndPoint)e.RemoteEndPoint;
ares = (SocketAsyncResult) BeginConnect (addresses, dep.Port, ConnectAsyncCallback, e);
}
@@ -984,8 +983,8 @@ namespace System.Net.Sockets
sockares.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
return sockares;
}
end_point = RemapIPEndPoint (ep);
sockares.EndPoint = end_point = RemapIPEndPoint (ep);
}
int error = 0;
@@ -145,22 +145,33 @@ namespace System.Net.Sockets
IsCompleted = true;
/* It is possible that this.socket is modified by this.Init which has been called by the callback. This
* would lead to inconsistency, as we would for example not release the correct socket.ReadSem or
* socket.WriteSem.
* For example, this can happen with AcceptAsync followed by a ReceiveAsync on the same
* SocketAsyncEventArgs */
Socket completedSocket = socket;
SocketOperation completedOperation = operation;
AsyncCallback callback = AsyncCallback;
if (callback != null) {
ThreadPool.UnsafeQueueUserWorkItem (_ => callback (this), null);
}
switch (operation) {
/* Warning: any field on the current SocketAsyncResult might have changed, as the callback might have
* called this.Init */
switch (completedOperation) {
case SocketOperation.Receive:
case SocketOperation.ReceiveFrom:
case SocketOperation.ReceiveGeneric:
case SocketOperation.Accept:
socket.ReadSem.Release ();
completedSocket.ReadSem.Release ();
break;
case SocketOperation.Send:
case SocketOperation.SendTo:
case SocketOperation.SendGeneric:
socket.WriteSem.Release ();
completedSocket.WriteSem.Release ();
break;
}
+285 -10
View File
@@ -29,10 +29,16 @@ using System.Net;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using ObjCRuntime;
namespace Mono.Net
{
internal class CFObject : IDisposable
internal class CFType {
[DllImport (CFObject.CoreFoundationLibrary, EntryPoint="CFGetTypeID")]
public static extern IntPtr GetTypeID (IntPtr typeRef);
}
internal class CFObject : IDisposable, INativeObject
{
public const string CoreFoundationLibrary = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation";
const string SystemLibrary = "/usr/lib/libSystem.dylib";
@@ -41,7 +47,7 @@ namespace Mono.Net
public static extern IntPtr dlopen (string path, int mode);
[DllImport (SystemLibrary)]
public static extern IntPtr dlsym (IntPtr handle, string symbol);
static extern IntPtr dlsym (IntPtr handle, string symbol);
[DllImport (SystemLibrary)]
public static extern void dlclose (IntPtr handle);
@@ -51,6 +57,25 @@ namespace Mono.Net
return dlsym (handle, symbol);
}
public static CFString GetStringConstant (IntPtr handle, string symbol)
{
var indirect = dlsym (handle, symbol);
if (indirect == IntPtr.Zero)
return null;
var actual = Marshal.ReadIntPtr (indirect);
if (actual == IntPtr.Zero)
return null;
return new CFString (actual, false);
}
public static IntPtr GetIntPtr (IntPtr handle, string symbol)
{
var indirect = dlsym (handle, symbol);
if (indirect == IntPtr.Zero)
return IntPtr.Zero;
return Marshal.ReadIntPtr (indirect);
}
public static IntPtr GetCFObjectHandle (IntPtr handle, string symbol)
{
var indirect = dlsym (handle, symbol);
@@ -76,7 +101,7 @@ namespace Mono.Net
public IntPtr Handle { get; private set; }
[DllImport (CoreFoundationLibrary)]
extern static IntPtr CFRetain (IntPtr handle);
internal extern static IntPtr CFRetain (IntPtr handle);
void Retain ()
{
@@ -84,7 +109,7 @@ namespace Mono.Net
}
[DllImport (CoreFoundationLibrary)]
extern static void CFRelease (IntPtr handle);
internal extern static void CFRelease (IntPtr handle);
void Release ()
{
@@ -126,8 +151,22 @@ namespace Mono.Net
dlclose (handle);
}
}
public static CFArray FromNativeObjects (params INativeObject[] values)
{
return new CFArray (Create (values), true);
}
static unsafe CFArray Create (params IntPtr[] values)
public static unsafe IntPtr Create (params IntPtr[] values)
{
if (values == null)
throw new ArgumentNullException ("values");
fixed (IntPtr* pv = values) {
return CFArrayCreate (IntPtr.Zero, (IntPtr) pv, (IntPtr)values.Length, kCFTypeArrayCallbacks);
}
}
internal static unsafe CFArray CreateArray (params IntPtr[] values)
{
if (values == null)
throw new ArgumentNullException ("values");
@@ -138,16 +177,19 @@ namespace Mono.Net
return new CFArray (handle, false);
}
}
public static CFArray CreateArray (params INativeObject[] values)
{
return new CFArray (Create (values), true);
}
public static CFArray Create (params CFObject[] values)
public static IntPtr Create (params INativeObject[] values)
{
if (values == null)
throw new ArgumentNullException ("values");
IntPtr[] _values = new IntPtr [values.Length];
for (int i = 0; i < _values.Length; i++)
_values[i] = values[i].Handle;
for (int i = 0; i < _values.Length; ++i)
_values [i] = values [i].Handle;
return Create (_values);
}
@@ -166,6 +208,20 @@ namespace Mono.Net
return CFArrayGetValueAtIndex (Handle, (IntPtr) index);
}
}
static public T [] ArrayFromHandle<T> (IntPtr handle, Func<IntPtr, T> creation) where T : class, INativeObject
{
if (handle == IntPtr.Zero)
return null;
var c = CFArrayGetCount (handle);
T [] ret = new T [(int)c];
for (uint i = 0; i < (uint)c; i++) {
ret [i] = creation (CFArrayGetValueAtIndex (handle, (IntPtr)i));
}
return ret;
}
}
internal class CFNumber : CFObject
@@ -209,6 +265,15 @@ namespace Mono.Net
return value;
}
[DllImport (CoreFoundationLibrary)]
extern static IntPtr CFNumberCreate (IntPtr allocator, IntPtr theType, IntPtr valuePtr);
public static CFNumber FromInt32 (int number)
{
// 9 == kCFNumberIntType == C int
return new CFNumber (CFNumberCreate (IntPtr.Zero, (IntPtr)9, (IntPtr)number), true);
}
public static implicit operator int (CFNumber number)
{
@@ -328,13 +393,116 @@ namespace Mono.Net
}
}
internal class CFData : CFObject
{
public CFData (IntPtr handle, bool own) : base (handle, own) { }
[DllImport (CoreFoundationLibrary)]
extern static /* CFDataRef */ IntPtr CFDataCreate (/* CFAllocatorRef */ IntPtr allocator, /* UInt8* */ IntPtr bytes, /* CFIndex */ IntPtr length);
public unsafe static CFData FromData (byte [] buffer)
{
fixed (byte* p = buffer)
{
return FromData ((IntPtr)p, (IntPtr)buffer.Length);
}
}
public static CFData FromData (IntPtr buffer, IntPtr length)
{
return new CFData (CFDataCreate (IntPtr.Zero, buffer, length), true);
}
public IntPtr Length {
get { return CFDataGetLength (Handle); }
}
[DllImport (CoreFoundationLibrary)]
extern static /* CFIndex */ IntPtr CFDataGetLength (/* CFDataRef */ IntPtr theData);
[DllImport (CoreFoundationLibrary)]
extern static /* UInt8* */ IntPtr CFDataGetBytePtr (/* CFDataRef */ IntPtr theData);
/*
* Exposes a read-only pointer to the underlying storage.
*/
public IntPtr Bytes {
get { return CFDataGetBytePtr (Handle); }
}
public byte this [long idx] {
get {
if (idx < 0 || (ulong) idx > (ulong) Length)
throw new ArgumentException ("idx");
return Marshal.ReadByte (new IntPtr (Bytes.ToInt64 () + idx));
}
set {
throw new NotImplementedException ("NSData arrays can not be modified, use an NSMutableData instead");
}
}
}
internal class CFDictionary : CFObject
{
static readonly IntPtr KeyCallbacks;
static readonly IntPtr ValueCallbacks;
static CFDictionary ()
{
var handle = dlopen (CoreFoundationLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
KeyCallbacks = GetIndirect (handle, "kCFTypeDictionaryKeyCallBacks");
ValueCallbacks = GetIndirect (handle, "kCFTypeDictionaryValueCallBacks");
} finally {
dlclose (handle);
}
}
public CFDictionary (IntPtr handle, bool own) : base (handle, own) { }
public static CFDictionary FromObjectAndKey (IntPtr obj, IntPtr key)
{
return new CFDictionary (CFDictionaryCreate (IntPtr.Zero, new IntPtr[] { key }, new IntPtr [] { obj }, (IntPtr)1, KeyCallbacks, ValueCallbacks), true);
}
public static CFDictionary FromKeysAndObjects (IList<Tuple<IntPtr,IntPtr>> items)
{
var keys = new IntPtr [items.Count];
var values = new IntPtr [items.Count];
for (int i = 0; i < items.Count; i++) {
keys [i] = items [i].Item1;
values [i] = items [i].Item2;
}
return new CFDictionary (CFDictionaryCreate (IntPtr.Zero, keys, values, (IntPtr)items.Count, KeyCallbacks, ValueCallbacks), true);
}
[DllImport (CoreFoundationLibrary)]
extern static IntPtr CFDictionaryCreate (IntPtr allocator, IntPtr[] keys, IntPtr[] vals, IntPtr len, IntPtr keyCallbacks, IntPtr valCallbacks);
[DllImport (CoreFoundationLibrary)]
extern static IntPtr CFDictionaryGetValue (IntPtr handle, IntPtr key);
[DllImport (CoreFoundationLibrary)]
extern static IntPtr CFDictionaryCreateCopy (IntPtr allocator, IntPtr handle);
public CFDictionary Copy ()
{
return new CFDictionary (CFDictionaryCreateCopy (IntPtr.Zero, Handle), true);
}
public CFMutableDictionary MutableCopy ()
{
return new CFMutableDictionary (CFDictionaryCreateMutableCopy (IntPtr.Zero, IntPtr.Zero, Handle), true);
}
[DllImport (CoreFoundationLibrary)]
extern static IntPtr CFDictionaryCreateMutableCopy (IntPtr allocator, IntPtr capacity, IntPtr theDict);
public IntPtr GetValue (IntPtr key)
{
return CFDictionaryGetValue (Handle, key);
@@ -346,6 +514,31 @@ namespace Mono.Net
}
}
}
internal class CFMutableDictionary : CFDictionary
{
public CFMutableDictionary (IntPtr handle, bool own) : base (handle, own) { }
public void SetValue (IntPtr key, IntPtr val)
{
CFDictionarySetValue (Handle, key, val);
}
public static CFMutableDictionary Create ()
{
var handle = CFDictionaryCreateMutable (IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
if (handle == IntPtr.Zero)
throw new InvalidOperationException ();
return new CFMutableDictionary (handle, true);
}
[DllImport (CoreFoundationLibrary)]
extern static void CFDictionarySetValue (IntPtr handle, IntPtr key, IntPtr val);
[DllImport (CoreFoundationLibrary)]
extern static IntPtr CFDictionaryCreateMutable (IntPtr allocator, IntPtr capacity, IntPtr keyCallback, IntPtr valueCallbacks);
}
internal class CFUrl : CFObject
{
@@ -1066,4 +1259,86 @@ namespace Mono.Net
return new CFWebProxy ();
}
}
class CFBoolean : INativeObject, IDisposable {
IntPtr handle;
public static readonly CFBoolean True;
public static readonly CFBoolean False;
static CFBoolean ()
{
var handle = CFObject.dlopen (CFObject.CoreFoundationLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
True = new CFBoolean (CFObject.GetCFObjectHandle (handle, "kCFBooleanTrue"), false);
False = new CFBoolean (CFObject.GetCFObjectHandle (handle, "kCFBooleanFalse"), false);
}
finally {
CFObject.dlclose (handle);
}
}
internal CFBoolean (IntPtr handle, bool owns)
{
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
~CFBoolean ()
{
Dispose (false);
}
public IntPtr Handle {
get {
return handle;
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
public static implicit operator bool (CFBoolean value)
{
return value.Value;
}
public static explicit operator CFBoolean (bool value)
{
return FromBoolean (value);
}
public static CFBoolean FromBoolean (bool value)
{
return value ? True : False;
}
[DllImport (CFObject.CoreFoundationLibrary)]
[return: MarshalAs (UnmanagedType.I1)]
extern static /* Boolean */ bool CFBooleanGetValue (/* CFBooleanRef */ IntPtr boolean);
public bool Value {
get {return CFBooleanGetValue (handle);}
}
public static bool GetValue (IntPtr boolean)
{
return CFBooleanGetValue (boolean);
}
}
}
@@ -1016,6 +1016,18 @@ namespace System.Net
IAsyncResult result = null;
try {
result = s.BeginWrite (buffer, offset, size, cb, state);
} catch (ObjectDisposedException) {
lock (this) {
if (Data.request != request)
return null;
}
throw;
} catch (IOException e) {
SocketException se = e.InnerException as SocketException;
if (se != null && se.SocketErrorCode == SocketError.NotConnected) {
return null;
}
throw;
} catch (Exception) {
status = WebExceptionStatus.SendFailure;
throw;
@@ -16,7 +16,7 @@ using System.ComponentModel.Design;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
#if !MOBILE && !MONOMAC
#if !MOBILE && !MONOMAC && !XAMMAC_4_5
using System.Drawing.Design;
#endif
using NUnit.Framework;
@@ -1053,7 +1053,7 @@ namespace MonoTests.System.ComponentModel
return attr;
return null;
}
#if !MOBILE && !MONOMAC
#if !MOBILE && !MONOMAC && !XAMMAC_4_5
class GetEditor_test
{
[Editor (typeof (UIEditor), typeof (UITypeEditor))]
@@ -16,7 +16,7 @@ namespace MonoTests.System.ComponentModel
[TestFixture]
public class ToolboxItemAttributeTests
{
#if !MOBILE && !MONOMAC
#if !MOBILE && !MONOMAC && !XAMMAC_4_5
[Test]
public void DefaultType ()
{
@@ -287,7 +287,11 @@ namespace MonoTests.System.Configuration {
[Test]
public void TestSettings2_Properties ()
{
#if XAMMAC_4_5
string expected = "MonoTests.System.Configuration.ProviderPoker, xammac_net_4_5_System_test, Version=0.0.0.0";
#else
string expected = "MonoTests.System.Configuration.ProviderPoker, net_4_x_System_test, Version=0.0.0.0";
#endif
Assert.AreEqual (expected, new SettingsProviderAttribute (typeof (ProviderPoker)).ProviderTypeName.Substring (0, expected.Length), "#1");
TestSettings2 settings = new TestSettings2 ();
@@ -14,6 +14,7 @@ using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using NUnit.Framework;
@@ -22,6 +23,13 @@ namespace MonoTests.System.Diagnostics
[TestFixture]
public class ProcessTest
{
static bool RunningOnUnix {
get {
int p = (int)Environment.OSVersion.Platform;
return ((p == 128) || (p == 4) || (p == 6));
}
}
[Test]
public void GetProcessById_MachineName_Null ()
{
@@ -728,13 +736,6 @@ namespace MonoTests.System.Diagnostics
bytesRead = stm.EndRead (ar);
}
static bool RunningOnUnix {
get {
int p = (int)Environment.OSVersion.Platform;
return ((p == 128) || (p == 4) || (p == 6));
}
}
public int bytesRead = -1;
[Test]
@@ -1113,5 +1114,71 @@ namespace MonoTests.System.Diagnostics
}
}
#endif // MONO_FEATURE_PROCESS_START
[Test]
[NUnit.Framework.Category ("MobileNotWorking")]
public void GetProcessesByName()
{
// This should return Process[0] or a Process[] with all the "foo" programs running
Process.GetProcessesByName ("foo");
}
[Test]
[NUnit.Framework.Category ("MobileNotWorking")]
public void NonChildProcessWaitForExit ()
{
if (!RunningOnUnix)
Assert.Ignore ("accessing parent pid, only available on unix");
using (Process process = Process.GetProcessById (getppid ()))
using (ManualResetEvent mre = new ManualResetEvent (false))
{
Assert.IsFalse (process.WaitForExit (10), "#1");
Assert.IsFalse (process.HasExited, "#2");
Assert.Throws<InvalidOperationException>(delegate { int exitCode = process.ExitCode; }, "#3");
process.Exited += (s, e) => mre.Set ();
process.EnableRaisingEvents = true;
Assert.IsFalse (mre.WaitOne (100), "#4");
Assert.IsFalse (process.WaitForExit (10), "#5");
Assert.IsFalse (process.HasExited, "#6");
Assert.Throws<InvalidOperationException>(delegate { int exitCode = process.ExitCode; }, "#7");
}
}
[Test]
[NUnit.Framework.Category ("MobileNotWorking")]
public void NonChildProcessName ()
{
if (!RunningOnUnix)
Assert.Ignore ("accessing parent pid, only available on unix");
using (Process process = Process.GetProcessById (getppid ()))
{
string pname = process.ProcessName;
Assert.IsNotNull (pname, "#1");
AssertHelper.IsNotEmpty (pname, "#2");
}
}
[Test]
[NUnit.Framework.Category ("MobileNotWorking")]
public void NonChildProcessId ()
{
if (!RunningOnUnix)
Assert.Ignore ("accessing parent pid, only available on unix");
int ppid;
using (Process process = Process.GetProcessById (ppid = getppid ()))
{
int pid = process.Id;
Assert.AreEqual (ppid, pid, "#1");
AssertHelper.Greater (pid, 0, "#2");
}
}
[DllImport ("libc")]
static extern int getppid();
}
}
@@ -59,6 +59,7 @@ public class SslStreamTest {
}
[Test] //bug https://bugzilla.novell.com/show_bug.cgi?id=457120
[Category ("MacNotWorking")] // Works but launches a prompt on 10.12 that will fail if you don't click in a few seconds
#if FEATURE_NO_BSD_SOCKETS
[ExpectedException (typeof (PlatformNotSupportedException))]
#endif
@@ -4622,6 +4622,8 @@ namespace MonoTests.System.Net.Sockets
client.DualMode = true;
var ar1 = client.BeginConnect (ep, BCCallback, client);
Assert.IsTrue (BCCalledBack.WaitOne (10000), "#1");
Assert.AreEqual(server.AddressFamily, client.RemoteEndPoint.AddressFamily, "#2");
Assert.AreEqual(server.AddressFamily, client.LocalEndPoint.AddressFamily, "#3");
client.Disconnect (false);
client.Close ();
@@ -4629,7 +4631,9 @@ namespace MonoTests.System.Net.Sockets
client = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
client.DualMode = true;
var ar2 = client.BeginConnect (IPAddress.Loopback, ep.Port, BCCallback, client);
Assert.IsTrue (BCCalledBack.WaitOne (10000), "#2");
Assert.IsTrue (BCCalledBack.WaitOne (10000), "#4");
Assert.AreEqual(server.AddressFamily, client.RemoteEndPoint.AddressFamily, "#5");
Assert.AreEqual(server.AddressFamily, client.LocalEndPoint.AddressFamily, "#6");
client.Disconnect (false);
client.Close ();
@@ -4637,7 +4641,9 @@ namespace MonoTests.System.Net.Sockets
client = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
client.DualMode = true;
var ar3 = client.BeginConnect (new [] {IPAddress.Loopback}, ep.Port, BCCallback, client);
Assert.IsTrue (BCCalledBack.WaitOne (10000), "#2");
Assert.IsTrue (BCCalledBack.WaitOne (10000), "#7");
Assert.AreEqual(server.AddressFamily, client.RemoteEndPoint.AddressFamily, "#8");
Assert.AreEqual(server.AddressFamily, client.LocalEndPoint.AddressFamily, "#9");
client.Disconnect (false);
client.Close();
}
@@ -4675,6 +4681,26 @@ namespace MonoTests.System.Net.Sockets
Assert.IsTrue (mre.WaitOne (1000), "ConnectedAsync timeout");
}
[Test] // Covers https://bugzilla.xamarin.com/show_bug.cgi?id=52549
public void SocketMismatchProtocol ()
{
try {
using (Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Tcp));
Assert.Fail ("#1");
} catch (SocketException e) {
// Only work on OSX
// Assert.AreEqual(SocketError.ProtocolType, e.SocketErrorCode, "#2");
}
try {
using (Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp));
Assert.Fail ("#3");
} catch (SocketException e) {
// Only work on OSX
// Assert.AreEqual(SocketError.ProtocolType, e.SocketErrorCode, "#4");
}
}
}
}
@@ -166,7 +166,9 @@ namespace MonoTests.System.Net.WebSockets
Assert.AreEqual (WebSocketState.Closed, socket.State);
}
[Test, ExpectedException (typeof (InvalidOperationException))]
[Test]
[ExpectedException (typeof (InvalidOperationException))]
[Category ("MobileNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
public void SendAsyncArgTest_NotConnected ()
{
socket.SendAsync (new ArraySegment<byte> (new byte[0]), WebSocketMessageType.Text, true, CancellationToken.None);
@@ -180,7 +182,9 @@ namespace MonoTests.System.Net.WebSockets
socket.SendAsync (new ArraySegment<byte> (), WebSocketMessageType.Text, true, CancellationToken.None);
}
[Test, ExpectedException (typeof (InvalidOperationException))]
[Test]
[ExpectedException (typeof (InvalidOperationException))]
[Category ("MobileNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
public void ReceiveAsyncArgTest_NotConnected ()
{
socket.ReceiveAsync (new ArraySegment<byte> (new byte[0]), CancellationToken.None);
@@ -587,6 +587,7 @@ mgk3bWUV6ChegutbguiKrI/DbO7wPiDLxw==
}
[Test]
[Category ("MacNotWorking")] // SecCertificateCreateWithData does different things on 10.11 vs 10.12 with invalid certificates https://bugzilla.xamarin.com/show_bug.cgi?id=53689
[ExpectedException (typeof (CryptographicException))]
public void Pkcs12_1_WithoutPassword ()
{
@@ -601,6 +602,7 @@ mgk3bWUV6ChegutbguiKrI/DbO7wPiDLxw==
}
[Test]
[Category ("MacNotWorking")] // SecCertificateCreateWithData does different things on 10.11 vs 10.12 with invalid certificates https://bugzilla.xamarin.com/show_bug.cgi?id=53689
public void Pkcs12_2_Properties ()
{
CheckPkcs12 (new X509Certificate (farscape_nopwd_pfx));
@@ -732,6 +734,7 @@ mgk3bWUV6ChegutbguiKrI/DbO7wPiDLxw==
[Test]
[ExpectedException (typeof (CryptographicException))]
[Category ("MacNotWorking")] // SecCertificateCreateWithData does different things on 10.11 vs 10.12 with invalid certificates https://bugzilla.xamarin.com/show_bug.cgi?id=53689
public void Pkcs7_Ctor ()
{
new X509Certificate (farscape_pkcs7);
@@ -739,6 +742,7 @@ mgk3bWUV6ChegutbguiKrI/DbO7wPiDLxw==
[Test]
[ExpectedException (typeof (CryptographicException))]
[Category ("MacNotWorking")] // SecCertificateCreateWithData does different things on 10.11 vs 10.12 with invalid certificates https://bugzilla.xamarin.com/show_bug.cgi?id=53689
public void Pkcs7_Import ()
{
X509Certificate x = new X509Certificate ();
+16
View File
@@ -292,6 +292,20 @@ Mono.Btls/X509ChainImplBtls.cs
Mono.Http/NtlmClient.cs
Mono.AppleTls/AppleCertificateHelper.cs
Mono.AppleTls/AppleTlsContext.cs
Mono.AppleTls/AppleTlsProvider.cs
Mono.AppleTls/AppleTlsStream.cs
Mono.AppleTls/INativeObject.cs
Mono.AppleTls/Certificate.cs
Mono.AppleTls/ImportExport.cs
Mono.AppleTls/Enums.cs
Mono.AppleTls/SecureTransport.cs
Mono.AppleTls/Policy.cs
Mono.AppleTls/Trust.cs
Mono.AppleTls/SslConnection.cs
Mono.AppleTls/Items.cs
Mono.Net.Security/AsyncProtocolRequest.cs
Mono.Net.Security/CallbackHelpers.cs
Mono.Net.Security/ChainValidationHelper.cs
@@ -311,6 +325,8 @@ Mono.Net.Security/SystemCertificateValidator.cs
Mono.Util/MonoPInvokeCallbackAttribute.cs
MonoTouch/Dummy.cs
ReferenceSources/AutoWebProxyScriptEngine.cs
ReferenceSources/AssertWrapper.cs
ReferenceSources/CAPI.cs
@@ -1 +1,2 @@
#include net_4_x_System.dll.sources
Mono.Net.Security/MonoTlsProviderFactory.Apple.cs
Loaded 100 of 274 files, more files were not shown because too many files have changed in this diff. Show more