Compare commits

...
362 Commits
Author SHA1 Message Date
Lluis Sanchez 64f045b986 [Web Services] Fix regression caused by previous commit
Fixes a regression caused by the implementation of support
for optional parameters. GlobalIndex was not being set
when using SOAP RPC protocol.
2011-05-06 18:44:51 +02:00
Lluis Sanchez d5631ee2a6 [Web.Services] Add support for optional parameters
Non-nullable web service parameters can be made optional by
adding an additional parameter with the same name and a
'Specified' suffix. This was supported when serializing
classes, but not when serializing web service parameters.
This might fix bug 688496.
2011-04-28 20:16:44 +02:00
Veerapuram Varadhan 444eaef7de [bugfix][ado.net odbc]Fixes #676368 - make it thread safe to release
underlying statement handles and check for the validity of the same
before attempting to release them.  Fixes random crashes.
2011-03-22 01:04:40 +05:30
Veerapuram Varadhan 4ac3e74b2c [ado.net]Fixes 672113 - Keep a copy of columns array in constraints than
a reference
2011-03-15 23:35:08 +05:30
Rodrigo Kumpera ad659f3a5c Add missing version string 2011-03-01 18:01:44 +01:00
Geoff Norton 6621fbeb7b Avoid leaking a mach_port every time we query the counters 2011-02-19 12:22:22 -05:00
Miguel de Icaza 43907341f0 Backport support for add support for new PerformanceCounter("Process", "% Processor Time", "<process id as string>" on OS X 2011-02-19 12:05:40 -05:00
Gonzalo Paniagua Javier 9274d95d5f Fix the check for version and PublicKeyToken
When loading an assembly we were comparing Version(0,0,0,0) with null
	and a 0 length PKT with an actual one when those two cases are the
	default.
	Fixes bug #661461.
2011-02-19 10:15:10 -05:00
Rodrigo Kumpera d1c74ad254 Make sure we keep a root for the delegates when calling them.
* method-to-ir.c (mono_emit_method_call_full): Make sure
	we keep a root for delegates when calling them using the
	fast delegate dispatch.

	Fixes #667921
2011-02-17 21:59:43 +01:00
Veerapuram Varadhan 245249106c [bugfix]667855 - Fix handling of oracle raw data types 2011-02-15 01:25:06 +05:30
Gonzalo Paniagua Javier 6a07d34bc8 [HttpListener] UserHostName includes the port. 2011-02-14 14:38:14 -05:00
Gonzalo Paniagua Javier f78f915a4e [HttpWebRequest] EndGetResponse already does this. 2011-02-14 14:38:14 -05:00
Veerapuram Varadhan 04a2d46835 backport of r1012ab0b
Fixes 667236 - Handle numeric types appropriately
2011-02-14 22:13:26 +05:30
Gonzalo Paniagua Javier 0c26f66c0e [HttpWebRequest] Use the timeout in GetResponse()
The timeout was not being used in GetResponse.
	Fixes bug #603794.
2011-02-13 15:02:35 -05:00
Gonzalo Paniagua Javier e8c36a30f7 [HttpWebRequest] Avoid nullref on empty cookie header.
If the Set-Cookie header is empty, the cookie instance is not created.
	Fixes bug #670189.
2011-02-13 14:55:01 -05:00
Gonzalo Paniagua Javier c405df6c89 [HttpListener] Avoid multiple calls to Close()
HttpListenerResponse could be calling HttpConnection.Close() more than
	once.
2011-02-13 07:08:50 -05:00
Gonzalo Paniagua Javier d952408b45 [gzip] Allow partial flush
When Flush() is called explicitly, do a Z_PARTIAL_FLUSH to force gzip
	into giving us whatever is available. Less efficient, but compatible
	with MS.
2011-02-12 00:05:52 -05:00
Gonzalo Paniagua Javier d65f4ad268 [Socket] Fix invalid cast
Fix invalid cast when canceling pending operations due to socket.Close.
2011-02-11 18:39:18 -05:00
Gonzalo Paniagua Javier 9d4b9c5ed8 [HttpWebRequest] Can't ignore erros here 2011-02-10 17:18:02 -05:00
Gonzalo Paniagua Javier 7059614e3a [HttpWebRequest] Error handling for POST/PUT
When we get an error from the server before writing an entire
	unbuffered response, the server might close the connection leading to
	write errors. Ignore those and return the actual HTTP status code from
	the original server error.
2011-02-10 16:59:51 -05:00
Gonzalo Paniagua Javier 29ca124da5 [Socket] Use the queue for generic read/write.
This fixes a bug reported in stackoverflow and mono-list that affects
	Mono 2.8 and Mono 2.6 when using BeginReceive/BeginSend overloads that
	take an ILIst<ArraySegment> argument.
2011-02-10 00:23:18 -05:00
Gonzalo Paniagua Javier a5a6e65de0 [SmtpClient] Don't send empty display name.
If there's no display name, don't send '""'.
	Fixes bug #670475.
2011-02-08 21:03:02 -05:00
Rodrigo Kumpera 3d4ad69752 Align call instructions to make code patching SMP safe.
* mini-x86.c (emit_call): Align call instructions on
	3 mod 4 so the address is 4 bytes aligned and can't span
	two cache lines. This is required for proper SMP support
	as CAS is not atomic across cache lines.

	Fixes one of the crashes due to #667921.
2011-02-02 17:25:44 +01:00
Gonzalo Paniagua Javier f6ad1aa045 Allow forcing HTTP protocol version
If the version is manually set, ignore the version from the service
	point when set.

	Fixes bug #668199.
2011-01-31 10:49:19 -05:00
Lluis Sanchez 0bd026b0b5 Handle possible exceptions thrown by Socket.Close 2011-01-31 16:35:16 +01:00
Gonzalo Paniagua Javier 8d0d7aee01 [HttpListener] Set each cookie in its own header
Send a Set-Cookie header per cookie instead of a Set-Cookie2 with
	multiple cookies.

	Fixes bug #667550.
2011-01-27 15:47:00 -05:00
Marek Habersack cbb12bed7b [asp.net] A bunch of fixes related to the default VirtualPathProvider (needed for Orchard)
* DefaultVirtualDirectory is now more careful when snipping off parts of the path passed to
  its constructor. Before removing the file part it checks whether the file indeed exists.
  Also sealed the class and made it use generic List instead of ArrayList
* HttpRequest does not normalize mapped paths when converting them to absolute ones. This is
  to avoid errors when path like "~/bin/../../file.txt" is passed to MapPath.
* VirtualPathUtility.ToAbsolute overload with normalize parameter really doesn't normalize
  the resulting path now.
2011-01-27 15:37:32 +01:00
Marek Habersack 79fd57e6f1 [machine.config] Added the <system.transactions> section definition 2011-01-27 15:37:25 +01:00
Geoff Norton 653d9b8951 Avoid leaking the vmmap allocated by the kernel for the thread_act_array_t 2011-01-24 15:27:15 -05:00
Marek Habersack 5f3abc4fe4 [asp.net,routing] Fix for bug #651966. Regular expression constraints must be treated as absolute regexps. 2011-01-22 12:45:03 +01:00
Gonzalo Paniagua Javier 209ba3996a [HttpListener] Fix incorrect 411 error
Don't send a 411 for unknown methods without content length.
	No need to assign input_stream until requested.

	Fixes bug #666251.
2011-01-21 23:54:49 -05:00
Bassam Tabbara 06f7dd3fc4 Fix for 666225 2011-01-21 21:00:41 -05:00
Miguel de Icaza fb489fae22 [getline] Fix history search in the cmdline editor 2011-01-21 20:48:58 -05:00
Miguel de Icaza 7231a2e606 [Mono.CSharp] Fix bug where overwriting variables cleared the wrong value
This fixes #641910
2011-01-21 20:20:23 -05:00
Miguel de Icaza bfdc16656d [csharp] repl using statement fix + support for --fatal
Fixes #638585 which kept reporting the same error on the using statements over and over
Added support for the --fatal flag to the REPL
2011-01-21 19:57:11 -05:00
Jb Evain a9d4d0bfa3 [bug] Prevent a GetMethodBody call on a dynamic method. Fixes 665788 2011-01-20 16:46:22 +01:00
Marek Safar b21b6ce374 Remove devirtualization for Type members 2011-01-20 08:37:41 +00:00
Gonzalo Paniagua Javier 9dbbf9af39 Happy new year. 2011-01-18 22:44:37 -05:00
Rodrigo Kumpera ca57ca7215 Make GetGenericTypeDefinitionImpl not init the class.
* icall.c (ves_icall_Type_GetGenericTypeDefinition_impl):
	Don't mono_class_init the type. Fixes test-792.
2011-01-17 22:29:11 +01:00
Rodrigo Kumpera 60c5cea58f MonoType::GetGenericArguments don't need to mono_class_init.
* icall.c (ves_icall_MonoType_GetGenericArguments): Don't
	mono_class_init here since it's not needed.

	Fixes #648725
2011-01-17 22:28:37 +01:00
Rodrigo Kumpera 964beac183 Don't check for brokeness when verifying contraints.
* verify.c (is_valid_generic_instantiation): Don't
	check if any argument is broken during constraint check
	as an instance should be valid, but not realizable, even
	if it has broken arguments.

	Fixes one of the issues with #664612
2011-01-17 20:03:23 +01:00
Marek Habersack c8c0d4c686 [asp.net] (4.0) Validate the form data in Form getter 2011-01-17 14:02:42 +01:00
Marek Habersack 3d01665a68 [asp.net] Make StopRoutingHandler actually stop the routing instead of throwing an exception
Patch from Damir Simunic <[email protected]>, thanks!
2011-01-14 21:39:26 +01:00
Marek Habersack fd0576d5a1 [data-annotations] Added some missing 4.0 members 2011-01-13 20:25:00 +01:00
Marek Habersack 928e3753ab [asp.net] Implemented the 4.0 type, FileLevelMasterPageControlBuilder 2011-01-13 20:24:54 +01:00
Rodrigo Kumpera 01c127b14e Fix array assignability to one of its generic interfaces.
* verify.c: mono_class_is_assignable_from can't handle
	IList<GTD<T>> x GTD[] since GTD[] won't have the right
	iface slots set. This isn't a problem for the runtime
	since GTD[] will never happen as it's an unrealizable type.

	Fixes #663815
2011-01-12 18:10:25 +01:00
Christian Hergert bf9c5ac50f Fix broken g_int_hash/g_int_equal semantics
Both g_int_hash and g_int_equal used the semantics that an
integer is stored directly in the pointer. This is incorrect
as the pointer actually points to a location containing an
integer.

For those wanting the previous (incorrect) implementation,
they should look at g_direct_hash and g_direct_equal.
2011-01-11 19:44:14 -05:00
Marek Habersack 5e6bc44634 [asp.net] Fix for bug #662918. Do not create the HtmlTitle child control for HtmlHead if <title> wasn't used in the page code. 2011-01-11 23:27:47 +01:00
Marek Habersack 0ea0bb6823 [asp.net] Fix for bug #659078. AsyncPostBackTrigger must react to events from sub-controls.
Sub-control IDs can be separated using both '$' and '_'.
2011-01-11 01:57:41 +01:00
Marek Habersack 6ff4f0d165 [asp.net] Fix for bug #659064. UpdatePanel triggers must always be initialized.
UpdatePanel triggers must be initialized not only during the Load event but also when they are
inserted after that point.
2011-01-10 22:27:56 +01:00
Miguel de Icaza 0d6b705d6f [eglib] Add more tests for the g_shell_parse 2011-01-08 23:14:47 -05:00
Miguel de Icaza c7443a190a [eglib] Another bug fix for g_shell_parse
We do not create a new string after a quotation, unless the next
character after a closing quote is a space.   This allows parsing
the string:
	"foo","bar"

As:
	foo,bar

This fixes #655896

1# Explicit paths specified without -i nor -o; assuming --only paths...
2011-01-08 23:14:38 -05:00
Gonzalo Paniagua Javier 029ff9b9f4 Revert 2011-01-06 16:03:07 -05:00
Gonzalo Paniagua Javier ab2dd91b35 [windows] Improve drive search
Windows allows "A", "A:", @"a:\"... as synonyms for the same drive.
	Patch by Vincent Povirk that fixes bug #660911.
2011-01-06 15:52:54 -05:00
Gonzalo Paniagua Javier 7e771a3cdf [Windows] Implement GetDrives.
Drive names are ok, but the type is always 'Fixed'.
	Fixes bug #660907.
2011-01-06 15:42:52 -05:00
Marek Habersack 260054f385 [xml] Out of range errors should be swallowed when doing string -> datetime conversion 2011-01-06 10:38:45 +01:00
Gonzalo Paniagua Javier c019dacc11 [sockets] Fixed reading blocking flag
Calling ioctlsocket() would set the flag...
	Thanks to Thad Thompson for finding this.
2011-01-05 13:38:24 -05:00
Sebastien Pouliot 434ae3d9c2 Backport fix to unit tests
* MachineKeySectionUtilsTest.cs: Avoid random failures
2011-01-05 13:19:40 -05:00
Marek Habersack 4beb7ab705 [wcf] Remove two tests which are invalid for 2.8 2011-01-05 15:04:36 +01:00
Jonathan Pobst 810fad1ed9 Reverse #elif check since 4.0 profile defines NET_2_0. Fixes broken test. 2011-01-05 14:22:07 +01:00
Jonathan Pobst 8199cba724 Fix some broken tests that check for assembly version 2.0.0.0 on the 4.0 profile. 2011-01-05 14:21:50 +01:00
Marek Habersack 7253c44b34 [asp.net] Disabled a racy test 2011-01-05 14:16:27 +01:00
Marek Habersack 61ac96f496 [runtime] Include the al script in temporary installation directory
This is needed as the 4.0 profile calls 'al' (which is defaults to 4.0) and not
'al2' and if Mono older than 2.8 is installed on the machine, 'al' coming from it
will fail to work with the current Mono and thus some tests will fail.

The commit should fix the 300+ failing tests on the build bots.
2011-01-05 12:17:36 +01:00
Jérémie Laval 84570ffb93 Use correct exception when a key is not found in ConcurrentDictionary 2011-01-04 17:39:55 +00:00
Jérémie Laval 1d44ba22a5 Use proper pattern for executing synchronous Task 2011-01-04 17:39:54 +00:00
Jérémie Laval 057a9ed68d Update ThreadLocal to use default(T) for initialization with parameterless ctor following comment on https://connect.microsoft.com/VisualStudio/feedback/details/630350/threadlocal-documentation-and-actual-behavior-mismatch 2011-01-04 17:39:54 +00:00
Marek Habersack 52f09e41d0 [wcf] UriTemplate must trim the first leading slash in the rendered template.
When using BindBy{Name,Position} UriTemplate must remove the the first slash from
the rendered URI. This fixes the 4 failing tests.
2011-01-04 13:58:46 +01:00
Marek Habersack bcdd136b2d [asp.net] The test must always run with the en-US locale 2011-01-04 13:22:59 +01:00
Marek Habersack b30f057280 [system.runtime.caching] Do not test the invalid behavior 2011-01-04 10:23:18 +01:00
Marek Habersack 27a9c4a5d0 [asp.net] Failing tests fixes. 2011-01-04 10:03:41 +01:00
Marek Habersack 5e0ee04d51 [asp.net] Added code to handle local resources copying in the test suite 2011-01-04 08:45:31 +01:00
Marek Habersack 851ab61b7a [asp.net] Don't attempt to use System.Web resources in System.Web.Extensions test build
WebTest is now a partial class and every code outside System.Web that uses it can copy its own
resources in addition to the common ones by implementing the CopyResourcesLocal partial method.
2011-01-04 08:45:20 +01:00
Gonzalo Paniagua Javier a4083fe77d Socket is not connected after error 2011-01-03 21:12:24 -05:00
Zoltan Varga e660bf8aca Implement VBByRefStr marshalling. Fixes #661917. 2011-01-03 22:24:34 +01:00
Marek Habersack 2b3d9079e2 [corlib] Fix for bug #659061. Adjust size of the last group when formatting numbers with group separators.
When the number format includes several groups make sure that the last (leftmost) one is adjusted
so that its width is not larger than the number of remaining characters.
2011-01-03 13:16:30 +01:00
Jb Evain a4d064ed4e [LINQ] Fix non generic AsQueryable issue #661462 2010-12-30 16:24:27 +01:00
Andrew Jorgensen 53d9fc14ad Bump version to 2.8.2 for next bugfix release 2010-12-22 10:28:50 -07:00
Andrew Jorgensen ed14894a33 get-monolite-latest now pulls a versioned archive
In order to ensure that monolite actually works you need to ensure that
the corlib in it has the same version as your runtime.  Monolite
archives are now versioned monolite-MONO_CORLIB_VERSION-DATE.
2010-12-22 10:28:49 -07:00
Geoff Norton 14fdf85cbd Add some missing files needed for windows to the tarball 2010-12-22 12:05:49 -05:00
Gonzalo Paniagua Javier f388ef6c2c Previous patch was wrong. 2010-12-20 21:53:18 -05:00
Gonzalo Paniagua Javier 04961930be [OSX] semaphore_timedwait might return > 0 for errors
Errors, including timeout, are reported with a positive return in
	semaphore_timedwait.
2010-12-20 20:46:39 -05:00
Gonzalo Paniagua Javier e684bbfe57 Mach uses wait_time not abs_time
The time to wait is relative in the Mac functions.
2010-12-17 15:08:29 -05:00
Jérémie Laval 248aeba2c7 Backport ParallelFx changes from master in System.Collections.Concurrent 2010-12-17 15:28:57 +00:00
Jérémie Laval 78604dca27 Backport ParallelFx changes from master in System.Linq.Parallel.QueryNodes 2010-12-17 15:28:56 +00:00
Jérémie Laval 6bae1bb5c3 Backport ParallelFx changes from master in System.Linq.Parallel 2010-12-17 15:28:56 +00:00
Jérémie Laval f7c769111a Backport ParallelFx changes from master in System.Linq 2010-12-17 15:28:55 +00:00
Jérémie Laval 2a332a7951 Backport ParallelFx changes from master in System.Threading.Tasks 2010-12-17 15:28:55 +00:00
Jérémie Laval c330e594e4 Backport ParallelFx changes from master in corlib unit tests 2010-12-17 15:28:54 +00:00
Jérémie Laval 0f1268df35 Backport ParallelFx changes from master in System.Collections.Concurrent 2010-12-17 15:28:54 +00:00
Jérémie Laval 49310de53e Backport ParallelFx changes from master in System.Threading.Tasks 2010-12-17 11:17:32 +00:00
Jérémie Laval a19d806bb1 Backport ParallelFx changes from master in System.Threading 2010-12-17 11:14:18 +00:00
Gonzalo Paniagua Javier ddbc3e479b [ThreadPool] Reset the abort state when unloading a domain
Properly reset the abort state of threadpool threads that processed
	domain unloading or were running in a domain that was being unloaded.

	Thanks go to Kumpera for finding this out.
2010-12-17 00:36:09 -05:00
Miguel de Icaza 2aa5af6c2f [winforms] revert patch, it regresses the test suite: https://github.com/mono/mono/commit/8334fe3a56c978ffe7f8cb199536f9b3234afdbe 2010-12-16 12:56:37 -05:00
Jonathan Pryor 1fe06b40e8 Don't load app.config when we're processing app.config
Fixes #605033.

'cause stack overflow is back, mkay?

  at System.Diagnostics.TraceImpl.InitOnce () <0x0005b>
  at System.Diagnostics.TraceImpl.get_IndentLevel () <0x0000b>
  at System.Diagnostics.TraceListenerCollection.InitializeListener (System.Diagnostics.TraceListener) <0x0000f>
  at System.Diagnostics.TraceListenerCollection.Add (System.Diagnostics.TraceListener) <0x00017>
  at System.Diagnostics.TraceListenerCollection..ctor (bool) <0x0007f>
  at System.Diagnostics.TraceListenerCollection..ctor () <0x00013>
  at System.Diagnostics.DiagnosticsConfigurationHandler.GetSharedListeners (System.Collections.IDictionary) <0x00083>
  at System.Diagnostics.DiagnosticsConfigurationHandler.Create (object,object,System.Xml.XmlNode) <0x003cf>
  at System.Configuration.ConfigurationSection.GetRuntimeObject () <0x0033d>
  at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection (string) <0x00041>
  at System.Configuration.ConfigurationManager.GetSection (string) <0x00030>
  at System.Configuration.ConfigurationSettings.GetConfig (string) <0x0000f>
  at System.Diagnostics.DiagnosticsConfiguration.get_Settings () <0x00043>
  at System.Diagnostics.TraceImpl.InitOnce () <0x0005b>

Thus, when we're getting the <sharedListeners/> element, we shouldn't call
the TraceListenerCollection default constructor, as that will attempt to add
the DefaultTraceListener (which isn't needed anyway, as the
DefaultTraceListener is explicitly added by TraceImplSettings).
2010-12-15 15:26:53 -05:00
Jb Evain b78eb3caad Make sure AppdDomain.PermissionSet doesn't return null 2010-12-15 18:40:01 +01:00
Marek Safar c84551fd73 [656150] Fix repl recovery after invalid expression. 2010-12-15 13:31:08 +00:00
Marek Safar 25b0805e20 [641146] Implemented IStructuralComparable.CompareTo
shana: Backported (a57254256) to support F#
2010-12-15 02:54:06 +00:00
Zoltan Varga a3a68d4083 Fix a merge problem introduced by e10b6ddad7. 2010-12-15 03:48:27 +01:00
Marek Habersack 776a60617a [asp.net] Fix for bug #467221. Properly match location sub-paths for security trimming
When security trimming is requested for sub-path of a location specified in the config file,
make sure that we match such a request to its parent location.

Based on patch from Mike Morano <[email protected]>, thanks!
2010-12-14 10:15:37 +01:00
Gonzalo Paniagua Javier 095322953b Don't throw in EndReceive/EndSend + out error
The overloads of EndReceive and EndSend that have an out SocketError
	parameter do not throw.

	Patch by Sven Groot that fixes bug #659056.
2010-12-13 18:52:59 -05:00
Lluis Sanchez 3a5f48bced Fix several issues in the code generator
Issues include: casts not being properly generated for nullable
types, missing cast when the type of a member does not match
the forced serialization type, and incorrect code generated
for handling [XmlText] members.
2010-12-13 17:48:34 +01:00
Lluis Sanchez b598aee4dc Fix code generation issue with nested generic types
The type argument list for generic nested types include
all types arguments for the whole declaring type chain.
When generating the C# name of the class, each type
argument has to be assigned to the correct class in
the chain.
2010-12-13 17:48:09 +01:00
Lluis Sanchez 98ff1ec075 Throw correct exceptions when using generated serializer
Invocations to generated serializers are done through
reflection, so exceptions are masked by TargetInvocationException.
The inner exception has to be rethrown so that the client
code gets the correct exception.
2010-12-13 17:47:32 +01:00
vvaradhan c5f5d263d7 Merge branch 'mono-2-8' of github.com:mono/mono into mono-2-8 2010-12-13 21:19:13 +05:30
vvaradhan 4d06d66e19 ** Fixes #582732
* DataColumn.cs (Clone): Deep copy the ExtendedProperties
       collection.
       * XmlSchemaDataImporter.cs: Support import of extended
       properties.
       * XmlSchemaWriter.cs: Fix exception by writing the extended
       properties before simpletype element.
2010-12-13 21:08:36 +05:30
Marek Habersack 487e9a1f0a [asp.net] Test suite configuration updates for 4.0
When running the tests on the 4.0 profile, the configuration must no longer include
the System.Web.Extensions section declarations as they are merged with machine.config right now.
2010-12-13 14:42:03 +01:00
Jérémie Laval c9316a0bcc Increment Count even on single-processor in SpinWait. Fix #624849. 2010-12-13 13:40:38 +00:00
Marek Habersack 3a40dfbb24 [asp.net] Fix for bug #658278. Panels render children only when parent is present and ChildrenAsTriggers is enabled
Fix from Avior Computing <[email protected]>, thanks!
2010-12-13 13:06:50 +01:00
Marek Habersack 2ff17cce11 [asp.net] Part of fix for bug #649546. Better handling of nested UpdatePanels
Nested update panels don't ever output a script block in RenderChildren, they write to the passed
HtmlTextWriter instead.
2010-12-13 13:06:41 +01:00
Marek Habersack ff738c616f [asp.net] .NET 4.0 declares the <system.web.extensions> section in machine.config 2010-12-13 09:03:26 +01:00
Marek Habersack 6f76bef3f9 [asp.net] Implmeneted the System.Web.Configuration.ScriptingRoleServiceSection type 2010-12-13 09:03:07 +01:00
Tom Hindle d17d1101a4 [winforms] Fix ContextMenuStrip vertical position can be wrong.
Fixes #658945

This can lead to the top of the context menu being off the screen.
This only happens with context menus with lots of items.
2010-12-10 19:49:54 -05:00
Tom Hindle 7954648dbe [winforms] WM_SETFOCUS is sent before Keyboard Focus is changed.
Switches Keyboard focus so that it occurs before WM_SETFOCUS is sent.

This means that the wrong keyboard im is selected while process winform events
caused by WM_SETFOCUS.

Attaching patch that changes this so that keyboard im is focused before
WM_SETFOCUS is sent.

Fixes: #557277
2010-12-10 19:42:29 -05:00
Tom Hindle 96bc53e927 [winforms] Add modal support to Forms
This fixes 614850 "Modal dialogs should prevent closing their parent windows."
2010-12-10 19:32:03 -05:00
Tom Hindle d5c12cf568 [winforms] DataGridView.cs : Made MoveCurrentCell not attempt access Column index -1.
Fixes #516960
2010-12-10 19:26:33 -05:00
Tom Hindle 92dd07a485 [winforms,fix] Prevent Clipboard APIs from running any Idle handlers
Fixes: 641756

This prevents idle methods to be invoked when calling the Clipboard
APIs on X11, which is not the expected behavior.

The description from the bug report is:

Mono X11 Clipboard handling calls UpdateMessageQueue, which has the side affect
of potentially calling Idle handlers.

If any Idle handlers call Clipboard functions, this can cause idle handler
reentry.

See attached test case.

Incidentally removing the reentry check from the idle handler will actually
cause mono to segfault.

I will attach a patch shortly which fixes this by overloading
UpdateMessageQueue to allow Clipboard methods to call a version that doesn't
run idle processing.
2010-12-10 19:20:36 -05:00
Andy Hume 0d7102d039 [fix, winforms] Fix the ProgressBar speed in Marquee situations
This issue was identified as:

 Marquee speed is very weird, changing between very very fast and very very
very very fast, and in inverse to the speed setting?

In https://bugzilla.novell.com/show_bug.cgi?id=440220

Also fixes this bug which was the test case isolated:

https://bugzilla.novell.com/show_bug.cgi?id=655797
2010-12-10 19:04:24 -05:00
Jackson Harper fa30544d3c Parse RequestPathInvalidCharacters properly. Fixes urls with commas in them.
This fixes bug #654476. https://bugzilla.novell.com/show_bug.cgi?id=654476

These values are stored as a comma separated list, not just a list
of chars. So we need to parse out all the values, ignoring whitespace.
(cherry picked from commit ea5741998a)
2010-12-10 17:31:07 -05:00
Zoltan Varga b44bd65f75 Fix handling of gshared methods declared in generic superclasses of nongeneric classes in stack traces. Fixes #658645. 2010-12-10 16:13:26 +01:00
Gonzalo Paniagua Javier f7d12c2b05 Get system.web/httpRuntime only once
Get that section only once and keep it in HttpRuntime.
2010-12-09 19:02:00 -05:00
Gonzalo Paniagua Javier 7288206bdf InitOnce does not throw 2010-12-08 14:37:46 -05:00
Gonzalo Paniagua Javier bb874a687b Fixes problem with exceptions on init
Multiple threads might be waiting on the lock and the modules get
	loaded and initialized multiple times, leading to an error. This patch
	fixes it and always returns the right initialization exception, if any,
	to the client.
2010-12-08 14:12:02 -05:00
Gonzalo Paniagua Javier 5df3e05e0e Delete end local endpoint when stopping the server
Fixes bug #647204.
2010-12-07 17:05:04 -05:00
vvaradhan 6fdae5d654 ** Fixes #456234 - Patch by [email protected]
* OdbcDataReader.cs (GetValue): Handle SQL_NO_TOTAL sanely and
	use corresponding Decoder.GetChars instead of Encoding.GetString.
2010-12-07 22:59:47 +05:30
Guillaume Pouillet bdabf74a88 Fix bug in BlockingCollection<T>.TryTake Add corresponding unit test 2010-12-07 11:41:19 +00:00
Gonzalo Paniagua Javier fd42bcd36c Fix Process.HasExited regression
When we have a pseudo handle, we can at least check whether the process
	is alive or not, instead of always returning FALSE.

	Fixes bug #650979.
2010-12-06 19:56:12 -05:00
Joe Dluzen b26531ebba Fix for #656021. 2010-12-04 02:05:53 -05:00
Zoltan Varga 2a3bedbf8c Fix a backport problem. 2010-12-02 07:24:09 +01:00
Jérémie Laval e61d54040f [ReaderWriterLockSlim] Fix for #656353. Add corresponding unit test.
When in SupportsRecursion mode, a test was not including proper state check for short-circuiting.

Conflicts:

	mcs/class/System.Core/System.Threading/ReaderWriterLockSlim.cs
2010-12-01 14:43:58 +00:00
Zoltan Varga 870f4582ab Export mono_xdebug_flush (). 2010-12-01 14:39:38 +01:00
Zoltan Varga 06c93cd2cf Emit write barriers for multi-dim Array.Set (). Fixes #656128. 2010-12-01 05:53:26 +01:00
Daniel Sell 5da7907603 Fix Expression.MakeBinary so it can return ArrayIndex nodes 2010-11-29 22:57:50 +01:00
Zoltan Varga 68f5d0926d Add support for the internal boehm-gc on OpenBSD 2010-11-29 17:09:07 +01:00
Robert Nagy c9f58f07fe Add support for the internal boehm-gc on OpenBSD 2010-11-29 17:06:28 +01:00
Marek Safar dc671b1b4a [655766] Encode string null attribute argument 2010-11-26 10:29:43 +00:00
Jérémie Laval 44f95d3311 Fix ReaderWriterLockSlim Exit methods in SupportsRecursion mode and add corresponding unit tests 2010-11-26 10:20:13 +00:00
Zoltan Varga e10b6ddad7 Fix stack alignment when resuming from a signal handler in the soft debugger. Fixes #647464. 2010-11-25 23:33:25 +01:00
Rodrigo Kumpera 65292a69c8 Handle invalid instantiation of generic methods.
* verify.c: Add new function to internal verifier API to check
	method instantiations.

	* reflection.c (mono_reflection_bind_generic_method_parameters):
	Check the instantiation before returning it.

	Fixes #655847
2010-11-25 14:43:06 -02:00
Rodrigo Kumpera 7890fd60c5 Fix corlib testsuite crash.
* icall.c (ves_icall_Type_MakeGenericType): We can inflate
	into the gtd and the verifier function is not able to handle
	it.
2010-11-25 14:43:06 -02:00
Rodrigo Kumpera d8096023f2 Check generic instantions for constraint violations.
* class.c (mono_class_init): Check instantiations of generic
	instances.

	* icall.c (ves_icall_Type_MakeGenericType): Ditto.

	* verify.c: Add mono_verifier_class_is_valid_generic_instantiation
	to the internal API so generic instances can be checked.

	Fixes #654136
2010-11-25 14:43:06 -02:00
Gonzalo Paniagua Javier 79d5f2e009 Fix the moonlight build 2010-11-24 01:21:03 -05:00
Gonzalo Paniagua Javier 7628c67ef8 [Sockets] Support Remote/LocalEndPoint for AF_UNIX
We were not handling correctly the AF_UNIX family when getting the
	socket name or the peer name.

	Fixes bug #655637.
2010-11-24 00:49:29 -05:00
Geoff Norton b6b047eed9 Fix a potential NRE when using bitmap contexts 2010-11-22 11:14:16 -05:00
Gonzalo Paniagua Javier 4cb8b2e6f3 [File.ReadLines] Dispose the StreamReader in the right place.
The StreamReader was being disposed immediately after the call to
	ReadLines() causing the enumerator to fails.

	Fixes bug #649464.
2010-11-21 15:14:51 -05:00
Zoltan Varga 237cee6dc6 Link the iomap profiler against eglib. Fixes #627889. 2010-11-21 05:29:58 +01:00
Zoltan Varga e1d8ee37b1 Increase maximum size of ppc prolog. Fixes #654460. 2010-11-20 03:14:03 +01:00
Zoltan Varga 84bf2fd468 Add support for the processorArchitecture field in assembly names. Fixes #655096. 2010-11-20 03:10:41 +01:00
Gonzalo Paniagua Javier d945da7eeb Web service help fix
Generate the wsdl document with UTF8 encoding.
2010-11-19 12:48:31 -05:00
Zoltan Varga 85b7cae565 Fix the previous arm EH change. 2010-11-19 17:19:42 +01:00
Zoltan Varga 26ee955aca Load dependent assemblies of an aot image from the assembly's basedir. Fixes #654850. 2010-11-19 17:09:00 +01:00
Zoltan Varga b509f42a7e Set the thumb bit in the CPSR when resuming from a signal handler to a thumb function on arm. 2010-11-19 01:39:23 +01:00
Zoltan Varga 717982c7cf Fix the thumb build. 2010-11-19 00:58:10 +01:00
Gonzalo Paniagua Javier 931e044108 Hush cross-compilation warnings 2010-11-18 18:15:15 -05:00
Gonzalo Paniagua Javier e171f51df0 Build fixing 2010-11-18 17:40:09 -05:00
Gonzalo Paniagua Javier d326d51789 Don't throw when unable to write autogen keys
It is possible that the user running the ASP.NET application does not
	have permission to write to the registry. In this case, the auto
	generated keys will be created on every application start.
2010-11-18 17:36:09 -05:00
Zoltan Varga ffd50c266e Fix an assert in single stepping if an IL offset doesn't correspond to a seq point. Fixes #654694. 2010-11-18 21:13:36 +01:00
Zoltan Varga 63c0a5d6d2 Don't allow EventType.Breakpoint in vm.EnableEvents (). 2010-11-18 21:13:22 +01:00
Zoltan Varga 06205b5084 Fix infinite recursion in the CompareExchange aot code. 2010-11-18 18:59:22 +01:00
Alex Fort 1bbc6a8a1b Add support for the CancelKeyPress event on Windows
Adds a call to the Win32 function SetConsoleCtrlHandler for Windows,
which adds the DoWindowsConsoleCancelEvent wrapper for
DoConsoleCancelEvent to the Ctrl-C handler when an event handler is
added, and removes the handler once all event handlers are removed.
2010-11-18 12:33:55 -05:00
Gonzalo Paniagua Javier d106cf2a5a Fix g_dir_open et al for windows.
This was using the *A functiones instead of the *W ones and passing in UTF16.
	It was also opening and closing the directory just to check that it was
	there and then open it again !?.

	Fixes bug #645189.
2010-11-18 12:31:06 -05:00
Gonzalo Paniagua Javier ded054284e Updated remove_wsq.
remove_wsq() should only clean up the queue when the runtime is shutting down.
	In any other case, removing a queue that still contains work items is an error.
2010-11-18 01:15:22 -05:00
Gonzalo Paniagua Javier 4ed8473ce9 Fix typo.
Thanks Rolf debugging this.
2010-11-18 01:15:22 -05:00
Gonzalo Paniagua Javier e30361a696 Wrong return value in mono_sem_timedwait()
The return value of mono_sem_timedwait() with a timeout 0 was incorrect
	(0=failure, !0=success instead of 0=success). This worked on
	non-Windows platforms because the only call with timeout 0 was
	expecting the incorrect return value, but it made the mono threadpool
	in Windows fail.

	Fixes bug #653928.
2010-11-18 01:15:21 -05:00
Gonzalo Paniagua Javier 6b51a1df2f User name and home directory initialization
User name and home directory are initialized at the same time from the
	information in /etc/passwd if possible.
2010-11-18 01:15:21 -05:00
Gonzalo Paniagua Javier 3aed7ab3c9 Get the user name from the UID not the USER env
Fixes bug #653564.
2010-11-18 01:15:21 -05:00
Zoltan Varga 9d534c9413 Pop the arguments to the throw trampoline from the stack on x86. Fixes #654322. 2010-11-18 03:46:54 +01:00
Marek Habersack adb66a513a [asp.net] Part of fix for bug #653013. AsyncPostBackTrigger must react to events generated by the trigger control's children. 2010-11-17 14:22:32 +01:00
Marek Habersack c11559c7ef [asp.net] Part of fix for bug #653013. StateManagedCollection must perform a full clear in LoadViewState
If all the items in the collections were saved to the view state, the collection must call the Clear ()
method in order for the OnClear and OnClearComplete methods to be invoked. Telerik RadComboBox depends
on it to remove dynamically added entries before they are recreated when the view state is loaded by
the control.
2010-11-17 14:22:21 +01:00
Zoltan Varga 32e235d68b Bump the max size of the arm prolog to prevent overflows. 2010-11-16 23:30:41 +01:00
Zoltan Varga ba625becd6 Remove a debug printf. 2010-11-16 22:43:32 +01:00
Zoltan Varga 5588a6f078 Special case Interlocked.CompareExchange<T> in the aot runtime. 2010-11-16 20:45:32 +01:00
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
427 changed files with 12689 additions and 4605 deletions

No files matched your search

+2 -1
View File
@@ -37,7 +37,8 @@ DISTCLEANFILES= mono-uninstalled.pc
# building with monolite
mcslib = $(mcs_topdir)/class/lib
monolite = $(mcslib)/monolite
monolite_url = http://mono.ximian.com/daily/monolite-latest.tar.gz
mono_corlib_version = $(shell sed -n "s/\#define MONO_CORLIB_VERSION //p" $(srcdir)/mono/metadata/appdomain.c)
monolite_url = http://mono.ximian.com/daily/monolite-$(mono_corlib_version)-latest.tar.gz
.PHONY: get-monolite-latest
get-monolite-latest:
-rm -fr $(mcslib)/monolite-*
+1 -1
View File
@@ -6,7 +6,7 @@ AC_CANONICAL_SYSTEM
m4_ifdef([_A][M_PROG_TAR],[_A][M_SET_OPTION([tar-ustar])])
AM_CONFIG_HEADER(config.h)
AM_INIT_AUTOMAKE(mono,2.8.1)
AM_INIT_AUTOMAKE(mono,2.8.2)
AM_MAINTAINER_MODE
API_VER=2.0
+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"/>
+6 -1
View File
@@ -474,10 +474,15 @@ private CodeDomProvider GetProvider(string langId)
//
// Document generation
//
class UTF8StringWriter : StringWriter {
public override Encoding Encoding {
get { return Encoding.UTF8; }
}
}
string GenerateDocument ()
{
StringWriter sw = new StringWriter ();
UTF8StringWriter sw = new UTF8StringWriter ();
if (CurrentDocType == "wsdl")
descriptions [CurrentDocInd].Write (sw);
+4
View File
@@ -84,6 +84,10 @@
<section name="serviceHostingEnvironment" type="System.ServiceModel.Configuration.ServiceHostingEnvironmentSection, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="services" type="System.ServiceModel.Configuration.ServicesSection, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</sectionGroup>
<sectionGroup name="system.transactions" type="System.Transactions.Configuration.TransactionsSectionGroup, System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null">
<section name="defaultSettings" type="System.Transactions.Configuration.DefaultSettingsSection, System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null"/>
<section name="machineSettings" type="System.Transactions.Configuration.MachineSettingsSection, System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null" allowDefinition="MachineOnly" allowExeDefinition="MachineOnly"/>
</sectionGroup>
<section name="system.webServer" type="System.Configuration.IgnoreSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
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
+15
View File
@@ -62,6 +62,17 @@
</sectionGroup>
<section name="monoSettings" type="System.Web.Configuration.MonoSettingsSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</sectionGroup>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
<sectionGroup name="system.net" type="System.Net.Configuration.NetSectionGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="authenticationModules" type="System.Net.Configuration.AuthenticationModulesSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="connectionManagement" type="System.Net.Configuration.ConnectionManagementSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
@@ -84,6 +95,10 @@
<section name="serviceHostingEnvironment" type="System.ServiceModel.Configuration.ServiceHostingEnvironmentSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="services" type="System.ServiceModel.Configuration.ServicesSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</sectionGroup>
<sectionGroup name="system.transactions" type="System.Transactions.Configuration.TransactionsSectionGroup, System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null">
<section name="defaultSettings" type="System.Transactions.Configuration.DefaultSettingsSection, System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null"/>
<section name="machineSettings" type="System.Transactions.Configuration.MachineSettingsSection, System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null" allowDefinition="MachineOnly" allowExeDefinition="MachineOnly"/>
</sectionGroup>
<section name="system.webServer" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="uri" type="System.Configuration.UriSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<sectionGroup name="system.runtime.caching" type="System.Runtime.Caching.Configuration.CachingSectionGroup, System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
+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"/>
+1 -1
View File
@@ -8,5 +8,5 @@ SUBDIRS = src test
endif
endif
EXTRA_DIST = autogen.sh README NEWS AUTHORS ChangeLog
EXTRA_DIST = autogen.sh README NEWS AUTHORS ChangeLog winconfig.h
+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))"
+1
View File
@@ -1,6 +1,7 @@
noinst_LTLIBRARIES = libeglib.la libeglib-static.la
win_files = \
eglib-config.hw \
gdate-win32.c gdir-win32.c gfile-win32.c gmisc-win32.c \
gmodule-win32.c gtimer-win32.c
+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
+10 -16
View File
@@ -51,46 +51,40 @@ g_dir_open (const gchar *path, guint flags, GError **error)
g_return_val_if_fail (path != NULL, NULL);
g_return_val_if_fail (error == NULL || *error == NULL, NULL);
dir = g_new0 (GDir, 1);
path_utf16 = u8to16 (path);
path_utf16_search = g_malloc ((wcslen(path_utf16) + 3)*sizeof(gunichar2));
wcscpy (path_utf16_search, path_utf16);
wcscat (path_utf16_search, L"\\*");
dir->handle = FindFirstFile (path_utf16, &find_data);
dir->handle = FindFirstFileW (path_utf16_search, &find_data);
if (dir->handle == INVALID_HANDLE_VALUE) {
if (error) {
gint err = errno;
*error = g_error_new (G_LOG_DOMAIN, g_file_error_from_errno (err), strerror (err));
}
g_free (dir);
g_free (path_utf16_search);
g_free (path_utf16);
g_free (dir);
return NULL;
}
/* now get files */
FindClose (dir->handle);
path_utf16_search = g_malloc ((wcslen(path_utf16) + 3)*sizeof(gunichar2));
wcscpy (path_utf16_search, path_utf16);
wcscat (path_utf16_search, L"\\*");
dir->handle = FindFirstFile (path_utf16_search, &find_data);
g_free (path_utf16_search);
g_free (path_utf16);
while ((wcscmp (find_data.cFileName, L".") == 0) || (wcscmp (find_data.cFileName, L"..") == 0)) {
if (!FindNextFile (dir->handle, &find_data)) {
if (!FindNextFileW (dir->handle, &find_data)) {
if (error) {
gint err = errno;
*error = g_error_new (G_LOG_DOMAIN, g_file_error_from_errno (err), strerror (err));
}
g_free (dir);
g_free (path_utf16);
return NULL;
}
}
dir->current = NULL;
dir->next = u16to8 (find_data.cFileName);
g_free (path_utf16);
return dir;
}
@@ -113,7 +107,7 @@ g_dir_read_name (GDir *dir)
dir->next = NULL;
do {
if (!FindNextFile (dir->handle, &find_data)) {
if (!FindNextFileW (dir->handle, &find_data)) {
dir->next = NULL;
return dir->current;
}
+2 -2
View File
@@ -515,13 +515,13 @@ g_direct_hash (gconstpointer v1)
gboolean
g_int_equal (gconstpointer v1, gconstpointer v2)
{
return GPOINTER_TO_INT (v1) == GPOINTER_TO_INT (v2);
return *(gint *)v1 == *(gint *)v2;
}
guint
g_int_hash (gconstpointer v1)
{
return GPOINTER_TO_UINT(v1);
return *(guint *)v1;
}
gboolean
+39 -21
View File
@@ -72,39 +72,57 @@ g_path_is_absolute (const char *filename)
return (*filename == '/');
}
static pthread_mutex_t home_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t pw_lock = PTHREAD_MUTEX_INITIALIZER;
static const gchar *home_dir;
static const gchar *user_name;
static void
get_pw_data (void)
{
#ifdef HAVE_GETPWUID_R
struct passwd pw;
struct passwd *result;
char buf [4096];
#endif
if (user_name != NULL)
return;
pthread_mutex_lock (&pw_lock);
if (user_name != NULL) {
pthread_mutex_unlock (&pw_lock);
return;
}
#ifdef HAVE_GETPWUID_R
if (getpwuid_r (getuid (), &pw, buf, 4096, &result) == 0) {
home_dir = g_strdup (pw.pw_dir);
user_name = g_strdup (pw.pw_name);
}
#endif
if (home_dir == NULL)
home_dir = g_getenv ("HOME");
if (user_name == NULL) {
user_name = g_getenv ("USER");
if (user_name == NULL)
user_name = "somebody";
}
pthread_mutex_unlock (&pw_lock);
}
/* Give preference to /etc/passwd than HOME */
const gchar *
g_get_home_dir (void)
{
if (home_dir == NULL){
pthread_mutex_lock (&home_lock);
if (home_dir == NULL){
#ifdef HAVE_GETPWUID_R
struct passwd pw;
struct passwd *result;
char buf [4096];
if (getpwuid_r (getuid (), &pw, buf, 4096, &result) == 0)
home_dir = g_strdup (pw.pw_dir);
#endif
if (home_dir == NULL)
home_dir = g_getenv ("HOME");
}
pthread_mutex_unlock (&home_lock);
}
get_pw_data ();
return home_dir;
}
const char *
g_get_user_name (void)
{
const char *retName = g_getenv ("USER");
if (!retName)
retName = "somebody";
return retName;
get_pw_data ();
return user_name;
}
static const char *tmp_dir;
+24 -13
View File
@@ -33,8 +33,7 @@ split_cmdline (const gchar *cmdline, GPtrArray *array, GError **error)
{
gchar *ptr;
gchar c;
gboolean in_quote = FALSE;
gboolean escaped = FALSE;
gboolean escaped = FALSE, fresh = TRUE;
gchar quote_char = '\0';
GString *str;
@@ -42,18 +41,30 @@ 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) {
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 {
g_string_append_c (str, c);
if (!g_ascii_isspace (c))
g_string_append_c (str, c);
}
escaped = FALSE;
} else if (quote_char) {
if (c == quote_char) {
quote_char = '\0';
if (fresh && g_ascii_isspace (*ptr)){
g_ptr_array_add (array, g_string_free (str, FALSE));
str = g_string_new ("");
}
} 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 +73,7 @@ split_cmdline (const gchar *cmdline, GPtrArray *array, GError **error)
} else if (c == '\\') {
escaped = TRUE;
} else if (c == '\'' || c == '"') {
in_quote = TRUE;
fresh = str->len == 0;
quote_char = c;
} else {
g_string_append_c (str, c);
@@ -76,7 +87,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);
+91 -12
View File
@@ -55,7 +55,7 @@ test_shell_argv1 ()
if (!ret)
return FAILED ("11. It should return TRUE");
if (argc != 2)
return FAILED ("12. argc was %d", argc);
return FAILED ("12. argc was %d expected 2", argc);
if (strcmp (argv [0], "hola"))
return FAILED ("13. argv[0] was %s", argv [0]);
if (strcmp (argv [1], "bola"))
@@ -72,7 +72,7 @@ test_shell_argv1 ()
if (!ret)
return FAILED ("16. It should return TRUE");
if (argc != 3)
return FAILED ("17. argc was %d", argc);
return FAILED ("17. argc was %d expected 3", argc);
if (strcmp (argv [0], "hola"))
return FAILED ("18. argv[0] was %s", argv [0]);
if (strcmp (argv [1], ""))
@@ -85,6 +85,19 @@ test_shell_argv1 ()
g_strfreev (argv);
argv = NULL;
argc = 0;
error = NULL;
ret = g_shell_parse_argv ("hola'' bola", &argc, &argv, &error);
if (!ret)
return FAILED ("21. It should return TRUE");
if (argc != 2)
return FAILED ("22. argc was %d expected 2", argc);
if (strcmp (argv [0], "hola"))
return FAILED ("23. argv[0] was %s", argv [0]);
if (strcmp (argv [1], "bola"))
return FAILED ("24. argv[2] was %s", argv [1]);
if (error != NULL)
return FAILED ("25. error is not null");
return OK;
}
@@ -103,7 +116,7 @@ test_shell_argv2 ()
if (!ret)
return FAILED ("1. It should return TRUE");
if (argc != 2)
return FAILED ("2. argc was %d", argc);
return FAILED ("2. argc was %d expected 2", argc);
if (strcmp (argv [0], "hola"))
return FAILED ("3. argv[0] was %s", argv [0]);
if (strcmp (argv [1], "bola"))
@@ -119,7 +132,7 @@ test_shell_argv2 ()
if (!ret)
return FAILED ("6. It should return TRUE");
if (argc != 3)
return FAILED ("7. argc was %d", argc);
return FAILED ("7. argc was %d expected 3", argc);
if (strcmp (argv [0], "hola"))
return FAILED ("8. argv[0] was %s", argv [0]);
if (strcmp (argv [1], ""))
@@ -137,7 +150,7 @@ test_shell_argv2 ()
if (!ret)
return FAILED ("10. It should return TRUE");
if (argc != 3)
return FAILED ("11. argc was %d", argc);
return FAILED ("11. argc was %d expected 3", argc);
if (strcmp (argv [0], "hola"))
return FAILED ("12. argv[0] was %s", argv [0]);
if (strcmp (argv [1], "\t"))
@@ -155,7 +168,7 @@ test_shell_argv2 ()
if (!ret)
return FAILED ("16. It should return TRUE");
if (argc != 3)
return FAILED ("17. argc was %d", argc);
return FAILED ("17. argc was %d expected 3", argc);
if (strcmp (argv [0], "hola"))
return FAILED ("18. argv[0] was %s", argv [0]);
if (strcmp (argv [1], "\t"))
@@ -184,7 +197,7 @@ test_shell_argv3 ()
if (ret)
return FAILED ("1. It should return FALSE");
if (argc != 0)
return FAILED ("2. argc was %d", argc);
return FAILED ("2. argc was %d expected 0", argc);
if (argv != NULL)
return FAILED ("3. argv[0] was %s", argv [0]);
if (error == NULL)
@@ -197,7 +210,7 @@ test_shell_argv3 ()
if (!ret)
return FAILED ("5. It should return TRUE");
if (argc != 2)
return FAILED ("6. argc was %d", argc);
return FAILED ("6. argc was %d expected 2", argc);
if (strcmp (argv [0], "hola"))
return FAILED ("18. argv[0] was %s", argv [0]);
if (strcmp (argv [1], "\"bola"))
@@ -212,7 +225,7 @@ test_shell_argv3 ()
if (!ret)
return FAILED ("9. It should return TRUE. %s", error->message);
if (argc != 2)
return FAILED ("10. argc was %d", argc);
return FAILED ("10. argc was %d expected 2", argc);
if (strcmp (argv [0], "hola"))
return FAILED ("11. argv[0] was %s", argv [0]);
if (strcmp (argv [1], "\n\\'bola"))
@@ -226,6 +239,70 @@ 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 expected 3", 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;
}
// This is https://bugzilla.novell.com/show_bug.cgi?id=655896
RESULT
test_shell_argv5 ()
{
GError *error;
gint argc;
gchar **argv;
gboolean ret;
char *str = "echo \"foo\",\"bar\"";
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 != 2)
return FAILED ("2. argc was %d expected 2", argc);
if (argv == NULL)
return FAILED ("3. argv[0] was NULL");
if (error != NULL)
return FAILED ("4. error was set");
if (strcmp (argv [0], "echo"))
return FAILED ("5. Expected echo got %s", argv [0]);
if (strcmp (argv [1], "foo,bar"))
return FAILED ("6. Expected foo,bar, got: %s", argv [1]);
return OK;
}
RESULT
test_quote ()
{
@@ -241,9 +318,11 @@ test_quote ()
}
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},
{"test_shell_argv1", test_shell_argv1},
{"test_shell_argv2", test_shell_argv2},
{"test_shell_argv3", test_shell_argv3},
{"test_shell_argv4", test_shell_argv4},
{"test_shell_argv5", test_shell_argv5},
{"g_shell_quote", test_quote},
{NULL, NULL}
};
+1 -1
View File
@@ -47,7 +47,7 @@ obj_map.c os_dep.c pcr_interface.c ptr_chck.c real_malloc.c reclaim.c \
solaris_pthreads.c solaris_threads.c specific.c stubborn.c typd_mlc.c \
backgraph.c win32_threads.c \
pthread_support.c pthread_stop_world.c darwin_stop_world.c \
$(asm_libgc_sources)
openbsd_stop_world.c $(asm_libgc_sources)
# Include THREADDLLIBS here to ensure that the correct versions of
# linuxthread semaphore functions get linked:
+7
View File
@@ -147,6 +147,13 @@ case "$THREADS" in
fi
AC_DEFINE(THREAD_LOCAL_ALLOC)
;;
*-*-openbsd*)
AC_DEFINE(GC_OPENBSD_THREADS)
if test "${enable_parallel_mark}" = yes; then
AC_DEFINE(PARALLEL_MARK)
fi
AC_DEFINE(THREAD_LOCAL_ALLOC)
;;
*-*-osf*)
AC_DEFINE(GC_OSF1_THREADS)
if test "${enable_parallel_mark}" = yes; then
+8 -1
View File
@@ -57,6 +57,7 @@
!defined(HPUX) && !(defined(LINUX) && defined(__ELF__)) && \
!defined(RS6000) && !defined(SCO_ELF) && !defined(DGUX) && \
!(defined(FREEBSD) && defined(__ELF__)) && \
!(defined(OPENBSD) && (defined(__ELF__) || defined(M68K))) && \
!(defined(NETBSD) && defined(__ELF__)) && !defined(HURD) && \
!defined(DARWIN)
--> We only know how to find data segments of dynamic libraries for the
@@ -92,9 +93,12 @@
#if defined(LINUX) && defined(__ELF__) || defined(SCO_ELF) || \
(defined(FREEBSD) && defined(__ELF__)) || defined(DGUX) || \
(defined(OPENBSD) && defined(__ELF__)) || \
(defined(NETBSD) && defined(__ELF__)) || defined(HURD)
# include <stddef.h>
# if !defined(OPENBSD)
# include <elf.h>
# endif
# include <link.h>
#endif
@@ -295,6 +299,7 @@ void GC_register_dynamic_libraries()
#if defined(LINUX) && defined(__ELF__) || defined(SCO_ELF) || \
(defined(FREEBSD) && defined(__ELF__)) || defined(DGUX) || \
(defined(OPENBSD) && defined(__ELF__)) || \
(defined(NETBSD) && defined(__ELF__)) || defined(HURD)
@@ -473,8 +478,10 @@ GC_bool GC_register_main_static_data()
/* This doesn't necessarily work in all cases, e.g. with preloaded
* dynamic libraries. */
#if defined(NETBSD)
#if defined(NETBSD) || defined(OPENBSD)
# if !defined(OPENBSD)
# include <sys/exec_elf.h>
# endif
/* for compatibility with 1.4.x */
# ifndef DT_DEBUG
# define DT_DEBUG 21
+5
View File
@@ -57,6 +57,7 @@
defined(GC_HPUX_THREADS) || defined(GC_OSF1_THREADS) || \
defined(GC_DGUX386_THREADS) || defined(GC_DARWIN_THREADS) || \
defined(GC_AIX_THREADS) || defined(GC_NETBSD_THREADS) || \
defined(GC_OPENBSD_THREADS) || \
(defined(GC_WIN32_THREADS) && defined(__CYGWIN32__))
# define GC_PTHREADS
# endif
@@ -87,6 +88,10 @@
# define GC_DARWIN_THREADS
# define GC_PTHREADS
# endif
# if !defined(GC_PTHREADS) && defined(__OpenBSD__)
# define GC_OPENBSD_THREADS
# define GC_PTHREADS
# endif
# if !defined(GC_PTHREADS) && defined(__FreeBSD__)
# define GC_FREEBSD_THREADS
# define GC_PTHREADS
+32
View File
@@ -231,6 +231,10 @@
# define I386
# define mach_type_known
# endif
# if defined(OPENBSD) && defined(__amd64__)
# define X86_64
# define mach_type_known
# endif
# if defined(LINUX) && defined(__x86_64__)
# define X86_64
# define mach_type_known
@@ -1304,6 +1308,18 @@
# endif
# ifdef OPENBSD
# define OS_TYPE "OPENBSD"
# ifdef GC_OPENBSD_THREADS
# define UTHREAD_SP_OFFSET 192
# else
# include <sys/param.h>
# include <uvm/uvm_extern.h>
# define STACKBOTTOM USRSTACK
# endif
extern int __data_start[];
# define DATASTART ((ptr_t)(__data_start))
extern char _end[];
# define DATAEND ((ptr_t)(&_end))
# define DYNAMIC_LOADING
# endif
# ifdef FREEBSD
# define OS_TYPE "FREEBSD"
@@ -2086,6 +2102,22 @@
extern char etext[];
# define SEARCH_FOR_DATA_START
# endif
# ifdef OPENBSD
# define OS_TYPE "OPENBSD"
# define ELF_CLASS ELFCLASS64
# ifdef GC_OPENBSD_THREADS
# define UTHREAD_SP_OFFSET 400
# else
# include <sys/param.h>
# include <uvm/uvm_extern.h>
# define STACKBOTTOM USRSTACK
# endif
extern int __data_start[];
# define DATASTART ((ptr_t)(__data_start))
extern char _end[];
# define DATAEND ((ptr_t)(&_end))
# define DYNAMIC_LOADING
# endif
# endif
#if defined(LINUX) && defined(USE_MMAP)
@@ -0,0 +1,12 @@
#ifndef GC_OPENBSD_STOP_WORLD_H
#define GC_OPENBSD_STOP_WORLD_H
#if !defined(GC_OPENBSD_THREADS)
#error openbsd_stop_world.h included without GC_OPENBSD_THREADS defined
#endif
struct thread_stop_info {
ptr_t stack_ptr; /* Valid only when stopped. */
};
#endif
+2
View File
@@ -8,6 +8,8 @@
#if defined(GC_DARWIN_THREADS)
# include "private/darwin_stop_world.h"
#elif defined(GC_OPENBSD_THREADS)
# include "private/openbsd_stop_world.h"
#else
# include "private/pthread_stop_world.h"
#endif
+1 -1
View File
@@ -492,7 +492,7 @@ ptr_t cold_gc_frame;
/* the stack. Return sp. */
# ifdef SPARC
asm(" .seg \"text\"");
# if defined(SVR4) || defined(NETBSD) || defined(FREEBSD)
# if defined(SVR4) || defined(NETBSD) || defined(FREEBSD) || defined(OPENBSD)
asm(" .globl GC_save_regs_in_stack");
asm("GC_save_regs_in_stack:");
asm(" .type GC_save_regs_in_stack,#function");
+2 -2
View File
@@ -473,7 +473,7 @@ size_t GC_get_total_bytes GC_PROTO(())
int GC_get_suspend_signal GC_PROTO(())
{
#if defined(SIG_SUSPEND) && defined(GC_PTHREADS) && !defined(GC_MACOSX_THREADS)
#if defined(SIG_SUSPEND) && defined(GC_PTHREADS) && !defined(GC_MACOSX_THREADS) && !defined(GC_OPENBSD_THREADS)
return SIG_SUSPEND;
#else
return -1;
@@ -684,7 +684,7 @@ void GC_init_inner()
# if defined(SEARCH_FOR_DATA_START)
GC_init_linux_data_start();
# endif
# if (defined(NETBSD) || defined(OPENBSD)) && defined(__ELF__)
# if defined(NETBSD) && defined(__ELF__)
GC_init_netbsd_elf();
# endif
# if defined(GC_PTHREADS) || defined(GC_SOLARIS_THREADS) \
+161
View File
@@ -0,0 +1,161 @@
#include "private/pthread_support.h"
/* derived from pthread_stop_world.c */
# if defined(GC_OPENBSD_THREADS)
#define THREAD_EQUAL(id1, id2) pthread_equal(id1, id2)
/* We hold allocation lock. Should do exactly the right thing if the */
/* world is stopped. Should not fail if it isn't. */
void GC_push_all_stacks()
{
GC_bool found_me = FALSE;
size_t nthreads = 0;
int i;
GC_thread p;
ptr_t lo, hi;
pthread_t me = pthread_self();
if (!GC_thr_initialized) GC_thr_init();
# if DEBUG_THREADS
GC_printf("Pushing stacks from thread 0x%x\n", (unsigned) me);
# endif
for (i = 0; i < THREAD_TABLE_SZ; i++) {
for (p = GC_threads[i]; p != 0; p = p -> next) {
if (p -> flags & FINISHED) continue;
++nthreads;
if (THREAD_EQUAL(p -> id, me)) {
# ifdef SPARC
lo = (ptr_t)GC_save_regs_in_stack();
# else
lo = GC_approx_sp();
# endif
found_me = TRUE;
} else {
lo = p -> stop_info.stack_ptr;
}
if ((p -> flags & MAIN_THREAD) == 0) {
hi = p -> stack_end;
} else {
/* The original stack. */
hi = GC_stackbottom;
}
# if DEBUG_THREADS
GC_printf("Stack for thread 0x%x = [%p,%p)\n",
(unsigned)(p -> id), lo, hi);
# endif
if (0 == lo) ABORT("GC_push_all_stacks: sp not set!\n");
# ifdef STACK_GROWS_UP
/* We got them backwards! */
GC_push_all_stack(hi, lo);
# else
GC_push_all_stack(lo, hi);
# endif
}
}
if (!found_me && !GC_in_thread_creation)
ABORT("Collecting from unknown thread.");
}
/* We hold the allocation lock. Suspend all threads that might */
/* still be running. */
void GC_suspend_all()
{
int i;
GC_thread p;
int result;
pthread_t my_thread = pthread_self();
for (i = 0; i < THREAD_TABLE_SZ; i++) {
for (p = GC_threads[i]; p != 0; p = p -> next) {
if (!THREAD_EQUAL(p -> id, my_thread)) {
if (p -> flags & FINISHED) continue;
if (p -> thread_blocked) /* Will wait */ continue;
# if DEBUG_THREADS
GC_printf("Suspending thread 0x%x\n",
(unsigned)(p -> id));
# endif
if (pthread_suspend_np(p -> id) != 0)
ABORT("pthread_suspend_np failed");
/*
* This will only work for userland pthreads. It will
* fail badly on rthreads. Perhaps we should consider
* a pthread_sp_np() function that returns the stack
* pointer for a suspended thread and implement in
* both pthreads and rthreads.
*/
p -> stop_info.stack_ptr = *(ptr_t*)((char *)p -> id + UTHREAD_SP_OFFSET);
}
}
}
}
void GC_stop_world()
{
int i;
GC_ASSERT(I_HOLD_LOCK());
# if DEBUG_THREADS
GC_printf("Stopping the world from 0x%x\n", (unsigned)pthread_self());
# endif
/* Make sure all free list construction has stopped before we start. */
/* No new construction can start, since free list construction is */
/* required to acquire and release the GC lock before it starts, */
/* and we have the lock. */
# ifdef PARALLEL_MARK
GC_acquire_mark_lock();
GC_ASSERT(GC_fl_builder_count == 0);
/* We should have previously waited for it to become zero. */
# endif /* PARALLEL_MARK */
GC_suspend_all();
# ifdef PARALLEL_MARK
GC_release_mark_lock();
# endif
#if DEBUG_THREADS
GC_printf("World stopped from 0x%x\n", (unsigned)pthread_self());
#endif
}
/* Caller holds allocation lock, and has held it continuously since */
/* the world stopped. */
void GC_start_world()
{
pthread_t my_thread = pthread_self();
register int i;
register GC_thread p;
register int result;
# if DEBUG_THREADS
GC_printf("World starting\n");
# endif
for (i = 0; i < THREAD_TABLE_SZ; i++) {
for (p = GC_threads[i]; p != 0; p = p -> next) {
if (!THREAD_EQUAL(p -> id, my_thread)) {
if (p -> flags & FINISHED) continue;
if (p -> thread_blocked) continue;
#if DEBUG_THREADS
GC_printf("Resuming thread 0x%x\n",
(unsigned)(p -> id));
#endif
if (pthread_resume_np(p -> id) != 0)
ABORT("pthread_kill failed");
}
}
}
# if DEBUG_THREADS
GC_printf("World started\n");
# endif
}
void GC_stop_init() {
}
#endif
+144 -2
View File
@@ -392,7 +392,7 @@ static void *tiny_sbrk(ptrdiff_t increment)
#define sbrk tiny_sbrk
# endif /* ECOS */
#if (defined(NETBSD) || defined(OPENBSD)) && defined(__ELF__)
#if defined(NETBSD) && defined(__ELF__)
ptr_t GC_data_start;
void GC_init_netbsd_elf()
@@ -405,6 +405,102 @@ static void *tiny_sbrk(ptrdiff_t increment)
}
#endif
#if defined(OPENBSD)
static struct sigaction old_segv_act;
sigjmp_buf GC_jmp_buf_openbsd;
# if defined(GC_OPENBSD_THREADS)
# include <sys/syscall.h>
sigset_t __syscall(quad_t, ...);
# endif
/*
* Dont use GC_find_limit() because siglongjmp out of the
* signal handler by-passes our userland pthreads lib, leaving
* SIGSEGV and SIGPROF masked. Instead use this custom one
* that works-around the issues.
*/
/*ARGSUSED*/
void GC_fault_handler_openbsd(int sig)
{
siglongjmp(GC_jmp_buf_openbsd, 1);
}
/* Return the first nonaddressible location > p or bound */
/* Requires allocation lock. */
ptr_t GC_find_limit_openbsd(ptr_t p, ptr_t bound)
{
static volatile ptr_t result;
/* Safer if static, since otherwise it may not be */
/* preserved across the longjmp. Can safely be */
/* static since it's only called with the */
/* allocation lock held. */
struct sigaction act;
size_t pgsz = (size_t)sysconf(_SC_PAGESIZE);
GC_ASSERT(I_HOLD_LOCK());
act.sa_handler = GC_fault_handler_openbsd;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_NODEFER | SA_RESTART;
sigaction(SIGSEGV, &act, &old_segv_act);
if (sigsetjmp(GC_jmp_buf_openbsd, 1) == 0) {
result = (ptr_t)(((word)(p)) & ~(pgsz-1));
for (;;) {
result += pgsz;
if (result >= bound) {
result = bound;
break;
}
GC_noop1((word)(*result));
}
}
# if defined(GC_OPENBSD_THREADS)
/* due to the siglongjump we need to manually unmask SIGPROF */
__syscall(SYS_sigprocmask, SIG_UNBLOCK, sigmask(SIGPROF));
# endif
sigaction(SIGSEGV, &old_segv_act, 0);
return(result);
}
/* Return first addressable location > p or bound */
/* Requires allocation lock. */
ptr_t GC_skip_hole_openbsd(ptr_t p, ptr_t bound)
{
static volatile ptr_t result;
struct sigaction act;
size_t pgsz = (size_t)sysconf(_SC_PAGESIZE);
static volatile int firstpass;
GC_ASSERT(I_HOLD_LOCK());
act.sa_handler = GC_fault_handler_openbsd;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_NODEFER | SA_RESTART;
sigaction(SIGSEGV, &act, &old_segv_act);
firstpass = 1;
result = (ptr_t)(((word)(p)) & ~(pgsz-1));
if (sigsetjmp(GC_jmp_buf_openbsd, 1) != 0 || firstpass) {
firstpass = 0;
result += pgsz;
if (result >= bound) {
result = bound;
} else
GC_noop1((word)(*result));
}
sigaction(SIGSEGV, &old_segv_act, 0);
return(result);
}
#endif
# ifdef OS2
# include <stddef.h>
@@ -1021,7 +1117,8 @@ void *GC_set_stackbottom = NULL;
#endif /* FREEBSD_STACKBOTTOM */
#if !defined(BEOS) && !defined(AMIGA) && !defined(MSWIN32) \
&& !defined(MSWINCE) && !defined(OS2) && !defined(NOSYS) && !defined(ECOS)
&& !defined(MSWINCE) && !defined(OS2) && !defined(NOSYS) && !defined(ECOS) \
&& !defined(GC_OPENBSD_THREADS)
ptr_t GC_get_stack_base()
{
@@ -1081,6 +1178,25 @@ ptr_t GC_get_stack_base()
# endif /* ! AMIGA, !OS 2, ! MS Windows, !BEOS, !NOSYS, !ECOS */
#if defined(GC_OPENBSD_THREADS)
/* Find the stack using pthread_stackseg_np() */
# include <sys/signal.h>
# include <pthread.h>
# include <pthread_np.h>
#define HAVE_GET_STACK_BASE
ptr_t GC_get_stack_base()
{
stack_t stack;
pthread_stackseg_np(pthread_self(), &stack);
return stack.ss_sp;
}
#endif /* GC_OPENBSD_THREADS */
/*
* Register static data segment(s) as roots.
* If more data segments are added later then they need to be registered
@@ -1445,6 +1561,31 @@ int * etext_addr;
#else /* !OS2 && !Windows && !AMIGA */
#if defined(OPENBSD)
/*
* Depending on arch alignment there can be multiple holes
* between DATASTART & DATAEND. Scan from DATASTART - DATAEND
* and register each region.
*/
void GC_register_data_segments(void)
{
ptr_t region_start, region_end;
region_start = DATASTART;
for(;;) {
region_end = GC_find_limit_openbsd(region_start, DATAEND);
GC_add_roots_inner(region_start, region_end, FALSE);
if (region_end < DATAEND)
region_start = GC_skip_hole_openbsd(region_end, DATAEND);
else
break;
}
}
# else /* !OS2 && !Windows && !AMIGA && !OPENBSD */
void GC_register_data_segments()
{
# if !defined(PCR) && !defined(SRC_M3) && !defined(MACOS)
@@ -1504,6 +1645,7 @@ void GC_register_data_segments()
/* change. */
}
# endif /* ! OPENBSD */
# endif /* ! AMIGA */
# endif /* ! MSWIN32 && ! MSWINCE*/
# endif /* ! OS2 */
+2 -1
View File
@@ -2,7 +2,8 @@
#if defined(GC_PTHREADS) && !defined(GC_SOLARIS_THREADS) \
&& !defined(GC_IRIX_THREADS) && !defined(GC_WIN32_THREADS) \
&& !defined(GC_DARWIN_THREADS) && !defined(GC_AIX_THREADS)
&& !defined(GC_DARWIN_THREADS) && !defined(GC_AIX_THREADS) \
&& !defined(GC_OPENBSD_THREADS)
#include <signal.h>
#include <semaphore.h>
+7 -5
View File
@@ -68,7 +68,8 @@
# if (defined(GC_DGUX386_THREADS) || defined(GC_OSF1_THREADS) || \
defined(GC_DARWIN_THREADS) || defined(GC_AIX_THREADS)) || \
defined(GC_NETBSD_THREADS) && !defined(USE_PTHREAD_SPECIFIC)
defined(GC_NETBSD_THREADS) && !defined(USE_PTHREAD_SPECIFIC) || \
defined(GC_OPENBSD_THREADS)
# define USE_PTHREAD_SPECIFIC
# endif
@@ -129,7 +130,7 @@
# include <sys/sysctl.h>
#endif /* GC_DARWIN_THREADS */
#if defined(GC_NETBSD_THREADS)
#if defined(GC_NETBSD_THREADS) || defined(GC_OPENBSD_THREADS)
# include <sys/param.h>
# include <sys/sysctl.h>
#endif
@@ -1037,7 +1038,7 @@ void GC_thr_init()
GC_nprocs = sysconf(_SC_NPROC_ONLN);
if (GC_nprocs <= 0) GC_nprocs = 1;
# endif
# if defined(GC_DARWIN_THREADS) || defined(GC_FREEBSD_THREADS) || defined(GC_NETBSD_THREADS)
# if defined(GC_DARWIN_THREADS) || defined(GC_FREEBSD_THREADS) || defined(GC_NETBSD_THREADS) || defined(GC_OPENBSD_THREADS)
int ncpus = 1;
size_t len = sizeof(ncpus);
sysctl((int[2]) {CTL_HW, HW_NCPU}, 2, &ncpus, &len, NULL, 0);
@@ -1113,7 +1114,7 @@ void GC_init_parallel()
}
#if !defined(GC_DARWIN_THREADS)
#if !defined(GC_DARWIN_THREADS) && !defined(GC_OPENBSD_THREADS)
int WRAP_FUNC(pthread_sigmask)(int how, const sigset_t *set, sigset_t *oset)
{
sigset_t fudged_set;
@@ -1341,7 +1342,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();
+1 -1
View File
@@ -15,7 +15,7 @@ int main()
|| defined(GC_DARWIN_THREADS) || defined(GC_AIX_THREADS)
printf("-lpthread\n");
# endif
# if defined(GC_FREEBSD_THREADS)
# if defined(GC_FREEBSD_THREADS) || defined(GC_OPENBSD_THREADS)
# if (__FREEBSD_version >= 500000)
printf("-lpthread\n");
# else
+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 () {
@@ -410,7 +410,7 @@ namespace System.Windows.Forms {
else if (e.NewIndex <= listposition) {
/* the deleted row was either the current one, or one earlier in the list.
Update the index and emit PositionChanged, CurrentChanged, and ItemChanged. */
ChangeRecordState (e.NewIndex,
ChangeRecordState (listposition+1,
false, false, e.NewIndex != listposition, false);
}
else {
@@ -6272,7 +6272,7 @@ namespace System.Windows.Forms {
if (disp_x == Columns.Count - 1)
delta_x = horizontalScrollBar.Maximum - horizontalScrollBar.Value;
else
for (int i = first_col_index + displayedColumnsCount - 1; i < disp_x; i++)
for (int i = first_col_index + displayedColumnsCount - 1; i < disp_x && i != -1; i++)
delta_x += Columns[ColumnDisplayIndexToIndex (i)].Width;
horizontalScrollBar.SafeValueSet (horizontalScrollBar.Value + delta_x);
@@ -103,6 +103,10 @@ namespace System.Windows.Forms {
private Rectangle restore_bounds;
private bool autoscale_base_size_set;
#endif
internal ArrayList disabled_by_showdialog = new ArrayList();
internal static ArrayList modal_dialogs = new ArrayList();
#endregion // Local Variables
#region Private & Internal Methods
@@ -1787,6 +1791,16 @@ namespace System.Windows.Forms {
XplatUI.UngrabWindow(capture_window);
}
foreach (Form form in Application.OpenForms)
{
if (form.Enabled == true)
{
disabled_by_showdialog.Add(form);
form.Enabled = false;
}
}
modal_dialogs.Add(this);
#if not
// Commented out; we instead let the Visible=true inside the runloop create the control
// otherwise setting DialogResult inside any of the events that are triggered by the
@@ -2660,6 +2674,9 @@ namespace System.Windows.Forms {
private void WmClose (ref Message m)
{
if (this.Enabled == false)
return; // prevent closing a disabled form.
Form act = Form.ActiveForm;
// Don't close this form if there's another modal form visible.
if (act != null && act != this && act.Modal == true) {
@@ -2744,6 +2761,12 @@ namespace System.Windows.Forms {
#endif
private void WmActivate (ref Message m)
{
if (!this.Enabled && modal_dialogs.Count > 0)
{
(modal_dialogs[modal_dialogs.Count -1] as Form).Activate ();
return; // prevent Activating of disabled form.
}
if (m.WParam != (IntPtr)WindowActiveFlags.WA_INACTIVE) {
if (is_loaded) {
SelectActiveControl ();
@@ -3241,6 +3264,14 @@ namespace System.Windows.Forms {
FormClosedEventHandler eh = (FormClosedEventHandler)(Events[FormClosedEvent]);
if (eh != null)
eh (this, e);
foreach (Form form in disabled_by_showdialog)
{
form.Enabled = true;
}
disabled_by_showdialog.Clear();
if (modal_dialogs.Contains(this))
modal_dialogs.Remove(this);
}
// Consider calling FireClosingEvents instead of calling this directly.
@@ -1153,7 +1153,8 @@ namespace System.Windows.Forms
break;
case 2: // Marquee
int ms_diff = (int)(DateTime.Now - ctrl.start).TotalMilliseconds;
double percent_done = (double)ms_diff % (double)ctrl.MarqueeAnimationSpeed / (double)ctrl.MarqueeAnimationSpeed;
double percent_done = (double) ms_diff / ProgressBarMarqueeSpeedScaling
% (double)ctrl.MarqueeAnimationSpeed / (double)ctrl.MarqueeAnimationSpeed;
max_blocks = 5;
start_pixel = client_area.X + (int)(client_area.Width * percent_done);
goto default;
@@ -4287,7 +4287,8 @@ namespace System.Windows.Forms
case 2: // Marquee
if (XplatUI.ThemesEnabled) {
int ms_diff = (int) (DateTime.Now - ctrl.start).TotalMilliseconds;
double percent_done = (double) ms_diff % (double)ctrl.MarqueeAnimationSpeed / (double)ctrl.MarqueeAnimationSpeed;
double percent_done = (double) ms_diff / ProgressBarMarqueeSpeedScaling
% (double)ctrl.MarqueeAnimationSpeed / (double)ctrl.MarqueeAnimationSpeed;
max_blocks = 5;
start_pixel = client_area.X + (int) (client_area.Width * percent_done);
}
@@ -4353,6 +4354,8 @@ namespace System.Windows.Forms
}
}
public const double ProgressBarMarqueeSpeedScaling = 15;
#endregion // ProgressBar
#region RadioButton
@@ -449,20 +449,20 @@ namespace System.Windows.Forms
direction = ToolStripDropDownDirection.BelowRight;
break;
case ToolStripDropDownDirection.BelowLeft:
if (show_point.Y + this.Height > max_screen.Y)
if (show_point.Y + this.Height > max_screen.Y && show_point.Y - this.Height > 0)
direction = ToolStripDropDownDirection.AboveLeft;
break;
case ToolStripDropDownDirection.BelowRight:
case ToolStripDropDownDirection.Default:
if (show_point.Y + this.Height > max_screen.Y)
if (show_point.Y + this.Height > max_screen.Y && show_point.Y - this.Height > 0)
direction = ToolStripDropDownDirection.AboveRight;
break;
case ToolStripDropDownDirection.Left:
if (show_point.Y + this.Height > max_screen.Y)
if (show_point.Y + this.Height > max_screen.Y && show_point.Y - this.Height > 0)
direction = ToolStripDropDownDirection.AboveLeft;
break;
case ToolStripDropDownDirection.Right:
if (show_point.Y + this.Height > max_screen.Y)
if (show_point.Y + this.Height > max_screen.Y && show_point.Y - this.Height > 0)
direction = ToolStripDropDownDirection.AboveRight;
break;
}
@@ -486,12 +486,18 @@ namespace System.Windows.Forms
break;
}
// Fix offscreen positions
// Fix offscreen horizontal positions
if ((show_point.X + this.Width) > max_screen.X)
show_point.X = max_screen.X - this.Width;
if (show_point.X < 0)
show_point.X = 0;
// Fix offscreen vertical positions
if ((show_point.Y + this.Height) > max_screen.Y)
show_point.Y = max_screen.Y - this.Height;
if (show_point.Y < 0)
show_point.Y = 0;
if (this.Location != show_point)
this.Location = show_point;
@@ -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,
@@ -1648,6 +1648,10 @@ namespace System.Windows.Forms {
}
private void UpdateMessageQueue (XEventQueue queue) {
UpdateMessageQueue(queue, true);
}
private void UpdateMessageQueue (XEventQueue queue, bool allowIdle) {
DateTime now;
int pending;
Hwnd hwnd;
@@ -1658,7 +1662,7 @@ namespace System.Windows.Forms {
pending = XPending (DisplayHandle);
}
if (pending == 0) {
if (pending == 0 && allowIdle) {
if ((queue == null || queue.DispatchIdle) && Idle != null) {
Idle (this, EventArgs.Empty);
}
@@ -2679,7 +2683,7 @@ namespace System.Windows.Forms {
Clipboard.Enumerating = true;
while (Clipboard.Enumerating) {
UpdateMessageQueue(null);
UpdateMessageQueue(null, false);
}
f = f.Next;
}
@@ -2740,7 +2744,7 @@ namespace System.Windows.Forms {
Clipboard.Retrieving = true;
while (Clipboard.Retrieving) {
UpdateMessageQueue(null);
UpdateMessageQueue(null, false);
}
return Clipboard.Item;
@@ -4444,8 +4448,8 @@ namespace System.Windows.Forms {
}
goto ProcessNextMessage;
}
SendMessage(FocusWindow, Msg.WM_SETFOCUS, IntPtr.Zero, IntPtr.Zero);
Keyboard.FocusIn (FocusWindow);
SendMessage(FocusWindow, Msg.WM_SETFOCUS, IntPtr.Zero, IntPtr.Zero);
goto ProcessNextMessage;
}
@@ -5607,9 +5611,9 @@ namespace System.Windows.Forms {
if (prev_focus_window != IntPtr.Zero) {
SendMessage(prev_focus_window, Msg.WM_KILLFOCUS, FocusWindow, IntPtr.Zero);
}
SendMessage(FocusWindow, Msg.WM_SETFOCUS, prev_focus_window, IntPtr.Zero);
}
Keyboard.FocusIn (FocusWindow);
SendMessage(FocusWindow, Msg.WM_SETFOCUS, prev_focus_window, IntPtr.Zero);
//XSetInputFocus(DisplayHandle, Hwnd.ObjectFromHandle(handle).client_window, RevertTo.None, IntPtr.Zero);
}
+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;
@@ -189,8 +189,11 @@ namespace Mono.Debugger.Soft
}
public void EnableEvents (params EventType[] events) {
foreach (EventType etype in events)
foreach (EventType etype in events) {
if (etype == EventType.Breakpoint)
throw new ArgumentException ("Breakpoint events cannot be requested using EnableEvents", "events");
conn.EnableEvent (etype, SuspendPolicy.All, null);
}
}
public BreakpointEventRequest SetBreakpoint (MethodMirror method, long il_offset) {
+34 -2
View File
@@ -243,6 +243,7 @@ public class Tests : TestsBase
ss6 (true);
} catch {
}
ss_regress_654694 ();
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
@@ -409,7 +410,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 +424,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 +621,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)]
@@ -706,6 +726,18 @@ public class Tests : TestsBase
public static void frames_in_native () {
Thread.Sleep (500);
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static void string_call (string s) {
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static void ss_regress_654694 () {
if (true) {
string h = "hi";
string_call (h);
}
}
}
public class CrossDomain : MarshalByRefObject
+87 -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);
@@ -2385,4 +2428,43 @@ public class DebuggerTests
vm.CreateEnumMirror (enumType, vm.CreateValue ((long)1));
});
}
[Test]
public void VirtualMachine_EnableEvents_Breakpoint () {
AssertThrows<ArgumentException> (delegate () {
vm.EnableEvents (EventType.Breakpoint);
});
}
[Test]
public void SingleStepRegress654694 () {
int il_offset = -1;
MethodMirror m = entry_point.DeclaringType.GetMethod ("ss_regress_654694");
foreach (Location l in m.Locations) {
if (l.ILOffset > 0 && il_offset == -1)
il_offset = l.ILOffset;
}
Event e = run_until ("ss_regress_654694");
Assert.IsNotNull (m);
vm.SetBreakpoint (m, il_offset);
vm.Resume ();
e = vm.GetNextEvent ();
Assert.IsTrue (e is BreakpointEvent);
var req = vm.CreateStepRequest (e.Thread);
req.Depth = StepDepth.Over;
req.Size = StepSize.Line;
req.Enable ();
vm.Resume ();
e = vm.GetNextEvent ();
Assert.IsTrue (e is StepEvent);
}
}
@@ -310,9 +310,12 @@ namespace Mono.Remoting.Channels.Unix
}
finally
{
_stream.Close();
_client.Close ();
_serverChannel.ReleaseConnection (Thread.CurrentThread);
try {
_serverChannel.ReleaseConnection (Thread.CurrentThread);
_stream.Close();
_client.Close ();
} catch {
}
}
}
@@ -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);
@@ -75,6 +75,13 @@ namespace Mono.Unix
throw new ArgumentException ("socketAddress is not a unix socket address.");
*/
if (socketAddress.Size == 2) {
// Empty filename.
// Probably from RemoteEndPoint which on linux does not return the file name.
UnixEndPoint uep = new UnixEndPoint ("a");
uep.filename = "";
return uep;
}
byte [] bytes = new byte [socketAddress.Size - 2 - 1];
for (int i = 0; i < bytes.Length; i++) {
bytes [i] = socketAddress [i + 2];
@@ -150,6 +150,10 @@ namespace Mono.Unix {
return;
if (disposing) {
try {
File.Delete (((UnixEndPoint) savedEP).Filename);
} catch {
}
if (server != null)
server.Close ();
@@ -4,7 +4,7 @@
// Author:
// Atsushi Enomoto <[email protected]>
//
// Copyright (C) 2008 Novell Inc. http://novell.com
// Copyright (C) 2008-2011 Novell Inc. http://novell.com
//
//
@@ -44,6 +44,9 @@ namespace System.ComponentModel.DataAnnotations
MultilineText,
EmailAddress,
Password,
Url
Url,
#if NET_4_0
ImageUrl
#endif
}
}
@@ -39,5 +39,8 @@ namespace System.ComponentModel.DataAnnotations
public bool ConvertEmptyStringToNull { get; set; }
public string DataFormatString { get; set; }
public string NullDisplayText { get; set; }
#if NET_4_0
public bool HtmlEncode { get; set; }
#endif
}
}
@@ -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;
}
@@ -100,7 +100,7 @@ namespace System.Configuration {
if (relativePath.StartsWith (relConfigPath, StringComparison.Ordinal))
relativePath = relativePath.Substring (relConfigPath.Length);
ConfigurationLocation loc = Locations.Find (relativePath);
ConfigurationLocation loc = Locations.FindBest (relativePath);
if (loc == null)
return parentConfig;
@@ -107,6 +107,9 @@ namespace System.Configuration {
internal void SetParentConfiguration (Configuration parent)
{
if (parentResolved)
return;
parentResolved = true;
this.parent = parent;
if (configuration != null)
@@ -54,7 +54,42 @@ namespace System.Configuration {
return loc;
return null;
}
internal ConfigurationLocation FindBest (string location)
{
if(String.IsNullOrEmpty (location))
return null;
ConfigurationLocation bestMatch = null;
int locationlen = location.Length;
int bestmatchlen = 0;
foreach (ConfigurationLocation loc in InnerList) {
string lpath = loc.Path;
if (String.IsNullOrEmpty (lpath))
continue;
int lpathlen = lpath.Length;
if (location.StartsWith (lpath, StringComparison.OrdinalIgnoreCase)) {
// Exact match always takes precedence
if (locationlen == lpathlen)
return loc;
// ensure path based comparisons consider full directory names (i.e. so 'admin' does not match an 'administration' path)
if(locationlen > lpathlen && location [lpathlen] != '/')
continue;
if(bestMatch == null)
bestMatch = loc;
else if (bestmatchlen < lpathlen) {
bestMatch = loc;
bestmatchlen = lpathlen;
}
}
}
return bestMatch;
}
}
}
#endif
@@ -28,8 +28,6 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using System;
using System.Collections;
using System.Collections.Specialized;
@@ -147,6 +145,8 @@ namespace MonoTests.System.Configuration {
FileInfo fi = new FileInfo (config.FilePath);
#if TARGET_JVM
Assert.AreEqual ("nunit-console.jar.config", fi.Name);
#elif NET_4_0
Assert.AreEqual ("System.Configuration_test_net_4_0.dll.config", fi.Name);
#else
Assert.AreEqual ("System.Configuration_test_net_2_0.dll.config", fi.Name);
#endif
@@ -492,5 +492,3 @@ namespace MonoTests.System.Configuration {
}
}
}
#endif
@@ -27,7 +27,6 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using System;
using System.Configuration;
@@ -153,18 +152,28 @@ namespace MonoTests.System.Configuration {
{
ConfigurationPermission p = new ConfigurationPermission (PermissionState.Unrestricted);
#if NET_4_0
Assert.AreEqual(
"<IPermission class=\"System.Configuration.ConfigurationPermission, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"\nversion=\"1\"\nUnrestricted=\"true\"/>\n",
"<IPermission class=\"System.Configuration.ConfigurationPermission, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"\nversion=\"1\"\nUnrestricted=\"true\"/>\n",
p.ToString().Replace ("\r\n", "\n"), "A1");
#else
Assert.AreEqual (
"<IPermission class=\"System.Configuration.ConfigurationPermission, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"\nversion=\"1\"\nUnrestricted=\"true\"/>\n",
p.ToString ().Replace ("\r\n", "\n"), "A1");
#endif
p = new ConfigurationPermission (PermissionState.None);
#if NET_4_0
Assert.AreEqual (
"<IPermission class=\"System.Configuration.ConfigurationPermission, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"\nversion=\"1\"/>\n",
p.ToString().Replace ("\r\n", "\n"), "A2");
#else
Assert.AreEqual (
"<IPermission class=\"System.Configuration.ConfigurationPermission, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"\nversion=\"1\"/>\n",
p.ToString().Replace ("\r\n", "\n"), "A2");
p.ToString ().Replace ("\r\n", "\n"), "A2");
#endif
}
}
}
#endif
@@ -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
@@ -871,6 +871,8 @@ namespace System.Linq.Expressions {
return AddChecked (left, right, method);
case ExpressionType.AndAlso:
return AndAlso (left, right);
case ExpressionType.ArrayIndex:
return ArrayIndex (left, right);
case ExpressionType.Coalesce:
return Coalesce (left, right, conversion);
case ExpressionType.Divide:
@@ -53,11 +53,17 @@ namespace System.Linq.Expressions {
return self == typeof (Expression) || self.IsSubclassOf (typeof (Expression));
}
public static bool IsGenericImplementationOf (this Type self, Type type)
public static bool IsGenericImplementationOf (this Type self, Type type, out Type generic_iface)
{
foreach (Type iface in self.GetInterfaces ())
if (iface.IsGenericInstanceOf (type))
return true;
foreach (var iface in self.GetInterfaces ()) {
if (!iface.IsGenericInstanceOf (type))
continue;
generic_iface = iface;
return true;
}
generic_iface = null;
return false;
}
@@ -86,23 +86,17 @@ namespace System.Linq.Parallel.QueryNodes
internal override IList<IEnumerable<KeyValuePair<long, TResult>>> GetOrderedEnumerables (QueryOptions options)
{
var source = Parent.GetOrderedEnumerables (options);
var sizeRequests = new Tuple<long, int, IEnumerable<TCollection>> [options.PartitionCount];
if (collectionSelectorIndexed == null)
collectionSelectorIndexed = (e, i) => collectionSelector (e);
var sizeRequests = new SizeRequest[source.Count];
long deviation = 0;
Barrier barrier = new Barrier (options.PartitionCount, delegate {
Array.Sort (sizeRequests, (e1, e2) => e1.Item1.CompareTo (e2.Item1));
long newDeviation = deviation;
for (int i = sizeRequests.Length - 1; i >= 0; i--) {
var reqi = sizeRequests[i];
long newIndex = reqi.Item1 + deviation;
newDeviation += reqi.Item2 - 1;
for (int j = i - 1; j >= 0; j--)
newIndex += sizeRequests[j].Item2 - 1;
sizeRequests[i] = Tuple.Create (newIndex, reqi.Item2, reqi.Item3);
Barrier barrier = new Barrier (source.Count, delegate (Barrier b) {
Array.Sort (sizeRequests, KeyComparator);
for (int i = 0; i < b.ParticipantCount; ++i) {
if (sizeRequests[i].Key == -1)
continue;
sizeRequests[i].Key = deviation;
deviation += sizeRequests[i].Size;
}
deviation = newDeviation;
});
return source
@@ -120,25 +114,46 @@ namespace System.Linq.Parallel.QueryNodes
}
IEnumerable<KeyValuePair<long, TResult>> GetOrderedEnumerableInternal (IEnumerable<KeyValuePair<long, TSource>> source,
Tuple<long, int, IEnumerable<TCollection>>[] sizeRequests,
SizeRequest[] sizeRequests,
int index,
Barrier barrier)
{
IEnumerator<KeyValuePair<long, TSource>> enumerator = source.GetEnumerator ();
bool isIndexed = IsIndexed;
try {
foreach (KeyValuePair<long, TSource> element in source) {
IEnumerable<TCollection> collection = collectionSelectorIndexed (element.Value, (int)element.Key);
sizeRequests[index] = Tuple.Create (element.Key, GetCount (ref collection), collection);
while (true) {
KeyValuePair<long, TSource> element;
IEnumerable<TCollection> collection;
if (enumerator.MoveNext ()) {
element = enumerator.Current;
collection = isIndexed ?
collectionSelectorIndexed (element.Value, (int)element.Key) :
collectionSelector (element.Value);
var count = GetCount (ref collection);
sizeRequests[index].Update (element.Key, count, collection, element.Value);
}
barrier.SignalAndWait ();
long i = sizeRequests[index].Item1;
collection = sizeRequests[index].Item3;
long i = sizeRequests[index].Key;
collection = sizeRequests[index].Collection;
var elementValue = sizeRequests[index].ElementValue;
sizeRequests[index].Clear ();
if (i == -1)
break;
foreach (TCollection item in collection)
yield return new KeyValuePair<long, TResult> (i++, resultSelector (element.Value, item));
yield return new KeyValuePair<long, TResult> (i++, resultSelector (elementValue, item));
}
} finally {
barrier.RemoveParticipant ();
enumerator.Dispose ();
}
}
@@ -157,6 +172,35 @@ namespace System.Linq.Parallel.QueryNodes
return foo.Count;
}
static int KeyComparator (SizeRequest e1, SizeRequest e2)
{
return e1.Key.CompareTo (e2.Key);
}
struct SizeRequest
{
public long Key;
public int Size;
public IEnumerable<TCollection> Collection;
public TSource ElementValue;
public void Update (long k, int s, IEnumerable<TCollection> c, TSource ev)
{
Key = k;
Size = s;
Collection = c;
ElementValue = ev;
}
public void Clear ()
{
Key = -1;
Size = 0;
Collection = null;
ElementValue = default (TSource);
}
}
}
}
@@ -55,6 +55,19 @@ namespace System.Linq.Parallel.QueryNodes
this.customPartitioner = custom;
}
// If possible, this property will return the number of element the query
// is going to process. If that number if pretty low, executing the query
// sequentially is better
internal int Count {
get {
if (source == null)
return -1;
ICollection coll = source as ICollection;
return coll == null ? -1 : coll.Count;
}
}
public override void Visit (INodeVisitor visitor)
{
visitor.Visit<T> (this);
@@ -63,14 +63,14 @@ namespace System.Linq.Parallel.QueryNodes
internal override IList<IEnumerable<TSource>> GetEnumerablesIndexed (QueryOptions options)
{
return Parent.GetOrderedEnumerables (options)
.Select ((i) => i.Where ((e) => indexedPredicate (e.Value, (int)e.Key)).Select ((e) => e.Value))
.Select (i => i.Where (e => indexedPredicate (e.Value, (int)e.Key)).Select (e => e.Value))
.ToList ();
}
internal override IList<IEnumerable<TSource>> GetEnumerablesNonIndexed (QueryOptions options)
{
return Parent.GetEnumerables (options)
.Select ((i) => i.Where (predicate))
.Select (i => i.Where (predicate))
.ToList ();
}
@@ -78,7 +78,7 @@ namespace System.Linq.Parallel.QueryNodes
{
IList<IEnumerable<KeyValuePair<long, TSource>>> sources = Parent.GetOrderedEnumerables (options);
Tuple<TSource, long, bool>[] store = new Tuple<TSource, long, bool>[sources.Count];
ProcessingSlot[] store = new ProcessingSlot[sources.Count];
long lastIndex = 0;
Barrier barrier = new Barrier (sources.Count, delegate (Barrier b) {
@@ -87,11 +87,8 @@ namespace System.Linq.Parallel.QueryNodes
// Reassign a good index
int i = 0;
for (i = 0; i < store.Length && store[i].Item3; i++) {
Tuple<TSource, long, bool> old = store[i];
store[i] = Tuple.Create (old.Item1, lastIndex + i, old.Item3);
}
for (i = 0; i < store.Length && store[i].IsValid; ++i)
store[i].Index = lastIndex + i;
// Update lastIndex for next round
lastIndex += i;
@@ -102,43 +99,42 @@ namespace System.Linq.Parallel.QueryNodes
.ToList ();
}
static int ArraySortMethod (Tuple<TSource, long, bool> lhs, Tuple<TSource, long, bool> rhs)
static int ArraySortMethod (ProcessingSlot lhs, ProcessingSlot rhs)
{
if (lhs.Item3 && !rhs.Item3)
if (lhs.IsValid && !rhs.IsValid)
return -1;
if (!lhs.Item3 && rhs.Item3)
if (!lhs.IsValid && rhs.IsValid)
return 1;
if (!lhs.Item3 && !rhs.Item3)
if (!lhs.IsValid && !rhs.IsValid)
return 0;
return (lhs.Item2 < rhs.Item2) ? -1 : 1;
return lhs.Index < rhs.Index ? -1 : 1;
}
IEnumerable<KeyValuePair<long, TSource>> GetEnumerator (IEnumerable<KeyValuePair<long, TSource>> source,
Barrier barrier,
CancellationToken token,
Tuple<TSource, long, bool>[] store, int index)
ProcessingSlot[] store, int index)
{
IEnumerator<KeyValuePair<long, TSource>> current = source.GetEnumerator ();
bool result;
Tuple<TSource, long, bool> reset = Tuple.Create (default (TSource), long.MaxValue, false);
bool isIndexed = IsIndexed;
try {
while (current.MoveNext ()) {
KeyValuePair<long, TSource> curr = current.Current;
result = IsIndexed ? indexedPredicate (curr.Value, (int)curr.Key) : predicate (curr.Value);
store[index] = Tuple.Create (curr.Value, curr.Key, result);
bool result = isIndexed ? indexedPredicate (curr.Value, (int)curr.Key) : predicate (curr.Value);
store[index].Update (curr.Value, curr.Key, result);
barrier.SignalAndWait (token);
Tuple<TSource, long, bool> value = store [index];
var value = store [index];
if (value.Item3)
yield return new KeyValuePair<long, TSource> (value.Item2, value.Item1);
if (value.IsValid)
yield return new KeyValuePair<long, TSource> (value.Index, value.Value);
// Reset
store[index] = reset;
store[index].Clear ();
}
} finally {
// Remove our participation
@@ -146,6 +142,25 @@ namespace System.Linq.Parallel.QueryNodes
current.Dispose ();
}
}
struct ProcessingSlot
{
public TSource Value;
public long Index;
public bool IsValid;
public void Update (TSource v, long i, bool t)
{
Value = v;
Index = i;
IsValid = t;
}
public void Clear ()
{
Update (default (TSource), long.MaxValue, false);
}
}
}
}
#endif
@@ -37,13 +37,15 @@ namespace System.Linq.Parallel
{
internal class SlotBucket
{
ConcurrentDictionary<long, T> temporaryArea = new ConcurrentDictionary<long, T> ();
KeyValuePair<long, T>?[] stagingArea;
readonly ConcurrentDictionary<long, T> temporaryArea = new ConcurrentDictionary<long, T> ();
readonly KeyValuePair<long, T>[] stagingArea;
long currentIndex;
readonly int count;
CountdownEvent stagingCount;
CountdownEvent participantCount;
CancellationTokenSource src = new CancellationTokenSource ();
CancellationToken mergedToken;
@@ -52,7 +54,7 @@ namespace System.Linq.Parallel
this.count = count;
stagingCount = new CountdownEvent (count);
participantCount = new CountdownEvent (count);
stagingArea = new KeyValuePair<long, T>?[count];
stagingArea = new KeyValuePair<long, T>[count];
currentIndex = -count;
mergedToken = CancellationTokenSource.CreateLinkedTokenSource (src.Token, token).Token;
}
@@ -89,31 +91,36 @@ namespace System.Linq.Parallel
src.Cancel ();
}
void Skim ()
bool Skim ()
{
bool result = false;
for (int i = 0; i < count; i++) {
T temp;
int index = i + (int)currentIndex;
if (stagingArea[index % count].HasValue)
if (stagingArea[i].Key != -1)
continue;
if (!temporaryArea.TryRemove (index, out temp))
continue;
stagingArea [index % count] = new KeyValuePair<long, T> (index, temp);
result = true;
stagingArea [i] = new KeyValuePair<long, T> (index, temp);
if (stagingCount.Signal ())
break;
}
return result;
}
void Clean ()
{
for (int i = 0; i < stagingArea.Length; i++)
stagingArea[i] = new Nullable<KeyValuePair<long, T>> ();
stagingArea[i] = new KeyValuePair<long, T> (-1, default (T));
}
public IEnumerator<KeyValuePair<long, T>?> Wait ()
public KeyValuePair<long, T>[] Wait ()
{
Clean ();
stagingCount.Reset ();
@@ -123,35 +130,36 @@ namespace System.Linq.Parallel
Skim ();
while (!stagingCount.IsSet) {
if (!participantCount.IsSet)
if (!participantCount.IsSet) {
try {
stagingCount.Wait (mergedToken);
} catch {
Skim ();
}
}
if (participantCount.IsSet) {
if (Skim ())
continue;
// Totally finished
if (stagingArea[0].HasValue)
if (stagingArea[0].Key != -1)
break;
else
return null;
}
}
return ((IEnumerable<KeyValuePair<long, T>?>)stagingArea).GetEnumerator ();
return stagingArea;
}
}
readonly int num;
SlotBucket slotBucket;
IEnumerator<KeyValuePair<long, T>?> currEnum;
KeyValuePair<long, T> curr;
KeyValuePair<long, T>[] slot;
int current;
internal OrderingEnumerator (int num, CancellationToken token)
{
this.num = num;
slotBucket = new SlotBucket (num, token);
}
@@ -168,28 +176,25 @@ namespace System.Linq.Parallel
public bool MoveNext ()
{
do {
while (currEnum == null || !currEnum.MoveNext ()) {
if (currEnum != null)
currEnum.Dispose ();
if ((currEnum = slotBucket.Wait ()) == null)
if (slot == null || ++current >= slot.Length) {
if ((slot = slotBucket.Wait ()) == null)
return false;
current = 0;
}
} while (!currEnum.Current.HasValue);
curr = currEnum.Current.Value;
} while (slot[current].Key == -1);
return true;
}
public T Current {
get {
return curr.Value;
return slot[current].Value;
}
}
object IEnumerator.Current {
get {
return curr.Value;
return slot[current].Value;
}
}
@@ -93,26 +93,30 @@ namespace System.Linq.Parallel
Action endAction,
QueryOptions options)
{
CancellationTokenSource src
= CancellationTokenSource.CreateLinkedTokenSource (options.ImplementerToken, options.Token);
IList<IEnumerable<TElement>> enumerables = acquisitionFunc (node, options);
Task[] tasks = new Task[enumerables.Count];
CancellationTokenSource src
= CancellationTokenSource.CreateLinkedTokenSource (options.ImplementerToken, options.Token);
for (int i = 0; i < tasks.Length; i++) {
int index = i;
tasks[i] = Task.Factory.StartNew (() => {
foreach (TElement item in enumerables[index]) {
// This is from specific operators
if (options.ImplementerToken.IsCancellationRequested)
break;
if (options.Token.IsCancellationRequested)
throw new OperationCanceledException (options.Token);
try {
foreach (TElement item in enumerables[index]) {
// This is from specific operators
if (options.ImplementerToken.IsCancellationRequested)
break;
if (options.Token.IsCancellationRequested)
throw new OperationCanceledException (options.Token);
call (item, src.Token);
call (item, src.Token);
}
} finally {
if (endAction != null)
endAction ();
}
if (endAction != null)
endAction ();
}, options.Token);
}
@@ -165,28 +169,14 @@ namespace System.Linq.Parallel
}
for (int i = 0; i < tasks.Length; i++) {
int index = i;
bool firstRun = true;
var procSlot = new AggregateProcessSlot<T, U> (options,
i,
enumerables[i].GetEnumerator (),
locals,
localCall,
seedFunc);
tasks[i] = Task.Factory.StartNew (() => {
foreach (T item in enumerables[index]) {
// This is from specific operators
if (options.ImplementerToken.IsCancellationRequested)
break;
if (options.Token.IsCancellationRequested)
throw new OperationCanceledException (options.Token);
if (firstRun && seedFunc == null) {
firstRun = false;
// HACK: TODO: omgwtfitsuckssomuch
locals[index] = (U)(object)item;
continue;
}
U acc = locals[index];
locals[index] = localCall (acc, item);
}
}, options.Token);
tasks[i] = Task.Factory.StartNew (procSlot.Process, options.Token);
}
Task.WaitAll (tasks, options.Token);
@@ -194,6 +184,54 @@ namespace System.Linq.Parallel
if (call != null)
call (locals);
}
class AggregateProcessSlot<T, U>
{
readonly QueryOptions options;
readonly int index;
readonly IEnumerator<T> enumerator;
readonly U[] locals;
readonly Func<U, T, U> localCall;
readonly Func<U> seedFunc;
public AggregateProcessSlot (QueryOptions options,
int index,
IEnumerator<T> enumerator,
U[] locals,
Func<U, T, U> localCall,
Func<U> seedFunc)
{
this.options = options;
this.index = index;
this.enumerator = enumerator;
this.locals = locals;
this.localCall = localCall;
this.seedFunc = seedFunc;
}
public void Process ()
{
var token = options.Token;
var implementerToken = options.ImplementerToken;
try {
if (seedFunc == null) {
if (!enumerator.MoveNext ())
return;
locals[index] = (U)(object)enumerator.Current;
}
while (enumerator.MoveNext ()) {
if (implementerToken.IsCancellationRequested)
break;
token.ThrowIfCancellationRequested ();
locals[index] = localCall (locals[index], enumerator.Current);
}
} finally {
enumerator.Dispose ();
}
}
}
}
}
#endif
@@ -24,11 +24,12 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if NET_4_0
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
#if NET_4_0
using System.Collections.Concurrent.Partitioners;
namespace System.Linq.Parallel
{
@@ -50,24 +50,30 @@ namespace System.Linq.Parallel
internal ParallelQueryEnumerator (QueryBaseNode<T> node)
{
this.options = ParallelExecuter.CheckQuery (node);
Setup ();
// Launch adding to the buffer asynchronously via Tasks
if (options.BehindOrderGuard.Value) {
waitAction = ParallelExecuter.ProcessAndCallback (node,
ordEnumerator.Add,
ordEnumerator.EndParticipation,
ordEnumerator.Stop,
options);
if (options.ShouldBeSequential && options.Mode != ParallelExecutionMode.ForceParallelism) {
IEnumerable<T> buffer = node.GetSequential ();
loader = buffer.GetEnumerator ();
} else {
waitAction = ParallelExecuter.ProcessAndCallback (node,
buffer.Add,
buffer.CompleteAdding,
options);
}
Setup ();
if (options.Options.HasValue && options.Options.Value == ParallelMergeOptions.FullyBuffered)
waitAction ();
// Launch adding to the buffer asynchronously via Tasks
if (options.BehindOrderGuard.Value) {
waitAction = ParallelExecuter.ProcessAndCallback (node,
ordEnumerator.Add,
ordEnumerator.EndParticipation,
ordEnumerator.Stop,
options);
} else {
waitAction = ParallelExecuter.ProcessAndCallback (node,
buffer.Add,
buffer.CompleteAdding,
options);
}
if (options.Options.HasValue && options.Options.Value == ParallelMergeOptions.FullyBuffered)
waitAction ();
}
}
void Setup ()
@@ -35,6 +35,8 @@ namespace System.Linq.Parallel
internal class QueryCheckerVisitor : INodeVisitor
{
const int minSequentialThreshold = 20;
// Information gathering
ParallelMergeOptions? options = null;
ParallelExecutionMode? mode = null;
@@ -75,6 +77,10 @@ namespace System.Linq.Parallel
behindOrderGuard = false;
if (degreeOfParallelism != null)
partitionCount = degreeOfParallelism.Value;
int count;
if ((count = node.Count) != -1 && count < minSequentialThreshold)
ShouldBeSequential = true;
}
public void Visit<T, TParent> (QueryStreamNode<T, TParent> node)
@@ -117,7 +123,7 @@ namespace System.Linq.Parallel
internal QueryOptions Options {
get {
return new QueryOptions (options, mode, token == null ? CancellationToken.None : token.Value,
UseStrip, behindOrderGuard, partitionCount, implementerToken);
UseStrip, behindOrderGuard, partitionCount, implementerToken, ShouldBeSequential);
}
}
@@ -32,9 +32,20 @@ namespace System.Linq.Parallel
{
internal class QueryOptions
{
public ParallelMergeOptions? Options;
public ParallelExecutionMode? Mode;
public CancellationToken Token;
public ParallelMergeOptions? Options {
get;
private set;
}
public ParallelExecutionMode? Mode {
get;
private set;
}
public CancellationToken Token {
get;
private set;
}
/* This token is to be used by some operator (like Take) to tell that
* the execution of the query can be prematurly stopped
*
@@ -43,11 +54,40 @@ namespace System.Linq.Parallel
* set. Operator may chain up multiple cancellation token that way.
* When checking for this token, the task body should simply return.
*/
public CancellationToken ImplementerToken;
public bool UseStrip;
public bool? BehindOrderGuard;
public int PartitionCount;
public Tuple<bool, bool, bool> PartitionerSettings;
public CancellationToken ImplementerToken {
get;
private set;
}
public bool UseStrip {
get;
private set;
}
public bool? BehindOrderGuard {
get;
private set;
}
public int PartitionCount {
get;
private set;
}
public Tuple<bool, bool, bool> PartitionerSettings {
get;
internal set;
}
public CancellationToken MergedToken {
get;
private set;
}
public bool ShouldBeSequential {
get;
private set;
}
public QueryOptions (ParallelMergeOptions? options,
ParallelExecutionMode? mode,
@@ -55,7 +95,8 @@ namespace System.Linq.Parallel
bool useStrip,
bool? behindOrderGuard,
int partitionCount,
CancellationToken implementerToken)
CancellationToken implementerToken,
bool shouldBeSequential)
{
Options = options;
Mode = mode;
@@ -65,6 +106,7 @@ namespace System.Linq.Parallel
PartitionCount = partitionCount;
PartitionerSettings = null;
ImplementerToken = implementerToken;
ShouldBeSequential = shouldBeSequential;
MergeTokens (token, implementerToken);
}
@@ -82,11 +124,6 @@ namespace System.Linq.Parallel
else
MergedToken = CancellationToken.None;
}
public CancellationToken MergedToken {
get;
private set;
}
}
}
#endif
@@ -48,12 +48,12 @@ namespace System.Linq
return (new RangeList (start, count)).AsParallel ();
}
public static ParallelQuery<TResult> Repeat<TResult> (TResult obj, int count)
public static ParallelQuery<TResult> Repeat<TResult> (TResult element, int count)
{
if (count < 0)
throw new ArgumentOutOfRangeException ("count", "count is less than 0");
return (new RepeatList<TResult> (obj, count)).AsParallel ();
return (new RepeatList<TResult> (element, count)).AsParallel ();
}
#endregion
@@ -70,7 +70,12 @@ namespace System.Linq
if (source == null)
throw new ArgumentNullException ("source");
return new ParallelQuery<TSource> (new QueryStartNode<TSource> (source));
/* Someone might be trying to use AsParallel a bit too much, if the query was in fact
* already a ParallelQuery, just cast it
*/
ParallelQuery<TSource> query = source as ParallelQuery<TSource>;
return query ?? new ParallelQuery<TSource> (new QueryStartNode<TSource> (source));
}
public static ParallelQuery<TSource> AsParallel<TSource> (this Partitioner<TSource> source)
@@ -78,7 +83,12 @@ namespace System.Linq
if (source == null)
throw new ArgumentNullException ("source");
return new ParallelQuery<TSource> (new QueryStartNode<TSource> (source));
/* Someone might be trying to use AsParallel a bit too much, if the query was in fact
* already a ParallelQuery, just cast it
*/
ParallelQuery<TSource> query = source as ParallelQuery<TSource>;
return query ?? new ParallelQuery<TSource> (new QueryStartNode<TSource> (source));
}
public static ParallelQuery AsParallel (this IEnumerable source)
@@ -86,7 +96,12 @@ namespace System.Linq
if (source == null)
throw new ArgumentNullException ("source");
return new ParallelQuery<object> (new QueryStartNode<object> (source.Cast<object> ()));
/* Someone might be trying to use AsParallel a bit too much, if the query was in fact
* already a ParallelQuery, just cast it
*/
ParallelQuery query = source as ParallelQuery;
return query ?? new ParallelQuery<object> (new QueryStartNode<object> (source.Cast<object> ()));
}
public static IEnumerable<TSource> AsEnumerable<TSource> (this ParallelQuery<TSource> source)
@@ -161,14 +176,14 @@ namespace System.Linq
}
public static ParallelQuery<TSource> WithDegreeOfParallelism<TSource> (this ParallelQuery<TSource> source,
int degreeParallelism)
int degreeOfParallelism)
{
if (degreeParallelism < 1 || degreeParallelism > 63)
throw new ArgumentException ("degreeOfParallelism is less than 1 or greater than 63", "degreeParallelism");
if (degreeOfParallelism < 1 || degreeOfParallelism > 63)
throw new ArgumentException ("degreeOfParallelism is less than 1 or greater than 63", "degreeOfParallelism");
if (source == null)
throw new ArgumentNullException ("source");
return new ParallelQuery<TSource> (new DegreeOfParallelismNode<TSource> (degreeParallelism, source.Node));
return new ParallelQuery<TSource> (new DegreeOfParallelismNode<TSource> (degreeOfParallelism, source.Node));
}
internal static ParallelQuery<TSource> WithImplementerToken<TSource> (this ParallelQuery<TSource> source,
@@ -319,15 +334,15 @@ namespace System.Linq
}
public static TResult Aggregate<TSource, TAccumulate, TResult> (this ParallelQuery<TSource> source,
Func<TAccumulate> seedFunc,
Func<TAccumulate> seedFactory,
Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc,
Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc,
Func<TAccumulate, TResult> resultSelector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (seedFunc == null)
throw new ArgumentNullException ("seedFunc");
if (seedFactory == null)
throw new ArgumentNullException ("seedFactory");
if (updateAccumulatorFunc == null)
throw new ArgumentNullException ("updateAccumulatorFunc");
if (combineAccumulatorsFunc == null)
@@ -337,7 +352,7 @@ namespace System.Linq
TAccumulate accumulator = default (TAccumulate);
ParallelExecuter.ProcessAndAggregate<TSource, TAccumulate> (source.Node, seedFunc, updateAccumulatorFunc, (list) => {
ParallelExecuter.ProcessAndAggregate<TSource, TAccumulate> (source.Node, seedFactory, updateAccumulatorFunc, (list) => {
accumulator = list [0];
for (int i = 1; i < list.Count; i++)
accumulator = combineAccumulatorsFunc (accumulator, list[i]);
@@ -1200,104 +1215,104 @@ namespace System.Linq
return source.Select ((e) => e.HasValue ? e.Value : 0).Average ();
}
public static double Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, int> func)
public static double Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, int> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Average ();
return source.Select (selector).Average ();
}
public static double Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, long> func)
public static double Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, long> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Average ();
return source.Select (selector).Average ();
}
public static float Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, float> func)
public static float Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, float> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Average ();
return source.Select (selector).Average ();
}
public static double Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, double> func)
public static double Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, double> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Average ();
return source.Select (selector).Average ();
}
public static decimal Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal> func)
public static decimal Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Average ();
return source.Select (selector).Average ();
}
public static double? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, int?> func)
public static double? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, int?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Average ();
return source.Select (selector).Average ();
}
public static double? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, long?> func)
public static double? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, long?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Average ();
return source.Select (selector).Average ();
}
public static float? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, float?> func)
public static float? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, float?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Average ();
return source.Select (selector).Average ();
}
public static double? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, double?> func)
public static double? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, double?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Average ();
return source.Select (selector).Average ();
}
public static decimal? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal?> func)
public static decimal? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Average ();
return source.Select (selector).Average ();
}
#endregion
@@ -1379,104 +1394,104 @@ namespace System.Linq
return source.Select ((e) => e.HasValue ? e.Value : 0).Sum ();
}
public static int Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, int> func)
public static int Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, int> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Sum ();
return source.Select (selector).Sum ();
}
public static long Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, long> func)
public static long Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, long> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Sum ();
return source.Select (selector).Sum ();
}
public static decimal Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal> func)
public static decimal Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Sum ();
return source.Select (selector).Sum ();
}
public static float Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, float> func)
public static float Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, float> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Sum ();
return source.Select (selector).Sum ();
}
public static double Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, double> func)
public static double Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, double> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Sum ();
return source.Select (selector).Sum ();
}
public static int? Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, int?> func)
public static int? Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, int?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Sum ();
return source.Select (selector).Sum ();
}
public static long? Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, long?> func)
public static long? Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, long?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Sum ();
return source.Select (selector).Sum ();
}
public static decimal? Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal?> func)
public static decimal? Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Sum ();
return source.Select (selector).Sum ();
}
public static float? Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, float?> func)
public static float? Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, float?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Sum ();
return source.Select (selector).Sum ();
}
public static double? Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, double?> func)
public static double? Sum<TSource> (this ParallelQuery<TSource> source, Func<TSource, double?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Sum ();
return source.Select (selector).Sum ();
}
#endregion
@@ -1527,14 +1542,14 @@ namespace System.Linq
return BestOrder (source, (first, second) => comparer.Compare (first, second) < 0, default (TSource));
}
public static TResult Min<TSource, TResult> (this ParallelQuery<TSource> source, Func<TSource, TResult> func)
public static TResult Min<TSource, TResult> (this ParallelQuery<TSource> source, Func<TSource, TResult> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Min ();
return source.Select (selector).Min ();
}
public static int? Min (this ParallelQuery<int?> source)
@@ -1577,104 +1592,104 @@ namespace System.Linq
return source.Select ((e) => e.HasValue ? e.Value : decimal.MaxValue).Min ();
}
public static int Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, int> func)
public static int Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, int> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Min ();
return source.Select (selector).Min ();
}
public static long Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, long> func)
public static long Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, long> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Min ();
return source.Select (selector).Min ();
}
public static float Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, float> func)
public static float Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, float> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Min ();
return source.Select (selector).Min ();
}
public static double Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, double> func)
public static double Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, double> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Min ();
return source.Select (selector).Min ();
}
public static decimal Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal> func)
public static decimal Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Min ();
return source.Select (selector).Min ();
}
public static int? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, int?> func)
public static int? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, int?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Min ();
return source.Select (selector).Min ();
}
public static long? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, long?> func)
public static long? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, long?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Min ();
return source.Select (selector).Min ();
}
public static float? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, float?> func)
public static float? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, float?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Min ();
return source.Select (selector).Min ();
}
public static double? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, double?> func)
public static double? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, double?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Min ();
return source.Select (selector).Min ();
}
public static decimal? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal?> func)
public static decimal? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Min ();
return source.Select (selector).Min ();
}
public static int Max (this ParallelQuery<int> source)
@@ -1709,14 +1724,14 @@ namespace System.Linq
return BestOrder (source, (first, second) => comparer.Compare (first, second) > 0, default (TSource));
}
public static TResult Max<TSource, TResult> (this ParallelQuery<TSource> source, Func<TSource, TResult> func)
public static TResult Max<TSource, TResult> (this ParallelQuery<TSource> source, Func<TSource, TResult> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Max ();
return source.Select (selector).Max ();
}
public static int? Max (this ParallelQuery<int?> source)
@@ -1759,104 +1774,104 @@ namespace System.Linq
return source.Select ((e) => e.HasValue ? e.Value : decimal.MinValue).Max ();
}
public static int Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, int> func)
public static int Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, int> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Max ();
return source.Select (selector).Max ();
}
public static long Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, long> func)
public static long Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, long> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Max ();
return source.Select (selector).Max ();
}
public static float Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, float> func)
public static float Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, float> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Max ();
return source.Select (selector).Max ();
}
public static double Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, double> func)
public static double Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, double> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Max ();
return source.Select (selector).Max ();
}
public static decimal Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal> func)
public static decimal Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Max ();
return source.Select (selector).Max ();
}
public static int? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, int?> func)
public static int? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, int?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Max ();
return source.Select (selector).Max ();
}
public static long? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, long?> func)
public static long? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, long?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Max ();
return source.Select (selector).Max ();
}
public static float? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, float?> func)
public static float? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, float?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Max ();
return source.Select (selector).Max ();
}
public static double? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, double?> func)
public static double? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, double?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Max ();
return source.Select (selector).Max ();
}
public static decimal? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal?> func)
public static decimal? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal?> selector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (func == null)
throw new ArgumentNullException ("func");
if (selector == null)
throw new ArgumentNullException ("selector");
return source.Select (func).Max ();
return source.Select (selector).Max ();
}
#endregion
@@ -158,13 +158,12 @@ namespace System.Linq {
if (queryable != null)
return queryable;
var type = source.GetType ();
if (!type.IsGenericImplementationOf (typeof (IEnumerable<>)))
Type ienumerable;
if (!source.GetType ().IsGenericImplementationOf (typeof (IEnumerable<>), out ienumerable))
throw new ArgumentException ("source is not IEnumerable<>");
return (IQueryable) Activator.CreateInstance (
typeof (QueryableEnumerable<>).MakeGenericType (type.GetFirstGenericArgument ()), source);
typeof (QueryableEnumerable<>).MakeGenericType (ienumerable.GetFirstGenericArgument ()), source);
}
#endregion
@@ -0,0 +1,78 @@
//
// TaskExtensions.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.
//
#if NET_4_0 && !BOOTSTRAP_NET_4_0
using System;
using System.Threading.Tasks;
namespace System.Threading.Tasks
{
public static class TaskExtensions
{
const TaskContinuationOptions opt = TaskContinuationOptions.ExecuteSynchronously;
public static Task<TResult> Unwrap<TResult> (this Task<Task<TResult>> task)
{
if (task == null)
throw new ArgumentNullException ("task");
TaskCompletionSource<TResult> src = new TaskCompletionSource<TResult> ();
task.ContinueWith (t1 => CopyCat (t1, src, () => t1.Result.ContinueWith (t2 => CopyCat (t2, src, () => src.SetResult (t2.Result)), opt)), opt);
return src.Task;
}
public static Task Unwrap (this Task<Task> task)
{
if (task == null)
throw new ArgumentNullException ("task");
TaskCompletionSource<object> src = new TaskCompletionSource<object> ();
task.ContinueWith (t1 => CopyCat (t1, src, () => t1.Result.ContinueWith (t2 => CopyCat (t2, src, () => src.SetResult (null)), opt)), opt);
return src.Task;
}
static void CopyCat<TResult> (Task source,
TaskCompletionSource<TResult> dest,
Action normalAction)
{
if (source.IsCanceled)
dest.SetCanceled ();
else if (source.IsFaulted)
dest.SetException (source.Exception.InnerExceptions);
else
normalAction ();
}
}
}
#endif
@@ -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)
|| recursionPolicy == LockRecursionPolicy.SupportsRecursion) {
if (CurrentLockState.Has (LockState.Upgradable)
|| (recursionPolicy == LockRecursionPolicy.SupportsRecursion && ctstate.LockState.Has (LockState.Write))) {
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,12 +153,16 @@ 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;
if (Interlocked.Add (ref rwlock, -RwRead) >> RwReadBit == 0)
readerDoneEvent.Set ();
if (--ctstate.ReaderRecursiveCount == 0) {
ctstate.LockState ^= LockState.Read;
if (Interlocked.Add (ref rwlock, -RwRead) >> RwReadBit == 0)
readerDoneEvent.Set ();
}
}
public void EnterWriteLock ()
@@ -186,39 +172,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 +233,20 @@ 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);
writerDoneEvent.Set ();
if (--ctstate.WriterRecursiveCount == 0) {
bool isUpgradable = ctstate.LockState.Has (LockState.Upgradable);
ctstate.LockState ^= LockState.Write;
int value = Interlocked.Add (ref rwlock, isUpgradable ? RwRead - RwWrite : -RwWrite);
writerDoneEvent.Set ();
if (isUpgradable && value >> RwReadBit == 1)
readerDoneEvent.Reset ();
}
}
public void EnterUpgradeableReadLock ()
@@ -251,10 +260,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 +285,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 +307,16 @@ namespace System.Threading {
public void ExitUpgradeableReadLock ()
{
if (!CurrentThreadState.Has (ThreadLockState.Upgradable | ThreadLockState.Read))
throw new SynchronizationLockException ("The current thread has not entered the lock in upgradable mode");
upgradableTaken.Value = false;
upgradableEvent.Set ();
ThreadLockState ctstate = CurrentThreadState;
CurrentThreadState = CurrentThreadState ^ ThreadLockState.Upgradable;
Interlocked.Add (ref rwlock, -RwRead);
if (--ctstate.UpgradeableRecursiveCount == 0) {
upgradableTaken.Value = false;
upgradableEvent.Set ();
ctstate.LockState ^= LockState.Upgradable;
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;
}
}
@@ -34,7 +34,7 @@ using System.Linq;
namespace MonoTests.System.Threading
{
[TestFixture]
public class ReaderWriterLockSlim2Test
public class ReaderWriterLockSlimTests
{
[Test]
public void DefaultValues ()
@@ -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,172 @@ 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");
}
[Test]
public void RecursiveEnterExitReadTest ()
{
var v = new ReaderWriterLockSlim (LockRecursionPolicy.SupportsRecursion);
v.EnterReadLock ();
v.EnterReadLock ();
v.EnterReadLock ();
Assert.IsTrue (v.IsReadLockHeld);
Assert.AreEqual (3, v.RecursiveReadCount);
v.ExitReadLock ();
Assert.IsTrue (v.IsReadLockHeld);
Assert.AreEqual (2, v.RecursiveReadCount);
}
[Test]
public void RecursiveEnterExitWriteTest ()
{
var v = new ReaderWriterLockSlim (LockRecursionPolicy.SupportsRecursion);
v.EnterWriteLock ();
v.EnterWriteLock ();
v.EnterWriteLock ();
Assert.IsTrue (v.IsWriteLockHeld);
Assert.AreEqual (3, v.RecursiveWriteCount);
v.ExitWriteLock ();
v.ExitWriteLock ();
Assert.IsTrue (v.IsWriteLockHeld);
Assert.AreEqual (1, v.RecursiveWriteCount);
}
[Test]
public void RecursiveEnterExitUpgradableTest ()
{
var v = new ReaderWriterLockSlim (LockRecursionPolicy.SupportsRecursion);
v.EnterUpgradeableReadLock ();
v.EnterUpgradeableReadLock ();
v.EnterUpgradeableReadLock ();
Assert.IsTrue (v.IsUpgradeableReadLockHeld);
Assert.AreEqual (3, v.RecursiveUpgradeCount);
v.ExitUpgradeableReadLock ();
Assert.IsTrue (v.IsUpgradeableReadLockHeld);
Assert.AreEqual (2, v.RecursiveUpgradeCount);
}
[Test]
public void RecursiveWriteReadAcquisitionInterleaving ()
{
var v = new ReaderWriterLockSlim (LockRecursionPolicy.SupportsRecursion);
v.EnterWriteLock ();
Assert.IsTrue (v.IsWriteLockHeld, "#1");
bool result = true;
var t = new Thread (delegate () {
result = v.TryEnterReadLock (100);
});
t.Start ();
t.Join ();
Assert.IsFalse (result, "#2");
v.ExitWriteLock ();
t = new Thread (delegate () {
result = v.TryEnterReadLock (100);
});
t.Start ();
t.Join ();
Assert.IsTrue (result, "#3");
}
}
}
@@ -66,6 +66,9 @@ 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.Threading.Tasks/TaskExtensions.cs
System.Linq.Expressions/Extensions.cs
System.Linq.Expressions/ExpressionTransformer.cs
@@ -254,7 +257,6 @@ System.Linq.Parallel/IVisitableNode.cs
System.Linq.Parallel/QueryCheckerVisitor.cs
System.Linq.Parallel/QueryIsOrderedVisitor.cs
System.Linq.Parallel/QueryOptions.cs
../corlib/System.Collections.Concurrent/Partitioners/EnumerablePartitioner.cs
../corlib/System.Collections.Concurrent.Partitioners/EnumerablePartitioner.cs
../corlib/System.Collections.Concurrent/ConcurrentSkipList.cs
../corlib/System.Threading/AtomicBoolean.cs
@@ -1,3 +1,16 @@
2010-02-14 Veerapuram Varadhan <[email protected]>
** Fixes 667855
* OracleParameter.cs (InferSize): For Raw types, use the appropriate
methods to convert value to bytearray and use them to bind.
(Bind): Fix index parameters in call to Array.ConstrainedCopy.
2010-01-30 Veerapuram Varadhan <[email protected]>
** Fixes #667236 - Based on patch by [email protected]
* OracleParameter.cs (GetOutValue): Handle OciDataType.Integer
appropriately using the underlying dbType.
2009-10-29 Veerapuram Varadhan <[email protected]>
** Fixes #322695
@@ -1,4 +1,4 @@
//
//
// OracleParameter.cs
//
// Part of the Mono class libraries at
@@ -763,7 +763,11 @@ namespace System.Data.OracleClient
if (direction == ParameterDirection.Input ||
direction == ParameterDirection.InputOutput) {
byteCount = 0;
byte[] val = v as byte[];
byte[] val;
if (dbType == DbType.Guid)
val = ((Guid)v).ToByteArray();
else
val = v as byte[];
if (val.Length > 0) {
byteCount = val.Length;
// LONG VARRAW prepends a 4-byte length
@@ -771,7 +775,7 @@ namespace System.Data.OracleClient
byteArrayLen = BitConverter.GetBytes ((ushort) byteCount);
bytes[0] = byteArrayLen[0];
bytes[1] = byteArrayLen[1];
Array.ConstrainedCopy (val, 2, bytes, 0, byteCount);
Array.ConstrainedCopy (val, 0, bytes, 2, byteCount);
}
}
}
@@ -795,7 +799,7 @@ namespace System.Data.OracleClient
bytes[1] = byteArrayLen[1];
bytes[2] = byteArrayLen[2];
bytes[3] = byteArrayLen[3];
Array.ConstrainedCopy (val, 4, bytes, 0, byteCount);
Array.ConstrainedCopy (val, 0, bytes, 4, byteCount);
}
}
}
@@ -1022,6 +1026,12 @@ namespace System.Data.OracleClient
case OciDataType.RSet: // REF CURSOR
newSize = -1;
break;
case OciDataType.Raw:
if (dbType == DbType.Guid)
newSize = ((Guid)value).ToByteArray().Length;
else
newSize = (value as byte[]).Length;
break;
default:
if (value == null || value == DBNull.Value)
newSize = 0;
@@ -1107,6 +1117,7 @@ namespace System.Data.OracleClient
private void SetOracleType (OracleType type, bool inferring)
{
FreeHandle ();
Type valType = value.GetType ();
string exception = String.Format ("No mapping exists from OracleType {0} to a known DbType.", type);
switch (type) {
case OracleType.BFile:
@@ -1116,7 +1127,10 @@ namespace System.Data.OracleClient
break;
case OracleType.LongRaw:
case OracleType.Raw:
dbType = DbType.Binary;
if (valType.FullName == "System.Guid")
dbType = DbType.Guid;
else
dbType = DbType.Binary;
ociType = OciDataType.Raw;
break;
case OracleType.Byte:
@@ -1305,8 +1319,25 @@ namespace System.Data.OracleClient
OciCalls.OCICharSetToUnicode (env, ret, bytes, out rsize);
// if not empty, parse string as a decimal using session format
if (ret.Length > 0)
value = Decimal.Parse (ret.ToString (), cmd.Connection.SessionFormatProvider);
if (ret.Length > 0) {
switch (dbType) {
case DbType.UInt16:
value = UInt16.Parse (ret.ToString (), cmd.Connection.SessionFormatProvider);
break;
case DbType.UInt32:
value = UInt32.Parse (ret.ToString (), cmd.Connection.SessionFormatProvider);
break;
case DbType.Int16:
value = Int16.Parse (ret.ToString (), cmd.Connection.SessionFormatProvider);
break;
case DbType.Int32:
value = Int32.Parse (ret.ToString (), cmd.Connection.SessionFormatProvider);
break;
default:
value = Decimal.Parse (ret.ToString (), cmd.Connection.SessionFormatProvider);
break;
}
}
break;
case OciDataType.TimeStamp:
value = dateTimeDesc.GetDateTime (connection.Environment, dateTimeDesc.ErrorHandle);
@@ -1,3 +1,16 @@
2011-03-22 Veerapuram Varadhan <[email protected]>
** Fixes #676368 - Patch by [email protected]
* OdbcConnection.cs: Make linking/unlinking of OdbcCommands thread safe.
* OdbcCommand.cs: Check generation object from connection in order to
free the associated statement handle.
2010-12-07 Veerapuram Varadhan <[email protected]>
** Fixes #456234 - Patch by [email protected]
* OdbcDataReader.cs (GetValue): Handle SQL_NO_TOTAL sanely and
use corresponding Decoder.GetChars instead of Encoding.GetString.
2010-06-15 Jonathan Chambers <[email protected]>
* OdbcDataReader.cs: Remove unneeded cast on ref parameter
@@ -67,6 +67,7 @@ namespace System.Data.Odbc
bool designTimeVisible;
bool prepared;
IntPtr hstmt = IntPtr.Zero;
object generation = null; // validity of hstmt
bool disposed;
@@ -353,10 +354,11 @@ namespace System.Data.Odbc
OdbcReturn ret;
if (hstmt != IntPtr.Zero)
// Free the existing hstmt. Also unlinks from the connection.
FreeStatement ();
else
Connection.Link (this);
// Link this command to the connection. The hstmt created below
// only remains valid while generation == Connection.generation.
generation = Connection.Link (this);
ret = libodbc.SQLAllocHandle (OdbcHandleType.Stmt, Connection.hDbc, ref hstmt);
if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
throw connection.CreateOdbcException (OdbcHandleType.Dbc, Connection.hDbc);
@@ -376,18 +378,29 @@ namespace System.Data.Odbc
if (hstmt == IntPtr.Zero)
return;
// Normally the command is unlinked from the connection, but during
// OdbcConnection.Close() this would be pointless and (quadratically)
// slow.
if (unlink)
Connection.Unlink (this);
// free previously allocated handle.
OdbcReturn ret = libodbc.SQLFreeStmt (hstmt, libodbc.SQLFreeStmtOptions.Close);
if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
throw connection.CreateOdbcException (OdbcHandleType.Stmt, hstmt);
// Serialize with respect to the connection's own destruction
lock(Connection) {
// If the connection has already called SQLDisconnect then hstmt
// may have already been freed, in which case it is not safe to
// use. Thus the generation check.
if(Connection.Generation == generation) {
// free previously allocated handle.
OdbcReturn ret = libodbc.SQLFreeStmt (hstmt, libodbc.SQLFreeStmtOptions.Close);
if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
throw connection.CreateOdbcException (OdbcHandleType.Stmt, hstmt);
ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Stmt, hstmt);
if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
throw connection.CreateOdbcException (OdbcHandleType.Stmt, hstmt);
hstmt = IntPtr.Zero;
ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Stmt, hstmt);
if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
throw connection.CreateOdbcException (OdbcHandleType.Stmt, hstmt);
}
hstmt = IntPtr.Zero;
}
}
private void ExecSQL (CommandBehavior behavior, bool createReader, string sql)
@@ -82,6 +82,14 @@ namespace System.Data.Odbc
get { return hdbc; }
}
internal object Generation {
// We use the linkedCommands array as a generation indicator for statement
// handles allocated in our subsiduary OdbcCommands. The rule is that the
// statement handles are only valid if the generation matches the one
// returned when the command was linked to the connection.
get { return linkedCommands; }
}
[OdbcCategoryAttribute ("DataCategory_Data")]
[DefaultValue ("")]
[OdbcDescriptionAttribute ("Information used to connect to a Data Source")]
@@ -261,21 +269,31 @@ namespace System.Data.Odbc
{
OdbcReturn ret = OdbcReturn.Error;
if (State == ConnectionState.Open) {
// close any associated commands
if (linkedCommands != null) {
for (int i = 0; i < linkedCommands.Count; i++) {
WeakReference wr = (WeakReference) linkedCommands [i];
if (wr == null)
continue;
OdbcCommand c = (OdbcCommand) wr.Target;
if (c != null)
c.Unlink ();
lock(this) {
// close any associated commands
// NOTE: we may 'miss' some if the garbage collector has
// already started to destroy them.
if (linkedCommands != null) {
for (int i = 0; i < linkedCommands.Count; i++) {
WeakReference wr = (WeakReference) linkedCommands [i];
if (wr == null)
continue;
OdbcCommand c = (OdbcCommand) wr.Target;
if (c != null)
c.Unlink ();
}
linkedCommands = null;
}
linkedCommands = null;
}
// disconnect
ret = libodbc.SQLDisconnect (hdbc);
// disconnect
ret = libodbc.SQLDisconnect (hdbc);
}
// There could be OdbcCommands outstanding (see NOTE above); their
// hstmts will have been freed and therefore will be invalid.
// However, they will find that their definition of Generation
// does not match the connection's, so they won't try and free
// those hstmt.
if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
@@ -580,27 +598,33 @@ namespace System.Data.Odbc
return value.TrimEnd ('\0');
}
internal void Link (OdbcCommand cmd)
internal object Link (OdbcCommand cmd)
{
if (linkedCommands == null)
linkedCommands = new ArrayList ();
linkedCommands.Add (new WeakReference (cmd));
lock(this) {
if (linkedCommands == null)
linkedCommands = new ArrayList ();
linkedCommands.Add (new WeakReference (cmd));
return linkedCommands;
}
}
internal void Unlink (OdbcCommand cmd)
internal object Unlink (OdbcCommand cmd)
{
if (linkedCommands == null)
return;
lock(this) {
if (linkedCommands == null)
return null;
for (int i = 0; i < linkedCommands.Count; i++) {
WeakReference wr = (WeakReference) linkedCommands [i];
if (wr == null)
continue;
OdbcCommand c = (OdbcCommand) wr.Target;
if (c == cmd) {
linkedCommands [i] = null;
break;
for (int i = 0; i < linkedCommands.Count; i++) {
WeakReference wr = (WeakReference) linkedCommands [i];
if (wr == null)
continue;
OdbcCommand c = (OdbcCommand) wr.Target;
if (c == cmd) {
linkedCommands [i] = null;
break;
}
}
return linkedCommands;
}
}
@@ -732,6 +732,8 @@ namespace System.Data.Odbc
bufsize = (col.MaxLength < 127 ? (col.MaxLength*2+1) : 255);
buffer = new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
StringBuilder sb = new StringBuilder ();
char[] charBuffer = new char[bufsize];
Decoder unicodeDecoder = Encoding.Unicode.GetDecoder ();
do {
ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
if (ret == OdbcReturn.Error)
@@ -740,24 +742,24 @@ namespace System.Data.Odbc
if (ret == OdbcReturn.Success && outsize==-1)
ret = OdbcReturn.NoData;
if (ret != OdbcReturn.NoData && outsize > 0) {
string value = null;
if (outsize < bufsize)
value = Encoding.Unicode.GetString (buffer, 0, outsize);
else
value = Encoding.Unicode.GetString (buffer, 0, bufsize);
sb.Append (RemoveTrailingNullChar (value));
if (ret == OdbcReturn.Success || ret == OdbcReturn.SuccessWithInfo) {
if (outsize >= bufsize || outsize == (int)OdbcLengthIndicator.NoTotal)
outsize = bufsize;
int charCount = unicodeDecoder.GetChars (buffer, 0, outsize, charBuffer, 0);
string strValue = new String (charBuffer, 0, charCount);
sb.Append (RemoveTrailingNullChar (strValue));
}
} while (ret != OdbcReturn.NoData);
DataValue = sb.ToString ();
charBuffer = null;
break;
case OdbcType.Text:
case OdbcType.VarChar:
bufsize = (col.MaxLength < 255 ? (col.MaxLength+1) : 255);
buffer = new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
StringBuilder sb1 = new StringBuilder ();
charBuffer = new char[bufsize];
Decoder defaultDecoder = Encoding.Default.GetDecoder();
do {
ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
if (ret == OdbcReturn.Error)
@@ -765,11 +767,11 @@ namespace System.Data.Odbc
// Fix for strance ODBC drivers (like psqlODBC)
if (ret == OdbcReturn.Success && outsize==-1)
ret = OdbcReturn.NoData;
if (ret != OdbcReturn.NoData && outsize > 0) {
if (outsize < bufsize)
sb1.Append (Encoding.Default.GetString (buffer, 0, outsize));
else
sb1.Append (Encoding.Default.GetString (buffer, 0, bufsize - 1));
if (ret == OdbcReturn.Success || ret == OdbcReturn.SuccessWithInfo) {
if (outsize >= bufsize || outsize == (int)OdbcLengthIndicator.NoTotal)
outsize = bufsize - 1;
int charCount = defaultDecoder.GetChars(buffer, 0, outsize, charBuffer, 0);
sb1.Append(charBuffer, 0, charCount);
}
} while (ret != OdbcReturn.NoData);
DataValue = sb1.ToString ();
Loaded 100 of 427 files, more files were not shown because too many files have changed in this diff. Show more