Compare commits

...
Author SHA1 Message Date
Daniel J Sell 5d600522ed [asp.net] Fix for bug #653192. making MasterPageFile handle relative paths
MasterPageFile should be relative to the file being parsed, not the
request path
2010-11-12 11:24:41 +01:00
Gonzalo Paniagua Javier 2427b2b861 Don't cache child nodes when security trimming is enabled.
When SecurityTrimmingEnabled is set to true for the node, the cached children
collection also depends on the IPrincipal set for the current context.

Fixes bug #641449.
2010-11-11 21:19:43 -05:00
Marek Habersack 11aeecfa3a [corlib] Fix for bug #652807. Handle RegistryValueKind.QWord in Win32RegistryApi.{Get,Set}Value 2010-11-11 01:59:17 +01:00
Zoltan Varga e27b81a652 When single stepping from a exception throw site, single step to the catch site. Fixes #652590. 2010-11-10 18:27:01 +01:00
Zoltan Varga 8f3f18568c Fix a typo in process_breakpoint_inner which doesn't break our tests for some reason. 2010-11-08 20:23:34 +01:00
Zoltan Varga f886d89ef7 Enlarge try-finally blocks preceeded by a Monitor.Enter () call to include the call itself, to avoid races inherent in such code. Fixes #651546. 2010-11-05 19:12:35 +01:00
Zoltan Varga 44ea00024a Fix DISABLE_REFLECTION_EMIT build. 2010-11-05 16:30:40 +01:00
Marek Habersack 4aabcf3455 [asp.net,routing] Fix for bug #651593. Don't match all-literal routes for URLs with excessive segments. 2010-11-05 11:37:55 +01:00
Zoltan Varga a22f24834e Fix a bug introduced by the previous change to mono_jit_walk_stack_from_ctx_in_thread (). 2010-11-05 07:46:12 +01:00
Zoltan Varga cea5d2223b Fix crashes in the debugger stack walk code if a gshared method calls another using a managed-to-native translation. 2010-11-05 06:54:06 +01:00
Zoltan Varga bc1373c0d8 Fix more gshared problems in the soft debugger. 2010-11-05 06:38:19 +01:00
Zoltan Varga c8d96f618a Fix gshared support in the soft debugger. Fixes #651251. 2010-11-05 05:33:57 +01:00
Martin Baulig c530931921 Add mono_register_symfile_for_assembly() for bundles.
2010-11-03  Martin Baulig  <[email protected]>

	* mono-debug.c (mono_register_symfile_for_assembly): New method.
	This is used together with mono_register_bundled_assemblies() and
	mono_register_config_for_assembly() to support bundles.
2010-11-03 20:42:41 +01:00
Zoltan Varga e373b1cf49 Fix encoding of large strings in the soft debugger api. Fixes #648832. 2010-11-03 19:17:27 +01:00
Gonzalo Paniagua Javier ba5de9d036 Revert change in FromBinary 2010-11-02 18:58:16 -04:00
Andrew Jorgensen a51e35bbec Map libcups for mac
Fixes bnc#649994
2010-11-02 15:18:54 -06:00
Gonzalo Paniagua Javier 681aff17d2 Renaming a dangling symlink works now
Ditto.

	Fixes bug #650779.
2010-11-02 14:50:58 -04:00
Marek Habersack d1703c40ef [asp.net] 4.0-only types don't need the NET_4_0 ifdef and should be in net_4_0_System.Web.dll.sources 2010-11-02 11:31:55 +01:00
Marek Habersack c53bce8e0a [asp.net] ObjectStateFormatter.{De}serialize methods taking stream use a magic value to mark the stream. 2010-11-02 11:23:35 +01:00
Sebastien Pouliot 3aad88e828 Fix (likely copy-paste) typo on FormsAuthPasswordFormat
* System.Web.Security/FormsAuthentication.cs: Fix typo (MD5->SHA1).
I suspect the later is not used very much by mono users

* Test/System.Web.Security/FormsAuthenticationTest.cs: Small change to
make sure the hash name is not case sensitive
2010-11-02 11:22:45 +01:00
Sebastien Pouliot 2037a51576 Adjust System.Web.Extensions[_1.0].dll.sources wrt MachineKeySectionUtils.cs move 2010-11-02 11:22:23 +01:00
Sebastien Pouliot 8d8cae9016 A few moves/changes following previous patch review
* Makefile: Compile tests with TEST defined (to include System.Web.Util.
MachineKeySectionUtils unit tests)
* System.Web.dll.sources: Move MachineKeySectionUtils.cs from System.
Web.Configuration_2.0 to System.Web.Util
* System.Web_test.dll.sources: Move MachineKeySectionUtilsTest.cs from
System.Web.Configuration_2.0 to System.Web.Util

* System.Web.Configuration_2.0/MachineKeySection.cs: Adjust using
clauses. Uncomment some code. Fix TripleDES versus 3DES for Validation
under NET_4_0. Remove 'private' on fields/methods.
* System.Web.Handlers/AssemblyResourceLoader.cs: Adjust using clauses
* System.Web.Security/MembershipHelper.cs: Adjust using clauses
* System.Web.Security/RolePrincipal.cs: Adjust using clauses
* System.Web.SessionState_2.0/SessionId.cs: Adjust using clauses
* System.Web.UI/LosFormatter.cs: Adjust using clauses.
* System.Web.Util/MachineKeySectionUtils.cs: Moved from System.Web.
Configuration_2.0. Rename namespace and remove 'internal' on type
declaration

* Test/System.Web.Util/MachineKeySectionUtilsTest.cs: Moved from Test/
System.Web.Configuration/MachineKeySectionTest.cs. Add test case for
TripleDES versus 3DES
2010-11-02 11:22:06 +01:00
Sebastien Pouliot 4106e07cca Normalization of cryptographic uses in asp.net
* System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs:
Remove key length check and generic key generation.

* System.Web.Configuration_2.0/MachineKeySection.cs: Add support for 4.0
ValidationAlgorithm and the use of custom algorithms (validation and
decryption). Allow the use of any, valid, key length (based on the
algorithm). Let each algorithm creates its own key (e.g. special needs,
default length...)

* System.Web.Configuration_2.0/MachineKeySectionUtils.cs: Remove key
generation (from random) code and 192bits key length hack (won't work
with custom algorithms). Add support for new (4.0) algorithms, including
custom ones. Provide uniform/shared code to Encrypt/Decrypt, Sign/Verify
and EncryptSign/VerifyDecrypt using MachineKeySection data.

* System.Web.Configuration_2.0/MachineKeyValidation.cs: Add new (4.0)
values.

* System.Web.Configuration_2.0/MachineKeyValidationConverter.cs: Add
support for new (4.0) algorithms.

* System.Web.Handlers/AssemblyResourceLoader.cs: Use the new common
cryptographic code and base64 the encrypted data.

* System.Web.Security/FormsAuthentication.cs: Use the new common
cryptographic code and base64 the signed and/or encrypted data.

* System.Web.Security/MembershipHelper.cs: Use the new common
cryptographic code - this should be 100% compatible with existing data.

* System.Web.Security/RolePrincipal.cs: Use the new common cryptographic
code.

* System.Web.Security/SqliteMembershipProvider.cs: Adapt code for
internal API change.

* System.Web.UI/LosFormatter.cs: Adapt code for internal API change.
Fix some small behaviro changes wrt NET_4_0

* System.Web.UI/ObjectStateFormatter.cs: Use the new common cryptographic
code.

* System.Web.UI/Page.cs: Remove code that is now unneeded (with the new
common cryptogrraphic code).

* System.Web.Configuration_2.0/MachineKeyCompatibilityMode.cs: New.

* Test/System.Web.Configuration/MachineKeyValidationConverterTest.cs:
Add more, mostly 4.0, test cases.

* Test/System.Web.Security/FormsAuthenticationTest.cs: Add test case to
ensure HashPasswordForStoringInConfigFile is not case sensitive.

* Test/System.Web.UI/LosFormatterTest.cs: Add some rountrip test cases
with the different ctors
2010-11-02 11:16:12 +01:00
Marek Habersack 963f28f38b [runtime] mono_cfg_set_exception is not present in 2.8. Fixes the build. 2010-11-02 11:09:52 +01:00
Gonzalo Paniagua Javier bd045fc008 Avoid killing the thread if socket already null
In some weird cases socket is null when we try to close it.
2010-11-01 18:53:53 -04:00
Marek Safar cff2890d8d Set correct result type for chained folded enum subtraction 2010-11-01 11:42:35 +00:00
Zoltan Varga 101eaf3215 Cache the array of classes in find_typespec_for_class (). 2010-11-01 00:44:58 +01:00
Zoltan Varga 5cfa597a30 Avoid asserts if a forced inline fails. Fix typos. Fixes #650407. 2010-11-01 00:44:43 +01:00
Brian Luczkiewicz 84be0b20e5 Enable --aot (but not --aot=full) on osx/x86 2010-10-31 21:48:41 +01:00
Miguel de Icaza e7de26c774 Expose some of our internals to the Mono.Winforms assembly 2010-10-31 15:59:51 -04:00
Miguel de Icaza 8a31a4b263 Fix broken patch 2010-10-31 15:54:41 -04:00
Miguel de Icaza 06e2e82bb0 Allow this file to expose its types as public if needed 2010-10-31 15:51:38 -04:00
Zoltan Varga 47429fb521 Fix the generation of GenericEqualityComparer () instances in AOT. 2010-10-31 02:57:30 +02:00
Geoff Norton 42459678e9 Fix the build 2010-10-30 18:22:49 -04:00
Geoff Norton 44dc98ddd1 [OSX] Reintroduce Cocoa System.Drawing support
The old Cocoa backend for System.Drawing appears to still work.  You must
pass in a NSView.Handle while in the DrawRect method, or with lockFocus
called to prepare the NSGraphicsContext.
2010-10-30 14:53:18 -04:00
Marek Habersack 32832e39bb [asp.net] Fix for bug #649551. The LosFormatter (bool, string) constructor does not expect a base64-encoded string.
Telerik controls pass the string "string" as the macKeyModifier parameter to the constructor. Tests show that .NET
accepts such input without throwing an error. The passed string is now converted into a byte array and passed to
the LosFormatter (bool, byte[]) constructor.

This is a backport of 19e5207189
2010-10-29 16:18:53 +02:00
Marek Habersack de60018067 [asp.net] Fix for bug #649034. Control.FindControl continues to search for controls above itself if it's a naming container.
When a control is a naming container and an attempt to find a control with non-segmented id (e.g. 'myControl') is made,
the search continues to the control's naming container if pathOffset is 0, that is we're at the start of the search.
2010-10-29 14:49:52 +02:00
Geoff Norton 06e3b0379b [OSX] Fix debug=casts on OSX (Bug: 639172)
mono --debug=casts requires fast tls access and the jit tls intrinsic.
We already had support for OP_TLS_GET on darwin/x86, but we did not
expose the "tls offset (pthread_key_t)" from mini to the intrinsic,
instead falling back on the io-layer keys.  We now store mono_lmf_addr
in a pthread_key for darwin/x86 so that we can do fast-tls in the jit
and fix this feature.  X86 only for now.

r: kumpera
2010-10-28 19:52:58 -04:00
Marek Safar 2626e53a2e [646997] Correctly emit platform ILOnly flag 2010-10-27 13:40:46 +01:00
Rodrigo Kumpera 5015ec260b Fix some counters under 32bits. 2010-10-26 23:26:01 -02:00
Marek Habersack 91f700f9d4 [asp.net] HttpRuntime.AppDomainAppPath may be null during tests, check it before using. 2010-10-26 02:02:21 +02:00
Marek Habersack 63f589c152 [asp.net,routing] Fix for bug #648901. Matching engine must ignore trailing slash in the URLs. 2010-10-26 02:01:44 +02:00
Zoltan Varga c223d5999b Disable catchpoints when the DISABLE_BREAKPOINTS flag is used during an invoke. Fixes #632224. 2010-10-25 18:09:32 +02:00
Marek Habersack 6d8bafaa07 [asp.net] Better handling of application's AppDomain restart
* HttpRuntime.cs: disable filesystem watchers on appdomain shutdown and refuse to process
  requests while the current AppDomain is unloading
* HttpApplicationFactory.cs: if the current AppDomain is unloading, ignore FileSystemWatcher
  notifications
* WebConfigurationManager.cs: work around a deadlock issue when entering a ReaderWriterLockSlim
  upgradeable read lock very early during ASP.NET runtime/AppDomain initialization. Every few runs
  the attempt would lock up and since adding a section to cache is not a critical operation we can
  afford timing the lock out in this case. The lockup is probably due to the fact that RWLS is using
  thread local storage to store the current thread's lock status and it may happen that the TLS is
  not cleared during thread object finalization (see metadata/threads.c, the start_wrapper function)
2010-10-25 14:30:35 +02:00
Zoltan Varga 5625f3afe8 Use int 3 as G_BREAKPOINT on x86-64 too. Hopefully fixes #648838. 2010-10-23 20:38:59 +02:00
Zoltan Varga 59959cefb2 Fix another regression in the Array.Sort () methods, allow keys and items to be of different length. Fixes #648828. 2010-10-23 16:48:11 +02:00
Zoltan Varga 217ec2ce11 Implement memory barriers for amd64/x86. Fixes #648831. 2010-10-23 16:31:09 +02:00
Zoltan Varga 4f47316df0 Emit GenericEqualityComparer<T> instances for each EqualityComparer<T> instance in AOT, the former is created dynamically by the latter. 2010-10-22 17:58:08 +02:00
Zoltan Varga 589a83dfa4 Use locale_charset() from iconv which will use nl_langinfo (CODESET) anyways but it will
do canonicalization so we will get the correct charset name, because nl_langinfo (CODESET)
can return different things on different systems. This at least fixes OpenBSD.
2010-10-22 17:28:47 +02:00
Marek Habersack b54ac46230 [asp.net] Part of fix for bug #579837. AuthorizationRule.SerializeElement will not process unmodified elements.
* AuthorizationRule.cs: if the configuration save is not Full, SerializeElement checks whether the rule being
  serialized is modified. If it isn't, validation and serialization are not performed.
* AuthorizationRuleCollection.cs: there is no element name for the collection.
2010-10-22 15:48:14 +02:00
Marek Habersack 7c22cb0135 [configuration] Part of fix for bug #579837. CommaDelimitedStringCollection must properly note that it was modified.
When one manipulates the collection as an instance of StringCollection, the 'modified' field will not
be set (Add, Remove etc. from the underlying StringCollection type will be used). To work around it
a check has to be performed in IsModified whether the contents of the collection changed. It is done
by comparing string hash codes of the original vs current string.
CommaDelimitedStringCollectionConverter forces string hash code update on the new collection, so that IsModified
works correctly on collections converted from comma-delimited strings.
2010-10-22 15:47:57 +02:00
Paolo Molaro 8e890a3bf8 Search for dllimported shared libs in the base directory, not cwd.
* loader.c: we don't search the current directory anymore for shared
libraries referenced in DllImport attributes, as it has a slight
security risk. We search in the same directory where the referencing
image was loaded from, instead. Fixes bug# 641915.
2010-10-22 10:51:15 +02:00
Gonzalo Paniagua Javier b80ffc9882 Replace EnumProcesses with OpenProcess
namedmutex_prewait was (partially) listing the running processes and
	then searching through them. Now we use OpenProcess to verify the owner
	of the mutex is still alive.

	Fixes bug #648133 (note that you need MONO_ENABLE_SHM for this to work)
2010-10-21 18:58:45 -04:00
Ankit Jain 61c8b99b3f [xbuild] Fix bug #646941. Add explicit System.Core for >=3.5 projects.
For projects targeting TargetFrameworkVersion >= 3.5, automatically
add a reference to System.Core . This can be controlled via two
properties:

 $(AddAdditionalExplicitAssemblyReferences) and
 $(AdditionalExplicitAssemblyReferences) .

This is used only for projects built with ToolsVersion=4.0 .
2010-10-22 02:57:07 +05:30
Ankit Jain 4a60b3f3fa [xbuild] Set default TargetFrameworkVersion=4.0 for ToolsVersion=4.0 2010-10-22 02:57:07 +05:30
Ankit Jain d2bb6fe8e1 [xbuild] Add ResolveAssemblyReferencesDependsOn .
Add GetFrameworkPaths and PrepareForBuild as dependencies for
the ResolveAssemblyReferences target. This is required when it is
invoked directly from MD.

Patch from Michael Hutchinson ([email protected]).
2010-10-22 02:57:06 +05:30
Ankit Jain 9f384277cd [xbuild] Reset cache of built targets, on a new project build.
All targets that get built are tracked by the engine, to avoid
unnecessary builds of targets. This should be reset on engine.Build,
unless it is explicitly requested *not to* reset it, via BuildFlags.
2010-10-22 02:57:06 +05:30
Ankit Jain 10b7c361bb [xbuild] Reset ConsoleLogger when a build finishes.
MSBuild hosts like monodevelop, which use the same logger
for multiple builds, get errors/warnings from older builds.
So, reset them whenever the BuildFinished event is raised.

ILogger.Shutdown () is invoked when the host is about to quit,
according to msdn, so can't use that.
2010-10-22 02:57:05 +05:30
Ankit Jain 1e535e61d3 [xbuild] Log TaskFinished even when task fails to initialize. 2010-10-22 02:57:05 +05:30
Ankit Jain fb42e1e12b [xbuild] Update regex to not require EndProject in a sln file.
In a solution file, a Project might not have a corresponding
EndProject. This seems to be supported by VS, so updating xbuild
to support that too. Updated the regex.
2010-10-22 02:57:05 +05:30
Ankit Jain 7358969934 [xbuild] Use files referenced by resx for dependency check.
For .resx resource files, check files referenced by the resx
file also, to determine whether to resgen it or not.

IsResgenRequired () has been taken from MonoDevelop
(main/src/core/MonoDevelop.Core/MonoDevelop.Projects.Formats.MD1/MD1DotNetProjectHandler.cs)
2010-10-22 02:57:04 +05:30
Ankit Jain 89c7bb82d4 [xbuild] Fix case sensitive environment variables for ToolTask.
Use ProcessStringDictionary in ToolTask for EnvironmentVariables,
as this retains the original case of the keys. Without this
environment vars would all be passed as lowercase!

This was removed in a previous patch by mistake.
2010-10-22 02:57:04 +05:30
Ankit Jain c28b4ea9d7 [xbuild] Add ToolTask.EnvironmentVariables property.
* class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
	(EnvironmentVariables): New.
	(ExecuteTool): Merge EnvironmentVariables with
	EnvironmentOverride
	* class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/GenerateResource.cs
	(Resgen.Execute): Use EnvironmentVariables to set MONO_IOMAP=drive .
2010-10-22 02:57:03 +05:30
Ankit Jain b80d1ca6eb [xbuild] Fix a race condition in ToolTask.
* class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
 (ExecuteTool): When StartProcess returns, the process has already .Start()'ed
 If we subscribe to the output events after that, then for processes that
 finish executing before we can subscribe, we won't get the output/error
 events at all! So, pass the handlers to StartProcess itself, so that
 they get added before the process is started.
2010-10-22 02:57:03 +05:30
Ankit Jain 5f80fd9448 [xbuild] Fix handling of tool output.
The *StreamChanged event for ProcessWrapper may get parts of
long lines, so process the complete ones that we have (for matching
error/warning), and save rest for processing when the rest of it
is received.

Also, don't ignore empty lines.

* class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
2010-10-22 02:57:02 +05:30
Ankit Jain e53a4c3776 [xbuild] Fix ConsoleLogger's output, extra blank lines etc. 2010-10-22 02:57:02 +05:30
Ankit Jain 69a95ff53d [xbuild] Reduce ConsoleLogger's unnecessary output.
ConsoleLogger was emitting target names, even if they didn't have
any useful output, which resulted in lots of "Target foo:" in the
output, with no other related msgs.

 Target Foo:
 Target Bar:
 Target Xyz:

Emit project/target/task headers only if they result in a message,
error or warning. This results in much cleaner output.
2010-10-22 02:57:01 +05:30
Ankit Jain 5025f28490 [xbuild] Log default msg for TargetSkipped if @reason is null or empty. 2010-10-22 02:57:01 +05:30
Gonzalo Paniagua Javier e3c340f1c1 FromBinary does not need ToLocalTime
When converting to DateTime from a long, we don't need ToLocalTime().
	Setting the kind to Local is enough.
	Patch from Mig.

	Fixes bug #648252.
2010-10-21 16:02:43 -04:00
Zoltan Varga 2fdbdc2bc0 Fix building the logging profiler. 2010-10-21 21:57:45 +02:00
Miguel de Icaza 2875496241 Document server option to --debugger-agent 2010-10-21 14:13:45 -04:00
Andrew Jorgensen f98dc57542 Bump version to 2.8.1 2010-10-21 11:54:30 -06:00
Zoltan Varga 905e43efe2 Fix an assert in the LLVM backend if a long value was passed to 'localloc'. 2010-10-21 19:01:55 +02:00
Rodrigo Kumpera b6a25dfdd2 Disable cardtable unde 64bits as it is broken for 2.8. 2010-10-21 14:40:59 -02:00
Geoff Norton 16c125bc9b Fix a crash when using the embedding api
error_msg is null when passed into this function from a few places, so
lets not do a null deref here.
2010-10-21 12:29:02 -04:00
Michael Hutchinson 33d466d421 [Embedding] Make mono-dl-fallback.h public-safe 2010-10-21 12:29:01 -04:00
Miguel de Icaza 4b0101dd80 Do not install sample header, add to EXTRA_DIST 2010-10-21 12:29:01 -04:00
Miguel de Icaza 84e9b39b17 [Embedded] Add new fallback API to allow hooking up to the P/Invoke lookup system
This patch allows a developer to register a fallback for P/Invoke when
embedding Mono.   Typically this is done when you statically link all of your
libraries in some embedded systems and you need to dynamically resolve symbol
names.

There is a *sample* API included (but not compiled into Mono itself) called
mono-embed.c that shows a layman use of the API.   A full implementation would
mandate sorted tables, and would use a bsearch or a hashtable instead of having
linear searches.
2010-10-21 12:29:00 -04:00
Gonzalo Paniagua Javier 8a5647b1d6 Allow ordinal entry points in windows.
Windows allows entry point names like "#10" which refer to the Nth
	function (n > 1 and less than the highest ordinal value in the .def
	file).

	Fixes bug #636966.
2010-10-21 12:24:53 -04:00
Gonzalo Paniagua Javier 733d3f45d1 Linux /proc/mounts might have escaped characters
Translate escaped characters in mount paths.

	Fixes bug #637078.
2010-10-21 12:24:43 -04:00
Gonzalo Paniagua Javier 29ffd5258c Use UTF8 instead of ASCII when reading mount info
This allows for mount points with UTF8 characters in them.
2010-10-21 12:24:27 -04:00
Gonzalo Paniagua Javier e845f96a79 Fixed GetLogicalDriveString
When calling GetLogicalDriveString, icall.c was passing the
	length in the wrong units.

	GetLogicalDriveString now translates any octal sequence found
	into its corresponding byte. Use the UTF16 length
	('items_written') instead of the UTF8 input string length
	('items_read') when computing the total size.
2010-10-21 12:24:02 -04:00
Gonzalo Paniagua Javier 51e0ca445a Fix return value of items_read
items_read was not being initialized and it was not being set in the
	fast common case of g_utf8_to_utf16().
2010-10-21 12:23:43 -04:00
Gonzalo Paniagua Javier f95ed5726f UDP sockets allow connections to Any
UDP sockets that call Connect() to set a default address for datagrams
	sent, can call Connect() again with IPv6Any or Any to 'disconnect'.

	Fixes bug #639098.
2010-10-21 12:22:05 -04:00
Gonzalo Paniagua Javier 03af9e4c5d GetProcessById now works on the Mac too
Ditto.
	This should fix MD problems when SHM is disabled.
2010-10-21 12:21:16 -04:00
Gonzalo Paniagua Javier 921a0951d8 Map SO_EXCLUSIVEADDRUSE to !SO_REUSEADDR
This will make windows app that use that property work on *nix.
	Fixes bug #643475.
2010-10-21 12:18:04 -04:00
Gonzalo Paniagua Javier c6ee6980ce Fix the collision handling code
After the fix for bug #605092, inserting timers with an equal due time
	was failing because searching in the list was also using a reference
	comparison. Now, when adding a new timer, we search using just the due
	time.
	Fixes bug #648130.
2010-10-21 11:36:52 -04:00
Zoltan Varga 429c26b022 Avoid caching stuff in socket-io.c in static variables, since the socket assembly can be unloaded, cache them in MonoDomain instead. 2010-10-21 16:17:50 +02:00
Marek Habersack 5b4ab167be [asp.net,wcf] WCF proxies are generated using a slightly different mode of operation.
WCF proxies don't include full namespace of the contract.
2010-10-21 10:29:16 +02:00
Marek Habersack 58e8a395c4 [wcf] make /js and /jsdebug dispatchers work.
There were several issues here:

- The IChannelDispatcherBoundListener was defined twice, in two different namespaces, and it caused code in
  ChannelDispatcher.Attach not to set its associated listener's ChannelDispatcher property to the correct value.
  This, in turn, caused incorrect HttpListenerManagerTable operation, where it would put the "/js" and "/jsdebug"
  dispatchers in separate HttpListenerManagers, instead of in the main (base) service's one.
- After fixing the above, it turned out that SvcHttpHandler selected the manager based on the host's base address,
  when it should first try to find one whose URL matches the current request exactly.
2010-10-21 10:28:58 +02:00
Marek Habersack 0e93173683 [asp.net] make sure the string we pass to DecryptAssemblyResource is a valid Base64 string 2010-10-21 10:27:21 +02:00
Marek Habersack 20f6a72044 [wcf] ServiceHost directive can span several lines. 2010-10-21 10:27:07 +02:00
Marek Habersack 552a1f5c7e [wcf] Don't close HTTP response prematurely.
Service is invoked in the context of the System.Web pipeline and closing the response before the final
output stream flush causes the generated response not to ever reach the client. This patch makes sure
the System.Web pipeline takes care of all the response housekeeping.
2010-10-21 10:26:53 +02:00
Atsushi Eno d3b4997ff1 Remove extra call to HttpResponse.Flush() which would crash. 2010-10-21 10:26:39 +02:00
Gonzalo Paniagua Javier 722e143cc0 Set have_response
Set have_response to true when there's a protocol error or a previous
	exception for POST/PUT.
	Patch by Bassam Tabbara.
2010-10-20 13:57:25 -04:00
Gonzalo Paniagua Javier 0875d61ca2 Add support for EnableSsl in smtp config.
Ditto.
	Fixes bug #644816.
2010-10-20 13:57:24 -04:00
Gonzalo Paniagua Javier 0d8e8f7df9 Handle special case when disposing a socket.
When disposing a socket that has more than one asynchronous read/write
	pending, one of the callbacks could call DisposeAllOnClose() while
	another one is waiting on the lock. Once the lock is acquired,
	queue.Count will be 0 and Dequeue would fail.
	This is fixed now.

	Fixes bug #645675.
2010-10-20 13:57:23 -04:00
Gonzalo Paniagua Javier 135e5eb0df Able to read MS serialized nullable<primitive>
Handle boxed primitive types for nullable fields.
	Fixes bug #646556.
2010-10-20 01:37:26 -04:00
Zoltan Varga b2ba1f46f7 Avoid trying to read the gc name in the AOT runtime from older AOT images. Fixes #647918. 2010-10-20 05:10:30 +02:00
Tak 15e954d508 [Fix] Ensure that exceptions are propagated when embedding
* metadata/object.c:
* mini/mini.c:
Ensure that exceptions get propagated back to the caller
when mono is being embedded.
License: MIT/X11
2010-10-19 14:20:20 +02:00
Zoltan Varga 86bc7170e5 Avoid calling sem_post on a uninitialized semaphore during thread attach, it works under linux, but fails under *bsd. Fixes #647248. 2010-10-18 01:57:05 +02:00
Gonzalo Paniagua Javier 3779a70dcc [ThreadPool] Clear the thread state
Clear the thread state after finishing a work item. We were only
	resetting the background state.
2010-10-14 16:49:46 -04:00
Zoltan Varga 160cf6a24e Fix crashes in the AOT compiler when the loaded LLVM module is used. Fixes #646314. 2010-10-14 22:20:06 +02:00
Zoltan Varga 1cd68dd08c Update the IMT thunk creation code on sparc to support net 4.0. 2010-10-14 21:57:28 +02:00
Zoltan Varga 0ee4f2dbd1 Avoid a crash in g_convert () if iconv_open () fails. 2010-10-14 21:56:33 +02:00
Jb Evain 44d00f87d5 Add pretty print support for null values in JsonObjects 2010-10-14 14:23:37 +02:00
Jb Evain b214e1e693 Allow null values in JsonObjects 2010-10-14 14:23:19 +02:00
Marek Safar cda5880b42 [646298] Compile multiple interface event declarators 2010-10-14 10:57:25 +01:00
Robert Nagy e97de6b450 merge from head 2010-10-14 02:23:20 +02:00
Marek Safar d8034534d0 [642975] Fix initializer of partially static multidimensional arrays 2010-10-08 12:36:34 -04:00
Gonzalo Paniagua Javier b49c845d35 X509Chain always uses the LM store
X509Chain will now add the LM store certificates always, even when the
	CU store is selected.
2010-10-08 02:08:21 -04:00
Zoltan Varga b6a60964d8 Fix the sparc build. 2010-10-08 05:16:34 +02:00
Geoff Norton 3b5c655c05 Fix the build on windows 2010-10-05 15:59:29 -04:00
Michael Hutchinson 3b6f5c3308 [io-layer] Cope with pids > 16 bits
Fixes an issue in Process where "pseudo-handles" for processes with
pids > 16 bits would overflow and start getting treated as normal
handles. This would frequently segfault MonoDevelop on MacOS.
2010-10-05 13:38:52 -04:00
Geoff Norton 579a0ca72b Its possible that we're calling Process_free_internal on a pseudo-handle.
When we are not using SHM we use psuedo handles to return processes from pids,
however we dont guard against pseudo-handles in CloseProcess, which could lead to
calling unref on a fake handle.
2010-10-05 13:02:07 -04:00
Marek Habersack 577dfd5d78 [asp.net] Fix for bug #643298. A typo prevented the EnableViewStateMac from being recognized in the Page directive. 2010-10-05 08:04:46 +02:00
Miguel de Icaza 57dae7a311 Retval is not a reserved keyword, fixes 643345 2010-10-03 12:31:14 -04:00
Zoltan Varga a21c08a924 Check the debugger_thread_exited condition in a loop to guard against spurious wakeups. Fixes #642780. 2010-10-01 23:53:09 +02:00
Zoltan Varga e763cd5010 Fix code buffer reallocation check for OP_SWITCH on arm. 2010-10-01 16:27:51 +02:00
Zoltan Varga 964d3433d8 Fix a deadlock introduced by 5c2e3bf7 by using a separate low level lock to procect access to the file_share_hash hash table. Fixes #642985. 2010-10-01 10:03:27 +02:00
Gonzalo Paniagua Javier 89f92560a1 Invoke the callback in separate threads
The callbacks need to be invoked in different threads to avoid clogging
	the IO pool.

	Fixes bug #639656.
2010-09-30 01:41:22 -04:00
Marek Safar b1752875e8 [642437] Nested types have to check type arguments only and not full class 2010-09-29 09:06:09 -06:00
Alan McGovern 2a308efd0a [System.ServiceModel] Fix a few potential exceptions in background threads
Pass the listener as it's own async state so that we avoid potential null derefs in the callback. Also wrap the BeginAccept and EndAccept calls in their own try/catches in case they throw an exception.
2010-09-29 08:46:52 -06:00
Jérémie Laval bff2b8d6c4 [ReaderWriterLockSlim] Fix state corruption and race in a special interleaving.
Fix possible state corruption in the case where Upgradeable wasn't reactivating its read bit after a downgrade and set events accordingly. Fix possible race where a write process wannabe could step in the middle of Upgradeable actually upgrading to write mode.

Conflicts:

	mcs/class/System.Core/System.Threading/ReaderWriterLockSlim.cs
2010-09-29 15:45:21 +01:00
Marek Habersack 9f2d34d689 [asp.net] Remove lock recursion in Cache.ExpireItems 2010-09-28 22:36:04 +02:00
Atsushi Eno 37edaa18f7 TCP channel listener: remove extra complication (threads) in the previous change. 2010-09-28 10:57:39 -06:00
Atsushi Eno 77d12442c4 Rework TCP listening model, and fix AcceptTcpClient() to not drop timed out requests that actually steals next requests in the air. 2010-09-28 10:57:38 -06:00
Jérémie Laval 3ad4bb8e3d Turn Is*LockHeld properties into thread-specific values in ReaderWriterLockSlim. Add corresponding unit tests. 2010-09-28 13:24:25 +01:00
Marek Habersack 67c7faf279 [asp.net] Get rid of a possible (although unlikely) race condition when acquiring locks
The patch removes a small race condition where a boolean flag is set after acquiring a lock to
indicate to code executing in the finally {} block that it should release the lock. The boolean
variable is now removed and the lock is released unconditionally. It carries a potential to
throw an exception when the lock is not held, but it's better than to fail to release it and
lead the application to a deadlock.
2010-09-28 13:32:15 +02:00
Jackson Harper 7757931e8e On 64bit this is turning into a 16 byte struct, this works around the issue. 2010-09-24 00:26:29 -04:00
Andrew Jorgensen 5a55034e93 move DynamicData to mvc because it depends on Extensions 2010-09-23 14:18:16 -06:00
Gonzalo Paniagua Javier bab18ab6d2 epoll_ctl takes an int, not IntPtr
Ditto.
2010-09-23 15:02:32 -04:00
Gonzalo Paniagua Javier 4c601b8522 EpollEvent size adjustment
EpollEvent has to be one uint32 plus one int64, i.e. 12 bytes long.
	Manos libres now.
2010-09-22 18:15:57 -04:00
Jérémie Laval 36e827b0be Also set readerDoneEvent when exiting an upgradeable lock and reader condition is correct.
It could cause a deadlock when a writer tested the rwlock value before RwRead was removed and another Upgradeable operation happened at the same time.
2010-09-22 11:10:56 +01:00
Marek Safar e137468dc6 [640722] Consider delegate parameters when checking member hiding 2010-09-21 10:22:11 -06:00
Marek Safar aa92238b98 [640709] Don't reuse method parameters for base proxy, they can be hoisted 2010-09-21 10:21:46 -06:00
Marek Safar 093a537205 [640699] Reduced compound expressions need explicit conversion too. 2010-09-21 10:09:36 -06:00
Andrew Jorgensen fe1653eae0 put the x11 devel package back in buildrequires and a couple other spec fixes 2010-09-20 17:25:14 -06:00
Rodrigo Kumpera 58f029f2d1 Report the broken type name instead of assembly's. 2010-09-20 14:54:25 -03:00
Rodrigo Kumpera f16036819a Use List<Exception> instead of ArrayList to make things prettier. 2010-09-20 14:44:56 -03:00
Rodrigo Kumpera 784d21f5fd Fix AssemblyBuilder::GetTypes () with unfinished types.
* AssemblyBuilder.cs (GetTypes): Raise ReflectionTypeLoadException
	if any type was not finished.

	* AssemblyBuilderTest.cs: Add test for GetTypes () and incomplete
	TypeBuilders'.

	Fixes #640288
2010-09-20 14:36:41 -03:00
Andrew Jorgensen c101a18be3 errant file 2010-09-17 12:20:56 -06:00
Marek Safar f038e86294 [639603] Don't emit statements as expressions when they don't support it. 2010-09-17 12:09:26 -06:00
Gonzalo Paniagua Javier ef47ac3d22 Revert my last patch
Not only it didn't fix anything but it broke a test.
2010-09-17 09:48:59 -06:00
Atsushi Eno 95617646ba Add working .svc handler in 4.0 web.config. 2010-09-17 09:47:46 -06:00
Atsushi Eno 652ff412d2 (merge master 3a7d8b3) Avoid crash for use of deprecated InstallTrackingHandler in Snow Leopard. 2010-09-17 12:42:08 +09:00
Andrew Jorgensen 8ca77a27fa More .spec reorgs 2010-09-16 17:12:57 -06:00
Gonzalo Paniagua Javier 3b8eeb54d3 Fix typo. It has been there for 4 years.
Why on earth this wasn't found earlier? $20 reward to whoever gives a
	plausible explanation.
2010-09-16 15:10:58 -04:00
Marek Safar 6e23108f39 [639407] Clean up more static stuff to fix repl instances. 2010-09-16 12:06:42 -06:00
Miguel de Icaza 052fd53f21 Revert 2010-09-15 17:18:41 -04:00
Rodrigo Kumpera 164ba0d204 Fix a sgen shutdown crash.
* threads.c (mono_thread_suspend_all_other_threads): wait_data
	must not be malloc'd since it holds managed pointers. Alloc
	it on stack since the struct is about 512/1024 bytes long.

	* threads.c (mono_thread_manage): Ditto.

	* threads.c (mono_threads_request_thread_dump): Ditto.
2010-09-15 17:39:44 -03:00
Marek Safar 8853b1acb3 [637935] Fixed 3.5 version of msbuild dlls to reference 3.5 version of the engine
MONO_PATH does not work for subsequent dlls, so have to workaround it by
using full path for dlls in 3.5 profile which does not have it's own
mscorlib
2010-09-15 13:07:21 -06:00
Miguel de Icaza d2bc3285b1 Make the thread-id field be of the proper size on 64 bit machines.
This error was found by Gonzalo when he was looking at another problem
when thread IDs overflowed ints.

Currently we use gpointers in the io-layer for the threadid, but we were
only exposing the value as an int32.   The good news is that the code is
not really used right now, but could cause problems in the future as we
extend Process.
2010-09-15 14:28:58 -04:00
Ankit Jain 019cca88ce [xbuild] Fix references to Microsoft.Build.* assemblies for 3.5 . 2010-09-15 12:15:10 -06:00
Andrew Jorgensen b2ac405dbb mono-configuration-crypto is a 4.0 assembly, not 2.0 2010-09-15 10:39:11 -06:00
Rodrigo Kumpera 24ef405181 Fix monotouch bootstrap.
* Type.cs (GetTypeCodeImpl): If the type is a TypeBuilder
	call into specific code.

	* TypeBuilder.cs (GetTypeCodeInternal): New method that
	handles enums correctly.

	This change is required because calling into the runtime
	with incomplete TypeBuilders cause the runtime to crash.
2010-09-15 12:26:12 -04:00
Geoff Norton e2aecacc87 Fix the embedded mono on OSX code to support a symlinked mono into the framework.
The embedding code looks at the executable name, and builds the embedding profile
from that, however the default install has a /usr/bin/mono symlink pointing to
/Library/Frameworks/Mono.framework.  We now resolve the symlink before allowing
the embedding code to proceed.
2010-09-15 12:25:57 -04:00
Marek Safar d6038fc397 [639403] Fixes the endless recursion with hacked EOF 2010-09-15 09:07:12 -06:00
Gonzalo Paniagua Javier 0d7b33cbc9 GetProcessById now works on the Mac too
Ditto.
	This should fix MD problems when SHM is disabled.
2010-09-14 18:25:36 -04:00
Marek Safar f40fc6829d Initialize all core types 2010-09-14 16:15:39 -06:00
Gonzalo Paniagua Javier eb12be05d9 From master 2010-09-14 16:00:04 -04:00
Jérémie Laval f68a0cd137 Allow recursive Write + n * Read lock pattern for ReaderWriterLockSlim and add corresponding unit test 2010-09-14 16:00:04 -04:00
Jérémie Laval 815ec755b4 Generalize ThreadLockState to include recursive count informations and update them accordingly in the different Enter/Exit methods 2010-09-14 16:00:04 -04:00
Jérémie Laval f751095363 Split ReaderWriterLockSlim helper classes into their own files 2010-09-14 16:00:04 -04:00
Marek Safar 30f3260cc1 Finish predefined attributes instance access to allow compile time dynamic support in repl.
Fixes 639010
2010-09-14 11:27:01 -06:00
Geoff Norton 50a2d76b29 Fix a typo in my last commit 2010-09-13 19:59:19 -04:00
Geoff Norton 006d9f248d The tid is passed around internally as a unsigned value.
We were having a crash on OSX due to thread->tid not equalling the
passed tid due to a signedness issue.
2010-09-13 18:43:36 -04:00
Geoff Norton f16e13ead3 Mono 2.8 has a few more usages of the old type 2010-09-13 18:38:09 -04:00
Zoltan Varga 904b7563aa Bump minor version to 2 to be compatible with the runtime. 2010-09-13 15:32:28 -06:00
Geoff Norton 05378ccef9 Fix the build when compiling without shared handle support entirely
The wapi init functions call this even when shared is compiled out,
lets just return FALSE to get into the right codepaths.
2010-09-13 14:46:11 -04:00
Geoff Norton 911929eed1 Rename major -> major_collector and drop unguarded usage of ucontext_t.
Android defines a variable called "major" in its headers, lets rename
major -> major_collector to work around the conflict.

Not every architecture/platform has ucontext_t, so lets not strongly
type our contexts to that and let the macros do their job.
2010-09-13 14:45:55 -04:00
Zoltan Varga ae557e488d Avoid freeing the allocated monitors on shutdown, it seems to cause crashes
when running with SGEN, since SGEN writes to those arrays in:

==29095==    at 0x6844E5: add_or_remove_disappearing_link (sgen-gc.c:4143)
==29095==    by 0x6845F8: mono_gc_register_disappearing_link (sgen-gc.c:4167)
==29095==    by 0x67DE35: clear_domain_process_object (sgen-gc.c:1384)
==29095==    by 0x67DEA3: clear_domain_process_major_object_callback (sgen-gc.c:1400)
==29095==    by 0x6DE2DC: major_iterate_objects (sgen-marksweep.c:692)
==29095==    by 0x67E00B: mono_gc_clear_domain (sgen-gc.c:1459)
2010-09-10 16:58:05 -06:00
Geoff Norton d88e223dd4 Forward port this change for MonoVS 2010-09-10 14:55:45 -06:00
Geoff Norton 1867fd1486 fix typo
svn path=/branches/mono-2-6/mono/; revision=148851
2010-09-10 14:55:43 -06:00
Geoff Norton 1f42b9026c 2009-12-14 Geoff Norton <[email protected]>
* debugger-agent.c: The end_runtime_invoke guard isn't working
        on AMD64 as __builtin_frame_address (1) returns NULL.  Disable the
        behaviour by default, and make it runtime configurable.

svn path=/branches/mono-2-6/mono/; revision=148421
2010-09-10 14:55:41 -06:00
Miguel de Icaza 4b649e0805 [Fix] Correct fix for the g_shell_parse_argv bug
Simplifies the code a little bit by eliminating the in_quote variable,
but also fixes the rules to follow the requirements from the
"Shell Command Language" specification on the Unix03 site:

http://opengroup.org/onlinepubs/007908775/xcu/chap2.html#tag_001_002

In particular, the interpretation of the backslash inside double quotes
is limited to a handful of characters.   Notice that this differs from
the glib implementation which is not correct either.
2010-09-10 01:04:15 -04:00
Miguel de Icaza 2ce8ebda5f [Fix] Allow escape characters inside quoted text, and do not let nested quote reset the quoting state
This should fix #637680
2010-09-09 19:48:41 -04:00
Andrew Jorgensen 3b7c1f8741 Various cleanup and addition 2010-09-09 09:57:59 -06:00
Zoltan Varga faa1dd5646 Add a few more remaps. 2010-09-07 15:50:00 -06:00
Zoltan Varga 21b9ee9deb Remap g_strdupv too. 2010-09-07 15:49:59 -06:00
Marek Habersack db99cebd57 [asp.net] Fix for bug #636709. ClientID must be reset when ID is assigned. 2010-09-07 23:21:26 +02:00
Marek Habersack a8c3708337 [asp.net] Fix for bug #636475. A typo caused ads not to be matched in ChooseAd
The second loop over the ads hashtable must not reject an app if the keyword filter is empty.
2010-09-07 22:11:41 +02:00
Gonzalo Paniagua Javier b40cb0cc14 Add wsdl help generator to the 4.0 files
Ditto.

	Fixes bug #636841.
2010-09-07 14:32:44 -04:00
Gonzalo Paniagua Javier 5640b0a889 Remove Content-Length header when not needed
If we are redirecting to a GET from a POST, the Content-Length header
	might have stale data and it will be sent. Some servers, instead of
	ignoring it, keep waiting for the data to be sent (for a GET!).

	Fixes bug #636219.
2010-09-01 16:07:04 -06:00
Gonzalo Paniagua Javier 693cbe7207 Use the request itself as the key for the cache.
We were usign teh URL, but that might not be unique among several
	requests that need to be authenticated using NTLM. This led to
	different requests sharing the same authentication session which fails
	miserably.

	Bug #631315 fixed.
2010-09-01 16:07:03 -06:00
Gonzalo Paniagua Javier 93d6cc3bf9 Avoid sending data in the challenge phase of NTLM
If there's a POST/PUT request that gets a NTLM 401, we save the data
	and don't send it again until after the challenge phase. Ie, instead of
	sending all the data 3 times, we only send it at most twice.
2010-09-01 16:07:02 -06:00
Ankit Jain 0474947f86 [xbuild] Update man page to add "/tv:" option.
Add option to specify toolsversion from the command line,
to the man page.
2010-09-01 15:34:14 -06:00
Ankit Jain 0013378bfa [xbuild] Unsubscribe events on ConsoleLogger.Shutdown ()
Reported by Lluis Sanchez.
2010-09-01 15:34:03 -06:00
Geoff Norton 0e5aff05c4 Fix build of mono-basic on ppc64
OP_BREAK can take up to 40 bytes on ppc64
2010-09-01 12:15:25 -06:00
Jonathan Pryor 38a79cb7b8 [mdoc-update] Only check for duplicate elements, not duplicate nodes.
The duplicate-element checking algorithm wasn't restricted to just elements;
consequently, an 'invalid token' exception was generated from XPath because we
were trying to call XmlNode.SelectNodes("#text"), and '#' isn't valid.  Oops.

Fixes building gendarme from mono-tools.
2010-09-01 09:12:12 -06:00
Andrew Jorgensen fc767570a8 Version 2.8 2010-08-31 16:38:26 -06:00
215 changed files with 6952 additions and 2171 deletions

No files matched your search

+1
View File
@@ -18,6 +18,7 @@
<dllmap dll="libX11" target="@X11@" os="!windows" />
<dllmap dll="libcairo-2.dll" target="libcairo.so.2" os="!windows"/>
<dllmap dll="libcups" target="libcups.so.2" os="!windows"/>
<dllmap dll="libcups" target="libcups.dylib" os="osx"/>
<dllmap dll="i:kernel32.dll">
<dllentry dll="__Internal" name="CopyMemory" target="mono_win32_compat_CopyMemory"/>
<dllentry dll="__Internal" name="FillMemory" target="mono_win32_compat_FillMemory"/>
File diff suppressed because it is too large. Load diff
+2
View File
@@ -4,9 +4,11 @@ monodir = $(sysconfdir)/mono/4.0
EXTRA_DIST = machine.config \
web.config \
DefaultWsdlHelpGenerator.aspx \
settings.map
mono_DATA = machine.config \
web.config \
DefaultWsdlHelpGenerator.aspx \
settings.map
+1
View File
@@ -76,6 +76,7 @@
<!--
<add path="*.svc" verb="*" type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False"/>
-->
<add verb="*" path="*.svc" type="System.ServiceModel.Channels.SvcHttpHandlerFactory, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add path="*.rules" verb="*" type="System.Web.HttpForbiddenHandler" validate="True"/>
<!--
<add path="*.xoml" verb="*" type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False"/>
+2 -3
View File
@@ -14,9 +14,8 @@ BREAKPOINT="G_STMT_START { raise (SIGTRAP); } G_STMT_END"
if test x$GCC = xyes; then
GNUC_UNUSED='__attribute__((__unused__))'
GNUC_NORETURN='__attribute__((__noreturn__))'
echo target_cpu=$target_cpu
case $target_cpu in
i*86) BREAKPOINT="G_STMT_START { __asm__ (\"int \$03\"); } G_STMT_END" ;;
i*86|x86_64) BREAKPOINT="G_STMT_START { __asm__ (\"int \$03\"); } G_STMT_END" ;;
esac
fi
AC_SUBST(GNUC_PRETTY)
@@ -110,7 +109,7 @@ if test "x$have_iso_varargs" = "xyes"; then
fi
AC_SUBST(G_HAVE_ISO_VARARGS)
AC_CHECK_HEADERS(getopt.h sys/time.h sys/wait.h pwd.h langinfo.h iconv.h)
AC_CHECK_HEADERS(getopt.h sys/time.h sys/wait.h pwd.h langinfo.h iconv.h localcharset.h)
if test $ac_cv_sizeof_void_p != $ac_cv_sizeof_int; then
GPOINTER_TO_INT="((gint)(long) (ptr))"
+3
View File
@@ -50,6 +50,7 @@
#define g_hash_table_new_full monoeg_g_hash_table_new_full
#define g_hash_table_remove monoeg_g_hash_table_remove
#define g_hash_table_size monoeg_g_hash_table_size
#define g_hash_table_print_stats monoeg_g_hash_table_print_stats
#define g_int_equal monoeg_g_int_equal
#define g_int_hash monoeg_g_int_hash
#define g_list_alloc monoeg_g_list_alloc
@@ -99,6 +100,7 @@
#define g_pattern_spec_new monoeg_g_pattern_spec_new
#define g_print monoeg_g_print
#define g_printf monoeg_g_printf
#define g_printerr monoeg_g_printerr
#define g_propagate_error monoeg_g_propagate_error
#define g_ptr_array_add monoeg_g_ptr_array_add
#define g_ptr_array_foreach monoeg_g_ptr_array_foreach
@@ -166,6 +168,7 @@
#define g_strerror monoeg_g_strerror
#define g_strescape monoeg_g_strescape
#define g_strfreev monoeg_g_strfreev
#define g_strdupv monoeg_g_strdupv
#define g_string_append monoeg_g_string_append
#define g_string_append_c monoeg_g_string_append_c
#define g_string_append_len monoeg_g_string_append_len
+17 -9
View File
@@ -33,7 +33,6 @@ split_cmdline (const gchar *cmdline, GPtrArray *array, GError **error)
{
gchar *ptr;
gchar c;
gboolean in_quote = FALSE;
gboolean escaped = FALSE;
gchar quote_char = '\0';
GString *str;
@@ -42,18 +41,28 @@ split_cmdline (const gchar *cmdline, GPtrArray *array, GError **error)
ptr = (gchar *) cmdline;
while ((c = *ptr++) != '\0') {
if (escaped) {
escaped = FALSE;
if (!g_ascii_isspace (c))
/*
* \CHAR is only special inside a double quote if CHAR is
* one of: $`"\ and newline
*/
if (quote_char == '\"'){
if (!(c == '$' || c == '`' || c == '"' || c == '\\'))
g_string_append_c (str, '\\');
g_string_append_c (str, c);
} else if (in_quote) {
} else {
if (!g_ascii_isspace (c))
g_string_append_c (str, c);
}
escaped = FALSE;
} else if (quote_char) {
if (c == quote_char) {
in_quote = FALSE;
quote_char = '\0';
g_ptr_array_add (array, g_string_free (str, FALSE));
str = g_string_new ("");
} else {
} else if (c == '\\'){
escaped = TRUE;
} else
g_string_append_c (str, c);
}
} else if (g_ascii_isspace (c)) {
if (str->len > 0) {
g_ptr_array_add (array, g_string_free (str, FALSE));
@@ -62,7 +71,6 @@ split_cmdline (const gchar *cmdline, GPtrArray *array, GError **error)
} else if (c == '\\') {
escaped = TRUE;
} else if (c == '\'' || c == '"') {
in_quote = TRUE;
quote_char = c;
} else {
g_string_append_c (str, c);
@@ -76,7 +84,7 @@ split_cmdline (const gchar *cmdline, GPtrArray *array, GError **error)
return -1;
}
if (in_quote) {
if (quote_char) {
if (error)
*error = g_error_new (G_LOG_DOMAIN, 0, "Unfinished quote.");
g_string_free (str, TRUE);
+10 -3
View File
@@ -53,6 +53,9 @@
# ifdef HAVE_ICONV_H
# include <iconv.h>
# endif
# ifdef HAVE_LOCALCHARSET_H
# include <localcharset.h>
# endif
#endif
static char *my_charset;
@@ -217,8 +220,10 @@ g_convert (const gchar *str, gssize len,
convertor = iconv_open (to_codeset, from_codeset);
if (convertor == (iconv_t) -1){
*bytes_written = 0;
*bytes_read = 0;
if (bytes_written)
*bytes_written = 0;
if (bytes_read)
*bytes_read = 0;
return NULL;
}
@@ -303,7 +308,9 @@ g_get_charset (G_CONST_RETURN char **charset)
#else
if (my_charset == NULL){
/* These shouldn't be heap allocated */
#if HAVE_LANGINFO_H
#if HAVE_LOCALCHARSET_H
my_charset = locale_charset ();
#elif defined(HAVE_LANGINFO_H)
my_charset = nl_langinfo (CODESET);
#else
my_charset = "UTF-8";
+8 -1
View File
@@ -74,8 +74,11 @@ utf8_to_utf16_len (const gchar *str, glong len, glong *items_read, GError **erro
for (in_pos = 0; in_pos < len && str [in_pos] < 0x80; in_pos++)
ret ++;
if (in_pos == len)
if (in_pos == len) {
if (items_read)
*items_read = in_pos;
return ret;
}
mb_size = 0;
mb_remain = 0;
@@ -214,6 +217,8 @@ g_utf8_to_utf16 (const gchar *str, glong len, glong *items_read, glong *items_wr
if (len < 0)
len = strlen (str);
if (items_read)
*items_read = 0;
if (items_written)
*items_written = 0;
utf16_len = utf8_to_utf16_len (str, len, items_read, error);
@@ -311,6 +316,8 @@ g_utf16_to_utf8 (const gunichar2 *str, glong len, glong *items_read, glong *item
out_pos = 0;
surrogate = FALSE;
if (items_read)
*items_read = 0;
if (items_written)
*items_written = 0;
utf8_len = utf16_to_utf8_len (str, len, items_read, error);
+34
View File
@@ -226,6 +226,39 @@ test_shell_argv3 ()
return OK;
}
// This was the 2.8 showstopper error
RESULT
test_shell_argv4 ()
{
GError *error;
gint argc;
gchar **argv;
gboolean ret;
char *str = "'/usr/bin/gnome-terminal' -e \"bash -c 'read -p \\\"Press any key to continue...\\\" -n1;'\"";
argv = NULL;
argc = 0;
error = NULL;
ret = g_shell_parse_argv (str, &argc, &argv, &error);
if (!ret)
return FAILED ("1. It should return TRUE");
if (argc != 3)
return FAILED ("2. argc was %d", argc);
if (argv == NULL)
return FAILED ("3. argv[0] was NULL");
if (error != NULL)
return FAILED ("4. error was set");
if (strcmp (argv [0], "/usr/bin/gnome-terminal"))
return FAILED ("5. Expected /usr/bin/gnome-terminal got %s", argv [0]);
if (strcmp (argv [1], "-e"))
return FAILED ("6. Expected -e, got: %s", argv [1]);
if (strcmp (argv [2], "bash -c 'read -p \"Press any key to continue...\" -n1;'"))
return FAILED ("7. Got unexpected result: %s\n", argv [2]);
return OK;
}
RESULT
test_quote ()
{
@@ -244,6 +277,7 @@ static Test shell_tests [] = {
{"g_shell_parse_argv1", test_shell_argv1},
{"g_shell_parse_argv2", test_shell_argv2},
{"g_shell_parse_argv3", test_shell_argv3},
{"g_shell_parse_argv4", test_shell_argv4},
{"g_shell_quote", test_quote},
{NULL, NULL}
};
+2 -1
View File
@@ -1341,7 +1341,8 @@ void * GC_start_routine_head(void * arg, void *base_addr,
if (start) *start = si -> start_routine;
if (start_arg) *start_arg = si -> arg;
sem_post(&(si -> registered)); /* Last action on si. */
if (!(si->flags & FOREIGN_THREAD))
sem_post(&(si -> registered)); /* Last action on si. */
/* OK to deallocate. */
# if defined(THREAD_LOCAL_ALLOC) && !defined(DBG_HDRS_ALL)
LOCK();
+7
View File
@@ -220,6 +220,13 @@ Specifies the diagnostics log level for
.Sp
Used to specify the file where the log will be stored, it defaults to
standard output.
.TP
.I server=[y/n]
Defaults to no, with the default option Mono will actively connect to the
host/port configured with the \fBaddress\fR option. If you set it to 'y', it
instructs the Mono runtime to start debugging in server mode, where Mono
actively waits for the debugger front end to connect to the Mono process.
Mono will print out to stdout the IP address and port where it is listening.
.ne
.RE
.TP
+9
View File
@@ -23,6 +23,15 @@ Set or override project properties
.B \//logger:<logger>
Custom logger to log build events
.TP
.B \//toolsversion:version , /tv:version
Specify the toolset version to use.
Eg. /tv:4.0
This would cause 4.0 version of the Microsoft.Common.targets (among others) to be used. This overrides
the value specified in a project file.
Valid values: 2.0, 3.0, 3.5 and 4.0
.TP
.B \//verbosity:<level>
Logger verbosity level : quiet, minimal, normal, detailed, diagnostic
.TP
@@ -37,24 +37,14 @@ using System.Diagnostics;
[assembly: AssemblyDelaySign (true)]
[assembly: AssemblyKeyFile("../ecma.pub")]
#if NET_2_0
[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
[assembly: Debuggable (DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CompilationRelaxations (CompilationRelaxations.NoStringInterning)]
[assembly: Dependency ("System.Drawing,", LoadHint.Always)]
[assembly: Dependency ("System,", LoadHint.Always)]
[assembly: StringFreezing]
[assembly: ComCompatibleVersion (1, 0, 3300, 0)]
#elif NET_1_1
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: ComCompatibleVersion (1, 0, 3300, 0)]
[assembly: TypeLibVersion (1, 10)]
#elif NET_1_0
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyConfiguration ("")]
#endif
[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
[assembly: Debuggable (DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CompilationRelaxations (CompilationRelaxations.NoStringInterning)]
[assembly: Dependency ("System.Drawing,", LoadHint.Always)]
[assembly: Dependency ("System,", LoadHint.Always)]
[assembly: StringFreezing]
[assembly: ComCompatibleVersion (1, 0, 3300, 0)]
[assembly: InternalsVisibleTo("UIAutomationWinforms, PublicKey=00240000048000009400000006020000002400005253413100040000110000004bb98b1af6c1df0df8c02c380e116b7a7f0c8c827aecfccddc6e29b7c754cd608b49dfcef4df9699ad182e50f66afa4e68dabc7b6aeeec0aa4719a5f8e0aae8c193080a706adc3443a8356b1f254142034995532ac176398e12a30f6a74a119a89ac47672c9ae24d7e90de686557166e3b873cd707884431a0451d9d6f7fe795")]
[assembly: InternalsVisibleTo("Mono.WinformsSupport, PublicKey=00240000048000009400000006020000002400005253413100040000110000004bb98b1af6c1df0df8c02c380e116b7a7f0c8c827aecfccddc6e29b7c754cd608b49dfcef4df9699ad182e50f66afa4e68dabc7b6aeeec0aa4719a5f8e0aae8c193080a706adc3443a8356b1f254142034995532ac176398e12a30f6a74a119a89ac47672c9ae24d7e90de686557166e3b873cd707884431a0451d9d6f7fe795")]
#if NET_2_0
[assembly: InternalsVisibleTo("UIAutomationWinforms, PublicKey=00240000048000009400000006020000002400005253413100040000110000004bb98b1af6c1df0df8c02c380e116b7a7f0c8c827aecfccddc6e29b7c754cd608b49dfcef4df9699ad182e50f66afa4e68dabc7b6aeeec0aa4719a5f8e0aae8c193080a706adc3443a8356b1f254142034995532ac176398e12a30f6a74a119a89ac47672c9ae24d7e90de686557166e3b873cd707884431a0451d9d6f7fe795")]
#endif
@@ -50,7 +50,11 @@ namespace System.Windows.Forms.CarbonInternal {
private static DragTrackingDelegate DragTrackingHandler = new DragTrackingDelegate (TrackingCallback);
static Dnd () {
InstallTrackingHandler (DragTrackingHandler, IntPtr.Zero, IntPtr.Zero);
try {
InstallTrackingHandler (DragTrackingHandler, IntPtr.Zero, IntPtr.Zero);
} catch (EntryPointNotFoundException) {
// it is deprecated in 10.6 and does not exist anymore.
}
}
internal Dnd () {
@@ -30,9 +30,19 @@ using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace System.Windows.Forms {
#if PUBLIC_TYPES
namespace Mono.Winforms
#else
namespace System.Windows.Forms
#endif
{
[Flags]
internal enum WindowStyles : int {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum WindowStyles : int {
WS_OVERLAPPED = 0x00000000,
WS_POPUP = unchecked((int)0x80000000),
WS_CHILD = 0x40000000,
@@ -63,7 +73,12 @@ namespace System.Windows.Forms {
}
[Flags]
internal enum WindowExStyles : int {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum WindowExStyles : int {
// Extended Styles
WS_EX_DLGMODALFRAME = 0x00000001,
WS_EX_DRAGDETECT = 0x00000002,
@@ -99,14 +114,24 @@ namespace System.Windows.Forms {
}
[Flags]
internal enum ToolBarStyles : int {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum ToolBarStyles : int {
TBSTYLE_TOOLTIPS = 0x100,
TBSTYLE_FLAT = 0x800,
TBSTYLE_LIST = 0x1000,
TBSTYLE_TRANSPARENT = 0x8000
}
internal enum Msg {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum Msg {
WM_NULL = 0x0000,
WM_CREATE = 0x0001,
WM_DESTROY = 0x0002,
@@ -358,7 +383,12 @@ namespace System.Windows.Forms {
NIN_BALLOONUSERCLICK = WM_USER + 0x0005
}
internal enum MsgButtons {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum MsgButtons {
MK_LBUTTON = 0x0001,
MK_RBUTTON = 0x0002,
MK_SHIFT = 0x0004,
@@ -367,8 +397,13 @@ namespace System.Windows.Forms {
MK_XBUTTON1 = 0x0020,
MK_XBUTTON2 = 0x0040,
}
internal enum MsgUIState {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum MsgUIState {
UIS_SET = 1,
UIS_CLEAR = 2,
UIS_INITIALIZE = 3,
@@ -378,17 +413,22 @@ namespace System.Windows.Forms {
}
[StructLayout(LayoutKind.Sequential)]
internal struct POINT {
internal int x;
internal int y;
#if PUBLIC_TYPES
public
#else
internal
#endif
struct POINT {
public int x;
public int y;
internal POINT (int x, int y)
public POINT (int x, int y)
{
this.x = x;
this.y = y;
}
internal Point ToPoint ()
public Point ToPoint ()
{
return new Point (x, y);
}
@@ -400,7 +440,12 @@ namespace System.Windows.Forms {
}
[StructLayout(LayoutKind.Sequential)]
internal struct MSG {
#if PUBLIC_TYPES
public
#else
internal
#endif
struct MSG {
internal IntPtr hwnd;
internal Msg message;
internal IntPtr wParam;
@@ -416,26 +461,46 @@ namespace System.Windows.Forms {
}
[Flags]
internal enum TransparencySupport {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum TransparencySupport {
None = 0x00,
Get = 0x01,
Set = 0x02,
GetSet = 0x03
}
internal enum WindowActiveFlags {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum WindowActiveFlags {
WA_INACTIVE = 0,
WA_ACTIVE = 1,
WA_CLICKACTIVE = 2
}
internal enum KeybdEventFlags {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum KeybdEventFlags {
None = 0,
ExtendedKey = 0x0001,
KeyUp = 0x0002
}
internal enum VirtualKeys {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum VirtualKeys {
VK_LBUTTON = 0x01,
VK_RBUTTON = 0x02,
VK_CANCEL = 0x03,
@@ -590,7 +655,12 @@ namespace System.Windows.Forms {
VK_OEM_CLEAR = 0xFE,
}
internal enum TtyKeys {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum TtyKeys {
XK_BackSpace = 0xff08, /* Back space, back char */
XK_Tab = 0xff09,
XK_Linefeed = 0xff0a, /* Linefeed, LF */
@@ -603,7 +673,12 @@ namespace System.Windows.Forms {
XK_Delete = 0xffff /* Delete, rubout */
}
internal enum MiscKeys {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum MiscKeys {
XK_ISO_Lock = 0xfe01,
XK_ISO_Last_Group_Lock = 0xfe0f,
XK_Select = 0xff60,
@@ -622,7 +697,12 @@ namespace System.Windows.Forms {
XK_Num_Lock = 0xff7f
}
internal enum KeypadKeys {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum KeypadKeys {
XK_KP_Space = 0xff80,
XK_KP_Tab = 0xff89,
XK_KP_Enter = 0xff8d, /* Enter */
@@ -663,7 +743,12 @@ namespace System.Windows.Forms {
XK_KP_9 = 0xffb9
}
internal enum DeadKeys {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum DeadKeys {
XK_dead_grave = 0xfe50,
XK_dead_acute = 0xfe51,
XK_dead_circumflex = 0xfe52,
@@ -687,7 +772,12 @@ namespace System.Windows.Forms {
}
[StructLayout(LayoutKind.Sequential)]
internal struct HELPINFO {
#if PUBLIC_TYPES
public
#else
internal
#endif
struct HELPINFO {
internal uint cbSize;
internal int iContextType;
internal int iCtrlId;
@@ -696,13 +786,23 @@ namespace System.Windows.Forms {
internal POINT MousePos;
}
internal enum PeekMessageFlags {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum PeekMessageFlags {
PM_NOREMOVE = 0x00000000,
PM_REMOVE = 0x00000001,
PM_NOYIELD = 0x00000002
}
internal enum StdCursor {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum StdCursor {
Default = 0,
AppStarting = 1,
Arrow = 2,
@@ -733,7 +833,12 @@ namespace System.Windows.Forms {
WaitCursor = 27
}
internal enum HitTest {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum HitTest {
HTERROR = -2,
HTTRANSPARENT = -1,
HTNOWHERE = 0,
@@ -765,14 +870,24 @@ namespace System.Windows.Forms {
HTHELP = 21
}
internal enum TitleStyle {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum TitleStyle {
None = 0,
Normal = 1,
Tool = 2
}
[StructLayout(LayoutKind.Sequential)]
internal struct BITMAPINFOHEADER {
#if PUBLIC_TYPES
public
#else
internal
#endif
struct BITMAPINFOHEADER {
internal uint biSize;
internal int biWidth;
internal int biHeight;
@@ -786,7 +901,12 @@ namespace System.Windows.Forms {
internal uint biClrImportant;
}
internal enum ClipboardFormats : ushort {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum ClipboardFormats : ushort {
CF_TEXT = 1,
CF_BITMAP = 2,
CF_METAFILEPICT = 3,
@@ -807,7 +927,12 @@ namespace System.Windows.Forms {
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct MINMAXINFO {
#if PUBLIC_TYPES
public
#else
internal
#endif
struct MINMAXINFO {
internal POINT ptReserved;
internal POINT ptMaxSize;
internal POINT ptMaxPosition;
@@ -816,7 +941,12 @@ namespace System.Windows.Forms {
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct KeyFilterData {
#if PUBLIC_TYPES
public
#else
internal
#endif
struct KeyFilterData {
internal bool Down;
internal int keycode;
internal int keysym;
@@ -824,7 +954,12 @@ namespace System.Windows.Forms {
internal String str;
}
internal enum ScrollBarCommands {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum ScrollBarCommands {
SB_LINEUP = 0,
SB_LINELEFT = 0,
SB_LINEDOWN = 1,
@@ -842,7 +977,12 @@ namespace System.Windows.Forms {
SB_ENDSCROLL = 8
}
internal enum ClipCombineMode {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum ClipCombineMode {
RGN_AND = 1,
RGN_OR,
RGN_XOR,
@@ -853,7 +993,12 @@ namespace System.Windows.Forms {
RGN_MAX = RGN_COPY
}
internal enum SystemCommands {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum SystemCommands {
SC_SIZE = 0xF000,
SC_MOVE = 0xF010,
SC_MINIMIZE = 0xF020,
@@ -875,7 +1020,12 @@ namespace System.Windows.Forms {
SC_CONTEXTHELP = 0xF180
}
internal enum AlertType {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum AlertType {
Default = 1,
Error = 2,
Question = 3,
+4 -8
View File
@@ -4,15 +4,11 @@ include ../../build/rules.make
LIBRARY = Microsoft.Build.Engine.dll
ifeq (1.0, $(FRAMEWORK_VERSION))
LIBRARY_NAME = dummy-Microsoft.Build.Engine.dll
NO_INSTALL = yes
NO_TEST = yes
NO_SIGN_ASSEMBLY = yes
endif
BUILD_FRAMEWORK = Microsoft.Build.Framework.dll
ifeq (3.5, $(FRAMEWORK_VERSION))
NAME_SUFFIX = .v3.5
BUILD_FRAMEWORK := $(topdir)/class/lib/$(PROFILE)/$(BUILD_FRAMEWORK)
else
ifeq (4.0, $(FRAMEWORK_VERSION))
NAME_SUFFIX = .v4.0
@@ -24,11 +20,11 @@ LIB_MCS_FLAGS = \
/r:System.dll \
/r:System.Core.dll \
/r:System.Xml.dll \
/r:Microsoft.Build.Framework.dll \
/r:$(BUILD_FRAMEWORK) \
/r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll
TEST_MCS_FLAGS = \
/r:Microsoft.Build.Framework.dll \
/r:$(BUILD_FRAMEWORK) \
/r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll
EXTRA_DISTFILES = \
@@ -84,36 +84,38 @@ namespace Microsoft.Build.BuildEngine {
[MonoTODO]
public bool Execute ()
{
bool result;
bool result = false;
TaskEngine taskEngine;
LogTaskStarted ();
ITask task = null;
try {
task = InitializeTask ();
} catch (Exception e) {
LogError ("Error initializing task {0}: {1}", taskElement.LocalName, e.Message);
LogMessage (MessageImportance.Low, "Error initializing task {0}: {1}",
taskElement.LocalName, e.ToString ());
return false;
try {
task = InitializeTask ();
} catch (Exception e) {
LogError ("Error initializing task {0}: {1}", taskElement.LocalName, e.Message);
LogMessage (MessageImportance.Low, "Error initializing task {0}: {1}",
taskElement.LocalName, e.ToString ());
return false;
}
try {
taskEngine = new TaskEngine (parentTarget.Project);
taskEngine.Prepare (task, this.taskElement, GetParameters (), this.Type);
result = taskEngine.Execute ();
if (result)
taskEngine.PublishOutput ();
} catch (Exception e) {
task_logger.LogError ("Error executing task {0}: {1}", taskElement.LocalName, e.Message);
task_logger.LogMessage (MessageImportance.Low,
"Error executing task {0}: {1}", taskElement.LocalName, e.ToString ());
result = false;
}
} finally {
LogTaskFinished (result);
}
try {
taskEngine = new TaskEngine (parentTarget.Project);
taskEngine.Prepare (task, this.taskElement, GetParameters (), this.Type);
result = taskEngine.Execute ();
if (result)
taskEngine.PublishOutput ();
} catch (Exception e) {
task_logger.LogError ("Error executing task {0}: {1}", taskElement.LocalName, e.Message);
task_logger.LogMessage (MessageImportance.Low,
"Error executing task {0}: {1}", taskElement.LocalName, e.ToString ());
result = false;
}
LogTaskFinished (result);
return result;
}
@@ -55,10 +55,11 @@ namespace Microsoft.Build.BuildEngine {
ConsoleColor errorColor, warningColor, eventColor, messageColor, highMessageColor;
ColorSetter colorSet;
ColorResetter colorReset;
IEventSource eventSource;
bool no_message_color, use_colors;
bool noItemAndPropertyList;
List<BuildStatusEventArgs> events;
List<BuildEvent> events;
Dictionary<string, List<string>> errorsTable;
Dictionary<string, List<string>> warningsTable;
SortedDictionary<string, PerfInfo> targetPerfTable, tasksPerfTable;
@@ -95,7 +96,7 @@ namespace Microsoft.Build.BuildEngine {
this.colorSet = colorSet;
this.colorReset = colorReset;
events = new List<BuildStatusEventArgs> ();
events = new List<BuildEvent> ();
errorsTable = new Dictionary<string, List<string>> ();
warningsTable = new Dictionary<string, List<string>> ();
targetPerfTable = new SortedDictionary<string, PerfInfo> ();
@@ -202,19 +203,25 @@ namespace Microsoft.Build.BuildEngine {
public virtual void Initialize (IEventSource eventSource)
{
eventSource.BuildStarted += new BuildStartedEventHandler (BuildStartedHandler);
eventSource.BuildFinished += new BuildFinishedEventHandler (BuildFinishedHandler);
eventSource.ProjectStarted += new ProjectStartedEventHandler (ProjectStartedHandler);
eventSource.ProjectFinished += new ProjectFinishedEventHandler (ProjectFinishedHandler);
eventSource.TargetStarted += new TargetStartedEventHandler (TargetStartedHandler);
eventSource.TargetFinished += new TargetFinishedEventHandler (TargetFinishedHandler);
eventSource.TaskStarted += new TaskStartedEventHandler (TaskStartedHandler);
eventSource.TaskFinished += new TaskFinishedEventHandler (TaskFinishedHandler);
eventSource.MessageRaised += new BuildMessageEventHandler (MessageHandler);
eventSource.WarningRaised += new BuildWarningEventHandler (WarningHandler);
eventSource.ErrorRaised += new BuildErrorEventHandler (ErrorHandler);
this.eventSource = eventSource;
eventSource.BuildStarted += BuildStartedHandler;
eventSource.BuildFinished += BuildFinishedHandler;
eventSource.ProjectStarted += PushEvent;
eventSource.ProjectFinished += PopEvent;
eventSource.TargetStarted += PushEvent;
eventSource.TargetFinished += PopEvent;
eventSource.TaskStarted += PushEvent;
eventSource.TaskFinished += PopEvent;
eventSource.MessageRaised += MessageHandler;
eventSource.WarningRaised += WarningHandler;
eventSource.ErrorRaised += ErrorHandler;
}
public void BuildStartedHandler (object sender, BuildStartedEventArgs args)
{
if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Normal)) {
@@ -228,9 +235,28 @@ namespace Microsoft.Build.BuildEngine {
}
public void BuildFinishedHandler (object sender, BuildFinishedEventArgs args)
{
BuildFinishedHandlerActual (args);
// Reset
events.Clear ();
errorsTable.Clear ();
warningsTable.Clear ();
targetPerfTable.Clear ();
tasksPerfTable.Clear ();
errors.Clear ();
warnings.Clear ();
indent = 0;
errorCount = 0;
warningCount = 0;
projectFailed = false;
}
void BuildFinishedHandlerActual (BuildFinishedEventArgs args)
{
if (!IsVerbosityGreaterOrEqual (LoggerVerbosity.Normal)) {
PopEvent ();
PopEvent (args);
return;
}
@@ -285,8 +311,9 @@ namespace Microsoft.Build.BuildEngine {
WriteLine (String.Format ("\t {0} Error(s)", errorCount));
WriteLine (String.Empty);
WriteLine (String.Format ("Time Elapsed {0}", timeElapsed));
}
PopEvent ();
}
PopEvent (args);
}
public void ProjectStartedHandler (object sender, ProjectStartedEventArgs args)
@@ -296,11 +323,9 @@ namespace Microsoft.Build.BuildEngine {
WriteLine (String.Format ("Project \"{0}\" ({1} target(s)):", args.ProjectFile,
String.IsNullOrEmpty (args.TargetNames) ? "default" : args.TargetNames));
ResetColor ();
WriteLine (String.Empty);
DumpProperties (args.Properties);
DumpItems (args.Items);
}
PushEvent (args);
}
public void ProjectFinishedHandler (object sender, ProjectFinishedEventArgs args)
@@ -317,8 +342,6 @@ namespace Microsoft.Build.BuildEngine {
if (!projectFailed)
// no project has failed yet, so update the flag
projectFailed = !args.Succeeded;
PopEvent ();
}
public void TargetStartedHandler (object sender, TargetStartedEventArgs args)
@@ -326,10 +349,10 @@ namespace Microsoft.Build.BuildEngine {
if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Normal)) {
indent++;
SetColor (eventColor);
WriteLine (String.Empty);
WriteLine (String.Format ("Target {0}:",args.TargetName));
ResetColor ();
}
PushEvent (args);
}
public void TargetFinishedHandler (object sender, TargetFinishedEventArgs args)
@@ -344,19 +367,16 @@ namespace Microsoft.Build.BuildEngine {
WriteLine (String.Empty);
}
indent--;
PopEvent ();
}
public void TaskStartedHandler (object sender, TaskStartedEventArgs args)
{
if (this.verbosity == LoggerVerbosity.Detailed) {
if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Detailed)) {
SetColor (eventColor);
WriteLine (String.Format ("Task \"{0}\"",args.TaskName));
ResetColor ();
}
indent++;
PushEvent (args);
}
public void TaskFinishedHandler (object sender, TaskFinishedEventArgs args)
@@ -371,15 +391,16 @@ namespace Microsoft.Build.BuildEngine {
WriteLine (String.Format ("Task \"{0}\" execution -- FAILED", args.TaskName));
ResetColor ();
}
PopEvent ();
}
public void MessageHandler (object sender, BuildMessageEventArgs args)
{
if (IsMessageOk (args)) {
if (no_message_color) {
ExecutePendingEventHandlers ();
WriteLine (args.Message);
} else {
ExecutePendingEventHandlers ();
SetColor (args.Importance == MessageImportance.High ? highMessageColor : messageColor);
WriteLine (args.Message);
ResetColor ();
@@ -391,6 +412,7 @@ namespace Microsoft.Build.BuildEngine {
{
string msg = FormatWarningEvent (args);
if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Quiet)) {
ExecutePendingEventHandlers ();
SetColor (warningColor);
WriteLineWithoutIndent (msg);
ResetColor ();
@@ -409,6 +431,7 @@ namespace Microsoft.Build.BuildEngine {
{
string msg = FormatErrorEvent (args);
if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Quiet)) {
ExecutePendingEventHandlers ();
SetColor (errorColor);
WriteLineWithoutIndent (msg);
ResetColor ();
@@ -441,16 +464,36 @@ namespace Microsoft.Build.BuildEngine {
}
}
void PushEvent (BuildStatusEventArgs args)
void PushEvent<T> (object sender, T args) where T: BuildStatusEventArgs
{
events.Add (args);
PushEvent (args);
}
void PushEvent<T> (T args) where T: BuildStatusEventArgs
{
BuildEvent be = new BuildEvent {
EventArgs = args,
StartHandlerHasExecuted = false,
ConsoleLogger = this
};
events.Add (be);
current_events_string = null;
}
void PopEvent ()
void PopEvent<T> (object sender, T finished_args) where T: BuildStatusEventArgs
{
PopEvent (finished_args);
}
void PopEvent<T> (T finished_args) where T: BuildStatusEventArgs
{
if (events.Count == 0)
throw new InvalidOperationException ("INTERNAL ERROR: Trying to pop from an empty events stack");
BuildEvent be = events [events.Count - 1];
if (performanceSummary || verbosity == LoggerVerbosity.Diagnostic) {
var args = events [events.Count - 1];
var args = be.EventArgs;
TargetStartedEventArgs tgt_args = args as TargetStartedEventArgs;
if (tgt_args != null) {
AddPerfInfo (tgt_args.TargetName, args.Timestamp, targetPerfTable);
@@ -461,17 +504,24 @@ namespace Microsoft.Build.BuildEngine {
}
}
be.ExecuteFinishedHandler (finished_args);
events.RemoveAt (events.Count - 1);
current_events_string = null;
}
void ExecutePendingEventHandlers ()
{
foreach (var be in events)
be.ExecuteStartedHandler ();
}
string EventsToString ()
{
StringBuilder sb = new StringBuilder ();
string last_imported_target_file = String.Empty;
for (int i = 0; i < events.Count; i ++) {
var args = events [i];
var args = events [i].EventArgs;
ProjectStartedEventArgs pargs = args as ProjectStartedEventArgs;
if (pargs != null) {
sb.AppendFormat ("{0} ({1}) ->\n", pargs.ProjectFile,
@@ -574,6 +624,24 @@ namespace Microsoft.Build.BuildEngine {
public virtual void Shutdown ()
{
if (eventSource == null)
return;
eventSource.BuildStarted -= BuildStartedHandler;
eventSource.BuildFinished -= BuildFinishedHandler;
eventSource.ProjectStarted -= PushEvent;
eventSource.ProjectFinished -= PopEvent;
eventSource.TargetStarted -= PushEvent;
eventSource.TargetFinished -= PopEvent;
eventSource.TaskStarted -= PushEvent;
eventSource.TaskFinished -= PopEvent;
eventSource.MessageRaised -= MessageHandler;
eventSource.WarningRaised -= WarningHandler;
eventSource.ErrorRaised -= ErrorHandler;
}
static bool InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
@@ -656,7 +724,7 @@ namespace Microsoft.Build.BuildEngine {
return;
SetColor (eventColor);
WriteLine ("\n");
WriteLine (String.Empty);
WriteLine ("Initial Properties:");
ResetColor ();
@@ -669,7 +737,6 @@ namespace Microsoft.Build.BuildEngine {
foreach (KeyValuePair<string, string> pair in dict)
WriteLine (String.Format ("{0} = {1}", pair.Key, pair.Value));
WriteLine ("\n");
}
void DumpItems (IEnumerable items)
@@ -678,7 +745,7 @@ namespace Microsoft.Build.BuildEngine {
return;
SetColor (eventColor);
WriteLine ("\n");
WriteLine (String.Empty);
WriteLine ("Initial Items:");
ResetColor ();
if (items == null)
@@ -700,7 +767,6 @@ namespace Microsoft.Build.BuildEngine {
WriteLine (item.ItemSpec);
indent--;
}
WriteLine ("\n");
}
public string Parameters {
@@ -745,6 +811,44 @@ namespace Microsoft.Build.BuildEngine {
}
}
class BuildEvent {
public BuildStatusEventArgs EventArgs;
public bool StartHandlerHasExecuted;
public ConsoleLogger ConsoleLogger;
public void ExecuteStartedHandler ()
{
if (StartHandlerHasExecuted)
return;
if (EventArgs is ProjectStartedEventArgs)
ConsoleLogger.ProjectStartedHandler (null, (ProjectStartedEventArgs)EventArgs);
else if (EventArgs is TargetStartedEventArgs)
ConsoleLogger.TargetStartedHandler (null, (TargetStartedEventArgs)EventArgs);
else if (EventArgs is TaskStartedEventArgs)
ConsoleLogger.TaskStartedHandler (null, (TaskStartedEventArgs)EventArgs);
else if (!(EventArgs is BuildStartedEventArgs))
throw new InvalidOperationException ("Unexpected event on the stack, type: " + EventArgs.GetType ());
StartHandlerHasExecuted = true;
}
public void ExecuteFinishedHandler (BuildStatusEventArgs finished_args)
{
if (!StartHandlerHasExecuted)
return;
if (EventArgs is ProjectStartedEventArgs)
ConsoleLogger.ProjectFinishedHandler (null, finished_args as ProjectFinishedEventArgs);
else if (EventArgs is TargetStartedEventArgs)
ConsoleLogger.TargetFinishedHandler (null, finished_args as TargetFinishedEventArgs);
else if (EventArgs is TaskStartedEventArgs)
ConsoleLogger.TaskFinishedHandler (null, finished_args as TaskFinishedEventArgs);
else if (!(EventArgs is BuildStartedEventArgs))
throw new InvalidOperationException ("Unexpected event on the stack, type: " + EventArgs.GetType ());
}
}
class PerfInfo {
public TimeSpan Time;
public int NumberOfCalls;
@@ -126,6 +126,7 @@ namespace Microsoft.Build.BuildEngine {
{
if (project == null)
throw new ArgumentException ("project");
builtTargetsOutputByName.Clear ();
return project.Build ();
}
@@ -164,6 +165,9 @@ namespace Microsoft.Build.BuildEngine {
if (targetNames == null)
return false;
if ((buildFlags & BuildSettings.DoNotResetPreviouslyBuiltTargets) != BuildSettings.DoNotResetPreviouslyBuiltTargets)
builtTargetsOutputByName.Clear ();
if (defaultToolsVersion != null)
// it has been explicitly set, xbuild does this..
project.ToolsVersion = defaultToolsVersion;
@@ -224,6 +228,9 @@ namespace Microsoft.Build.BuildEngine {
IDictionary targetOutputs,
BuildSettings buildFlags, string toolsVersion)
{
if ((buildFlags & BuildSettings.DoNotResetPreviouslyBuiltTargets) != BuildSettings.DoNotResetPreviouslyBuiltTargets)
builtTargetsOutputByName.Clear ();
Project project;
bool newProject = false;
@@ -241,8 +241,10 @@ namespace Microsoft.Build.BuildEngine {
void LogTargetSkipped (Target target, string reason)
{
BuildMessageEventArgs bmea;
bmea = new BuildMessageEventArgs (reason ?? String.Format ("Skipping target \"{0}\" because its outputs are up-to-date.", target.Name),
null, "MSBuild", MessageImportance.Normal);
bmea = new BuildMessageEventArgs (String.IsNullOrEmpty (reason)
? String.Format ("Skipping target \"{0}\" because its outputs are up-to-date.", target.Name)
: reason,
null, "MSBuild", MessageImportance.Normal);
target.Engine.EventSource.FireMessageRaised (this, bmea);
}
+8 -14
View File
@@ -3,17 +3,13 @@ SUBDIRS =
include ../../build/rules.make
LIBRARY = Microsoft.Build.Tasks.dll
ifeq (1.0, $(FRAMEWORK_VERSION))
LIBRARY_NAME = dummy-Microsoft.Build.Tasks.dll
NO_INSTALL = yes
NO_TEST = yes
NO_SIGN_ASSEMBLY = yes
else
BUILD_FRAMEWORK = Microsoft.Build.Framework.dll
BUILD_ENGINE = Microsoft.Build.Engine.dll
ifeq (3.5, $(FRAMEWORK_VERSION))
NAME_SUFFIX = .v3.5
BUILD_FRAMEWORK := $(topdir)/class/lib/$(PROFILE)/$(BUILD_FRAMEWORK)
BUILD_ENGINE := $(topdir)/class/lib/$(PROFILE)/$(BUILD_ENGINE)
else
ifeq (4.0, $(FRAMEWORK_VERSION))
NAME_SUFFIX = .v4.0
@@ -22,8 +18,6 @@ endif
LIBRARY_NAME = Microsoft.Build.Tasks$(NAME_SUFFIX).dll
endif
LIB_MCS_FLAGS = \
/r:$(corlib) \
/r:System.dll \
@@ -31,12 +25,12 @@ LIB_MCS_FLAGS = \
/r:System.Xml.dll \
/r:System.Windows.Forms.dll \
/r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll \
/r:Microsoft.Build.Framework.dll \
/r:Microsoft.Build.Engine.dll
/r:$(BUILD_FRAMEWORK) \
/r:$(BUILD_ENGINE)
TEST_MCS_FLAGS = \
/r:Microsoft.Build.Engine.dll \
/r:Microsoft.Build.Framework.dll \
/r:$(BUILD_ENGINE) \
/r:$(BUILD_FRAMEWORK) \
/r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll
EXTRA_DISTFILES = \
@@ -5,8 +5,11 @@
// Marek Sieradzki ([email protected])
// Paolo Molaro ([email protected])
// Gonzalo Paniagua Javier ([email protected])
// Lluis Sanchez Gual <[email protected]>
// Ankit Jain <[email protected]>
//
// (C) 2005 Marek Sieradzki
// Copyright 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -36,6 +39,7 @@ using System.Collections;
using System.Collections.Generic;
using System.Resources;
using System.Reflection;
using System.Xml;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.XBuild.Tasks.GenerateResourceInternal;
@@ -73,7 +77,8 @@ namespace Microsoft.Build.Tasks {
string sourceFile = source.ItemSpec;
string outputFile = Path.ChangeExtension (sourceFile, "resources");
result &= CompileResourceFile (sourceFile, outputFile);
if (IsResgenRequired (sourceFile, outputFile))
result &= CompileResourceFile (sourceFile, outputFile);
ITaskItem newItem = new TaskItem (source);
source.ItemSpec = outputFile;
@@ -93,7 +98,8 @@ namespace Microsoft.Build.Tasks {
continue;
}
result &= CompileResourceFile (sources [i].ItemSpec, outputResources [i].ItemSpec);
if (IsResgenRequired (sources [i].ItemSpec, outputResources [i].ItemSpec))
result &= CompileResourceFile (sources [i].ItemSpec, outputResources [i].ItemSpec);
temporaryFilesWritten.Add (outputResources [i]);
}
}
@@ -103,6 +109,78 @@ namespace Microsoft.Build.Tasks {
return result;
}
// true if the resx file or any file referenced
// by the resx is newer than the .resources file
//
// Code taken from monodevelop
// main/src/core/MonoDevelop.Core/MonoDevelop.Projects.Formats.MD1/MD1DotNetProjectHandler.cs
bool IsResgenRequired (string resx_filename, string resources_filename)
{
if (IsFileNewerThan (resx_filename, resources_filename)) {
Log.LogMessage (MessageImportance.Low,
"Resource file '{0}' is newer than the source file '{1}', skipping.",
resources_filename, resx_filename);
return true;
}
if (String.Compare (Path.GetExtension (resx_filename), ".resx", true) != 0)
return true;
// resx file, check for files referenced from there
XmlTextReader xr = null;
try {
// look for
// <data type="System.Resources.ResXFileRef, System.Windows.Forms" ..>
// <value>... filename;.. </value>
// </data>
xr = new XmlTextReader (resx_filename);
string basepath = Path.GetDirectoryName (resx_filename);
while (xr.Read ()) {
if (xr.NodeType != XmlNodeType.Element ||
String.Compare (xr.LocalName, "data") != 0)
continue;
string type = xr.GetAttribute ("type");
if (String.IsNullOrEmpty (type))
continue;
if (String.Compare (type, "System.Resources.ResXFileRef, System.Windows.Forms") != 0)
continue;
xr.ReadToDescendant ("value");
if (xr.NodeType != XmlNodeType.Element)
continue;
string value = xr.ReadElementContentAsString ();
string [] parts = value.Split (';');
if (parts.Length > 0) {
string referenced_filename = Utilities.FromMSBuildPath (
Path.Combine (basepath, parts [0]).Trim ());
if (File.Exists (referenced_filename) &&
IsFileNewerThan (referenced_filename, resources_filename))
return true;
}
}
} catch (XmlException) {
// Ignore xml errors, let resgen handle it
return true;
} finally {
if (xr != null)
xr.Close ();
}
return false;
}
// true if first is newer than second
static bool IsFileNewerThan (string first, string second)
{
FileInfo finfo_first = new FileInfo (first);
FileInfo finfo_second = new FileInfo (second);
return finfo_first.LastWriteTime > finfo_second.LastWriteTime;
}
#if false
private IResourceReader GetReader (Stream stream, string name)
{
@@ -154,13 +232,6 @@ namespace Microsoft.Build.Tasks {
return false;
}
if (File.GetLastWriteTime (sname) <= File.GetLastWriteTime (dname)) {
Log.LogMessage (MessageImportance.Low,
"Resource file '{0}' is newer than the source file '{1}', skipping.",
dname, sname);
return true;
}
Resgen resgen = new Resgen ();
resgen.BuildEngine = this.BuildEngine;
resgen.UseSourcePath = true;
@@ -298,7 +369,7 @@ namespace Microsoft.Build.Tasks {
public override bool Execute ()
{
if (String.IsNullOrEmpty (Environment.GetEnvironmentVariable ("MONO_IOMAP")))
EnvironmentOverride ["MONO_IOMAP"] = "drive";
EnvironmentVariables = new string [] { "MONO_IOMAP=drive" };
return base.Execute ();
}
@@ -28,6 +28,7 @@
#if NET_2_0
using System;
using System.IO;
namespace Microsoft.Build.Tasks {
internal static class Utilities {
@@ -42,6 +43,68 @@ namespace Microsoft.Build.Tasks {
}
}
internal static string FromMSBuildPath (string relPath)
{
if (relPath == null || relPath.Length == 0)
return null;
bool is_windows = Path.DirectorySeparatorChar == '\\';
string path = relPath;
if (!is_windows)
path = path.Replace ("\\", "/");
// a path with drive letter is invalid/unusable on non-windows
if (!is_windows && char.IsLetter (path [0]) && path.Length > 1 && path[1] == ':')
return null;
if (System.IO.File.Exists (path)){
return Path.GetFullPath (path);
}
if (Path.IsPathRooted (path)) {
// Windows paths are case-insensitive. When mapping an absolute path
// we can try to find the correct case for the path.
string[] names = path.Substring (1).Split ('/');
string part = "/";
for (int n=0; n<names.Length; n++) {
string[] entries;
if (names [n] == ".."){
if (part == "/")
return ""; // Can go further back. It's not an existing file
part = Path.GetFullPath (part + "/..");
continue;
}
entries = Directory.GetFileSystemEntries (part);
string fpath = null;
foreach (string e in entries) {
if (string.Compare (Path.GetFileName (e), names[n], true) == 0) {
fpath = e;
break;
}
}
if (fpath == null) {
// Part of the path does not exist. Can't do any more checking.
part = Path.GetFullPath (part);
for (; n < names.Length; n++)
part += "/" + names[n];
return part;
}
part = fpath;
}
return Path.GetFullPath (part);
} else {
return Path.GetFullPath (path);
}
}
}
}
+4 -8
View File
@@ -3,15 +3,11 @@ SUBDIRS =
include ../../build/rules.make
LIBRARY = Microsoft.Build.Utilities.dll
ifeq (1.0, $(FRAMEWORK_VERSION))
LIBRARY_NAME = dummy-Microsoft.Build.Utilities.dll
NO_INSTALL = yes
NO_TEST = yes
NO_SIGN_ASSEMBLY = yes
endif
BUILD_FRAMEWORK = Microsoft.Build.Framework.dll
ifeq (3.5, $(FRAMEWORK_VERSION))
LIBRARY_NAME = Microsoft.Build.Utilities.v3.5.dll
BUILD_FRAMEWORK := $(topdir)/class/lib/$(PROFILE)/$(BUILD_FRAMEWORK)
else
ifeq (4.0, $(FRAMEWORK_VERSION))
LIBRARY_NAME = Microsoft.Build.Utilities.v4.0.dll
@@ -21,9 +17,9 @@ endif
LIB_MCS_FLAGS = \
/r:$(corlib) \
/r:System.dll \
/r:Microsoft.Build.Framework.dll
/r:$(BUILD_FRAMEWORK)
TEST_MCS_FLAGS = /r:Microsoft.Build.Framework.dll
TEST_MCS_FLAGS = /r:$(BUILD_FRAMEWORK)
export TESTING_MONO=a
XBUILD_DIR=../../tools/xbuild
@@ -46,7 +46,6 @@ namespace Microsoft.Build.Utilities
{
public abstract class ToolTask : Task
{
SCS.ProcessStringDictionary environmentOverride;
int exitCode;
int timeout;
string toolPath, toolExe;
@@ -76,7 +75,6 @@ namespace Microsoft.Build.Utilities
this.toolPath = MonoLocationHelper.GetBinDir ();
this.responseFileEncoding = Encoding.UTF8;
this.timeout = Int32.MaxValue;
this.environmentOverride = new SCS.ProcessStringDictionary ();
}
[MonoTODO]
@@ -111,11 +109,8 @@ namespace Microsoft.Build.Utilities
if (pathToTool == null)
throw new ArgumentNullException ("pathToTool");
string output, error, responseFileName;
StreamWriter outwr, errwr;
outwr = errwr = null;
responseFileName = output = error = null;
string responseFileName;
responseFileName = null;
toolOutput = new StringBuilder ();
try {
@@ -129,11 +124,6 @@ namespace Microsoft.Build.Utilities
LogToolCommand (String.Format ("Tool {0} execution started with arguments: {1} {2}",
pathToTool, commandLineCommands, responseFileCommands));
output = Path.GetTempFileName ();
error = Path.GetTempFileName ();
outwr = new StreamWriter (output);
errwr = new StreamWriter (error);
ProcessStartInfo pinfo = new ProcessStartInfo (pathToTool, arguments);
pinfo.WorkingDirectory = GetWorkingDirectory () ?? Environment.CurrentDirectory;
@@ -141,15 +131,27 @@ namespace Microsoft.Build.Utilities
pinfo.RedirectStandardOutput = true;
pinfo.RedirectStandardError = true;
var pendingLineFragmentOutput = new StringBuilder ();
var pendingLineFragmentError = new StringBuilder ();
var environmentOverride = GetAndLogEnvironmentVariables ();
try {
ProcessWrapper pw = ProcessService.StartProcess (pinfo, outwr, errwr, null, environmentOverride);
pw.OutputStreamChanged += delegate (object o, string msg) { ProcessLine (msg, StandardOutputLoggingImportance); };
pw.ErrorStreamChanged += delegate (object o, string msg) { ProcessLine (msg, StandardErrorLoggingImportance); };
// When StartProcess returns, the process has already .Start()'ed
// If we subscribe to the events after that, then for processes that
// finish executing before we can subscribe, we won't get the output/err
// events at all!
ProcessWrapper pw = ProcessService.StartProcess (pinfo,
(_, msg) => ProcessLine (pendingLineFragmentOutput, msg, StandardOutputLoggingImportance),
(_, msg) => ProcessLine (pendingLineFragmentError, msg, StandardErrorLoggingImportance),
null,
environmentOverride);
pw.WaitForOutput (timeout == Int32.MaxValue ? Int32.MaxValue : timeout);
// Process any remaining line
ProcessLine (pendingLineFragmentOutput, StandardOutputLoggingImportance, true);
ProcessLine (pendingLineFragmentError, StandardErrorLoggingImportance, true);
pw.WaitForOutput (timeout == Int32.MaxValue ? -1 : timeout);
exitCode = pw.ExitCode;
outwr.Close();
errwr.Close();
pw.Dispose ();
} catch (System.ComponentModel.Win32Exception e) {
Log.LogError ("Error executing tool '{0}': {1}", pathToTool, e.Message);
@@ -159,17 +161,13 @@ namespace Microsoft.Build.Utilities
if (typeLoadException)
ProcessTypeLoadException ();
pendingLineFragmentOutput.Length = 0;
pendingLineFragmentError.Length = 0;
Log.LogMessage (MessageImportance.Low, "Tool {0} execution finished.", pathToTool);
return exitCode;
} finally {
DeleteTempFile (responseFileName);
if (outwr != null)
outwr.Dispose ();
if (errwr != null)
errwr.Dispose ();
DeleteTempFile (output);
DeleteTempFile (error);
}
}
@@ -192,9 +190,39 @@ namespace Microsoft.Build.Utilities
Log.LogError (output_str);
}
void ProcessLine (string line, MessageImportance importance)
void ProcessLine (StringBuilder outputBuilder, MessageImportance importance, bool isLastLine)
{
foreach (string singleLine in line.Split (new string [] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)) {
if (outputBuilder.Length == 0)
return;
if (isLastLine && !outputBuilder.ToString ().EndsWith (Environment.NewLine))
// last line, but w/o an trailing newline, so add that
outputBuilder.Append (Environment.NewLine);
ProcessLine (outputBuilder, null, importance);
}
void ProcessLine (StringBuilder outputBuilder, string line, MessageImportance importance)
{
// Add to any line fragment from previous call
if (line != null)
outputBuilder.Append (line);
// Don't remove empty lines!
var lines = outputBuilder.ToString ().Split (new string [] {Environment.NewLine}, StringSplitOptions.None);
// Clear the builder. If any incomplete line is found,
// then it will get added back
outputBuilder.Length = 0;
for (int i = 0; i < lines.Length; i ++) {
string singleLine = lines [i];
if (i == lines.Length - 1 && !singleLine.EndsWith (Environment.NewLine)) {
// Last line doesn't end in newline, could be part of
// a bigger line. Save for later processing
outputBuilder.Append (singleLine);
continue;
}
toolOutput.AppendLine (singleLine);
// in case of typeLoadException, collect all the output
@@ -206,9 +234,10 @@ namespace Microsoft.Build.Utilities
protected virtual void LogEventsFromTextOutput (string singleLine, MessageImportance importance)
{
singleLine = singleLine.Trim ();
if (singleLine.Length == 0)
if (singleLine.Length == 0) {
Log.LogMessage (singleLine, importance);
return;
}
if (singleLine.StartsWith ("Unhandled Exception: System.TypeLoadException") ||
singleLine.StartsWith ("Unhandled Exception: System.IO.FileNotFoundException")) {
@@ -319,11 +348,50 @@ namespace Microsoft.Build.Utilities
}
}
// If EnvironmentVariables is defined, then merge EnvironmentOverride
// EnvironmentOverride is Obsolete'd in 4.0
//
// Returns the final set of environment variables and logs them
SCS.StringDictionary GetAndLogEnvironmentVariables ()
{
var env_vars = GetEnvironmentVariables ();
if (env_vars == null)
return env_vars;
Log.LogMessage (MessageImportance.Low, "Environment variables being passed to the tool:");
foreach (DictionaryEntry entry in env_vars)
Log.LogMessage (MessageImportance.Low, "\t{0}={1}", (string)entry.Key, (string)entry.Value);
return env_vars;
}
SCS.StringDictionary GetEnvironmentVariables ()
{
if (EnvironmentVariables == null || EnvironmentVariables.Length == 0)
return EnvironmentOverride;
var env_vars = new SCS.ProcessStringDictionary ();
foreach (string pair in EnvironmentVariables) {
string [] key_value = pair.Split ('=');
if (!String.IsNullOrEmpty (key_value [0]))
env_vars [key_value [0]] = key_value.Length > 1 ? key_value [1] : String.Empty;
}
if (EnvironmentOverride != null)
foreach (DictionaryEntry entry in EnvironmentOverride)
env_vars [(string)entry.Key] = (string)entry.Value;
return env_vars;
}
protected virtual StringDictionary EnvironmentOverride
{
get { return environmentOverride; }
get { return null; }
}
// Ignore EnvironmentOverride if this is set
public string[] EnvironmentVariables { get; set; }
[Output]
public int ExitCode {
get { return exitCode; }
@@ -158,20 +158,6 @@ namespace Microsoft.CSharp.RuntimeBinder
IgnorePrivateMembers = false
};
var core_types = Compiler.TypeManager.InitCoreTypes ();
importer.Initialize ();
// I don't think dynamically loaded assemblies can be used as dynamic
// expression without static type to be loaded first
// AppDomain.CurrentDomain.AssemblyLoad += (sender, e) => { throw new NotImplementedException (); };
// Import all currently loaded assemblies
var ns = Compiler.GlobalRootNamespace.Instance;
foreach (System.Reflection.Assembly a in AppDomain.CurrentDomain.GetAssemblies ()) {
ns.AddAssemblyReference (a);
importer.ImportAssembly (a, ns);
}
var reporter = new Compiler.Report (ErrorPrinter.Instance) {
WarningLevel = 0
};
@@ -180,8 +166,29 @@ namespace Microsoft.CSharp.RuntimeBinder
IsRuntimeBinder = true
};
Compiler.TypeManager.InitCoreTypes (cc, core_types);
Compiler.TypeManager.InitOptionalCoreTypes (cc);
IList<Compiler.PredefinedTypeSpec> core_types = null;
// HACK: To avoid re-initializing static TypeManager types, like string_type
if (!Compiler.RootContext.EvalMode) {
core_types = Compiler.TypeManager.InitCoreTypes ();
}
importer.Initialize ();
// I don't think dynamically loaded assemblies can be used as dynamic
// expression without static type to be loaded first
// AppDomain.CurrentDomain.AssemblyLoad += (sender, e) => { throw new NotImplementedException (); };
// Import all currently loaded assemblies
var ns = cc.GlobalRootNamespace;
foreach (System.Reflection.Assembly a in AppDomain.CurrentDomain.GetAssemblies ()) {
ns.AddAssemblyReference (a);
importer.ImportAssembly (a, ns);
}
if (!Compiler.RootContext.EvalMode) {
Compiler.TypeManager.InitCoreTypes (cc, core_types);
Compiler.TypeManager.InitOptionalCoreTypes (cc);
}
dc = new DynamicContext (cc);
}
@@ -265,7 +265,7 @@ namespace Mono.Debugger.Soft
* with newer runtimes, and vice versa.
*/
public const int MAJOR_VERSION = 2;
public const int MINOR_VERSION = 1;
public const int MINOR_VERSION = 2;
enum WPSuspendPolicy {
NONE = 0,
@@ -678,32 +678,48 @@ namespace Mono.Debugger.Soft
int offset;
public PacketWriter () {
// FIXME:
data = new byte [1024];
offset = 0;
}
void MakeRoom (int size) {
if (offset + size >= data.Length) {
int new_len = data.Length * 2;
while (new_len < offset + size) {
new_len *= 2;
}
byte[] new_data = new byte [new_len];
Array.Copy (data, new_data, data.Length);
data = new_data;
}
}
public PacketWriter WriteByte (byte val) {
MakeRoom (1);
encode_byte (data, val, ref offset);
return this;
}
public PacketWriter WriteInt (int val) {
MakeRoom (4);
encode_int (data, val, ref offset);
return this;
}
public PacketWriter WriteId (long id) {
MakeRoom (8);
encode_id (data, id, ref offset);
return this;
}
public PacketWriter WriteLong (long val) {
MakeRoom (8);
encode_long (data, val, ref offset);
return this;
}
public PacketWriter WriteFloat (float f) {
MakeRoom (8);
byte[] b = DataConverter.GetBytesBE (f);
for (int i = 0; i < 4; ++i)
data [offset + i] = b [i];
@@ -712,6 +728,7 @@ namespace Mono.Debugger.Soft
}
public PacketWriter WriteDouble (double d) {
MakeRoom (8);
byte[] b = DataConverter.GetBytesBE (d);
for (int i = 0; i < 8; ++i)
data [offset + i] = b [i];
@@ -734,6 +751,7 @@ namespace Mono.Debugger.Soft
public PacketWriter WriteString (string s) {
encode_int (data, s.Length, ref offset);
byte[] b = Encoding.UTF8.GetBytes (s);
MakeRoom (b.Length);
Buffer.BlockCopy (b, 0, data, offset, b.Length);
offset += b.Length;
return this;
+21 -2
View File
@@ -409,7 +409,7 @@ public class Tests : TestsBase
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static void locals () {
locals1 (null);
locals2 (null, 5);
locals2<string> (null, 5, "ABC");
locals3 ();
}
@@ -423,13 +423,15 @@ public class Tests : TestsBase
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static void locals2 (string[] args, int arg) {
public static void locals2<T> (string[] args, int arg, T t) {
long i = 42;
string s = "AB";
for (int j = 0; j < 10; ++j) {
if (s != null)
i ++;
if (t != null)
i ++;
}
}
@@ -618,6 +620,23 @@ public class Tests : TestsBase
o.GetType ();
} catch (Exception) {
}
try {
exceptions2 ();
} catch (Exception) {
}
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static bool return_true () {
return true;
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static void exceptions2 () {
if (return_true ())
throw new Exception ();
Console.WriteLine ();
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
+48 -5
View File
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Threading;
using System.Net;
using System.Reflection;
using System.Text;
using Mono.Cecil.Cil;
using Mono.Debugger.Soft;
using Diag = System.Diagnostics;
@@ -93,7 +94,7 @@ public class DebuggerTests
}
Assert.IsInstanceOfType (typeof (BreakpointEvent), e);
Assert.AreEqual (m, (e as BreakpointEvent).Method);
Assert.AreEqual (m.Name, (e as BreakpointEvent).Method.Name);
return (e as BreakpointEvent);
}
@@ -885,7 +886,6 @@ public class DebuggerTests
}
[Test]
[Category ("only")]
public void Type_SetValue () {
var e = run_until ("o1");
var frame = e.Thread.GetFrames () [0];
@@ -1319,8 +1319,8 @@ public class DebuggerTests
StackFrame frame = e.Thread.GetFrames () [0];
var locals = frame.Method.GetLocals ();
Assert.AreEqual (5, locals.Length);
for (int i = 0; i < 5; ++i) {
Assert.AreEqual (6, locals.Length);
for (int i = 0; i < 6; ++i) {
if (locals [i].Name == "args") {
Assert.IsTrue (locals [i].IsArg);
Assert.AreEqual ("String[]", locals [i].Type.Name);
@@ -1336,6 +1336,10 @@ public class DebuggerTests
} else if (locals [i].Name == "s") {
Assert.IsFalse (locals [i].IsArg);
Assert.AreEqual ("String", locals [i].Type.Name);
} else if (locals [i].Name == "t") {
// gshared
Assert.IsTrue (locals [i].IsArg);
Assert.AreEqual ("String", locals [i].Type.Name);
} else {
Assert.Fail ();
}
@@ -1343,6 +1347,7 @@ public class DebuggerTests
}
[Test]
[Category ("only")]
public void Locals () {
var be = run_until ("locals1");
@@ -1385,6 +1390,8 @@ public class DebuggerTests
AssertValue (42, vals [i]);
if (locals [i].Name == "s")
AssertValue ("AB", vals [i]);
if (locals [i].Name == "t")
AssertValue ("ABC", vals [i]);
}
// Argument checking
@@ -1654,6 +1661,12 @@ public class DebuggerTests
Assert.AreEqual ("ABC", s.Value);
Assert.AreEqual (vm.RootDomain, s.Domain);
// Long strings
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < 1024; ++i)
sb.Append ('A');
s = vm.RootDomain.CreateString (sb.ToString ());
// Argument checking
AssertThrows <ArgumentNullException> (delegate () {
s = vm.RootDomain.CreateString (null);
@@ -1661,7 +1674,6 @@ public class DebuggerTests
}
[Test]
[Category ("only")]
public void CreateBoxedValue () {
ObjectMirror o = vm.RootDomain.CreateBoxedValue (new PrimitiveValue (vm, 42));
@@ -1975,6 +1987,7 @@ public class DebuggerTests
}
[Test]
[Category ("only")]
public void Frame_SetValue () {
Event e = run_until ("locals2");
@@ -2000,6 +2013,11 @@ public class DebuggerTests
frame.SetValue (p, vm.CreateValue (7));
AssertValue (7, frame.GetValue (p));
// gshared
p = frame.Method.GetParameters ()[2];
frame.SetValue (p, vm.RootDomain.CreateString ("DEF"));
AssertValue ("DEF", frame.GetValue (p));
// argument checking
// variable null
@@ -2117,6 +2135,31 @@ public class DebuggerTests
Assert.AreEqual ("NullReferenceException", (e as ExceptionEvent).Exception.Type.Name);
req.Disable ();
// Single stepping after an exception
req = vm.CreateExceptionRequest (null);
req.Enable ();
vm.Resume ();
e = vm.GetNextEvent ();
Assert.IsInstanceOfType (typeof (ExceptionEvent), e);
Assert.AreEqual ("Exception", (e as ExceptionEvent).Exception.Type.Name);
frames = e.Thread.GetFrames ();
Assert.AreEqual ("exceptions2", frames [0].Method.Name);
req.Disable ();
var sreq = vm.CreateStepRequest (e.Thread);
sreq.Depth = StepDepth.Over;
sreq.Size = StepSize.Line;
sreq.Enable ();
vm.Resume ();
e = vm.GetNextEvent ();
Assert.IsInstanceOfType (typeof (StepEvent), e);
frames = e.Thread.GetFrames ();
Assert.AreEqual ("exceptions", frames [0].Method.Name);
sreq.Disable ();
// Argument checking
AssertThrows<ArgumentException> (delegate {
vm.CreateExceptionRequest (e.Thread.Type);
@@ -1165,10 +1165,18 @@ namespace Mono.Unix.Native {
EPOLL_CTL_MOD = 3,
}
[StructLayout (LayoutKind.Sequential, Pack = 1)]
[StructLayout (LayoutKind.Explicit, Size=12, Pack=1)]
public struct EpollEvent {
[FieldOffset (0)]
public EpollEvents events;
public IntPtr fd;
[FieldOffset (4)]
public int fd;
[FieldOffset (4)]
public IntPtr ptr;
[FieldOffset (4)]
public uint u32;
[FieldOffset (4)]
public ulong u64;
}
#endregion
@@ -2669,7 +2677,7 @@ namespace Mono.Unix.Native {
return sys_epoll_create1 (flags);
}
public static int epoll_ctl (int epfd, EpollOp op, IntPtr fd, EpollEvents events)
public static int epoll_ctl (int epfd, EpollOp op, int fd, EpollEvents events)
{
EpollEvent ee = new EpollEvent ();
ee.events = events;
@@ -2693,7 +2701,7 @@ namespace Mono.Unix.Native {
private static extern int sys_epoll_create1 (EpollFlags flags);
[DllImport (LIBC, SetLastError=true, EntryPoint="epoll_ctl")]
private static extern int sys_epoll_ctl (int epfd, EpollOp op, IntPtr fd, ref EpollEvent ee);
private static extern int sys_epoll_ctl (int epfd, EpollOp op, int fd, ref EpollEvent ee);
[DllImport (LIBC, SetLastError=true, EntryPoint="epoll_wait")]
private static extern int sys_epoll_wait (int epfd, EpollEvent [] ee, int maxevents, int timeout);
@@ -39,9 +39,19 @@ namespace System.Configuration {
bool modified;
bool readOnly;
int originalStringHash = 0;
public bool IsModified {
get { return modified; }
get {
if (modified)
return true;
string str = ToString ();
if (str == null)
return false;
return str.GetHashCode () != originalStringHash;
}
}
public new bool IsReadOnly {
@@ -89,6 +99,7 @@ namespace System.Configuration {
CopyTo (contents, 0);
col.AddRange (contents);
col.originalStringHash = originalStringHash;
return col;
}
@@ -125,6 +136,15 @@ namespace System.Configuration {
return String.Join (",", contents);
}
internal void UpdateStringHash ()
{
string str = ToString ();
if (str == null)
originalStringHash = 0;
else
originalStringHash = str.GetHashCode ();
}
}
}
@@ -48,6 +48,7 @@ namespace System.Configuration
foreach (string datum in datums)
col.Add (datum.Trim());
col.UpdateStringHash ();
return col;
}
@@ -85,6 +85,8 @@ System.Threading/LockRecursionException.cs
System.Threading/LockRecursionPolicy.cs
System.Threading/ReaderWriterLockSlim.cs
../corlib/System.Threading/AtomicBoolean.cs
System.Threading/ThreadLockState.cs
System.Threading/ReaderWriterLockSlimExtensions.cs
Microsoft.Win32.SafeHandles/SafePipeHandle.cs
System.IO.Pipes/AnonymousPipeClientStream.cs
System.IO.Pipes/AnonymousPipeServerStream.cs
@@ -35,43 +35,6 @@ using System.Threading;
namespace System.Threading {
[Flags]
internal enum ThreadLockState
{
None = 0,
Read = 1,
Write = 2,
Upgradable = 4,
UpgradedRead = 5,
UpgradedWrite = 6
}
internal static class ReaderWriterLockSlimExtensions
{
internal static bool Has (this ThreadLockState state, ThreadLockState value)
{
return (state & value) > 0;
}
#if !NET_4_0 && !NET_4_0_BOOTSTRAP
internal static bool Wait (this ManualResetEvent self, int timeout)
{
return self.WaitOne (timeout);
}
internal static bool IsSet (this ManualResetEvent self)
{
return self.WaitOne (0);
}
#else
internal static bool IsSet (this ManualResetEventSlim self)
{
return self.IsSet;
}
#endif
}
[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
public class ReaderWriterLockSlim : IDisposable
@@ -104,8 +67,11 @@ namespace System.Threading {
int numReadWaiters, numUpgradeWaiters, numWriteWaiters;
bool disposed;
static int idPool = int.MinValue;
readonly int id = Interlocked.Increment (ref idPool);
[ThreadStatic]
static IDictionary<ReaderWriterLockSlim, ThreadLockState> currentThreadState;
static IDictionary<int, ThreadLockState> currentThreadState;
public ReaderWriterLockSlim () : this (LockRecursionPolicy.NoRecursion)
{
@@ -123,23 +89,30 @@ namespace System.Threading {
public bool TryEnterReadLock (int millisecondsTimeout)
{
if (CheckState (millisecondsTimeout, ThreadLockState.Read))
ThreadLockState ctstate = CurrentThreadState;
if (CheckState (millisecondsTimeout, LockState.Read)) {
ctstate.ReaderRecursiveCount++;
return true;
}
// This is downgrading from upgradable, no need for check since
// we already have a sort-of read lock that's going to disappear
// after user calls ExitUpgradeableReadLock.
// Same idea when recursion is allowed and a write thread wants to
// go for a Read too.
if (CurrentThreadState.Has (ThreadLockState.Upgradable)
if (CurrentLockState.Has (LockState.Upgradable)
|| recursionPolicy == LockRecursionPolicy.SupportsRecursion) {
Interlocked.Add (ref rwlock, RwRead);
CurrentThreadState = CurrentThreadState ^ ThreadLockState.Read;
ctstate.LockState ^= LockState.Read;
ctstate.ReaderRecursiveCount++;
return true;
}
Stopwatch sw = Stopwatch.StartNew ();
Interlocked.Increment (ref numReadWaiters);
int val = 0;
while (millisecondsTimeout == -1 || sw.ElapsedMilliseconds < millisecondsTimeout) {
if ((rwlock & 0x7) > 0) {
@@ -147,11 +120,20 @@ namespace System.Threading {
continue;
}
if ((Interlocked.Add (ref rwlock, RwRead) & 0x7) == 0) {
CurrentThreadState = CurrentThreadState ^ ThreadLockState.Read;
Interlocked.Decrement (ref numReadWaiters);
if (readerDoneEvent.IsSet ())
/* Optimistically try to add ourselves to the reader value
* if the adding was too late and another writer came in between
* we revert the operation.
*/
if (((val = Interlocked.Add (ref rwlock, RwRead)) & 0x7) == 0) {
/* If we are the first reader, reset the event to let other threads
* sleep correctly if they try to acquire write lock
*/
if (val >> RwReadBit == 1)
readerDoneEvent.Reset ();
ctstate.LockState ^= LockState.Read;
ctstate.ReaderRecursiveCount++;
Interlocked.Decrement (ref numReadWaiters);
return true;
}
@@ -171,10 +153,13 @@ namespace System.Threading {
public void ExitReadLock ()
{
if (!CurrentThreadState.Has (ThreadLockState.Read))
ThreadLockState ctstate = CurrentThreadState;
if (!ctstate.LockState.Has (LockState.Read))
throw new SynchronizationLockException ("The current thread has not entered the lock in read mode");
CurrentThreadState = ThreadLockState.None;
ctstate.LockState ^= LockState.Read;
ctstate.ReaderRecursiveCount--;
if (Interlocked.Add (ref rwlock, -RwRead) >> RwReadBit == 0)
readerDoneEvent.Set ();
}
@@ -186,39 +171,54 @@ namespace System.Threading {
public bool TryEnterWriteLock (int millisecondsTimeout)
{
bool isUpgradable = CurrentThreadState.Has (ThreadLockState.Upgradable);
if (CheckState (millisecondsTimeout, isUpgradable ? ThreadLockState.UpgradedWrite : ThreadLockState.Write))
ThreadLockState ctstate = CurrentThreadState;
if (CheckState (millisecondsTimeout, LockState.Write)) {
ctstate.WriterRecursiveCount++;
return true;
}
Stopwatch sw = Stopwatch.StartNew ();
Interlocked.Increment (ref numWriteWaiters);
bool isUpgradable = ctstate.LockState.Has (LockState.Upgradable);
// If the code goes there that means we had a read lock beforehand
/* If the code goes there that means we had a read lock beforehand
* that need to be suppressed, we also take the opportunity to register
* our interest in the write lock to avoid other write wannabe process
* coming in the middle
*/
if (isUpgradable && rwlock >= RwRead)
Interlocked.Add (ref rwlock, -RwRead);
if (Interlocked.Add (ref rwlock, RwWaitUpgrade - RwRead) >> RwReadBit == 0)
readerDoneEvent.Set ();
int stateCheck = isUpgradable ? RwWaitUpgrade : RwWait;
int appendValue = RwWait | (isUpgradable ? RwWaitUpgrade : 0);
while (millisecondsTimeout < 0 || sw.ElapsedMilliseconds < millisecondsTimeout) {
int state = rwlock;
if (state <= stateCheck) {
if (Interlocked.CompareExchange (ref rwlock, RwWrite, state) == state) {
CurrentThreadState = isUpgradable ? ThreadLockState.UpgradedWrite : ThreadLockState.Write;
writerDoneEvent.Reset ();
ctstate.LockState ^= LockState.Write;
ctstate.WriterRecursiveCount++;
Interlocked.Decrement (ref numWriteWaiters);
if (writerDoneEvent.IsSet ())
writerDoneEvent.Reset ();
return true;
}
state = rwlock;
}
while ((state & RwWait) == 0 && Interlocked.CompareExchange (ref rwlock, state | appendValue, state) == state)
state = rwlock;
// We register our interest in taking the Write lock (if upgradeable it's already done)
if (!isUpgradable)
while ((state & RwWait) == 0 && Interlocked.CompareExchange (ref rwlock, state | RwWait, state) == state)
state = rwlock;
while (rwlock > stateCheck && (millisecondsTimeout < 0 || sw.ElapsedMilliseconds < millisecondsTimeout))
readerDoneEvent.Wait (ComputeTimeout (millisecondsTimeout, sw));
// Before falling to sleep
while (rwlock > stateCheck && (millisecondsTimeout < 0 || sw.ElapsedMilliseconds < millisecondsTimeout)) {
if ((rwlock & RwWrite) != 0)
writerDoneEvent.Wait (ComputeTimeout (millisecondsTimeout, sw));
else if ((rwlock >> RwReadBit) > 0)
readerDoneEvent.Wait (ComputeTimeout (millisecondsTimeout, sw));
}
}
Interlocked.Decrement (ref numWriteWaiters);
@@ -232,12 +232,19 @@ namespace System.Threading {
public void ExitWriteLock ()
{
if (!CurrentThreadState.Has (ThreadLockState.Write))
ThreadLockState ctstate = CurrentThreadState;
if (!ctstate.LockState.Has (LockState.Write))
throw new SynchronizationLockException ("The current thread has not entered the lock in write mode");
CurrentThreadState = CurrentThreadState ^ ThreadLockState.Write;
Interlocked.Add (ref rwlock, -RwWrite);
bool isUpgradable = ctstate.LockState.Has (LockState.Upgradable);
ctstate.LockState ^= LockState.Write;
ctstate.WriterRecursiveCount--;
int value = Interlocked.Add (ref rwlock, isUpgradable ? RwRead - RwWrite : -RwWrite);
writerDoneEvent.Set ();
if (isUpgradable && value >> RwReadBit == 1)
readerDoneEvent.Reset ();
}
public void EnterUpgradeableReadLock ()
@@ -251,10 +258,14 @@ namespace System.Threading {
//
public bool TryEnterUpgradeableReadLock (int millisecondsTimeout)
{
if (CheckState (millisecondsTimeout, ThreadLockState.Upgradable))
return true;
ThreadLockState ctstate = CurrentThreadState;
if (CurrentThreadState.Has (ThreadLockState.Read))
if (CheckState (millisecondsTimeout, LockState.Upgradable)) {
ctstate.UpgradeableRecursiveCount++;
return true;
}
if (ctstate.LockState.Has (LockState.Read))
throw new LockRecursionException ("The current thread has already entered read mode");
Stopwatch sw = Stopwatch.StartNew ();
@@ -272,8 +283,10 @@ namespace System.Threading {
upgradableEvent.Reset ();
if (TryEnterReadLock (ComputeTimeout (millisecondsTimeout, sw))) {
CurrentThreadState = ThreadLockState.Upgradable;
ctstate.LockState = LockState.Upgradable;
Interlocked.Decrement (ref numUpgradeWaiters);
ctstate.ReaderRecursiveCount--;
ctstate.UpgradeableRecursiveCount++;
return true;
}
@@ -292,14 +305,18 @@ namespace System.Threading {
public void ExitUpgradeableReadLock ()
{
if (!CurrentThreadState.Has (ThreadLockState.Upgradable | ThreadLockState.Read))
ThreadLockState ctstate = CurrentThreadState;
if (!ctstate.LockState.Has (LockState.Upgradable | LockState.Read))
throw new SynchronizationLockException ("The current thread has not entered the lock in upgradable mode");
upgradableTaken.Value = false;
upgradableEvent.Set ();
CurrentThreadState = CurrentThreadState ^ ThreadLockState.Upgradable;
Interlocked.Add (ref rwlock, -RwRead);
ctstate.LockState ^= LockState.Upgradable;
ctstate.UpgradeableRecursiveCount--;
if (Interlocked.Add (ref rwlock, -RwRead) >> RwReadBit == 0)
readerDoneEvent.Set ();
}
public void Dispose ()
@@ -309,43 +326,43 @@ namespace System.Threading {
public bool IsReadLockHeld {
get {
return rwlock >= RwRead;
return rwlock >= RwRead && CurrentThreadState.LockState.Has (LockState.Read);
}
}
public bool IsWriteLockHeld {
get {
return (rwlock & RwWrite) > 0;
return (rwlock & RwWrite) > 0 && CurrentThreadState.LockState.Has (LockState.Write);
}
}
public bool IsUpgradeableReadLockHeld {
get {
return upgradableTaken.Value;
return upgradableTaken.Value && CurrentThreadState.LockState.Has (LockState.Upgradable);
}
}
public int CurrentReadCount {
get {
return (rwlock >> RwReadBit) - (IsUpgradeableReadLockHeld ? 1 : 0);
return (rwlock >> RwReadBit) - (upgradableTaken.Value ? 1 : 0);
}
}
public int RecursiveReadCount {
get {
return IsReadLockHeld ? IsUpgradeableReadLockHeld ? 0 : 1 : 0;
return CurrentThreadState.ReaderRecursiveCount;
}
}
public int RecursiveUpgradeCount {
get {
return IsUpgradeableReadLockHeld ? 1 : 0;
return CurrentThreadState.UpgradeableRecursiveCount;
}
}
public int RecursiveWriteCount {
get {
return IsWriteLockHeld ? 1 : 0;
return CurrentThreadState.WriterRecursiveCount;
}
}
@@ -372,28 +389,30 @@ namespace System.Threading {
return recursionPolicy;
}
}
ThreadLockState CurrentThreadState {
LockState CurrentLockState {
get {
// TODO: provide a IEqualityComparer thingie to have better hashes
if (currentThreadState == null)
currentThreadState = new Dictionary<ReaderWriterLockSlim, ThreadLockState> ();
ThreadLockState state;
if (!currentThreadState.TryGetValue (this, out state))
currentThreadState[this] = state = ThreadLockState.None;
return state;
return CurrentThreadState.LockState;
}
set {
if (currentThreadState == null)
currentThreadState = new Dictionary<ReaderWriterLockSlim, ThreadLockState> ();
currentThreadState[this] = value;
CurrentThreadState.LockState = value;
}
}
bool CheckState (int millisecondsTimeout, ThreadLockState validState)
ThreadLockState CurrentThreadState {
get {
if (currentThreadState == null)
currentThreadState = new Dictionary<int, ThreadLockState> ();
ThreadLockState state;
if (!currentThreadState.TryGetValue (id, out state))
currentThreadState[id] = state = new ThreadLockState ();
return state;
}
}
bool CheckState (int millisecondsTimeout, LockState validState)
{
if (disposed)
throw new ObjectDisposedException ("ReaderWriterLockSlim");
@@ -402,15 +421,15 @@ namespace System.Threading {
throw new ArgumentOutOfRangeException ("millisecondsTimeout");
// Detect and prevent recursion
ThreadLockState ctstate = CurrentThreadState;
LockState ctstate = CurrentLockState;
if (recursionPolicy == LockRecursionPolicy.NoRecursion)
if ((ctstate != ThreadLockState.None && ctstate != ThreadLockState.Upgradable)
|| (ctstate == ThreadLockState.Upgradable && validState == ThreadLockState.Upgradable))
if ((ctstate != LockState.None && ctstate != LockState.Upgradable)
|| (ctstate == LockState.Upgradable && validState == LockState.Upgradable))
throw new LockRecursionException ("The current thread has already a lock and recursion isn't supported");
// If we already had right lock state, just return
if (ctstate == validState)
if (ctstate.Has (validState))
return true;
CheckRecursionAuthorization (ctstate, validState);
@@ -418,10 +437,10 @@ namespace System.Threading {
return false;
}
static void CheckRecursionAuthorization (ThreadLockState ctstate, ThreadLockState desiredState)
static void CheckRecursionAuthorization (LockState ctstate, LockState desiredState)
{
// In read mode you can just enter Read recursively
if (ctstate == ThreadLockState.Read)
if (ctstate == LockState.Read)
throw new LockRecursionException ();
}
@@ -0,0 +1,57 @@
//
// ReaderWriterLockSlimExtensions.cs
//
// Author:
// Jérémie "Garuma" Laval <[email protected]>
//
// Copyright (c) 2010 Jérémie "Garuma" Laval
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace System.Threading
{
internal static class ReaderWriterLockSlimExtensions
{
internal static bool Has (this LockState state, LockState value)
{
return (state & value) > 0;
}
#if !NET_4_0 && !NET_4_0_BOOTSTRAP
internal static bool Wait (this ManualResetEvent self, int timeout)
{
return self.WaitOne (timeout);
}
internal static bool IsSet (this ManualResetEvent self)
{
return self.WaitOne (0);
}
#else
internal static bool IsSet (this ManualResetEventSlim self)
{
return self.IsSet;
}
#endif
}
}
@@ -0,0 +1,51 @@
//
// ThreadLockState.cs
//
// Author:
// Jérémie "Garuma" Laval <[email protected]>
//
// Copyright (c) 2010 Jérémie "Garuma" Laval
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace System.Threading
{
[Flags]
internal enum LockState
{
None = 0,
Read = 1,
Write = 2,
Upgradable = 4,
UpgradedRead = Upgradable | Read,
UpgradedWrite = Upgradable | Write
}
internal class ThreadLockState
{
public LockState LockState;
public int ReaderRecursiveCount;
public int WriterRecursiveCount;
public int UpgradeableRecursiveCount;
}
}
@@ -452,6 +452,28 @@ namespace MonoTests.System.Threading
Assert.IsTrue (v.TryEnterWriteLock (100), "#3");
}
[Test]
public void RecursiveWritePlusReadLockTest ()
{
var v = new ReaderWriterLockSlim (LockRecursionPolicy.SupportsRecursion);
Assert.IsTrue (v.TryEnterWriteLock (100), "#1");
Assert.AreEqual (1, v.RecursiveWriteCount, "1b");
Assert.AreEqual (0, v.RecursiveReadCount, "1c");
Assert.IsTrue (v.TryEnterReadLock (100), "#2");
Assert.AreEqual (1, v.RecursiveWriteCount, "2b");
Assert.AreEqual (1, v.RecursiveReadCount, "2c");
Assert.IsTrue (v.TryEnterReadLock (100), "#3");
Assert.AreEqual (1, v.RecursiveWriteCount, "3b");
Assert.AreEqual (2, v.RecursiveReadCount, "3c");
v.ExitReadLock ();
Assert.AreEqual (1, v.RecursiveWriteCount, "4b");
Assert.AreEqual (1, v.RecursiveReadCount, "4c");
}
[Test]
public void RecursiveUpgradeableReadLockTest ()
{
@@ -461,5 +483,92 @@ namespace MonoTests.System.Threading
Assert.IsTrue (v.TryEnterUpgradeableReadLock (100), "#2");
Assert.IsTrue (v.TryEnterUpgradeableReadLock (100), "#3");
}
[Test]
public void RecursiveReadPropertiesTest ()
{
var v = new ReaderWriterLockSlim (LockRecursionPolicy.SupportsRecursion);
v.EnterReadLock ();
v.EnterReadLock ();
Assert.AreEqual (true, v.IsReadLockHeld, "#1a");
Assert.AreEqual (1, v.CurrentReadCount, "#2a");
Assert.AreEqual (2, v.RecursiveReadCount, "#3a");
bool rLock = true;
int cReadCount = -1, rReadCount = -1;
Thread t = new Thread ((_) => {
rLock = v.IsReadLockHeld;
cReadCount = v.CurrentReadCount;
rReadCount = v.RecursiveReadCount;
});
t.Start ();
t.Join ();
Assert.AreEqual (false, rLock, "#1b");
Assert.AreEqual (1, cReadCount, "#2b");
Assert.AreEqual (0, rReadCount, "#3b");
}
[Test]
public void RecursiveUpgradePropertiesTest ()
{
var v = new ReaderWriterLockSlim (LockRecursionPolicy.SupportsRecursion);
v.EnterUpgradeableReadLock ();
v.EnterUpgradeableReadLock ();
Assert.AreEqual (true, v.IsUpgradeableReadLockHeld, "#1a");
Assert.AreEqual (false, v.IsReadLockHeld, "#11a");
Assert.AreEqual (0, v.CurrentReadCount, "#2a");
Assert.AreEqual (2, v.RecursiveUpgradeCount, "#3a");
bool upLock = false, rLock = false;
int rCount = -1, rUCount = -1;
Thread t = new Thread ((_) => {
upLock = v.IsUpgradeableReadLockHeld;
rLock = v.IsReadLockHeld;
rCount = v.CurrentReadCount;
rUCount = v.RecursiveUpgradeCount;
});
t.Start ();
t.Join ();
Assert.AreEqual (false, upLock, "#1b");
Assert.AreEqual (false, rLock, "#11b");
Assert.AreEqual (0, rCount, "#2b");
Assert.AreEqual (0, rUCount, "#3b");
}
[Test]
public void RecursiveWritePropertiesTest ()
{
var v = new ReaderWriterLockSlim (LockRecursionPolicy.SupportsRecursion);
v.EnterWriteLock ();
v.EnterWriteLock ();
Assert.AreEqual (true, v.IsWriteLockHeld, "#1a");
Assert.AreEqual (2, v.RecursiveWriteCount, "#3a");
bool wLock = false;
int rWrite = -1;
Thread t = new Thread ((_) => {
wLock = v.IsWriteLockHeld;
rWrite = v.RecursiveWriteCount;
});
t.Start ();
t.Join ();
Assert.AreEqual (false, wLock, "#1b");
Assert.AreEqual (0, rWrite, "#3b");
}
}
}
@@ -66,6 +66,8 @@ System.Security.Cryptography/SHA512CryptoServiceProvider.cs
System.Threading/LockRecursionException.cs
System.Threading/LockRecursionPolicy.cs
System.Threading/ReaderWriterLockSlim.cs
System.Threading/ThreadLockState.cs
System.Threading/ReaderWriterLockSlimExtensions.cs
System.Linq.Expressions/Extensions.cs
System.Linq.Expressions/ExpressionTransformer.cs
@@ -8,7 +8,7 @@ System.Drawing/BufferedGraphics.cs
System.Drawing/BufferedGraphicsManager.cs
System.Drawing/BufferedGraphicsContext.cs
System.Drawing/CharacterRange.cs
System.Drawing/carbonFunctions.cs
System.Drawing/macFunctions.cs
System.Drawing/ColorConverter.cs
System.Drawing/Color.cs
System.Drawing/ColorTranslator.cs
@@ -49,7 +49,7 @@ namespace System.Drawing
#endif
{
internal IntPtr nativeObject = IntPtr.Zero;
internal CarbonContext context;
internal IMacContext maccontext;
private bool disposed = false;
private static float defDpiX = 0;
private static float defDpiY = 0;
@@ -190,6 +190,8 @@ namespace System.Drawing
CopyFromScreenX11 (sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
} else if (GDIPlus.UseCarbonDrawable) {
CopyFromScreenMac (sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
} else if (GDIPlus.UseCocoaDrawable) {
CopyFromScreenMac (sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
} else {
CopyFromScreenWin32 (sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
}
@@ -293,11 +295,11 @@ namespace System.Drawing
{
Status status;
if (! disposed) {
if (GDIPlus.UseCarbonDrawable && context.ctx != IntPtr.Zero) {
if (GDIPlus.UseCarbonDrawable || GDIPlus.UseCocoaDrawable) {
Flush ();
Carbon.CGContextSynchronize (context.ctx);
Carbon.ReleaseContext (context.port, context.ctx);
maccontext.Release ();
}
status = GDIPlus.GdipDeleteGraphics (nativeObject);
nativeObject = IntPtr.Zero;
GDIPlus.CheckStatus (status);
@@ -1681,8 +1683,9 @@ namespace System.Drawing
Status status = GDIPlus.GdipFlush (nativeObject, intention);
GDIPlus.CheckStatus (status);
if (GDIPlus.UseCarbonDrawable && context.ctx != IntPtr.Zero)
Carbon.CGContextSynchronize (context.ctx);
if (maccontext != null)
maccontext.Synchronize ();
}
[EditorBrowsable (EditorBrowsableState.Advanced)]
@@ -1714,12 +1717,22 @@ namespace System.Drawing
{
IntPtr graphics;
if (GDIPlus.UseCocoaDrawable) {
CocoaContext context = MacSupport.GetCGContextForNSView (hwnd);
GDIPlus.GdipCreateFromContext_macosx (context.ctx, context.width, context.height, out graphics);
Graphics g = new Graphics (graphics);
g.maccontext = context;
return g;
}
if (GDIPlus.UseCarbonDrawable) {
CarbonContext context = Carbon.GetCGContextForView (hwnd);
CarbonContext context = MacSupport.GetCGContextForView (hwnd);
GDIPlus.GdipCreateFromContext_macosx (context.ctx, context.width, context.height, out graphics);
Graphics g = new Graphics (graphics);
g.context = context;
g.maccontext = context;
return g;
}
@@ -61,6 +61,7 @@ namespace System.Drawing
public static IntPtr Display = IntPtr.Zero;
public static bool UseX11Drawable = false;
public static bool UseCarbonDrawable = false;
public static bool UseCocoaDrawable = false;
#region gdiplus.dll functions
@@ -138,12 +139,12 @@ namespace System.Drawing
static public bool RunningOnWindows ()
{
return !UseX11Drawable && !UseCarbonDrawable;
return !UseX11Drawable && !UseCarbonDrawable && !UseCocoaDrawable;
}
static public bool RunningOnUnix ()
{
return UseX11Drawable || UseCarbonDrawable;
return UseX11Drawable || UseCarbonDrawable || UseCocoaDrawable;
}
// Copies a Ptr to an array of Points and releases the memory
@@ -36,9 +36,9 @@ namespace System.Drawing {
[SuppressUnmanagedCodeSecurity]
#if NET_2_0
internal static class Carbon {
internal static class MacSupport {
#else
internal sealed class Carbon {
internal sealed class MacSupport {
#endif
internal static Hashtable contextReference = new Hashtable ();
internal static object lockobj = new object ();
@@ -52,7 +52,7 @@ namespace System.Drawing {
internal static int debug_threshold = 1;
#endif
static Carbon () {
static MacSupport () {
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ()) {
if (String.Equals (asm.GetName ().Name, "System.Windows.Forms")) {
Type driver_type = asm.GetType ("System.Windows.Forms.XplatUICarbon");
@@ -63,6 +63,16 @@ namespace System.Drawing {
}
}
internal static CocoaContext GetCGContextForNSView (IntPtr handle) {
IntPtr graphicsContext = objc_msgSend (objc_getClass ("NSGraphicsContext"), sel_registerName ("currentContext"));
IntPtr ctx = objc_msgSend (graphicsContext, sel_registerName ("graphicsPort"));
Rect bounds = new Rect ();
objc_msgSend_stret (ref bounds, handle, sel_registerName ("bounds"));
return new CocoaContext (ctx, (int) bounds.size.width, (int) bounds.size.height);
}
internal static CarbonContext GetCGContextForView (IntPtr handle) {
IntPtr context = IntPtr.Zero;
IntPtr port = IntPtr.Zero;
@@ -289,7 +299,7 @@ namespace System.Drawing {
public short right;
}
internal struct CarbonContext
internal struct CarbonContext : IMacContext
{
public IntPtr port;
public IntPtr ctx;
@@ -303,5 +313,44 @@ namespace System.Drawing {
this.width = width;
this.height = height;
}
public void Synchronize ()
{
MacSupport.CGContextSynchronize (ctx);
}
public void Release ()
{
MacSupport.ReleaseContext (port, ctx);
}
}
internal struct CocoaContext : IMacContext
{
public IntPtr ctx;
public int width;
public int height;
public CocoaContext (IntPtr ctx, int width, int height)
{
this.ctx = ctx;
this.width = width;
this.height = height;
}
public void Synchronize ()
{
MacSupport.CGContextSynchronize (ctx);
}
public void Release ()
{
}
}
internal interface IMacContext
{
void Synchronize ();
void Release ();
}
}
@@ -66,8 +66,6 @@ namespace System.Json
{
if (key == null)
throw new ArgumentNullException ("key");
if (value == null)
throw new ArgumentNullException ("value");
map.Add (key, value);
}
@@ -143,7 +141,13 @@ namespace System.Json
stream.WriteByte ((byte) '"');
stream.WriteByte ((byte) ',');
stream.WriteByte ((byte) ' ');
pair.Value.Save (stream);
if (pair.Value == null) {
stream.WriteByte ((byte) 'n');
stream.WriteByte ((byte) 'u');
stream.WriteByte ((byte) 'l');
stream.WriteByte ((byte) 'l');
} else
pair.Value.Save (stream);
}
stream.WriteByte ((byte) '}');
}
@@ -148,7 +148,10 @@ namespace System.Json
w.Write ('\"');
w.Write (EscapeString (pair.Key));
w.Write ("\": ");
pair.Value.SaveInternal (w);
if (pair.Value == null)
w.Write ("null");
else
pair.Value.SaveInternal (w);
following = true;
}
w.Write ('}');
@@ -107,8 +107,8 @@ namespace System.ServiceModel.Description
var uri = new Uri (String.Concat (baseUriString, baseUriString [baseUriString.Length - 1] == '/' ? String.Empty : "/", subPath));
var listener = endpoint.Binding.BuildChannelListener<IReplyChannel> (uri);
var cd = new ChannelDispatcher (listener, String.Empty);
cd.MessageVersion = MessageVersion.None;
cd.MessageVersion = MessageVersion.None;
cd.Endpoints.Add (new EndpointDispatcher (new EndpointAddress (uri), "InteropScriptService", String.Empty)
{ ContractFilter = new MatchAllMessageFilter () });
@@ -40,11 +40,6 @@ using System.Threading;
namespace System.ServiceModel.Channels.Http
{
internal interface IChannelDispatcherBoundListener
{
ChannelDispatcher ChannelDispatcher { get; set; }
}
internal class HttpChannelListener<TChannel> : InternalChannelListenerBase<TChannel>, IChannelDispatcherBoundListener
where TChannel : class, IChannel
{
@@ -325,14 +325,15 @@ namespace System.ServiceModel.Channels.Http
public override void Abort ()
{
res.Flush ();
res.Close ();
res.End ();
}
public override void Close ()
{
res.Flush ();
res.Close ();
// We must not close the response here, as everything is taking place in the
// HttpApplication's pipeline context and the output is sent to the client
// _after_ we leave this method. Closing the response here will stop any
// output from reaching the client.
}
public override void SetLength (long value)
@@ -99,16 +99,43 @@ namespace System.ServiceModel.Channels {
string line;
bool directive_found = false;
StringBuilder content = new StringBuilder ();
StringBuilder directiveBuffer = null;
while ((line = reader.ReadLine ()) != null) {
string trimmed = line.Trim ();
if (!directive_found && trimmed == String.Empty)
if (!directive_found && trimmed.Length == 0)
continue;
if (trimmed.StartsWith ("<%@")) {
int directiveEnd = trimmed.IndexOf ("%>");
if (directiveEnd == -1) {
if (directiveBuffer == null)
directiveBuffer = new StringBuilder ();
directiveBuffer.Append (line);
continue;
}
ParseDirective (trimmed);
directive_found = true;
continue;
} else if (!directive_found && directiveBuffer != null) {
int directiveEnd = trimmed.IndexOf ("%>");
if (directiveEnd == -1) {
directiveBuffer.Append (trimmed);
continue;
}
directiveEnd += 2;
int tlen = trimmed.Length;
if (tlen > directiveEnd)
content.Append (trimmed.Substring (directiveEnd) + "\n");
directiveBuffer.Append (trimmed.Substring (0, directiveEnd));
ParseDirective (directiveBuffer.ToString ());
directive_found = true;
directiveBuffer = null;
continue;
}
content.Append (line + "\n");
@@ -119,7 +146,7 @@ namespace System.ServiceModel.Channels {
throw new Exception ("No @ServiceHost directive found");
this.program = content.ToString ().Trim ();
if (this.program.Trim () == "")
if (this.program.Trim ().Length == 0)
this.program = null;
}
@@ -75,7 +75,9 @@ namespace System.ServiceModel.Channels
EnsureServiceHost ();
var table = HttpListenerManagerTable.GetOrCreate (host);
var manager = table.GetOrCreateManager (host.BaseAddresses [0]);
var manager = table.GetOrCreateManager (context.Request.Url);
if (manager == null)
manager = table.GetOrCreateManager (host.BaseAddresses [0]);
var wait = new ManualResetEvent (false);
wcf_wait_handles [context] = wait;
manager.ProcessNewContext (new System.ServiceModel.Channels.Http.AspNetHttpContextInfo (this, context));
@@ -3,9 +3,30 @@
//
// Author:
// Marcos Cobena ([email protected])
// Atsushi Enomoto ([email protected])
//
// Copyright 2007 Marcos Cobena (http://www.youcannoteatbits.org/)
// Copyright 2009-2010 Novell, Inc (http://www.novell.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
@@ -46,8 +67,9 @@ namespace System.ServiceModel.Channels
info = new TcpChannelInfo (source, MessageEncoder, quotas);
}
List<ManualResetEvent> accept_handles = new List<ManualResetEvent> ();
List<TChannel> accepted_channels = new List<TChannel> ();
SynchronizedCollection<ManualResetEvent> accept_handles = new SynchronizedCollection<ManualResetEvent> ();
Queue<TcpClient> accepted_clients = new Queue<TcpClient> ();
SynchronizedCollection<TChannel> accepted_channels = new SynchronizedCollection<TChannel> ();
protected override TChannel OnAcceptChannel (TimeSpan timeout)
{
@@ -89,32 +111,28 @@ namespace System.ServiceModel.Channels
{
DateTime start = DateTime.Now;
TcpClient client = null;
if (tcp_listener.Pending ()) {
client = tcp_listener.AcceptTcpClient ();
} else {
TcpClient client = accepted_clients.Count == 0 ? null : accepted_clients.Dequeue ();
if (client == null) {
var wait = new ManualResetEvent (false);
tcp_listener.BeginAcceptTcpClient (delegate (IAsyncResult result) {
client = tcp_listener.EndAcceptTcpClient (result);
wait.Set ();
accept_handles.Remove (wait);
}, null);
if (State == CommunicationState.Closing)
return null;
accept_handles.Add (wait);
wait.WaitOne (timeout);
if (!wait.WaitOne (timeout)) {
accept_handles.Remove (wait);
return null;
}
accept_handles.Remove (wait);
// recurse with new timeout, or return null if it's either being closed or timed out.
timeout -= (DateTime.Now - start);
return State == CommunicationState.Opened && timeout > TimeSpan.Zero ? AcceptTcpClient (timeout) : null;
}
// This may be optional though ...
if (client != null) {
foreach (var ch in accepted_channels) {
var dch = ch as TcpDuplexSessionChannel;
if (dch == null || dch.TcpClient == null && !dch.TcpClient.Connected)
continue;
if (((IPEndPoint) dch.TcpClient.Client.RemoteEndPoint).Equals (client.Client.RemoteEndPoint))
// ... then it should be handled in another BeginTryReceive/EndTryReceive loop in ChannelDispatcher.
return AcceptTcpClient (timeout - (DateTime.Now - start));
}
// There might be bettwe way to exclude those TCP clients though ...
foreach (var ch in accepted_channels) {
var dch = ch as TcpDuplexSessionChannel;
if (dch == null || dch.TcpClient == null && !dch.TcpClient.Connected)
continue;
if (((IPEndPoint) dch.TcpClient.Client.RemoteEndPoint).Equals (client.Client.RemoteEndPoint))
// ... then it should be handled in another BeginTryReceive/EndTryReceive loop in ChannelDispatcher.
return AcceptTcpClient (timeout - (DateTime.Now - start));
}
return client;
@@ -132,25 +150,25 @@ namespace System.ServiceModel.Channels
{
if (State == CommunicationState.Closed)
return;
ProcessClose ();
ProcessClose (TimeSpan.Zero);
}
protected override void OnClose (TimeSpan timeout)
{
if (State == CommunicationState.Closed)
return;
ProcessClose ();
ProcessClose (timeout);
}
void ProcessClose ()
void ProcessClose (TimeSpan timeout)
{
if (tcp_listener == null)
throw new InvalidOperationException ("Current state is " + State);
lock (accept_handles) {
foreach (var wait in accept_handles)
wait.Set ();
}
//tcp_listener.Client.Close (Math.Max (50, (int) timeout.TotalMilliseconds));
tcp_listener.Stop ();
var l = new List<ManualResetEvent> (accept_handles);
foreach (var wait in l) // those handles will disappear from accepted_handles
wait.Set ();
tcp_listener = null;
}
@@ -164,6 +182,31 @@ namespace System.ServiceModel.Channels
int explicitPort = Uri.Port;
tcp_listener = new TcpListener (entry.AddressList [0], explicitPort <= 0 ? TcpTransportBindingElement.DefaultPort : explicitPort);
tcp_listener.Start ();
tcp_listener.BeginAcceptTcpClient (TcpListenerAcceptedClient, tcp_listener);
}
void TcpListenerAcceptedClient (IAsyncResult result)
{
var listener = (TcpListener) result.AsyncState;
try {
var client = listener.EndAcceptTcpClient (result);
if (client != null) {
accepted_clients.Enqueue (client);
if (accept_handles.Count > 0)
accept_handles [0].Set ();
}
} catch {
/* If an accept fails, just ignore it. Maybe the remote peer disconnected already */
} finally {
if (State == CommunicationState.Opened) {
try {
listener.BeginAcceptTcpClient (TcpListenerAcceptedClient, listener);
} catch {
/* If this fails, we must have disposed the listener */
}
}
}
}
}
}
@@ -37,11 +37,6 @@ using System.ServiceModel.Description;
namespace System.ServiceModel.Dispatcher
{
internal interface IChannelDispatcherBoundListener
{
ChannelDispatcher ChannelDispatcher { get; set; }
}
public class ChannelDispatcher : ChannelDispatcherBase
{
class EndpointDispatcherCollection : SynchronizedCollection<EndpointDispatcher>
@@ -0,0 +1,36 @@
//
// ChannelDispatcher.cs
//
// Author:
// Atsushi Enomoto <[email protected]>
//
// Copyright (C) 2005-2010 Novell, Inc. http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace System.ServiceModel.Dispatcher
{
internal interface IChannelDispatcherBoundListener
{
ChannelDispatcher ChannelDispatcher { get; set; }
}
}
@@ -643,6 +643,7 @@ System.ServiceModel.Dispatcher/FaultContractInfo.cs
System.ServiceModel.Dispatcher/FilterInvalidBodyAccessException.cs
System.ServiceModel.Dispatcher/FinalizeProcessingHandler.cs
System.ServiceModel.Dispatcher/ICallContextInitializer.cs
System.ServiceModel.Dispatcher/IChannelDispatcherBoundListener.cs
System.ServiceModel.Dispatcher/IChannelInitializer.cs
System.ServiceModel.Dispatcher/IClientMessageFormatter.cs
System.ServiceModel.Dispatcher/IClientMessageInspector.cs
@@ -1,7 +1,7 @@
../../build/common/Consts.cs
../../build/common/Locale.cs
../../build/common/MonoTODOAttribute.cs
../System.Web/System.Web.Configuration_2.0/MachineKeySectionUtils.cs
../System.Web/System.Web.Util/MachineKeySectionUtils.cs
../System.Web/System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs
../System.Web/System.Web.Handlers/AssemblyResourceLoader.cs
./Assembly/AssemblyInfo.cs
@@ -72,11 +72,13 @@ namespace System.Web.Script.Services
readonly MethodInfo _methodInfo;
internal readonly ParameterInfo [] _params;
internal readonly Dictionary<string, int> _paramMap;
LogicalTypeInfo _typeInfo;
protected LogicalMethodInfo (LogicalTypeInfo typeInfo, MethodInfo method)
{
_methodInfo = method;
_params = MethodInfo.GetParameters ();
_typeInfo = typeInfo;
if (HasParameters) {
_paramMap = new Dictionary<string, int> (_params.Length, StringComparer.Ordinal);
@@ -101,8 +103,10 @@ namespace System.Web.Script.Services
}
public void GenerateMethod (StringBuilder proxy, bool isPrototype, bool isPage) {
string service = isPage ? "PageMethods" : MethodInfo.DeclaringType.FullName;
string ns;
string service;// = isPage ? "PageMethods" : MethodInfo.DeclaringType.FullName;
_typeInfo.GetNamespaceAndServiceName (MethodInfo.DeclaringType, isPage, out ns, out service);
string useHttpGet = UseHttpGet ? "true" : "false";
string paramMap = GenerateParameters (true);
string paramList = GenerateParameters (false);
@@ -187,6 +191,12 @@ Type.registerNamespace('{0}');",
return name;
}
protected virtual void GetNamespaceAndServiceName (Type type, bool isPage, out string ns, out string service)
{
ns = isPage ? String.Empty : type.Namespace;
service = isPage ? "PageMethods" : type.FullName;
}
// instance members
internal readonly Type _type;
@@ -205,8 +215,9 @@ Type.registerNamespace('{0}');",
for (int i = 0; i < logicalMethods.Count; i++)
_methodMap.Add (logicalMethods [i].MethodName, logicalMethods [i]);
string ns = isPage ? String.Empty : t.Namespace;
string service = isPage ? "PageMethods" : t.FullName;
string ns;
string service;
GetNamespaceAndServiceName (t, isPage, out ns, out service);
StringBuilder proxy = new StringBuilder ();
List<string> registeredNamespaces = new List<string> ();
@@ -616,6 +627,16 @@ var gtc = Sys.Net.WebServiceProxy._generateTypedConstructor;");
yield break;
}
protected override void GetNamespaceAndServiceName (Type type, bool isPage, out string ns, out string service)
{
string name = type.Namespace;
int dot = name.LastIndexOf ('.');
if (dot > -1)
name = name.Substring (dot + 1);
ns = name;
service = name + "." + type.Name;
}
protected override void GenerateTypeRegistrationScript (StringBuilder proxy, List<string> registeredNamespaces)
{
bool gtc = false;
@@ -3,7 +3,7 @@
../../build/common/MonoTODOAttribute.cs
../System.Web/System.Web.Handlers/AssemblyResourceLoader.cs
../System.Web/System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs
../System.Web/System.Web.Configuration_2.0/MachineKeySectionUtils.cs
../System.Web/System.Web.Util/MachineKeySectionUtils.cs
../System.Web.Extensions/Assembly/AssemblyInfo.cs
../System.Web.Extensions/System.Web.Handlers/ScriptModule.cs
../System.Web.Extensions/System.Web.Handlers/ScriptResourceHandler.cs
@@ -302,8 +302,10 @@ namespace System.Web.Routing
argSegs = path.Split ('/');
argsCount = argSegs.Length;
if (String.IsNullOrEmpty (argSegs [argsCount - 1]))
argsCount--; // path ends with a trailinig '/'
}
bool haveDefaults = defaults != null && defaults.Count > 0;
if (argsCount == 1 && String.IsNullOrEmpty (argSegs [0]))
@@ -353,7 +355,8 @@ namespace System.Web.Routing
if (!defaults.ContainsKey (tokens [0].Name))
return null;
}
}
} else if (!haveSegmentWithCatchAll && argsCount > segmentCount)
return null;
return AddDefaults (ret, defaults);
}
@@ -907,6 +907,59 @@ namespace MonoTests.System.Web.Routing
Assert.AreEqual ("3", rd.Values ["baz"], "#4-2");
}
[Test]
public void GetRouteData44 ()
{
// {} matches and substitutes even at partial state ...
var r = new Route ("{foo}/bartes{baz}", null);
var hc = new HttpContextStub ("~/x/bartest/", String.Empty);
var rd = r.GetRouteData (hc);
Assert.IsNotNull (rd, "#1");
Assert.AreEqual (r, rd.Route, "#2");
Assert.AreEqual (0, rd.DataTokens.Count, "#3");
Assert.AreEqual (2, rd.Values.Count, "#4");
Assert.AreEqual ("x", rd.Values ["foo"], "#4-1");
Assert.AreEqual ("t", rd.Values ["baz"], "#4-2");
}
[Test]
public void GetRouteData45 ()
{
var r = new Route ("{foo}/{bar}", null);
var hc = new HttpContextStub ("~/x/y/", String.Empty);
var rd = r.GetRouteData (hc);
Assert.IsNotNull (rd, "#1");
Assert.AreEqual (r, rd.Route, "#2");
Assert.AreEqual (0, rd.DataTokens.Count, "#3");
Assert.AreEqual (2, rd.Values.Count, "#4");
Assert.AreEqual ("x", rd.Values ["foo"], "#4-1");
Assert.AreEqual ("y", rd.Values ["bar"], "#4-2");
}
[Test (Description="Bug #651593")]
public void GetRouteData46 ()
{
var r = new Route ("Foo", null) {
Defaults = new RouteValueDictionary (new {
controller = "Foo",
action = "Index"
})
};
var hc = new HttpContextStub ("/Foo/123", String.Empty);
var rd = r.GetRouteData (hc);
Assert.IsNull (rd, "#1");
r = new Route ("Foo", null) {
Defaults = new RouteValueDictionary (new {
controller = "Foo",
action = "Index"
})
};
hc = new HttpContextStub ("~/Foo/123", String.Empty);
rd = r.GetRouteData (hc);
Assert.IsNull (rd, "#2");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void GetVirtualPathNullContext ()
+2 -2
View File
@@ -287,7 +287,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -doc:$(test_lib:.dll=.xml) -nowarn:219,169,159
$(foreach file,$(NUNIT_APP_GLOBALRESOURCES_FILES),$(shell echo $(file) | sed -e 's;\(.*\)/\(.*\);/resource:\1/\2,App_GlobalResources/\2 ;g'))
ifeq (net_2_0, $(PROFILE))
TEST_MCS_FLAGS += -r:System.Web.Extensions.dll
TEST_MCS_FLAGS += -r:System.Web.Extensions.dll -d:TEST
endif
EXTRA_DISTFILES = \
@@ -442,4 +442,4 @@ ifdef STANDALONE_TEST_COMPILABLE_TESTS
done
endif
@@ -42,6 +42,21 @@ namespace System.Web.Caching
{
public static readonly DateTime NoAbsoluteExpiration = DateTime.MaxValue;
public static readonly TimeSpan NoSlidingExpiration = TimeSpan.Zero;
// cacheLock will be released in the code below without checking whether it was
// actually acquired. The API doesn't offer a reliable way to check whether the lock
// is being held by the current thread and since Mono does't implement CER
// (Constrained Execution Regions -
// http://msdn.microsoft.com/en-us/library/ms228973.aspx) currently, we have no
// reliable way of recording the information that the lock has been successfully
// acquired.
// It can happen that a Thread.Abort occurs while acquiring the lock and the lock
// isn't actually held. In this case the attempt to release a lock will throw an
// exception. It's better than a race of setting a boolean flag after acquiring the
// lock and then relying upon it here to release it - that may cause a deadlock
// should we fail to release the lock which was successfully acquired but
// Thread.Abort happened right after that during the stloc instruction to set the
// boolean flag. Once CERs are supported we can use the boolean flag reliably.
ReaderWriterLockSlim cacheLock;
Dictionary <string, CacheItem> cache;
CacheItemPriorityQueue timedItems;
@@ -153,19 +168,17 @@ namespace System.Web.Caching
{
if (key == null)
throw new ArgumentNullException ("key");
bool locked = false;
try {
cacheLock.EnterWriteLock ();
locked = true;
CacheItem it = GetCacheItem (key);
if (it != null)
return it.Value;
Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback, null, false);
} finally {
if (locked)
cacheLock.ExitWriteLock ();
// See comment at the top of the file, above cacheLock declaration
cacheLock.ExitWriteLock ();
}
return null;
@@ -173,10 +186,8 @@ namespace System.Web.Caching
public object Get (string key)
{
bool locked = false;
try {
cacheLock.EnterUpgradeableReadLock ();
locked = true;
CacheItem it = GetCacheItem (key);
if (it == null)
return null;
@@ -187,6 +198,7 @@ namespace System.Web.Caching
if (!NeedsUpdate (it, CacheItemUpdateReason.DependencyChanged, false))
Remove (it.Key, CacheItemRemovedReason.DependencyChanged, false, true);
} finally {
// See comment at the top of the file, above cacheLock declaration
cacheLock.ExitWriteLock ();
}
@@ -212,6 +224,7 @@ namespace System.Web.Caching
if (!NeedsUpdate (it, CacheItemUpdateReason.Expired, false))
Remove (key, CacheItemRemovedReason.Expired, false, true);
} finally {
// See comment at the top of the file, above cacheLock declaration
cacheLock.ExitWriteLock ();
}
@@ -221,9 +234,8 @@ namespace System.Web.Caching
return it.Value;
} finally {
if (locked) {
cacheLock.ExitUpgradeableReadLock ();
}
// See comment at the top of the file, above cacheLock declaration
cacheLock.ExitUpgradeableReadLock ();
}
}
@@ -282,20 +294,17 @@ namespace System.Web.Caching
internal void SetItemTimeout (string key, DateTime absoluteExpiration, TimeSpan slidingExpiration, bool doLock)
{
CacheItem ci = null;
bool locked = false;
CacheItem ci = null;
try {
if (doLock) {
if (doLock)
cacheLock.EnterWriteLock ();
locked = true;
}
ci = GetCacheItem (key);
if (ci != null)
SetItemTimeout (ci, absoluteExpiration, slidingExpiration, ci.OnRemoveCallback, null, key, false);
} finally {
if (locked) {
if (doLock) {
// See comment at the top of the file, above cacheLock declaration
cacheLock.ExitWriteLock ();
}
}
@@ -317,12 +326,9 @@ namespace System.Web.Caching
ci.OnRemoveCallback = onRemoveCallback;
ci.OnUpdateCallback = onUpdateCallback;
bool locked = false;
try {
if (doLock) {
if (doLock)
cacheLock.EnterWriteLock ();
locked = true;
}
if (ci.Timer != null) {
ci.Timer.Dispose ();
@@ -336,7 +342,8 @@ namespace System.Web.Caching
if (!disableExpiration && ci.AbsoluteExpiration != NoAbsoluteExpiration)
EnqueueTimedItem (ci);
} finally {
if (locked) {
if (doLock) {
// See comment at the top of the file, above cacheLock declaration
cacheLock.ExitWriteLock ();
}
}
@@ -376,16 +383,14 @@ namespace System.Web.Caching
object Remove (string key, CacheItemRemovedReason reason, bool doLock, bool invokeCallback)
{
CacheItem it = null;
bool locked = false;
try {
if (doLock) {
if (doLock)
cacheLock.EnterWriteLock ();
locked = true;
}
it = RemoveCacheItem (key);
} finally {
if (locked) {
if (doLock) {
// See comment at the top of the file, above cacheLock declaration
cacheLock.ExitWriteLock ();
}
}
@@ -424,10 +429,8 @@ namespace System.Web.Caching
internal void InvokePrivateCallbacks ()
{
CacheItemRemovedReason reason = CacheItemRemovedReason.Removed;
bool locked = false;
try {
cacheLock.EnterReadLock ();
locked = true;
foreach (string key in cache.Keys) {
CacheItem item = GetCacheItem (key);
if (item.Disabled)
@@ -442,25 +445,21 @@ namespace System.Web.Caching
}
}
} finally {
if (locked) {
cacheLock.ExitReadLock ();
}
// See comment at the top of the file, above cacheLock declaration
cacheLock.ExitReadLock ();
}
}
public IDictionaryEnumerator GetEnumerator ()
{
ArrayList list = new ArrayList ();
bool locked = false;
try {
cacheLock.EnterReadLock ();
locked = true;
foreach (CacheItem it in cache.Values)
list.Add (it);
} finally {
if (locked) {
cacheLock.ExitReadLock ();
}
// See comment at the top of the file, above cacheLock declaration
cacheLock.ExitReadLock ();
}
return new CacheItemEnumerator (list);
@@ -478,13 +477,9 @@ namespace System.Web.Caching
bool NeedsUpdate (CacheItem item, CacheItemUpdateReason reason, bool needLock)
{
bool locked = false;
try {
if (needLock) {
if (needLock)
cacheLock.EnterWriteLock ();
locked = true;
}
if (item == null || item.OnUpdateCallback == null)
return false;
@@ -525,8 +520,10 @@ namespace System.Web.Caching
} catch (Exception) {
return false;
} finally {
if (locked)
if (needLock) {
// See comment at the top of the file, above cacheLock declaration
cacheLock.ExitWriteLock ();
}
}
}
@@ -534,11 +531,9 @@ namespace System.Web.Caching
{
DateTime now = DateTime.Now;
CacheItem item = timedItems.Peek ();
bool locked = false;
try {
cacheLock.EnterWriteLock ();
locked = true;
while (item != null) {
if (!item.Disabled && item.ExpiresAt > now.Ticks)
@@ -549,13 +544,13 @@ namespace System.Web.Caching
}
item = timedItems.Dequeue ();
if (!NeedsUpdate (item, CacheItemUpdateReason.Expired, true))
if (!NeedsUpdate (item, CacheItemUpdateReason.Expired, false))
Remove (item.Key, CacheItemRemovedReason.Expired, false, true);
item = timedItems.Peek ();
}
} finally {
if (locked)
cacheLock.ExitWriteLock ();
// See comment at the top of the file, above cacheLock declaration
cacheLock.ExitWriteLock ();
}
if (item != null) {
@@ -574,10 +569,8 @@ namespace System.Web.Caching
internal void CheckDependencies ()
{
IList list;
bool locked = false;
try {
cacheLock.EnterWriteLock ();
locked = true;
list = new List <CacheItem> ();
foreach (CacheItem it in cache.Values)
list.Add (it);
@@ -587,18 +580,15 @@ namespace System.Web.Caching
Remove (it.Key, CacheItemRemovedReason.DependencyChanged, false, true);
}
} finally {
if (locked) {
cacheLock.ExitWriteLock ();
}
// See comment at the top of the file, above cacheLock declaration
cacheLock.ExitWriteLock ();
}
}
internal DateTime GetKeyLastChange (string key)
{
bool locked = false;
try {
cacheLock.EnterReadLock ();
locked = true;
CacheItem it = GetCacheItem (key);
if (it == null)
@@ -606,9 +596,8 @@ namespace System.Web.Caching
return it.LastChange;
} finally {
if (locked) {
cacheLock.ExitReadLock ();
}
// See comment at the top of the file, above cacheLock declaration
cacheLock.ExitReadLock ();
}
}
@@ -41,6 +41,8 @@ namespace System.Web.Caching
CacheItem[] heap;
int heapSize = 0;
int heapCount = 0;
// See comment for the cacheLock field at top of System.Web.Caching/Cache.cs
ReaderWriterLockSlim queueLock;
public int Count {
@@ -94,20 +96,18 @@ namespace System.Web.Caching
if (item == null)
return;
bool locked = false;
CacheItem[] heap;
try {
queueLock.EnterWriteLock ();
locked = true;
heap = GetHeapWithGrow ();
heap [heapCount++] = item;
BubbleUp (heap);
AddSequenceEntry (item, EDSequenceEntryType.Enqueue);
} finally {
if (locked)
queueLock.ExitWriteLock ();
// See comment at the top of the file, above queueLock declaration
queueLock.ExitWriteLock ();
}
}
@@ -115,12 +115,10 @@ namespace System.Web.Caching
{
CacheItem ret = null;
CacheItem[] heap;
bool locked = false;
int index;
try {
queueLock.EnterWriteLock ();
locked = true;
heap = GetHeapWithShrink ();
if (heap == null || heapCount == 0)
return null;
@@ -136,19 +134,17 @@ namespace System.Web.Caching
AddSequenceEntry (ret, EDSequenceEntryType.Dequeue);
return ret;
} finally {
if (locked)
queueLock.ExitWriteLock ();
// See comment at the top of the file, above queueLock declaration
queueLock.ExitWriteLock ();
}
}
public CacheItem Peek ()
{
bool locked = false;
CacheItem ret;
try {
queueLock.EnterReadLock ();
locked = true;
if (heap == null || heapCount == 0)
return null;
@@ -157,8 +153,8 @@ namespace System.Web.Caching
return ret;
} finally {
if (locked)
queueLock.ExitReadLock ();
// See comment at the top of the file, above queueLock declaration
queueLock.ExitReadLock ();
}
}
@@ -94,6 +94,7 @@ namespace System.Web.Compilation
// This is here _only_ for the purpose of unit tests!
internal static bool suppressDebugModeMessages;
// See comment for the cacheLock field at top of System.Web.Caching/Cache.cs
#if SYSTEMCORE_DEP
static ReaderWriterLockSlim buildCacheLock;
#else
@@ -817,14 +818,12 @@ namespace System.Web.Compilation
// to the assembly builder and, in effect, no assembly is produced but there are STILL types that need
// to be added to the cache.
Assembly compiledAssembly = results != null ? results.CompiledAssembly : null;
bool locked = false;
try {
#if SYSTEMCORE_DEP
buildCacheLock.EnterWriteLock ();
#else
buildCacheLock.AcquireWriterLock (-1);
#endif
locked = true;
if (compiledAssembly != null)
referencedAssemblies.Add (compiledAssembly);
@@ -835,13 +834,11 @@ namespace System.Web.Compilation
StoreInCache (bp, compiledAssembly, results);
}
} finally {
if (locked) {
#if SYSTEMCORE_DEP
buildCacheLock.ExitWriteLock ();
buildCacheLock.ExitWriteLock ();
#else
buildCacheLock.ReleaseWriterLock ();
buildCacheLock.ReleaseWriterLock ();
#endif
}
}
}
@@ -883,24 +880,19 @@ namespace System.Web.Compilation
#endif
static BuildManagerCacheItem GetCachedItem (string vp)
{
bool locked = false;
try {
#if SYSTEMCORE_DEP
buildCacheLock.EnterReadLock ();
#else
buildCacheLock.AcquireReaderLock (-1);
#endif
locked = true;
return GetCachedItemNoLock (vp);
} finally {
if (locked) {
#if SYSTEMCORE_DEP
buildCacheLock.ExitReadLock ();
buildCacheLock.ExitReadLock ();
#else
buildCacheLock.ReleaseReaderLock ();
buildCacheLock.ReleaseReaderLock ();
#endif
}
}
}
@@ -1290,27 +1282,22 @@ namespace System.Web.Compilation
else
return;
bool locked = false;
try {
#if SYSTEMCORE_DEP
buildCacheLock.EnterWriteLock ();
#else
buildCacheLock.AcquireWriterLock (-1);
#endif
locked = true;
if (HasCachedItemNoLock (virtualPath)) {
buildCache [virtualPath] = null;
OnEntryRemoved (virtualPath);
}
} finally {
if (locked) {
#if SYSTEMCORE_DEP
buildCacheLock.ExitWriteLock ();
buildCacheLock.ExitWriteLock ();
#else
buildCacheLock.ReleaseWriterLock ();
buildCacheLock.ReleaseWriterLock ();
#endif
}
}
}
@@ -49,7 +49,8 @@ namespace System.Web.Configuration {
static ConfigurationPropertyCollection properties;
AuthorizationRuleAction action;
ConfigurationSaveMode saveMode = ConfigurationSaveMode.Full;
static AuthorizationRule ()
{
rolesProp = new ConfigurationProperty ("roles", typeof (StringCollection), null,
@@ -130,7 +131,10 @@ namespace System.Web.Configuration {
[MonoTODO ("Not implemented")]
protected override bool IsModified ()
{
throw new NotImplementedException ();
if (((CommaDelimitedStringCollection)Roles).IsModified || ((CommaDelimitedStringCollection)Users).IsModified || ((CommaDelimitedStringCollection)Verbs).IsModified)
return true;
return false;
}
void VerifyData ()
@@ -168,6 +172,9 @@ namespace System.Web.Configuration {
protected override bool SerializeElement (XmlWriter writer, bool serializeCollectionKey)
{
if (saveMode != ConfigurationSaveMode.Full && !IsModified ())
return true;
PreSerialize (writer);
writer.WriteStartElement (action == AuthorizationRuleAction.Allow ? "allow" : "deny");
@@ -191,6 +198,7 @@ namespace System.Web.Configuration {
protected override void Unmerge (ConfigurationElement sourceElement, ConfigurationElement parentElement, ConfigurationSaveMode saveMode)
{
base.Unmerge (sourceElement, parentElement, saveMode);
this.saveMode = saveMode;
}
public AuthorizationRuleAction Action {
@@ -108,9 +108,8 @@ namespace System.Web.Configuration {
get { return ConfigurationElementCollectionType.BasicMapAlternate; }
}
[MonoTODO ("is it okay to return a comma delimited string here?")]
protected override string ElementName {
get { return "allow,deny"; }
get { return String.Empty; }
}
public AuthorizationRule this [int index] {
@@ -0,0 +1,36 @@
//
// System.Web.Configuration.MachineKeyCompatibilityMode
//
// Authors:
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace System.Web.Configuration {
public enum MachineKeyCompatibilityMode {
Framework20SP1 = 0,
Framework20SP2 = 1
}
}
@@ -28,8 +28,6 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
using Microsoft.Win32;
namespace System.Web.Configuration
@@ -42,9 +40,6 @@ namespace System.Web.Configuration
Encryption
};
const int encryptionKeyLength = 64;
const int validationKeyLength = 64;
static string keyEncryption;
static string keyValidation;
@@ -62,31 +57,16 @@ namespace System.Web.Configuration
}
public static byte[] Retrieve (KeyType kt)
{
byte[] ret = GetKey (kt);
if (ret == null) {
ret = Generate (kt);
if (ret != null)
Store (ret, kt);
}
return ret;
}
static byte[] GetKey (KeyType kt)
{
string key = null;
int len;
switch (kt) {
case KeyType.Validation:
key = keyValidation;
len = validationKeyLength;
break;
case KeyType.Encryption:
key = keyEncryption;
len = validationKeyLength;
break;
default:
@@ -107,11 +87,7 @@ namespace System.Web.Configuration
if (o == null || o.GetType () != typeof (byte[]))
return null;
byte[] ret = (byte[])o;
if (ret.Length != len)
return null;
return ret;
return (byte[]) o;
}
static RegistryKey OpenRegistryKey (string path, bool write)
@@ -134,23 +110,19 @@ namespace System.Web.Configuration
return ret;
}
static void Store (byte[] buf, KeyType kt)
public static void Store (byte[] buf, KeyType kt)
{
if (buf == null)
return;
string key = null;
int len;
switch (kt) {
case KeyType.Validation:
key = keyValidation;
len = validationKeyLength;
break;
case KeyType.Encryption:
key = keyEncryption;
len = validationKeyLength;
break;
default:
@@ -160,9 +132,6 @@ namespace System.Web.Configuration
if (key == null)
return;
if (buf.Length != len)
throw new ArgumentException ("Key has invalid length");
try {
using (RegistryKey rk = OpenRegistryKey (key, true)) {
#if NET_2_0
@@ -180,27 +149,5 @@ namespace System.Web.Configuration
throw new ApplicationException ("Failed to store encryption key in the registry.", ex);
}
}
static byte[] Generate (KeyType kt)
{
RandomNumberGenerator rng = RandomNumberGenerator.Create ();
byte[] ret = null;
switch (kt) {
case KeyType.Validation:
ret = new byte [validationKeyLength];
break;
case KeyType.Encryption:
ret = new byte [encryptionKeyLength];
break;
default:
throw new ArgumentException ("Unknown key type.");
}
rng.GetBytes (ret);
return ret;
}
}
}
@@ -3,8 +3,9 @@
//
// Authors:
// Chris Toshok ([email protected])
// Sebastien Pouliot <[email protected]>
//
// (c) Copyright 2005 Novell, Inc (http://www.novell.com)
// (c) Copyright 2005, 2010 Novell, Inc (http://www.novell.com)
//
//
@@ -28,12 +29,13 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using System;
using System.ComponentModel;
using System.Configuration;
using System.Security.Cryptography;
#if NET_2_0
using System.Web.Util;
namespace System.Web.Configuration {
@@ -44,6 +46,10 @@ namespace System.Web.Configuration {
static ConfigurationProperty validationProp;
static ConfigurationProperty validationKeyProp;
static ConfigurationPropertyCollection properties;
static MachineKeyValidationConverter converter = new MachineKeyValidationConverter ();
#if NET_4_0
MachineKeyValidation validation;
#endif
static MachineKeySection ()
{
@@ -55,10 +61,17 @@ namespace System.Web.Configuration {
PropertyHelper.WhiteSpaceTrimStringConverter,
PropertyHelper.NonEmptyStringValidator,
ConfigurationPropertyOptions.None);
validationProp = new ConfigurationProperty ("validation", typeof (MachineKeyValidation), MachineKeyValidation.SHA1,
new MachineKeyValidationConverter (),
#if NET_4_0
validationProp = new ConfigurationProperty ("validation", typeof (string), "HMACSHA256",
PropertyHelper.WhiteSpaceTrimStringConverter,
PropertyHelper.NonEmptyStringValidator,
ConfigurationPropertyOptions.None);
#else
validationProp = new ConfigurationProperty ("validation", typeof (MachineKeyValidation),
MachineKeyValidation.SHA1, converter,
PropertyHelper.DefaultValidator,
ConfigurationPropertyOptions.None);
#endif
validationKeyProp = new ConfigurationProperty ("validationKey", typeof (string), "AutoGenerate,IsolateApps",
PropertyHelper.WhiteSpaceTrimStringConverter,
PropertyHelper.NonEmptyStringValidator,
@@ -71,12 +84,30 @@ namespace System.Web.Configuration {
properties.Add (validationProp);
properties.Add (validationKeyProp);
MachineKeySectionUtils.AutoGenKeys ();
Config.AutoGenerate (MachineKeyRegistryStorage.KeyType.Encryption);
Config.AutoGenerate (MachineKeyRegistryStorage.KeyType.Validation);
}
#if NET_4_0
public MachineKeySection ()
{
// get DefaultValue from ValidationAlgorithm
validation = (MachineKeyValidation) converter.ConvertFrom (null, null, ValidationAlgorithm);
}
[MonoTODO]
public MachineKeyCompatibilityMode CompatibilityMode {
get; set;
}
#endif
protected override void Reset (ConfigurationElement parentElement)
{
base.Reset (parentElement);
decryption_key = null;
validation_key = null;
decryption_template = null;
validation_template = null;
}
[TypeConverter (typeof (WhiteSpaceTrimStringConverter))]
@@ -84,7 +115,10 @@ namespace System.Web.Configuration {
[ConfigurationProperty ("decryption", DefaultValue = "Auto")]
public string Decryption {
get { return (string) base [decryptionProp];}
set { base[decryptionProp] = value; }
set {
decryption_template = MachineKeySectionUtils.GetDecryptionAlgorithm (value);
base[decryptionProp] = value;
}
}
[TypeConverter (typeof (WhiteSpaceTrimStringConverter))]
@@ -94,16 +128,49 @@ namespace System.Web.Configuration {
get { return (string) base [decryptionKeyProp];}
set {
base[decryptionKeyProp] = value;
MachineKeySectionUtils.SetDecryptionKey (value);
SetDecryptionKey (value);
}
}
#if NET_4_0
// property exists for backward compatibility
public MachineKeyValidation Validation {
get { return validation; }
set {
if (value == MachineKeyValidation.Custom)
throw new ArgumentException ();
string algo = value.ToString ();
// enum and accept values differs for TripleDES
ValidationAlgorithm = (algo == "TripleDES") ? "3DES" : algo;
}
}
[StringValidator (MinLength = 1)]
[TypeConverter (typeof (WhiteSpaceTrimStringConverter))]
[ConfigurationProperty ("validation", DefaultValue = "HMACSHA256")]
public string ValidationAlgorithm {
get { return (string) base [validationProp];}
set {
if (value == null)
return;
if (value.StartsWith ("alg:"))
validation = MachineKeyValidation.Custom;
else
validation = (MachineKeyValidation) converter.ConvertFrom (null, null, value);
base[validationProp] = value;
}
}
#else
[TypeConverter (typeof (MachineKeyValidationConverter))]
[ConfigurationProperty ("validation", DefaultValue = "SHA1")]
public MachineKeyValidation Validation {
get { return (MachineKeyValidation) base [validationProp];}
set { base[validationProp] = value; }
}
#endif
[TypeConverter (typeof (WhiteSpaceTrimStringConverter))]
[StringValidator (MinLength = 1)]
@@ -112,13 +179,142 @@ namespace System.Web.Configuration {
get { return (string) base [validationKeyProp];}
set {
base[validationKeyProp] = value;
MachineKeySectionUtils.SetValidationKey (value);
SetValidationKey (value);
}
}
protected override ConfigurationPropertyCollection Properties {
get { return properties; }
}
internal static MachineKeySection Config {
get { return WebConfigurationManager.GetSection ("system.web/machineKey") as MachineKeySection; }
}
byte[] decryption_key;
byte[] validation_key;
SymmetricAlgorithm decryption_template;
KeyedHashAlgorithm validation_template;
internal SymmetricAlgorithm GetDecryptionAlgorithm ()
{
// code location to help with unit testing the code
return MachineKeySectionUtils.GetDecryptionAlgorithm (Decryption);
}
// not to be reused outside algorithm and key validation purpose
SymmetricAlgorithm DecryptionTemplate {
get {
if (decryption_template == null)
decryption_template = GetDecryptionAlgorithm ();
return decryption_template;
}
}
internal byte [] GetDecryptionKey ()
{
if (decryption_key == null)
SetDecryptionKey (DecryptionKey);
return decryption_key;
}
void SetDecryptionKey (string key)
{
if ((key == null) || key.StartsWith ("AutoGenerate")) {
decryption_key = AutoGenerate (MachineKeyRegistryStorage.KeyType.Encryption);
} else {
try {
decryption_key = MachineKeySectionUtils.GetBytes (key, key.Length);
DecryptionTemplate.Key = decryption_key;
}
catch {
decryption_key = null;
throw new ArgumentException ("Invalid key length");
}
}
}
internal KeyedHashAlgorithm GetValidationAlgorithm ()
{
// code location to help with unit testing the code
return MachineKeySectionUtils.GetValidationAlgorithm (this);
}
// not to be reused outside algorithm and key validation purpose
KeyedHashAlgorithm ValidationTemplate {
get {
if (validation_template == null)
validation_template = GetValidationAlgorithm ();
return validation_template;
}
}
internal byte [] GetValidationKey ()
{
if (validation_key == null)
SetValidationKey (ValidationKey);
return validation_key;
}
// key can be expended for HMAC - i.e. a small key, e.g. 32 bytes, is still accepted as valid
// the HMAC class already deals with keys larger than what it can use (digested to right size)
void SetValidationKey (string key)
{
if ((key == null) || key.StartsWith ("AutoGenerate")) {
validation_key = AutoGenerate (MachineKeyRegistryStorage.KeyType.Validation);
} else {
try {
validation_key = MachineKeySectionUtils.GetBytes (key, key.Length);
ValidationTemplate.Key = validation_key;
}
catch (CryptographicException) {
// second chance, use the key length that the HMAC really wants
try {
byte[] expanded_key = new byte [ValidationTemplate.Key.Length];
Array.Copy (validation_key, 0, expanded_key, 0, validation_key.Length);
ValidationTemplate.Key = expanded_key;
validation_key = expanded_key;
}
catch {
validation_key = null;
throw new ArgumentException ("Invalid key length");
}
}
}
}
byte[] AutoGenerate (MachineKeyRegistryStorage.KeyType type)
{
byte[] key = null;
#if TARGET_J2EE
{
#else
try {
key = MachineKeyRegistryStorage.Retrieve (type);
// ensure the stored key is usable with the selection algorithm
if (type == MachineKeyRegistryStorage.KeyType.Encryption)
DecryptionTemplate.Key = key;
else if (type == MachineKeyRegistryStorage.KeyType.Validation)
ValidationTemplate.Key = key;
} catch (Exception) {
key = null;
}
#endif
// some algorithms have special needs for key (e.g. length, parity, weak keys...)
// so we better ask them to provide a default key (than to generate/use bad ones)
if (key == null) {
if (type == MachineKeyRegistryStorage.KeyType.Encryption)
key = DecryptionTemplate.Key;
else if (type == MachineKeyRegistryStorage.KeyType.Validation)
key = ValidationTemplate.Key;
#if !TARGET_J2EE
MachineKeyRegistryStorage.Store (key, type);
#endif
}
return key;
}
}
}
@@ -1,187 +0,0 @@
//
// System.Web.Configuration.MachineKeySection
//
// Authors:
// Chris Toshok ([email protected])
//
// (c) Copyright 2005 Novell, Inc (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.ComponentModel;
using System.Configuration;
using System.Security.Cryptography;
#if NET_2_0
namespace System.Web.Configuration {
internal static class MachineKeySectionUtils
{
static byte [] autogenerated;
static byte [] autogenerated_decrypt;
static byte[] decryption_key;
static byte[] decryption_key_192bits;
static byte[] validation_key;
internal static void AutoGenKeys ()
{
#if TARGET_J2EE
{
#else
try {
if (autogenerated == null)
autogenerated = MachineKeyRegistryStorage.Retrieve (
MachineKeyRegistryStorage.KeyType.Validation);
if (autogenerated_decrypt == null)
autogenerated_decrypt = MachineKeyRegistryStorage.Retrieve (
MachineKeyRegistryStorage.KeyType.Encryption);
} catch (Exception) {
#endif
// Fall back to old method
RandomNumberGenerator rng = RandomNumberGenerator.Create ();
if (autogenerated == null) {
autogenerated = new byte [64];
rng.GetBytes (autogenerated);
}
if (autogenerated_decrypt == null) {
autogenerated_decrypt = new byte [64];
rng.GetBytes (autogenerated_decrypt);
}
}
}
static byte ToHexValue (char c, bool high)
{
byte v;
if (c >= '0' && c <= '9')
v = (byte) (c - '0');
else if (c >= 'a' && c <= 'f')
v = (byte) (c - 'a' + 10);
else if (c >= 'A' && c <= 'F')
v = (byte) (c - 'A' + 10);
else
throw new ArgumentException ("Invalid hex character");
if (high)
v <<= 4;
return v;
}
internal static byte [] GetBytes (string key, int len)
{
byte [] result = new byte [len / 2];
for (int i = 0; i < len; i += 2)
result [i / 2] = (byte) (ToHexValue (key [i], true) + ToHexValue (key [i + 1], false));
return result;
}
static byte [] MakeKey (string key, bool decryption) //, out bool isolate)
{
if (key == null || key.StartsWith ("AutoGenerate")){
//isolate = key.IndexOf ("IsolateApps") != 1;
AutoGenKeys ();
return (decryption) ? autogenerated_decrypt : autogenerated;
}
//isolate = false;
int len = key.Length;
if (len < 40 || len > 128 || (len % 2) == 1)
throw new ArgumentException ("Invalid key length");
return GetBytes (key, len);
}
internal static void SetDecryptionKey (string n)
{
decryption_key = MakeKey (n, true); //, out isolate_decryption);
decryption_key_192bits = new byte [24];
int count = 24;
if (decryption_key.Length < 24)
count = decryption_key.Length;
Buffer.BlockCopy (decryption_key, 0, decryption_key_192bits, 0, count);
}
internal static void SetValidationKey (string n)
{
validation_key = MakeKey (n, false); //, out isolate_validation);
}
static MachineKeySection Config {
get { return WebConfigurationManager.GetSection ("system.web/machineKey") as MachineKeySection; }
}
internal static byte [] ValidationKeyBytes ()
{
return ValidationKeyBytes (Config);
}
internal static byte [] ValidationKeyBytes (MachineKeySection section)
{
if (section == null)
throw new ArgumentNullException ("section");
if (validation_key == null)
SetValidationKey (section.ValidationKey);
return validation_key;
}
internal static byte [] DecryptionKeyBytes ()
{
return DecryptionKeyBytes (Config);
}
internal static byte [] DecryptionKeyBytes (MachineKeySection section)
{
if (section == null)
throw new ArgumentNullException ("section");
if (decryption_key == null)
SetDecryptionKey (section.DecryptionKey);
return decryption_key;
}
internal static byte [] DecryptionKey192Bits ()
{
return DecryptionKey192Bits (Config);
}
internal static byte [] DecryptionKey192Bits (MachineKeySection section)
{
if (section == null)
throw new ArgumentNullException ("section");
if (decryption_key_192bits == null)
SetDecryptionKey (section.DecryptionKey);
return decryption_key_192bits;
}
}
}
#endif
@@ -23,11 +23,9 @@
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
// Copyright (C) 2004, 2010 Novell, Inc (http://www.novell.com)
//
using System.Resources;
namespace System.Web.Configuration
{
#if NET_2_0
@@ -40,7 +38,13 @@ namespace System.Web.Configuration
MD5 = 0,
SHA1 = 1,
TripleDES = 2,
AES = 3
AES = 3,
#if NET_4_0
HMACSHA256 = 4,
HMACSHA384 = 5,
HMACSHA512 = 6,
Custom = 7
#endif
}
}
@@ -3,8 +3,9 @@
//
// Authors:
// Chris Toshok ([email protected])
// Sebastien Pouliot <[email protected]>
//
// (c) Copyright 2005 Novell, Inc (http://www.novell.com)
// Copyright (C) 2005, 2010 Novell, Inc (http://www.novell.com)
//
//
@@ -28,7 +29,6 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.ComponentModel;
using System.Configuration;
using System.Globalization;
@@ -39,40 +39,76 @@ namespace System.Web.Configuration {
public sealed class MachineKeyValidationConverter : ConfigurationConverterBase
{
#if NET_4_0
const string InvalidValue = "The enumeration value must be one of the following: SHA1, MD5, 3DES, AES, HMACSHA256, HMACSHA384, HMACSHA512.";
#else
const string InvalidValue = "The enumeration value must be one of the following: SHA1, MD5, 3DES, AES.";
#endif
public MachineKeyValidationConverter ()
{
}
public override object ConvertFrom (ITypeDescriptorContext ctx, CultureInfo ci, object data)
{
if ((string)data == "MD5")
switch ((string) data) {
case "MD5":
return MachineKeyValidation.MD5;
else if ((string)data == "SHA1")
case "SHA1":
return MachineKeyValidation.SHA1;
else if ((string)data == "3DES")
case "3DES":
return MachineKeyValidation.TripleDES;
else if ((string)data == "AES")
case "AES":
return MachineKeyValidation.AES;
else
throw new ArgumentException ("The enumeration value must be one of the following: SHA1, MD5, 3DES, AES.");
#if NET_4_0
case "HMACSHA256":
return MachineKeyValidation.HMACSHA256;
case "HMACSHA384":
return MachineKeyValidation.HMACSHA384;
case "HMACSHA512":
return MachineKeyValidation.HMACSHA512;
#endif
default:
throw new ArgumentException (InvalidValue);
}
}
public override object ConvertTo (ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type)
{
#if NET_4_0
if ((value == null) || (value.GetType () != typeof (MachineKeyValidation)))
throw new ArgumentException (InvalidValue);
#else
if (value.GetType () != typeof (MachineKeyValidation)) {
/* MS throws this exception on an invalid */
throw new FormatException ("invalid validation value");
throw new FormatException (InvalidValue);
}
#endif
MachineKeyValidation v = (MachineKeyValidation)value;
if (v == MachineKeyValidation.MD5) return "MD5";
else if (v == MachineKeyValidation.SHA1) return "SHA1";
else if (v == MachineKeyValidation.TripleDES) return "3DES";
else if (v == MachineKeyValidation.AES) return "AES";
else
switch ((MachineKeyValidation) value) {
case MachineKeyValidation.MD5:
return "MD5";
case MachineKeyValidation.SHA1:
return "SHA1";
case MachineKeyValidation.TripleDES:
return "3DES";
case MachineKeyValidation.AES:
return "AES";
#if NET_4_0
case MachineKeyValidation.HMACSHA256:
return "HMACSHA256";
case MachineKeyValidation.HMACSHA384:
return "HMACSHA384";
case MachineKeyValidation.HMACSHA512:
return "HMACSHA512";
default:
// includes MachineKeyValidation.Custom
throw new ArgumentException (InvalidValue);
#else
default:
/* MS throws this exception on an invalid */
throw new FormatException ("invalid validation value");
throw new FormatException (InvalidValue);
#endif
}
}
}
}
@@ -63,10 +63,13 @@ namespace System.Web.Configuration {
}
const int SAVE_LOCATIONS_CHECK_INTERVAL = 6000; // milliseconds
const int SECTION_CACHE_LOCK_TIMEOUT = 200; // milliseconds
static readonly char[] pathTrimChars = { '/' };
static readonly object suppressAppReloadLock = new object ();
static readonly object saveLocationsCacheLock = new object ();
// See comment for the cacheLock field at top of System.Web.Caching/Cache.cs
static readonly ReaderWriterLockSlim sectionCacheLock;
#if !TARGET_J2EE
@@ -225,14 +228,11 @@ namespace System.Web.Configuration {
static void ConfigurationSaveHandler (_Configuration sender, ConfigurationSaveEventArgs args)
{
bool locked = false;
try {
sectionCacheLock.EnterWriteLock ();
locked = true;
sectionCache.Clear ();
} finally {
if (locked)
sectionCacheLock.ExitWriteLock ();
sectionCacheLock.ExitWriteLock ();
}
lock (suppressAppReloadLock) {
@@ -442,7 +442,6 @@ namespace System.Web.Configuration {
int cacheKey;
bool pathPresent = !String.IsNullOrEmpty (path);
string locationPath = null;
bool locked = false;
if (pathPresent)
locationPath = "location_" + path;
@@ -453,7 +452,6 @@ namespace System.Web.Configuration {
try {
sectionCacheLock.EnterReadLock ();
locked = true;
object o;
if (pathPresent) {
@@ -469,8 +467,7 @@ namespace System.Web.Configuration {
if (sectionCache.TryGetValue (baseCacheKey, out o))
return o;
} finally {
if (locked)
sectionCacheLock.ExitReadLock ();
sectionCacheLock.ExitReadLock ();
}
string cachePath = null;
@@ -589,8 +586,9 @@ namespace System.Web.Configuration {
HttpContext ctx = HttpContext.Current;
HttpRequest req = ctx != null ? ctx.Request : null;
string physPath = req != null ? VirtualPathUtility.AppendTrailingSlash (MapPath (req, path)) : null;
string appDomainPath = HttpRuntime.AppDomainAppPath;
if (physPath != null && !physPath.StartsWith (HttpRuntime.AppDomainAppPath, StringComparison.Ordinal))
if (physPath != null && appDomainPath != null && !physPath.StartsWith (appDomainPath, StringComparison.Ordinal))
inAnotherApp = true;
string dir;
@@ -687,27 +685,31 @@ namespace System.Web.Configuration {
static void AddSectionToCache (int key, object section)
{
object cachedSection;
bool locked = false;
try {
sectionCacheLock.EnterUpgradeableReadLock ();
locked = true;
if (!sectionCacheLock.TryEnterUpgradeableReadLock (SECTION_CACHE_LOCK_TIMEOUT))
return;
if (sectionCache.TryGetValue (key, out cachedSection) && cachedSection != null)
return;
bool innerLocked = false;
try {
sectionCacheLock.EnterWriteLock ();
innerLocked = true;
if (!sectionCacheLock.TryEnterWriteLock (SECTION_CACHE_LOCK_TIMEOUT))
return;
sectionCache.Add (key, section);
} finally {
if (innerLocked)
try {
sectionCacheLock.ExitWriteLock ();
} catch (SynchronizationLockException) {
// we can ignore it here
}
}
} finally {
if (locked)
try {
sectionCacheLock.ExitUpgradeableReadLock ();
} catch (SynchronizationLockException) {
// we can ignore it here
}
}
}
@@ -34,10 +34,10 @@ using System.Reflection;
using System.IO;
using System.Resources;
using System.Collections;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Configuration;
using System.Web.Util;
namespace System.Web.Handlers {
#if SYSTEM_WEB_EXTENSIONS
@@ -58,11 +58,6 @@ namespace System.Web.Handlers {
const char QueryParamSeparator = '&';
static readonly Hashtable _embeddedResources = Hashtable.Synchronized (new Hashtable ());
#if SYSTEM_WEB_EXTENSIONS
static ScriptResourceHandler () {
MachineKeySectionUtils.AutoGenKeys ();
}
#endif
static void InitEmbeddedResourcesUrls (Assembly assembly, Hashtable hashtable)
{
@@ -93,67 +88,25 @@ namespace System.Web.Handlers {
}
#endif
static string GetHexString (byte [] bytes)
{
const int letterPart = 55;
const int numberPart = 48;
char [] result = new char [bytes.Length * 2];
for (int i = 0; i < bytes.Length; i++) {
int tmp = (int) bytes [i];
int second = tmp & 15;
int first = (tmp >> 4) & 15;
result [(i * 2)] = (char) (first > 9 ? letterPart + first : numberPart + first);
result [(i * 2) + 1] = (char) (second > 9 ? letterPart + second : numberPart + second);
}
return new string (result);
}
static byte[] GetEncryptionKey ()
{
#if NET_2_0
return MachineKeySectionUtils.DecryptionKey192Bits ();
#else
MachineKeyConfig config = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig;
return config.DecryptionKey192Bits;
#endif
}
static byte[] GetBytes (string val)
{
#if NET_2_0
return MachineKeySectionUtils.GetBytes (val, val.Length);
#else
return MachineKeyConfig.GetBytes (val, val.Length);
#endif
}
static byte [] init_vector = { 0xD, 0xE, 0xA, 0xD, 0xB, 0xE, 0xE, 0xF };
static string EncryptAssemblyResource (string asmName, string resName)
{
byte[] key = GetEncryptionKey ();
byte[] bytes = Encoding.UTF8.GetBytes (String.Concat (asmName, ";", resName));
string result;
ICryptoTransform encryptor = TripleDES.Create ().CreateEncryptor (key, init_vector);
result = GetHexString (encryptor.TransformFinalBlock (bytes, 0, bytes.Length));
bytes = null;
return String.Concat ("d=", result.ToLowerInvariant ());
bytes = MachineKeySectionUtils.Encrypt (MachineKeySection.Config, bytes);
return Convert.ToBase64String (bytes);
}
static void DecryptAssemblyResource (string val, out string asmName, out string resName)
{
byte[] key = GetEncryptionKey ();
byte[] bytes = GetBytes (val);
byte[] result;
byte[] bytes = Convert.FromBase64String (val);
asmName = null;
resName = null;
ICryptoTransform decryptor = TripleDES.Create ().CreateDecryptor (key, init_vector);
result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
byte[] result = MachineKeySectionUtils.Decrypt (MachineKeySection.Config, bytes);
bytes = null;
// null will be returned if, for any reason, decryption fails
if (result == null)
return;
string data = Encoding.UTF8.GetString (result);
result = null;
@@ -201,7 +154,7 @@ namespace System.Web.Handlers {
if (apath != String.Empty)
atime = String.Concat (QueryParamSeparator, "t=", File.GetLastWriteTimeUtc (apath).Ticks);
#endif
string href = HandlerFileName + "?" + EncryptAssemblyResource (aname, resourceName) + atime + extra;
string href = HandlerFileName + "?d=" + EncryptAssemblyResource (aname, resourceName) + atime + extra;
HttpContext ctx = HttpContext.Current;
if (ctx != null && ctx.Request != null) {
@@ -225,7 +178,13 @@ namespace System.Web.Handlers {
string asmName;
Assembly assembly;
DecryptAssemblyResource (request.QueryString ["d"], out asmName, out resourceName);
// val is URL-decoded, which means every + has been replaced with ' ', we
// need to revert that or the base64 conversion will fail.
string d = request.QueryString ["d"];
if (!String.IsNullOrEmpty (d))
d = d.Replace (' ', '+');
DecryptAssemblyResource (d, out asmName, out resourceName);
if (resourceName == null)
throw new HttpException (404, "No resource name given");
@@ -45,9 +45,6 @@ namespace System.Web.Security
[AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public sealed class FormsAuthentication
{
const int MD5_hash_size = 16;
const int SHA1_hash_size = 20;
static string authConfigPath = "system.web/authentication";
static string machineKeyConfigPath = "system.web/machineKey";
#if TARGET_J2EE
@@ -56,7 +53,6 @@ namespace System.Web.Security
const string Forms_cookiePath = "Forms.cookiePath";
const string Forms_timeout = "Forms.timeout";
const string Forms_protection = "Forms.protection";
const string Forms_init_vector = "Forms.init_vector";
static bool initialized
{
get {
@@ -88,11 +84,6 @@ namespace System.Web.Security
get { return (FormsProtectionEnum) AppDomain.CurrentDomain.GetData (Forms_protection); }
set { AppDomain.CurrentDomain.SetData (Forms_protection, value); }
}
static byte [] init_vector
{
get { return (byte []) AppDomain.CurrentDomain.GetData (Forms_init_vector); }
set { AppDomain.CurrentDomain.SetData (Forms_init_vector, value); }
}
static object locker = new object ();
#else
static bool initialized;
@@ -101,7 +92,6 @@ namespace System.Web.Security
static int timeout;
static FormsProtectionEnum protection;
static object locker = new object ();
static byte [] init_vector; // initialization vector used for 3DES
#endif
#if NET_1_1
#if TARGET_J2EE
@@ -230,25 +220,13 @@ namespace System.Web.Security
password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
break;
case FormsAuthPasswordFormat.SHA1:
password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
break;
}
return String.Compare (password, stored, caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0;
}
#if NET_2_0
static byte [] GetDecryptionKey (MachineKeySection config)
{
return MachineKeySectionUtils.DecryptionKey192Bits (config);
}
#else
static byte [] GetDecryptionKey (MachineKeyConfig config)
{
return config.DecryptionKey192Bits;
}
#endif
static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
{
if (protection == FormsProtectionEnum.None)
@@ -259,59 +237,14 @@ namespace System.Web.Security
#else
MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
#endif
bool all = (protection == FormsProtectionEnum.All);
byte [] result = bytes;
if (all || protection == FormsProtectionEnum.Encryption) {
ICryptoTransform decryptor;
decryptor = TripleDES.Create ().CreateDecryptor (GetDecryptionKey (config), init_vector);
result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
bytes = null;
}
if (all || protection == FormsProtectionEnum.Validation) {
int count;
MachineKeyValidation validationType;
#if NET_2_0
validationType = config.Validation;
#else
validationType = config.ValidationType;
#endif
if (validationType == MachineKeyValidation.MD5)
count = MD5_hash_size;
else
count = SHA1_hash_size; // 3DES and SHA1
#if NET_2_0
byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
#else
byte [] vk = config.ValidationKey;
#endif
byte [] mix = new byte [result.Length - count + vk.Length];
Buffer.BlockCopy (result, 0, mix, 0, result.Length - count);
Buffer.BlockCopy (vk, 0, mix, result.Length - count, vk.Length);
byte [] hash = null;
switch (validationType) {
case MachineKeyValidation.MD5:
hash = MD5.Create ().ComputeHash (mix);
break;
// From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
case MachineKeyValidation.TripleDES:
case MachineKeyValidation.SHA1:
hash = SHA1.Create ().ComputeHash (mix);
break;
}
if (result.Length < count)
throw new ArgumentException ("Error validating ticket (length).", "encryptedTicket");
int i, k;
for (i = result.Length - count, k = 0; k < count; i++, k++) {
if (result [i] != hash [k])
throw new ArgumentException ("Error validating ticket.", "encryptedTicket");
}
byte [] result = null;
if (protection == FormsProtectionEnum.All) {
result = MachineKeySectionUtils.VerifyDecrypt (config, bytes);
} else if (protection == FormsProtectionEnum.Encryption) {
result = MachineKeySectionUtils.Decrypt (config, bytes);
} else if (protection == FormsProtectionEnum.Validation) {
result = MachineKeySectionUtils.Verify (config, bytes);
}
return FormsAuthenticationTicket.FromByteArray (result);
@@ -325,11 +258,8 @@ namespace System.Web.Security
Initialize ();
FormsAuthenticationTicket ticket;
#if NET_2_0
byte [] bytes = MachineKeySectionUtils.GetBytes (encryptedTicket, encryptedTicket.Length);
#else
byte [] bytes = MachineKeyConfig.GetBytes (encryptedTicket, encryptedTicket.Length);
#endif
byte [] bytes = Convert.FromBase64String (encryptedTicket);
try {
ticket = Decrypt2 (bytes);
} catch (Exception) {
@@ -347,57 +277,23 @@ namespace System.Web.Security
Initialize ();
byte [] ticket_bytes = ticket.ToByteArray ();
if (protection == FormsProtectionEnum.None)
return GetHexString (ticket_bytes);
return Convert.ToBase64String (ticket_bytes);
byte [] result = ticket_bytes;
byte [] result = null;
#if NET_2_0
MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
#else
MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
#endif
bool all = (protection == FormsProtectionEnum.All);
if (all || protection == FormsProtectionEnum.Validation) {
byte [] valid_bytes = null;
#if NET_2_0
byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
#else
byte [] vk = config.ValidationKey;
#endif
byte [] mix = new byte [ticket_bytes.Length + vk.Length];
Buffer.BlockCopy (ticket_bytes, 0, mix, 0, ticket_bytes.Length);
Buffer.BlockCopy (vk, 0, mix, result.Length, vk.Length);
switch (
#if NET_2_0
config.Validation
#else
config.ValidationType
#endif
) {
case MachineKeyValidation.MD5:
valid_bytes = MD5.Create ().ComputeHash (mix);
break;
// From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
case MachineKeyValidation.TripleDES:
case MachineKeyValidation.SHA1:
valid_bytes = SHA1.Create ().ComputeHash (mix);
break;
}
int tlen = ticket_bytes.Length;
int vlen = valid_bytes.Length;
result = new byte [tlen + vlen];
Buffer.BlockCopy (ticket_bytes, 0, result, 0, tlen);
Buffer.BlockCopy (valid_bytes, 0, result, tlen, vlen);
if (protection == FormsProtectionEnum.All) {
result = MachineKeySectionUtils.EncryptSign (config, ticket_bytes);
} else if (protection == FormsProtectionEnum.Encryption) {
result = MachineKeySectionUtils.Encrypt (config, ticket_bytes);
} else if (protection == FormsProtectionEnum.Validation) {
result = MachineKeySectionUtils.Sign (config, ticket_bytes);
}
if (all || protection == FormsProtectionEnum.Encryption) {
ICryptoTransform encryptor;
encryptor = TripleDES.Create ().CreateEncryptor (GetDecryptionKey (config), init_vector);
result = encryptor.TransformFinalBlock (result, 0, result.Length);
}
return GetHexString (result);
return Convert.ToBase64String (result);
}
public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
@@ -478,21 +374,6 @@ namespace System.Web.Security
return returnUrl;
}
static string GetHexString (byte [] bytes)
{
const int letterPart = 55;
const int numberPart = 48;
char [] result = new char [bytes.Length * 2];
for (int i = 0; i < bytes.Length; i++) {
int tmp = (int) bytes [i];
int second = tmp & 15;
int first = (tmp >> 4) & 15;
result [(i * 2)] = (char) (first > 9 ? letterPart + first : numberPart + first);
result [(i * 2) + 1] = (char) (second > 9 ? letterPart + second : numberPart + second);
}
return new string (result);
}
static string HashPasswordForStoringInConfigFile (string password, FormsAuthPasswordFormat passwordFormat)
{
if (password == null)
@@ -512,7 +393,7 @@ namespace System.Web.Security
throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
}
return GetHexString (bytes);
return MachineKeySectionUtils.GetHexString (bytes);
}
public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
@@ -580,16 +461,6 @@ namespace System.Web.Security
}
#endif
// IV is 8 bytes long for 3DES
init_vector = new byte [8];
int len = cookieName.Length;
for (int i = 0; i < 8; i++) {
if (i >= len)
break;
init_vector [i] = (byte) cookieName [i];
}
initialized = true;
}
}
@@ -1,5 +1,5 @@
//
// System.Web.Security.MembershipEncryptionHelper
// System.Web.Security.MembershipHelper
//
// Authors:
// Ben Maurer ([email protected])
@@ -27,10 +27,11 @@
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Configuration.Provider;
using System.Security.Cryptography;
using System.Web.Configuration;
using System.Web.Util;
namespace System.Web.Security
{
@@ -49,56 +50,32 @@ namespace System.Web.Security
get { return Membership.Providers; }
}
static SymmetricAlgorithm GetAlg ()
static SymmetricAlgorithm GetAlgorithm ()
{
MachineKeySection section = (MachineKeySection) WebConfigurationManager.GetSection ("system.web/machineKey");
MachineKeySection section = MachineKeySection.Config;
if (section.DecryptionKey.StartsWith ("AutoGenerate"))
throw new ProviderException ("You must explicitly specify a decryption key in the <machineKey> section when using encrypted passwords.");
string alg_type = section.Decryption;
if (alg_type == "Auto")
alg_type = "AES";
SymmetricAlgorithm sa = section.GetDecryptionAlgorithm ();
if (sa == null)
throw new ProviderException (String.Format ("Unsupported decryption attribute '{0}' in <machineKey> configuration section", section.Decryption));
SymmetricAlgorithm alg = null;
if (alg_type == "AES")
alg = Rijndael.Create ();
else if (alg_type == "3DES")
alg = TripleDES.Create ();
else
throw new ProviderException (String.Format ("Unsupported decryption attribute '{0}' in <machineKey> configuration section", alg_type));
alg.Key = MachineKeySectionUtils.DecryptionKey192Bits (section);
return alg;
sa.Key = section.GetDecryptionKey ();
return sa;
}
public byte [] DecryptPassword (byte [] encodedPassword)
{
using (SymmetricAlgorithm alg = GetAlg ()) {
// alg.Key is set in GetAlg based on web.config
// iv is the first part of the encodedPassword
byte [] iv = new byte [alg.IV.Length];
Array.Copy (encodedPassword, 0, iv, 0, iv.Length);
using (ICryptoTransform decryptor = alg.CreateDecryptor (alg.Key, iv)) {
return decryptor.TransformFinalBlock (encodedPassword, iv.Length, encodedPassword.Length - iv.Length);
}
using (SymmetricAlgorithm sa = GetAlgorithm ()) {
return MachineKeySectionUtils.Decrypt (sa, encodedPassword, 0, encodedPassword.Length);
}
}
public byte[] EncryptPassword (byte[] password)
{
using (SymmetricAlgorithm alg = GetAlg ()) {
// alg.Key is set in GetAlg based on web.config
// alg.IV is randomly set (default behavior) and perfect for our needs
byte [] iv = alg.IV;
using (ICryptoTransform encryptor = alg.CreateEncryptor (alg.Key, iv)) {
byte [] encrypted = encryptor.TransformFinalBlock (password, 0, password.Length);
byte [] output = new byte [iv.Length + encrypted.Length];
// note: the IV can be public, however it should not be based on the password
Array.Copy (iv, 0, output, 0, iv.Length);
Array.Copy (encrypted, 0, output, iv.Length, encrypted.Length);
return output;
}
using (SymmetricAlgorithm sa = GetAlgorithm ()) {
return MachineKeySectionUtils.Encrypt (sa, password);
}
}
}
@@ -29,10 +29,10 @@
//
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Security.Principal;
using System.Web.Configuration;
using System.Web.Util;
using System.IO;
using System.Text;
@@ -146,42 +146,16 @@ namespace System.Web.Security {
CookieProtection cookieProtection = RoleManagerConfig.CookieProtection;
if (cookieProtection == CookieProtection.None)
return GetBase64FromBytes (ticket.GetBuffer (), 0, (int) ticket.Position);
if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) {
byte [] hashBytes = null;
byte [] validationBytes = MachineKeySectionUtils.ValidationKeyBytes (MachineConfig);
writer.Write (validationBytes);
switch (MachineConfig.Validation) {
case MachineKeyValidation.MD5:
hashBytes = MD5.Create ().ComputeHash (ticket.GetBuffer (), 0, (int) ticket.Position);
break;
case MachineKeyValidation.TripleDES:
case MachineKeyValidation.SHA1:
hashBytes = SHA1.Create ().ComputeHash (ticket.GetBuffer (), 0, (int) ticket.Position);
break;
}
writer.Seek (-validationBytes.Length, SeekOrigin.Current);
writer.Write (hashBytes);
byte[] ticket_data = ticket.GetBuffer ();
if (cookieProtection == CookieProtection.All) {
ticket_data = MachineKeySectionUtils.EncryptSign (MachineConfig, ticket_data);
} else if (cookieProtection == CookieProtection.Encryption) {
ticket_data = MachineKeySectionUtils.Encrypt (MachineConfig, ticket_data);
} else if (cookieProtection == CookieProtection.Validation) {
ticket_data = MachineKeySectionUtils.Sign (MachineConfig, ticket_data);
}
byte [] ticketBytes = null;
if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) {
ICryptoTransform enc;
enc = TripleDES.Create ().CreateEncryptor (MachineKeySectionUtils.DecryptionKey192Bits (MachineConfig),
InitVector);
ticketBytes = enc.TransformFinalBlock (ticket.GetBuffer (), 0, (int) ticket.Position);
}
if (ticketBytes == null)
return GetBase64FromBytes (ticket.GetBuffer (), 0, (int) ticket.Position);
else
return GetBase64FromBytes (ticketBytes, 0, ticketBytes.Length);
return GetBase64FromBytes (ticket_data, 0, ticket_data.Length);
}
void DecryptTicket (string encryptedTicket)
@@ -193,44 +167,17 @@ namespace System.Web.Security {
byte [] decryptedTicketBytes = null;
CookieProtection cookieProtection = RoleManagerConfig.CookieProtection;
if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) {
ICryptoTransform decryptor;
decryptor = TripleDES.Create ().CreateDecryptor (
MachineKeySectionUtils.DecryptionKey192Bits (MachineConfig),
InitVector);
decryptedTicketBytes = decryptor.TransformFinalBlock (ticketBytes, 0, ticketBytes.Length);
if (cookieProtection == CookieProtection.All) {
decryptedTicketBytes = MachineKeySectionUtils.VerifyDecrypt (MachineConfig, ticketBytes);
} else if (cookieProtection == CookieProtection.Encryption) {
decryptedTicketBytes = MachineKeySectionUtils.Decrypt (MachineConfig, ticketBytes);
} else if (cookieProtection == CookieProtection.Validation) {
decryptedTicketBytes = MachineKeySectionUtils.Verify (MachineConfig, ticketBytes);
}
else
decryptedTicketBytes = ticketBytes;
if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) {
byte [] validationBytes = MachineKeySectionUtils.ValidationKeyBytes (MachineConfig);
byte [] rolesWithValidationBytes = null;
byte [] tmpValidation = null;
int hashSize = (MachineConfig.Validation == MachineKeyValidation.MD5) ? 16 : 20; //md5 is 16 bytes, sha1 is 20 bytes
rolesWithValidationBytes = new byte [decryptedTicketBytes.Length - hashSize + validationBytes.Length];
Buffer.BlockCopy (decryptedTicketBytes, 0, rolesWithValidationBytes, 0, decryptedTicketBytes.Length - hashSize);
Buffer.BlockCopy (validationBytes, 0, rolesWithValidationBytes, decryptedTicketBytes.Length - hashSize, validationBytes.Length);
switch (MachineConfig.Validation) {
case MachineKeyValidation.MD5:
tmpValidation = MD5.Create ().ComputeHash (rolesWithValidationBytes);
break;
case MachineKeyValidation.TripleDES:
case MachineKeyValidation.SHA1:
tmpValidation = SHA1.Create ().ComputeHash (rolesWithValidationBytes);
break;
}
for (int i = 0; i < tmpValidation.Length; i++) {
if (i >= decryptedTicketBytes.Length ||
tmpValidation [i] != decryptedTicketBytes [i + decryptedTicketBytes.Length - hashSize])
throw new HttpException ("ticket validation failed");
}
}
if (decryptedTicketBytes == null)
throw new HttpException ("ticket validation failed");
MemoryStream ticket = new MemoryStream (decryptedTicketBytes);
BinaryReader reader = new BinaryReader (ticket);
@@ -276,11 +223,6 @@ namespace System.Web.Security {
_cachedRoles.Add (r, r);
}
byte [] InitVector
{
get { return new byte [] { 1, 2, 3, 4, 5, 6, 7, 8 }; }
}
public bool CachedListChanged {
get { return _listChanged; }
}
@@ -1048,11 +1048,22 @@ namespace System.Web.Security {
MembershipSection section = (MembershipSection) WebConfigurationManager.GetSection ("system.web/membership");
string alg_type = section.HashAlgorithmType;
if (alg_type == "") {
MachineKeySection keysection = (MachineKeySection) WebConfigurationManager.GetSection ("system.web/machineKey");
alg_type = keysection.Validation.ToString ();
if (alg_type.Length == 0) {
alg_type = MachineKeySection.Config.Validation.ToString ();
#if NET_4_0
// support new (4.0) custom algorithms
if (alg_type.StartsWith ("alg:"))
alg_type = alg_type.Substring (4);
#endif
}
using (HashAlgorithm hash = HashAlgorithm.Create (alg_type)) {
#if NET_4_0
// for compatibility (with 2.0) we'll allow MD5 and SHA1 not to map to HMACMD5 and HMACSHA1
// but that won't work with new (4.0) algorithms, like HMACSHA256|384|512 or custom, won't work without using the key
KeyedHashAlgorithm kha = (hash as KeyedHashAlgorithm);
if (kha != null)
kha.Key = MachineKeySection.Config.GetValidationKey ();
#endif
hash.TransformFinalBlock (hashBytes, 0, hashBytes.Length);
return Convert.ToBase64String (hash.Hash);
}
@@ -1432,7 +1432,7 @@ namespace System.Web.Security
case MembershipPasswordFormat.Hashed:
HMACSHA1 hash = new HMACSHA1();
if (machineKeyIsAutoGenerated)
hash.Key = MachineKeySectionUtils.ValidationKeyBytes ();
hash.Key = MachineKeySection.Config.GetValidationKey ();
else
hash.Key = HexToByte(m_MachineKey.ValidationKey);
encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
@@ -28,15 +28,12 @@
using System.Text;
using System.Security.Cryptography;
using System.Web.Util;
namespace System.Web.SessionState {
internal class SessionId {
static char [] allowed = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B',
'C', 'D', 'E', 'F' };
internal const int IdLength = 24;
const int half_len = IdLength / 2;
static RandomNumberGenerator rng = RandomNumberGenerator.Create ();
@@ -48,25 +45,9 @@ namespace System.Web.SessionState {
lock (rng) {
rng.GetBytes (key);
}
return Encode (key);
return MachineKeySectionUtils.GetHexString (key);
}
internal static string Encode (byte[] key)
{
if (key == null)
throw new ArgumentNullException ("key");
if (key.Length != half_len)
throw new ArgumentException (String.Concat ("key must be ", half_len.ToString (), " bytes long."));
// Just a standard hex conversion
char[] res = new char [IdLength];
for (int i=0; i < half_len; i++) {
int b = key [i];
res [i * 2] = allowed [b >> 4];
res [(i * 2) + 1] = allowed [b & 0xF];
}
return new String (res);
}
#if !NET_2_0
internal static string Lookup (HttpRequest request, bool cookieless)
{
@@ -143,7 +143,7 @@ namespace System.Web.UI.WebControls
int r = new Random ().Next (total_imp);
foreach (Hashtable a in ads) {
if (keywordFilterEmpty && KeywordFilter != (string) a ["Keyword"])
if (!keywordFilterEmpty && KeywordFilter != (string) a ["Keyword"])
continue;
cur_imp += a ["Impressions"] != null ? int.Parse ((string) a ["Impressions"]) : 1;
+14 -2
View File
@@ -821,6 +821,8 @@ namespace System.Web.UI
uniqueID = null;
#if NET_4_0
ClearCachedClientID ();
#else
clientID = null;
#endif
if (!HasControls ())
return;
@@ -1098,8 +1100,18 @@ namespace System.Web.UI
return null;
int separatorIdx = id.IndexOf (IdSeparator, pathOffset);
if (separatorIdx == -1)
return LookForControlByName (id.Substring (pathOffset));
if (separatorIdx == -1) {
if (pathOffset == 0) {
namingContainer = NamingContainer;
if (namingContainer != null) {
Control ctl = namingContainer.FindControl (id);
if (ctl != null)
return ctl;
}
}
return LookForControlByName (pathOffset > 0 ? id.Substring (pathOffset) : id);
}
string idfound = id.Substring (pathOffset, separatorIdx - pathOffset);
namingContainer = LookForControlByName (idfound);
@@ -28,10 +28,11 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Configuration;
using System.IO;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Web.Util;
namespace System.Web.UI {
@@ -46,42 +47,58 @@ namespace System.Web.UI {
osf = new ObjectStateFormatter ();
}
public LosFormatter (bool enableMac, string macKeyModifier) : this (enableMac, Convert.FromBase64String (macKeyModifier))
public LosFormatter (bool enableMac, string macKeyModifier) : this (enableMac, String.IsNullOrEmpty (macKeyModifier) ? null : Encoding.ASCII.GetBytes (macKeyModifier))
{
}
[MonoTODO]
public LosFormatter (bool enableMac, byte[] macKeyModifier)
{
if (enableMac)
osf = new ObjectStateFormatter (macKeyModifier);
else
osf = new ObjectStateFormatter ();
osf = new ObjectStateFormatter ();
if (enableMac && (macKeyModifier != null)) {
SetMacKey (macKeyModifier);
}
}
private void SetMacKey (byte[] macKeyModifier)
{
try {
osf.Section.ValidationKey = MachineKeySectionUtils.GetHexString (macKeyModifier);
}
catch (ArgumentException) {
}
catch (ConfigurationErrorsException) {
// bad key (e.g. size), default key will be used
}
}
public object Deserialize (Stream stream)
{
if (stream == null)
throw new ArgumentNullException ("stream");
#if NET_4_0
using (StreamReader sr = new StreamReader (stream)) {
return Deserialize (sr.ReadToEnd ());
}
#else
long streamLength = -1;
if (stream.CanSeek)
streamLength = stream.Length;
byte [] bytes = new byte [streamLength >= 0 ? streamLength : 2048];
MemoryStream ms = null;
if (streamLength != -1 && (stream is MemoryStream) && stream.Position == 0) {
// We save allocating a new stream and reading in this case.
ms = (MemoryStream) stream;
} else {
byte [] bytes = new byte [streamLength >= 0 ? streamLength : 2048];
ms = new MemoryStream ();
int n;
while ((n = stream.Read (bytes, 0, bytes.Length)) > 0)
ms.Write (bytes, 0, n);
streamLength = ms.Length;
}
string b64 = Encoding.ASCII.GetString (ms.GetBuffer (),
0, (int) streamLength);
return Deserialize (b64);
#endif
}
public object Deserialize (TextReader input)
@@ -109,7 +126,10 @@ namespace System.Web.UI {
{
if (stream == null)
throw new ArgumentNullException ("stream");
#if NET_4_0
if (!stream.CanSeek)
throw new NotSupportedException ();
#endif
string b64 = SerializeToBase64 (value);
byte [] bytes = Encoding.ASCII.GetBytes (b64);
stream.Write (bytes, 0, bytes.Length);
@@ -44,16 +44,16 @@ using System.Text;
using System.Web.UI.WebControls;
using System.Web.Util;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Web.Configuration;
namespace System.Web.UI
{
public sealed class ObjectStateFormatter : IFormatter, IStateFormatter
{
const ushort SERIALIZED_STREAM_MAGIC = 0x01FF;
Page page;
HashAlgorithm algo;
byte [] vkey;
MachineKeySection section;
public ObjectStateFormatter ()
{
@@ -64,65 +64,40 @@ namespace System.Web.UI
this.page = page;
}
internal ObjectStateFormatter (byte [] vkey)
{
this.vkey = vkey;
}
internal bool EnableMac {
bool EnableMac {
get {
if (page == null) {
if (vkey == null)
return false;
return true;
} else
return page.EnableViewStateMac;
return (page == null) ? (section != null) : page.EnableViewStateMac;
}
}
internal HashAlgorithm GetAlgo ()
{
if (algo != null)
return algo;
if (!EnableMac)
return null;
byte [] algoKey;
if (page != null) {
MachineKeySection mconfig = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection ("system.web/machineKey");
algoKey = MachineKeySectionUtils.ValidationKeyBytes (mconfig);
} else
algoKey = vkey;
algo = new HMACSHA1 (algoKey);
return algo;
}
static int ValidateInput (HashAlgorithm algo, byte [] data, int offset, int size)
{
if (algo == null)
throw new HttpException ("Unable to validate data.");
int hash_size = algo.HashSize / 8;
if (size != 0 && size < hash_size)
throw new HttpException ("Unable to validate data.");
int data_length = size - hash_size;
MemoryStream data_stream = new MemoryStream (data, offset, data_length, false, false);
byte [] hash = algo.ComputeHash (data_stream);
for (int i = 0; i < hash_size; i++) {
if (hash [i] != data [data_length + i])
throw new HttpException ("Unable to validate data.");
bool NeedViewStateEncryption {
get {
return (page == null) ? false : page.NeedViewStateEncryption;
}
return data_length;
}
internal MachineKeySection Section {
get {
if (section == null)
section = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection ("system.web/machineKey");
return section;
}
set {
section = value;
}
}
public object Deserialize (Stream inputStream)
{
if (inputStream == null)
throw new ArgumentNullException ("inputStream");
return DeserializeObject (new BinaryReader (inputStream));
BinaryReader reader = new BinaryReader (inputStream);
short magic = reader.ReadInt16 ();
if (magic != SERIALIZED_STREAM_MAGIC)
throw new ArgumentException ("The serialized data is invalid");
return DeserializeObject (reader);
}
public object Deserialize (string inputString)
@@ -132,45 +107,50 @@ namespace System.Web.UI
if (inputString.Length == 0)
throw new ArgumentNullException ("inputString");
byte [] buffer = Convert.FromBase64String (inputString);
int length;
if (buffer == null || (length = buffer.Length) == 0)
byte [] data = Convert.FromBase64String (inputString);
if (data == null || (data.Length) == 0)
throw new ArgumentNullException ("inputString");
if (page != null && EnableMac)
length = ValidateInput (GetAlgo (), buffer, 0, length);
bool isEncrypted = ((int)buffer [--length] == 1)? true : false;
Stream ms = new MemoryStream (buffer, 0, length, false, false);
if (isEncrypted)
ms = new CryptoStream (ms, page.GetCryptoTransform (CryptoStreamMode.Read), CryptoStreamMode.Read);
return Deserialize (ms);
if (NeedViewStateEncryption) {
if (EnableMac) {
data = MachineKeySectionUtils.VerifyDecrypt (Section, data);
} else {
data = MachineKeySectionUtils.Decrypt (Section, data);
}
} else if (EnableMac) {
data = MachineKeySectionUtils.Verify (Section, data);
}
if (data == null)
throw new HttpException ("Unable to validate data.");
using (MemoryStream ms = new MemoryStream (data)) {
return Deserialize (ms);
}
}
public string Serialize (object stateGraph)
{
if (stateGraph == null)
return String.Empty;
MemoryStream ms = new MemoryStream ();
Stream output = ms;
bool needEncryption = page == null ? false : page.NeedViewStateEncryption;
if (needEncryption){
output = new CryptoStream (output, page.GetCryptoTransform (CryptoStreamMode.Write), CryptoStreamMode.Write);
byte[] data = null;
using (MemoryStream ms = new MemoryStream ()) {
Serialize (ms, stateGraph);
data = ms.GetBuffer ();
}
Serialize (output, stateGraph);
ms.WriteByte((byte)(needEncryption? 1 : 0));
#if TRACE
ms.WriteTo (File.OpenWrite (Path.GetTempFileName ()));
#endif
if (EnableMac && ms.Length > 0) {
HashAlgorithm algo = GetAlgo ();
if (algo != null) {
byte [] hash = algo.ComputeHash (ms.GetBuffer (), 0, (int) ms.Length);
ms.Write (hash, 0, hash.Length);
if (NeedViewStateEncryption) {
if (EnableMac) {
data = MachineKeySectionUtils.EncryptSign (Section, data);
} else {
data = MachineKeySectionUtils.Encrypt (Section, data);
}
} else if (EnableMac) {
data = MachineKeySectionUtils.Sign (Section, data);
}
return Convert.ToBase64String (ms.GetBuffer (), 0, (int) ms.Length);
return Convert.ToBase64String (data, 0, data.Length);
}
public void Serialize (Stream outputStream, object stateGraph)
@@ -181,7 +161,10 @@ namespace System.Web.UI
if (stateGraph == null)
throw new ArgumentNullException ("stateGraph");
SerializeValue (new BinaryWriter (outputStream), stateGraph);
BinaryWriter writer = new BinaryWriter (outputStream);
writer.Write (SERIALIZED_STREAM_MAGIC);
SerializeValue (writer, stateGraph);
}
void SerializeValue (BinaryWriter w, object o)
@@ -39,7 +39,6 @@ using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
@@ -2375,74 +2374,6 @@ public partial class Page : TemplateControl, IHttpHandler
controlRegisteredForViewStateEncryption = true;
}
static byte [] AES_IV = null;
static byte [] TripleDES_IV = null;
static object locker = new object ();
static bool isEncryptionInitialized = false;
static void InitializeEncryption ()
{
if (isEncryptionInitialized)
return;
lock (locker) {
if (isEncryptionInitialized)
return;
string iv_string = "0BA48A9E-736D-40f8-954B-B2F62241F282";
AES_IV = new byte [16];
TripleDES_IV = new byte [8];
int i;
for (i = 0; i < AES_IV.Length; i++) {
AES_IV [i] = (byte) iv_string [i];
}
for (i = 0; i < TripleDES_IV.Length; i++) {
TripleDES_IV [i] = (byte) iv_string [i];
}
isEncryptionInitialized = true;
}
}
internal ICryptoTransform GetCryptoTransform (CryptoStreamMode cryptoStreamMode)
{
ICryptoTransform transform = null;
MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
switch (config.Validation) {
case MachineKeyValidation.SHA1:
transform = SHA1.Create ();
break;
case MachineKeyValidation.MD5:
transform = MD5.Create ();
break;
case MachineKeyValidation.AES:
InitializeEncryption ();
if (cryptoStreamMode == CryptoStreamMode.Read){
transform = Rijndael.Create().CreateDecryptor(vk, AES_IV);
} else {
transform = Rijndael.Create().CreateEncryptor(vk, AES_IV);
}
break;
case MachineKeyValidation.TripleDES:
InitializeEncryption ();
if (cryptoStreamMode == CryptoStreamMode.Read){
transform = TripleDES.Create().CreateDecryptor(vk, TripleDES_IV);
} else {
transform = TripleDES.Create().CreateEncryptor(vk, TripleDES_IV);
}
break;
}
return transform;
}
internal bool NeedViewStateEncryption {
get {
return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
@@ -404,6 +404,7 @@ namespace System.Web.UI
value = GetString (atts, "MasterPageFile", masterPage != null ? masterPage.Value : null);
if (!String.IsNullOrEmpty (value)) {
if (!BaseParser.IsExpression (value)) {
value = System.Web.VirtualPathUtility.Combine(BaseVirtualDir, value);
if (!HostingEnvironment.VirtualPathProvider.FileExists (value))
ThrowParseFileNotFound (value);
AddDependency (value);
@@ -432,7 +433,7 @@ namespace System.Web.UI
enable_event_validation = GetBool (atts, "EnableEventValidation", enable_event_validation);
maintainScrollPositionOnPostBack = GetBool (atts, "MaintainScrollPositionOnPostBack", maintainScrollPositionOnPostBack);
if (atts.Contains ("EnableViewState")) {
if (atts.Contains ("EnableViewStateMac")) {
enableViewStateMac = GetBool (atts, "EnableViewStateMac", enableViewStateMac);
enableViewStateMacSet = true;
}
@@ -0,0 +1,315 @@
//
// System.Web.Util.MachineKeySectionUtils
//
// Authors:
// Chris Toshok ([email protected])
// Sebastien Pouliot <[email protected]>
//
// (c) Copyright 2005, 2010 Novell, Inc (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.ComponentModel;
using System.Configuration;
using System.Configuration.Provider;
using System.Security.Cryptography;
using System.Text;
using System.Web.Configuration;
#if NET_2_0
namespace System.Web.Util {
static class MachineKeySectionUtils {
static byte ToHexValue (char c, bool high)
{
byte v;
if (c >= '0' && c <= '9')
v = (byte) (c - '0');
else if (c >= 'a' && c <= 'f')
v = (byte) (c - 'a' + 10);
else if (c >= 'A' && c <= 'F')
v = (byte) (c - 'A' + 10);
else
throw new ArgumentException ("Invalid hex character");
if (high)
v <<= 4;
return v;
}
internal static byte [] GetBytes (string key, int len)
{
byte [] result = new byte [len / 2];
for (int i = 0; i < len; i += 2)
result [i / 2] = (byte) (ToHexValue (key [i], true) + ToHexValue (key [i + 1], false));
return result;
}
static public string GetHexString (byte [] bytes)
{
StringBuilder sb = new StringBuilder (bytes.Length * 2);
int letterPart = 55;
const int numberPart = 48;
for (int i = 0; i < bytes.Length; i++) {
int tmp = (int) bytes [i];
int second = tmp & 15;
int first = (tmp >> 4) & 15;
sb.Append ((char) (first > 9 ? letterPart + first : numberPart + first));
sb.Append ((char) (second > 9 ? letterPart + second : numberPart + second));
}
return sb.ToString ();
}
// decryption="Auto" [Auto | DES | 3DES | AES | alg:algorithm_name]
// http://msdn.microsoft.com/en-us/library/w8h3skw9.aspx
public static SymmetricAlgorithm GetDecryptionAlgorithm (string name)
{
SymmetricAlgorithm sa = null;
switch (name) {
case "AES":
case "Auto":
sa = Rijndael.Create ();
break;
case "DES":
sa = DES.Create ();
break;
case "3DES":
sa = TripleDES.Create ();
break;
default:
#if NET_4_0
if (name.StartsWith ("alg:"))
sa = SymmetricAlgorithm.Create (name.Substring (4));
else
#endif
throw new ConfigurationErrorsException ();
break;
}
return sa;
}
// validation="HMACSHA256" [SHA1 | MD5 | 3DES | AES | HMACSHA256 | HMACSHA384 | HMACSHA512 | alg:algorithm_name]
// [1] http://msdn.microsoft.com/en-us/library/system.web.configuration.machinekeyvalidation.aspx
// [2] http://msdn.microsoft.com/en-us/library/w8h3skw9.aspx
public static KeyedHashAlgorithm GetValidationAlgorithm (MachineKeySection section)
{
KeyedHashAlgorithm kha = null;
switch (section.Validation) {
case MachineKeyValidation.MD5:
kha = new HMACMD5 ();
break;
case MachineKeyValidation.AES: // see link [1] or [2]
case MachineKeyValidation.TripleDES: // see link [2]
case MachineKeyValidation.SHA1:
kha = new HMACSHA1 ();
break;
#if NET_4_0
case MachineKeyValidation.HMACSHA256:
kha = new HMACSHA256 ();
break;
case MachineKeyValidation.HMACSHA384:
kha = new HMACSHA384 ();
break;
case MachineKeyValidation.HMACSHA512:
kha = new HMACSHA512 ();
break;
case MachineKeyValidation.Custom:
// remove the "alg:" from the start of the string
string algo = section.ValidationAlgorithm;
if (algo.StartsWith ("alg:"))
kha = KeyedHashAlgorithm.Create (algo.Substring (4));
break;
#endif
}
return kha;
}
// helpers to ease unit testing of the cryptographic code
#if TEST
static byte [] decryption_key;
static byte [] validation_key;
static SymmetricAlgorithm GetDecryptionAlgorithm (MachineKeySection section)
{
return GetDecryptionAlgorithm (section.Decryption);
}
static byte [] GetDecryptionKey (MachineKeySection section)
{
if (decryption_key == null)
decryption_key = GetDecryptionAlgorithm (section).Key;
return decryption_key;
}
static byte [] GetValidationKey (MachineKeySection section)
{
if (validation_key == null)
validation_key = GetValidationAlgorithm (section).Key;
return validation_key;
}
#else
static SymmetricAlgorithm GetDecryptionAlgorithm (MachineKeySection section)
{
return section.GetDecryptionAlgorithm ();
}
static byte[] GetDecryptionKey (MachineKeySection section)
{
return section.GetDecryptionKey ();
}
static byte [] GetValidationKey (MachineKeySection section)
{
return section.GetValidationKey ();
}
#endif
static public byte [] Decrypt (MachineKeySection section, byte [] encodedData)
{
return Decrypt (section, encodedData, 0, encodedData.Length);
}
static byte [] Decrypt (MachineKeySection section, byte [] encodedData, int offset, int length)
{
using (SymmetricAlgorithm sa = GetDecryptionAlgorithm (section)) {
sa.Key = GetDecryptionKey (section);
return Decrypt (sa, encodedData, offset, length);
}
}
static public byte [] Decrypt (SymmetricAlgorithm alg, byte [] encodedData, int offset, int length)
{
// alg.IV is randomly set (default behavior) and perfect for our needs
// iv is the first part of the encodedPassword
byte [] iv = new byte [alg.IV.Length];
Array.Copy (encodedData, 0, iv, 0, iv.Length);
using (ICryptoTransform decryptor = alg.CreateDecryptor (alg.Key, iv)) {
try {
return decryptor.TransformFinalBlock (encodedData, iv.Length + offset, length - iv.Length);
}
catch (CryptographicException) {
return null;
}
}
}
static public byte [] Encrypt (MachineKeySection section, byte [] data)
{
using (SymmetricAlgorithm sa = GetDecryptionAlgorithm (section)) {
sa.Key = GetDecryptionKey (section);
return Encrypt (sa, data);
}
}
static public byte [] Encrypt (SymmetricAlgorithm alg, byte [] data)
{
// alg.IV is randomly set (default behavior) and perfect for our needs
byte [] iv = alg.IV;
using (ICryptoTransform encryptor = alg.CreateEncryptor (alg.Key, iv)) {
byte [] encrypted = encryptor.TransformFinalBlock (data, 0, data.Length);
byte [] output = new byte [iv.Length + encrypted.Length];
// note: the IV can be public, however it should not be based on the password
Array.Copy (iv, 0, output, 0, iv.Length);
Array.Copy (encrypted, 0, output, iv.Length, encrypted.Length);
return output;
}
}
// in [data]
// return [data][signature]
public static byte [] Sign (MachineKeySection section, byte [] data)
{
return Sign (section, data, 0, data.Length);
}
static byte [] Sign (MachineKeySection section, byte [] data, int offset, int length)
{
using (KeyedHashAlgorithm kha = GetValidationAlgorithm (section)) {
kha.Key = GetValidationKey (section);
byte [] signature = kha.ComputeHash (data, offset, length);
byte [] block = new byte [length + signature.Length];
Array.Copy (data, block, length);
Array.Copy (signature, 0, block, length, signature.Length);
return block;
}
}
public static byte [] Verify (MachineKeySection section, byte [] data)
{
byte [] unsigned_data = null;
bool valid = true;
using (KeyedHashAlgorithm kha = GetValidationAlgorithm (section)) {
kha.Key = GetValidationKey (section);
int signlen = kha.HashSize >> 3; // bits to bytes
byte [] signature = Sign (section, data, 0, data.Length - signlen);
for (int i = 0; i < signature.Length; i++) {
if (signature [i] != data [data.Length - signature.Length + i])
valid = false; // do not return (timing attack)
}
unsigned_data = new byte [data.Length - signlen];
Array.Copy (data, 0, unsigned_data, 0, unsigned_data.Length);
}
return valid ? unsigned_data : null;
}
// do NOT sign then encrypt
public static byte [] EncryptSign (MachineKeySection section, byte [] data)
{
byte [] encdata = Encrypt (section, data);
return Sign (section, encdata);
}
// note: take no shortcut (timing attack) while verifying or decrypting
public static byte [] VerifyDecrypt (MachineKeySection section, byte [] block)
{
bool valid = true;
int signlen;
using (KeyedHashAlgorithm kha = GetValidationAlgorithm (section)) {
kha.Key = GetValidationKey (section);
signlen = kha.HashSize >> 3; // bits to bytes
byte [] signature = Sign (section, block, 0, block.Length - signlen);
for (int i = 0; i < signature.Length; i++) {
if (signature [i] != block [block.Length - signature.Length + i])
valid = false; // do not return (timing attack)
}
}
// whatever the signature continue with decryption
try {
byte [] decdata = Decrypt (section, block, 0, block.Length - signlen);
return valid ? decdata : null;
}
catch {
return null;
}
}
}
}
#endif
+1 -1
View File
@@ -182,7 +182,6 @@ System.Web.Configuration_2.0/IRemoteWebConfigurationHostServer.cs
System.Web.Configuration_2.0/LowerCaseStringConverter.cs
System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs
System.Web.Configuration_2.0/MachineKeySection.cs
System.Web.Configuration_2.0/MachineKeySectionUtils.cs
System.Web.Configuration_2.0/MachineKeyValidation.cs
System.Web.Configuration_2.0/MachineKeyValidationConverter.cs
System.Web.Configuration_2.0/MembershipSection.cs
@@ -1165,6 +1164,7 @@ System.Web.Util/HttpEncoder.cs
System.Web.Util/ICalls.cs
System.Web.Util/IWebObjectFactory.cs
System.Web.Util/IWebPropertyAccessor.cs
System.Web.Util/MachineKeySectionUtils.cs
System.Web.Util/RuntimeHelpers.cs
System.Web.Util/SearchPattern.cs
System.Web.Util/SerializationHelper.cs
@@ -712,6 +712,8 @@ namespace System.Web
static void OnFileChanged(object sender, FileSystemEventArgs args)
{
if (HttpRuntime.DomainUnloading)
return;
string name = args.Name;
bool isConfig = false;
@@ -441,6 +441,11 @@ namespace System.Web
static void RealProcessRequest (object o)
{
if (domainUnloading) {
Console.Error.WriteLine ("Domain is unloading, not processing the request.");
return;
}
HttpWorkerRequest req = (HttpWorkerRequest) o;
bool started_internally = req.StartedInternally;
do {
@@ -584,6 +589,7 @@ namespace System.Web
// TODO: call ReleaseResources
//
domainUnloading = true;
HttpApplicationFactory.DisableWatchers ();
ThreadPool.QueueUserWorkItem (delegate {
try {
ShutdownAppDomain ();
+11 -1
View File
@@ -35,6 +35,7 @@ using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Resources;
using System.Security.Principal;
namespace System.Web {
public class SiteMapNode : IHierarchyData, INavigateUIData, ICloneable {
@@ -177,12 +178,20 @@ namespace System.Web {
public virtual SiteMapNodeCollection ChildNodes {
get {
if (childNodes == null)
if (provider.SecurityTrimmingEnabled) {
IPrincipal p = HttpContext.Current.User;
if ((user == null && user != p) || user != null && user != p) {
user = p;
childNodes = provider.GetChildNodes (this);
}
} else if (childNodes == null) {
childNodes = provider.GetChildNodes (this);
}
return childNodes;
}
set {
CheckWritable ();
user = null;
childNodes = value;
}
}
@@ -439,6 +448,7 @@ namespace System.Web {
string resourceKey;
SiteMapNode parent;
SiteMapNodeCollection childNodes;
IPrincipal user;
#endregion
}
@@ -88,6 +88,7 @@ System.Web.Configuration/CustomErrorCollectionTest.cs
System.Web.Configuration/DeploymentSectionTest.cs
System.Web.Configuration/GlobalizationSectionTest.cs
System.Web.Configuration/HostingEnvironmentSectionTest.cs
System.Web.Configuration/MachineKeySectionTest.cs
System.Web.Configuration/MachineKeyValidationConverterTest.cs
System.Web.Configuration/NullableStringValidatorTest.cs
System.Web.Configuration/ProfilePropertySettingsTest.cs
@@ -549,6 +550,7 @@ System.Web.UI.WebControls/WebControlCas.cs
System.Web.UI.WebControls/XmlCas.cs
System.Web.UI.WebControls/XmlDataSourceCas.cs
System.Web.Util/HttpEncoderTest.cs
System.Web.Util/MachineKeySectionUtilsTest.cs
System.Web.Util/RequestValidatorTest.cs
System.Web.Util/TransactionsCas.cs
System.Web.Util/UrlUtilsTest.cs
@@ -0,0 +1,178 @@
//
// Unit tests for MachineKeySection
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Configuration;
using System.Web.Configuration;
using NUnit.Framework;
namespace MonoTests.System.Web.Configuration {
[TestFixture]
public class MachineKeySectionTest {
[Test]
public void DefaultValues ()
{
MachineKeySection section = new MachineKeySection ();
#if NET_4_0
Assert.AreEqual (MachineKeyCompatibilityMode.Framework20SP1, section.CompatibilityMode, "CompatibilityMode");
#endif
Assert.AreEqual ("Auto", section.Decryption, "Decryption");
Assert.AreEqual ("AutoGenerate,IsolateApps", section.DecryptionKey, "DecryptionKey");
#if NET_4_0
Assert.AreEqual (MachineKeyValidation.HMACSHA256, section.Validation, "Validation");
Assert.AreEqual ("HMACSHA256", section.ValidationAlgorithm, "ValidationAlgorithm");
#else
Assert.AreEqual (MachineKeyValidation.SHA1, section.Validation, "Validation");
#endif
Assert.AreEqual ("AutoGenerate,IsolateApps", section.ValidationKey, "ValidationKey");
}
[Test]
#if NET_4_0
[ExpectedException (typeof (NullReferenceException))]
#else
[ExpectedException (typeof (ConfigurationErrorsException))]
#endif
public void Decryption_Null ()
{
MachineKeySection section = new MachineKeySection ();
section.Decryption = null;
}
[Test]
[ExpectedException (typeof (ConfigurationErrorsException))]
public void Decryption_Empty ()
{
MachineKeySection section = new MachineKeySection ();
section.Decryption = String.Empty;
}
#if NET_4_0
[Test]
public void Decryption_RC2 ()
{
MachineKeySection section = new MachineKeySection ();
Assert.AreEqual ("Auto", section.Decryption, "before");
section.Decryption = "alg:RC2";
Assert.AreEqual ("alg:RC2", section.Decryption, "after");
}
[Test]
public void Decryption_InvalidName ()
{
MachineKeySection section = new MachineKeySection ();
Assert.AreEqual ("Auto", section.Decryption, "before");
section.Decryption = "alg:UnexistingType";
// looks like the problem is found (much) later
Assert.AreEqual ("alg:UnexistingType", section.Decryption, "Decryption");
}
[Test]
public void ValidationAlgorithm_Null ()
{
MachineKeySection section = new MachineKeySection ();
section.ValidationAlgorithm = null;
Assert.AreEqual ("HMACSHA256", section.ValidationAlgorithm, "ValidationAlgorithm");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ValidationAlgorithm_Empty ()
{
MachineKeySection section = new MachineKeySection ();
section.ValidationAlgorithm = String.Empty;
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Validation_Custom ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.Custom;
// cannot be set directly
}
[Test]
public void Validation ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.AES;
Assert.AreEqual ("AES", section.ValidationAlgorithm, "AES");
section.Validation = MachineKeyValidation.HMACSHA256;
Assert.AreEqual ("HMACSHA256", section.ValidationAlgorithm, "HMACSHA256");
section.Validation = MachineKeyValidation.HMACSHA384;
Assert.AreEqual ("HMACSHA384", section.ValidationAlgorithm, "HMACSHA384");
section.Validation = MachineKeyValidation.HMACSHA512;
Assert.AreEqual ("HMACSHA512", section.ValidationAlgorithm, "HMACSHA512");
section.Validation = MachineKeyValidation.MD5;
Assert.AreEqual ("MD5", section.ValidationAlgorithm, "MD5");
section.Validation = MachineKeyValidation.SHA1;
Assert.AreEqual ("SHA1", section.ValidationAlgorithm, "SHA1");
// special case, enum value and algorithm names differs
section.Validation = MachineKeyValidation.TripleDES;
Assert.AreEqual ("3DES", section.ValidationAlgorithm, "3DES");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ValidationAlgorithm ()
{
MachineKeySection section = new MachineKeySection ();
section.ValidationAlgorithm = "HMACRIPEMD160";
// syntax is: alg:something-deriving-from-KeyedHashAlgorithm
}
[Test]
public void ValidationAlgorithm_RIPEMD160 ()
{
MachineKeySection section = new MachineKeySection ();
Assert.AreEqual (MachineKeyValidation.HMACSHA256, section.Validation, "before");
section.ValidationAlgorithm = "alg:HMACRIPEMD160";
Assert.AreEqual (MachineKeyValidation.Custom, section.Validation, "after");
Assert.AreEqual ("alg:HMACRIPEMD160", section.ValidationAlgorithm, "ValidationAlgorithm");
}
[Test]
public void ValidationAlgorithm_InvalidName ()
{
MachineKeySection section = new MachineKeySection ();
Assert.AreEqual (MachineKeyValidation.HMACSHA256, section.Validation, "before");
section.ValidationAlgorithm = "alg:UnexistingType";
// looks like the problem is found (much) later
Assert.AreEqual (MachineKeyValidation.Custom, section.Validation, "after");
Assert.AreEqual ("alg:UnexistingType", section.ValidationAlgorithm, "ValidationAlgorithm");
}
#endif
}
}
@@ -2,10 +2,11 @@
// System.Web.Configuration.MachineKeyValidationConverterTest.cs - Unit tests
// for System.Web.Configuration.MachineKeyValidationConverter.
//
// Author:
// Authors:
// Chris Toshok <[email protected]>
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
// Copyright (C) 2005, 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -35,8 +36,7 @@ using NUnit.Framework;
namespace MonoTests.System.Web.Configuration {
[TestFixture]
public class MachineKeyValidationConverterTest
{
public class MachineKeyValidationConverterTest {
[Test]
public void CanConvertFrom ()
{
@@ -66,10 +66,46 @@ namespace MonoTests.System.Web.Configuration {
object o;
o = cv.ConvertFrom (null, null, "MD5");
Assert.AreEqual (typeof (MachineKeyValidation), o.GetType(), "A1");
Assert.AreEqual ("MD5", o.ToString(), "A2");
Assert.AreEqual (typeof (MachineKeyValidation), o.GetType (), "typeof");
Assert.AreEqual ("MD5", o.ToString (), "MD5");
o = cv.ConvertFrom (null, null, "SHA1");
Assert.AreEqual ("SHA1", o.ToString (), "SHA1");
// 3DES in, TripleDES out
o = cv.ConvertFrom (null, null, "3DES");
Assert.AreEqual ("TripleDES", o.ToString (), "3DES");
o = cv.ConvertFrom (null, null, "AES");
Assert.AreEqual ("AES", o.ToString(), "A3");
Assert.AreEqual ("AES", o.ToString (), "AES");
#if NET_4_0
o = cv.ConvertFrom (null, null, "HMACSHA256");
Assert.AreEqual ("HMACSHA256", o.ToString (), "HMACSHA256");
o = cv.ConvertFrom (null, null, "HMACSHA384");
Assert.AreEqual ("HMACSHA384", o.ToString (), "HMACSHA384");
o = cv.ConvertFrom (null, null, "HMACSHA512");
Assert.AreEqual ("HMACSHA512", o.ToString (), "HMACSHA512");
#endif
}
#if NET_4_0
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ConvertFrom_Custom ()
{
MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
cv.ConvertFrom (null, null, "Custom");
}
#endif
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ConvertFrom_CaseSensitive ()
{
MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
cv.ConvertFrom (null, null, "sha1");
}
[Test]
@@ -91,10 +127,29 @@ namespace MonoTests.System.Web.Configuration {
Assert.AreEqual ("MD5", cv.ConvertTo (null, null, MachineKeyValidation.MD5, typeof (string)), "A1");
Assert.AreEqual ("SHA1", cv.ConvertTo (null, null, MachineKeyValidation.SHA1, typeof (string)), "A2");
Assert.AreEqual ("3DES", cv.ConvertTo (null, null, MachineKeyValidation.TripleDES, typeof (string)), "A3");
#if NET_4_0
Assert.AreEqual ("HMACSHA256", cv.ConvertTo (null, null, MachineKeyValidation.HMACSHA256, typeof (string)), "HMACSHA256");
Assert.AreEqual ("HMACSHA384", cv.ConvertTo (null, null, MachineKeyValidation.HMACSHA384, typeof (string)), "HMACSHA384");
Assert.AreEqual ("HMACSHA512", cv.ConvertTo (null, null, MachineKeyValidation.HMACSHA512, typeof (string)), "HMACSHA512");
#endif
}
#if NET_4_0
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ConvertTo_Custom ()
{
MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
cv.ConvertTo (null, null, MachineKeyValidation.Custom, typeof (string));
}
#endif
[Test]
#if NET_4_0
[ExpectedException (typeof (ArgumentException))]
#else
[ExpectedException (typeof (NullReferenceException))]
#endif
public void ConvertTo_NullError ()
{
MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
@@ -103,7 +158,11 @@ namespace MonoTests.System.Web.Configuration {
}
[Test]
#if NET_4_0
[ExpectedException (typeof (ArgumentException))]
#else
[ExpectedException (typeof (FormatException))]
#endif
public void ConvertTo_TypeError1 ()
{
MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
@@ -120,6 +179,17 @@ namespace MonoTests.System.Web.Configuration {
Assert.AreEqual ("MD5", cv.ConvertTo (null, null, MachineKeyValidation.MD5, null), "A2");
}
[Test]
#if NET_4_0
[ExpectedException (typeof (ArgumentException))]
#else
[ExpectedException (typeof (FormatException))]
#endif
public void ConvertTo_TypeError3 ()
{
MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
cv.ConvertTo (null, null, (MachineKeyValidation)Int32.MinValue, typeof (string));
}
}
}
@@ -87,7 +87,7 @@ namespace MonoTests.System.Web.Security
// ä (C3-A4)
s = Encoding.UTF8.GetString (new byte [2] { 0xC3, 0xA4 });
Assert.AreEqual ("8419B71C87A225A2C70B50486FBEE545", FormsAuthentication.HashPasswordForStoringInConfigFile (s, "MD5"));
Assert.AreEqual ("8419B71C87A225A2C70B50486FBEE545", FormsAuthentication.HashPasswordForStoringInConfigFile (s, "md5"));
}
[Test]
@@ -99,7 +99,7 @@ namespace MonoTests.System.Web.Security
// ä (C3-A4)
s = Encoding.UTF8.GetString (new byte [2] { 0xC3, 0xA4 });
Assert.AreEqual ("961FA22F61A56E19F3F5F8867901AC8CF5E6D11F", FormsAuthentication.HashPasswordForStoringInConfigFile (s, "SHA1"));
Assert.AreEqual ("961FA22F61A56E19F3F5F8867901AC8CF5E6D11F", FormsAuthentication.HashPasswordForStoringInConfigFile (s, "sha1"));
}
[Test]
@@ -129,6 +129,16 @@ namespace MonoTests.System.Web.Security
{
FormsAuthentication.RedirectToLoginPage (String.Empty);
}
[Test]
[Category ("NotWorking")] // works on .net
public void Authenticate ()
{
Assert.IsFalse (FormsAuthentication.Authenticate (null, "password"), "null,string");
Assert.IsFalse (FormsAuthentication.Authenticate ("user", null), "string,null");
// not throwing
Assert.IsFalse (FormsAuthentication.Authenticate ("user", "password"), "string,string");
}
#endif
[TestFixtureTearDown]
@@ -1,6 +1,6 @@
//
// MembershipUserCollectionTest.cs
// - Unit tests for System.Web.Security.MembershipUserCollection
// RolePrincipalTest.cs
// - Unit tests for System.Web.Security.RolePrincipal
//
// Author:
// Sebastien Pouliot <[email protected]>
@@ -1,10 +1,12 @@
//
// LosFormatterTest.cs - Unit tests for System.Web.UI.LosFormatter
//
// Author:
// Authors:
// Gert Driesen <[email protected]>
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2007 Gert Driesen
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -38,6 +40,145 @@ namespace MonoTests.System.Web.UI
[TestFixture]
public class LosFormatterTest
{
static byte [] Empty = new byte [0];
string Serialize (LosFormatter lf, object value)
{
StringWriter sw = new StringWriter ();
lf.Serialize (sw, value);
return sw.ToString ();
}
object Deserialize (LosFormatter lf, string serializedData)
{
return lf.Deserialize (serializedData);
}
string NoKeyRoundTrip (LosFormatter lf, string assertionMessage)
{
string serializedData = Serialize (lf, "Mono");
Assert.AreEqual ("Mono", (string) Deserialize (lf, serializedData), assertionMessage);
return serializedData;
}
[Test]
public void Ctor_BoolByteArray ()
{
LosFormatter lf1 = new LosFormatter (false, (byte []) null);
string expected = NoKeyRoundTrip (lf1, "false, null");
LosFormatter lf2 = new LosFormatter (true, (byte []) null);
Assert.AreEqual (expected, NoKeyRoundTrip (lf2, "true, null"), "2");
LosFormatter lf3 = new LosFormatter (false, Empty);
Assert.AreEqual (expected, NoKeyRoundTrip (lf3, "false, empty"), "3");
// an empty key is still a key - a signature is appended
LosFormatter lf4 = new LosFormatter (true, Empty);
string signed = NoKeyRoundTrip (lf4, "true, empty");
Assert.AreNotEqual (expected, signed, "4");
byte [] data = Convert.FromBase64String (expected);
byte [] signed_data = Convert.FromBase64String (signed);
Assert.IsTrue (BitConverter.ToString (signed_data).StartsWith (BitConverter.ToString (data)), "4 / same data");
#if NET_4_0
// 32 bytes == 256 bits -> match HMACSHA256 as default
Assert.AreEqual (32, signed_data.Length - data.Length, "signature length");
#else
// 20 bytes == 160 bits -> match HMACSHA1 as default
Assert.AreEqual (20, signed_data.Length - data.Length, "signature length");
#endif
}
[Test]
public void Ctor_BoolString ()
{
LosFormatter lf1 = new LosFormatter (false, (string) null);
string expected = NoKeyRoundTrip (lf1, "false, null");
LosFormatter lf2 = new LosFormatter (true, (string) null);
Assert.AreEqual (expected, NoKeyRoundTrip (lf2, "true, null"), "2");
LosFormatter lf3 = new LosFormatter (false, String.Empty);
Assert.AreEqual (expected, NoKeyRoundTrip (lf3, "false, empty"), "3");
// an empty string is not an empty key!
LosFormatter lf4 = new LosFormatter (true, String.Empty);
Assert.AreEqual (expected, NoKeyRoundTrip (lf4, "true, empty"), "4");
byte [] key = new byte [32];
LosFormatter lf5 = new LosFormatter (true, Convert.ToBase64String (key));
string signed = NoKeyRoundTrip (lf5, "true, b64");
Assert.AreNotEqual (expected, signed, "5");
byte [] data = Convert.FromBase64String (expected);
byte [] signed_data = Convert.FromBase64String (signed);
Assert.IsTrue (BitConverter.ToString (signed_data).StartsWith (BitConverter.ToString (data)), "5 / same data");
#if NET_4_0
// 32 bytes == 256 bits -> match HMACSHA256 as default
Assert.AreEqual (32, signed_data.Length - data.Length, "signature length");
#else
// 20 bytes == 160 bits -> match HMACSHA1 as default
Assert.AreEqual (20, signed_data.Length - data.Length, "signature length");
#endif
}
string SerializeOverloads (LosFormatter lf, string message)
{
string stream_ser;
using (MemoryStream ms = new MemoryStream ()) {
lf.Serialize (ms, String.Empty);
stream_ser = Convert.ToBase64String (ms.ToArray ());
}
string tw_ser;
using (MemoryStream ms = new MemoryStream ()) {
using (TextWriter tw = new StreamWriter (ms)) {
lf.Serialize (tw, String.Empty);
}
tw_ser = Convert.ToBase64String (ms.ToArray ());
}
Assert.AreEqual (stream_ser, tw_ser, message);
return stream_ser;
}
[Test]
public void SerializeOverloads ()
{
LosFormatter lf1 = new LosFormatter (false, (string) null);
string r1 = SerializeOverloads (lf1, "false, null");
LosFormatter lf2 = new LosFormatter (true, (string) null);
string r2 = SerializeOverloads (lf2, "true, null");
Assert.AreEqual (r1, r2, "r1-r2");
LosFormatter lf3 = new LosFormatter (false, String.Empty);
string r3 = SerializeOverloads (lf3, "false, empty");
Assert.AreEqual (r2, r3, "r2-r3");
// an empty string is not an empty key!
LosFormatter lf4 = new LosFormatter (true, String.Empty);
string r4 = SerializeOverloads (lf4, "true, empty");
Assert.AreEqual (r3, r4, "r3-r4");
byte [] key = new byte [32];
LosFormatter lf5 = new LosFormatter (true, Convert.ToBase64String (key));
string r5 = SerializeOverloads (lf5, "false, b64");
Assert.AreNotEqual (r4, r5, "r4-r5");
}
#if NET_4_0
[Test]
[ExpectedException (typeof (NotSupportedException))]
public void Deserialize_Stream_NonSeekable ()
{
string s1 = "Hello world";
NonSeekableStream ns = new NonSeekableStream ();
LosFormatter lf = new LosFormatter ();
lf.Serialize (ns, s1);
}
#else
[Test] // bug #411115
public void Deserialize_Stream_NonSeekable ()
{
@@ -49,7 +190,7 @@ namespace MonoTests.System.Web.UI
string s2 = lf.Deserialize (ns) as string;
Assert.AreEqual (s1, s2);
}
#endif
[Test] // bug #324526
public void Serialize ()
{
@@ -30,6 +30,7 @@
#if NET_2_0
using System;
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.UI;
@@ -115,6 +116,20 @@ namespace MonoTests.System.Web.UI
HtmlDiff.AssertAreEqual (originalHtml, renderedHtml, "#A1");
}
#if false
[Test]
public void SerializeOverloads ()
{
ObjectStateFormatter osf = new ObjectStateFormatter ();
string s1 = osf.Serialize (String.Empty);
string s2;
using (MemoryStream ms = new MemoryStream ()) {
osf.Serialize (ms, String.Empty);
s2 = Convert.ToBase64String (ms.ToArray ());
}
Assert.AreEqual (s1, s2, "identical");
}
#endif
}
}
#endif
#endif
@@ -0,0 +1,310 @@
//
// Unit tests for MachineKeySectionUtils (internals)
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Web.Configuration;
using System.Web.Util;
using NUnit.Framework;
namespace MonoTests.System.Web.Util {
[TestFixture]
public class MachineKeySectionUtilsTest {
public void Encrypt_RoundTrip (MachineKeySection section)
{
byte [] data = new byte [14];
byte [] encdata = MachineKeySectionUtils.Encrypt (section, data);
byte [] decdata = MachineKeySectionUtils.Decrypt (section, encdata);
Assert.AreEqual (data, decdata, "roundtrip");
// changing length (missing first byte)
byte [] cut = new byte [encdata.Length - 1];
Array.Copy (encdata, 1, cut, 0, cut.Length);
Assert.IsNull (MachineKeySectionUtils.Decrypt (section, cut), "bad length");
// changing last byte (padding)
byte be = encdata [encdata.Length - 1];
encdata [encdata.Length - 1] ^= (byte) (be + 1);
Assert.IsNull (MachineKeySectionUtils.Decrypt (section, encdata), "bad padding");
}
[Test]
public void Encrypt_RoundTrip_Default ()
{
Encrypt_RoundTrip (new MachineKeySection ());
}
[Test]
public void Encrypt_RoundTrip_AES ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.AES;
Encrypt_RoundTrip (section);
}
[Test]
public void Encrypt_RoundTrip_TripleDES ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.TripleDES;
Encrypt_RoundTrip (section);
}
[Test]
public void Encrypt_RoundTrip_MD5 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.MD5;
Encrypt_RoundTrip (section);
}
[Test]
public void Encrypt_RoundTrip_SHA1 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.SHA1;
Encrypt_RoundTrip (section);
}
#if NET_4_0
[Test]
public void Encrypt_RoundTrip_HMACSHA256 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA256;
EncryptSign_RoundTrip (section);
}
[Test]
public void Encrypt_RoundTrip_HMACSHA384 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA384;
EncryptSign_RoundTrip (section);
}
[Test]
public void Encrypt_RoundTrip_HMACSHA512 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA512;
EncryptSign_RoundTrip (section);
}
[Test]
public void Encrypt_RoundTrip_Custom_RIPEMD160 ()
{
MachineKeySection section = new MachineKeySection ();
section.ValidationAlgorithm = "alg:HMACRIPEMD160";
EncryptSign_RoundTrip (section);
}
#endif
public void EncryptSign_RoundTrip (MachineKeySection section)
{
byte [] data = new byte [14];
byte [] block = MachineKeySectionUtils.EncryptSign (section, data);
byte [] decdata = MachineKeySectionUtils.VerifyDecrypt (section, block);
Assert.AreEqual (data, decdata, "roundtrip");
// changing a byte of the data
byte b0 = block [0];
block [0] ^= b0;
Assert.IsNull (MachineKeySectionUtils.VerifyDecrypt (section, block), "bad data");
block [0] = b0;
// changing a byte of the signature
byte be = block [block.Length - 1];
block [block.Length - 1] ^= (byte) (be + 1);
Assert.IsNull (MachineKeySectionUtils.VerifyDecrypt (section, block), "bad signature");
}
[Test]
public void EncryptSign_RoundTrip_Default ()
{
EncryptSign_RoundTrip (new MachineKeySection ());
}
[Test]
public void EncryptSign_RoundTrip_AES ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.AES;
EncryptSign_RoundTrip (section);
}
[Test]
public void EncryptSign_RoundTrip_TripleDES ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.TripleDES;
EncryptSign_RoundTrip (section);
}
[Test]
public void EncryptSign_RoundTrip_MD5 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.MD5;
EncryptSign_RoundTrip (section);
}
[Test]
public void EncryptSign_RoundTrip_SHA1 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.SHA1;
EncryptSign_RoundTrip (section);
}
#if NET_4_0
[Test]
public void EncryptSign_RoundTrip_HMACSHA256 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA256;
EncryptSign_RoundTrip (section);
}
[Test]
public void EncryptSign_RoundTrip_HMACSHA384 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA384;
EncryptSign_RoundTrip (section);
}
[Test]
public void EncryptSign_RoundTrip_HMACSHA512 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA512;
EncryptSign_RoundTrip (section);
}
[Test]
public void EncryptSign_RoundTrip_Custom_RIPEMD160 ()
{
MachineKeySection section = new MachineKeySection ();
section.ValidationAlgorithm = "alg:HMACRIPEMD160";
EncryptSign_RoundTrip (section);
}
#endif
public void Validation_RoundTrip (MachineKeySection section)
{
byte [] data = new byte [] { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 };
byte [] block = MachineKeySectionUtils.Sign (section, data);
Assert.AreEqual (data, MachineKeySectionUtils.Verify (section, block), "OK");
// changing last byte
for (int i = 0; i < data.Length; i++) {
byte b = block [i];
block [i] ^= 0xFF;
Assert.IsNull (MachineKeySectionUtils.Verify (section, block), "bad-" + i.ToString ());
block [i] = b;
}
}
[Test]
public void Validation_RoundTrip_Default ()
{
Validation_RoundTrip (new MachineKeySection ());
}
[Test]
public void Validation_RoundTrip_AES ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.AES;
Validation_RoundTrip (section);
}
[Test]
public void Validation_RoundTrip_TripleDES ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.TripleDES;
Validation_RoundTrip (section);
}
[Test]
public void Validation_RoundTrip_MD5 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.MD5;
Validation_RoundTrip (section);
}
[Test]
public void Validation_RoundTrip_SHA1 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.SHA1;
Validation_RoundTrip (section);
}
#if NET_4_0
[Test]
public void Validation_RoundTrip_HMACSHA256 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA256;
Validation_RoundTrip (section);
}
[Test]
public void Validation_RoundTrip_HMACSHA384 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA384;
Validation_RoundTrip (section);
}
[Test]
public void Validation_RoundTrip_HMACSHA512 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA512;
Validation_RoundTrip (section);
}
[Test]
public void Validation_RoundTrip_Custom_RIPEMD160 ()
{
MachineKeySection section = new MachineKeySection ();
section.ValidationAlgorithm = "alg:HMACRIPEMD160";
Validation_RoundTrip (section);
}
#endif
[Test]
public void GetHexString ()
{
Assert.AreEqual ("DEADC0DE", MachineKeySectionUtils.GetHexString (new byte [] { 0xde, 0xad, 0xc0, 0xde }), "deadcode");
}
}
}
@@ -13,6 +13,7 @@ System.Web.Caching/OutputCacheProviderCollection.cs
System.Web.Caching/ResponseElement.cs
System.Web.Caching/SubstitutionResponseElement.cs
System.Web.Configuration_2.0/VersionConverter.cs
System.Web.Configuration_2.0/MachineKeyCompatibilityMode.cs
System.Web.Compilation/FolderLevelBuildProviderAppliesTo.cs
System.Web.Compilation/FolderLevelBuildProviderAppliesToAttribute.cs
System.Web.Compilation/RouteUrlExpressionBuilder.cs
+2 -2
View File
@@ -134,10 +134,10 @@ namespace Mono.Http
return null;
lock (cache) {
NtlmSession ds = (NtlmSession) cache [request.RequestUri];
NtlmSession ds = (NtlmSession) cache [request];
if (ds == null) {
ds = new NtlmSession ();
cache.Add (request.RequestUri, ds);
cache.Add (request, ds);
}
return ds.Authenticate (header, webRequest, credentials);
Loaded 100 of 215 files, more files were not shown because too many files have changed in this diff. Show more