Compare commits

...
55 Commits
Author SHA1 Message Date
Alex Corrado 378032bf64 Fix prepending $(CURDIR) to paths failing under cygwin 2011-09-15 13:07:57 -04:00
Alex Corrado a19eb0760b 2.10.6 2011-09-13 23:37:20 -04:00
Gonzalo Paniagua Javier 5cfc62f415 Stop lying in the comments 2011-09-13 20:24:11 -04:00
Gonzalo Paniagua Javier 1ed1c4bed1 Report compilation errors when the type named in 'class' can't be loaded. 2011-09-13 20:24:01 -04:00
Rodrigo Kumpera 616f648f0d Avoid duplicates in the SSC xrefs.
* sgen-brige.c (scc_add_xref): Make sure that the xref
	array is kept sorted by doing sorted insertion for single elements
	and merging for a pair of lists.

	This avoids degenerated cases where performance of the dfs2 step
	goes unbound and slows us down significantly.

	Fixes bxc #496
2011-09-13 15:35:31 -03:00
Rodrigo Kumpera 4fccd4d599 Add logging to sgen-bridge. Log times and sizes. 2011-09-13 15:35:30 -03:00
Rolf Bjarne Kvinge bd4f80e803 [System.Data] Delay column expression evaluation after all the columns have been cloned when cloning a table. Fixes #666.
When cloning a table we loop over all the columns and clone them, but if a column
contains an expression with a reference to a later column, we'll throw an exception
unless we delay the expression compilation until all the columns have been added
to the new table clone.

So I've split out the expression compilation logic from the Expression property setter,
and now the column Clone method only sets the field. The Clone caller is responsible
for calling CompileExpression on the cloned column after adding all the cloned columns to
the cloned table.
2011-09-13 14:15:11 +02:00
Rolf Bjarne Kvinge 9e9b3f913d [System.Data] Properly clone a column's extended properties when cloning a table. Fixes #668. 2011-09-13 13:01:57 +02:00
Jérémie Laval a2a168e5f3 Add missing files. 2011-09-13 12:20:07 +02:00
Jérémie Laval 5f982b1908 Backport System.Threading.Tasks from master to mono-2-10 2011-09-13 12:18:39 +02:00
Gonzalo Paniagua Javier f00202d3e3 Delay initialization of the stream until first read
This way uri-based resources are not fetched before they are supposed
	to.

	Fixes Xamarin bug #762.
2011-09-13 01:24:14 -04:00
Gonzalo Paniagua Javier b4d4033040 Internal worker is kept while there is an ongoing operation
When there is an ongoing operation we can't dispose the internal
	worker because it might be used by the IO threadpool.

	Fixes Novell bug #691076 and Xamarin bug #766.
2011-09-13 00:06:12 -04:00
Sebastien Pouliot 68deb6335e More fixes for running unit tests under NET_2_1 profile 2011-09-12 12:53:17 -04:00
Miguel de Icaza cb965a9d3a Various fixes to the Expression parser, the fixes include:
* Fixes to the SUBSTRING and TRIM function to allow
	  a wider range of functions to be passed as
	  parameters.   This fixes xamarin #665

	* Fix to the Parser.jay grammar to eliminate the
	  reduce/reduce conflicts.

	* Dropping the string concatenation code and instead
	  use the existing arithmetic addition operator which
	  also fixes the concatenation operation in the presence
	  of null values

	* Adds the null literal

With the associated test cases.
2011-09-09 22:04:18 -04:00
Marek Habersack 86262ef424 Support colors on 256-color terminals 2011-09-09 22:04:02 -04:00
Sebastien Pouliot acfa4856b9 Adjust corlib unit tests to reduce failures when executed on the NET_2_1 profile 2011-09-09 13:48:15 -04:00
Sebastien Pouliot be8711a7e6 fix FileStream test failures under Mac OSX 2011-09-09 13:48:01 -04:00
Sebastien Pouliot 7e6a0ff51e Throwing IsolatedStorageException is a Moonlight-behavior and should not have been exposed to other 2.1 profiles 2011-09-09 13:47:48 -04:00
Sebastien Pouliot c989e10293 Ensure we can roundtrip 'Local' (special case) timezone. Fix bug #326 2011-09-09 13:29:40 -04:00
Sebastien Pouliot b04d809478 Return null instead of catching Activator exception (and return null). What was a corner case before is now very common when the linker is used (e.g. monotouch, m4a). Reported in assistly #1741 2011-09-09 13:29:26 -04:00
Miguel de Icaza 219276c182 Fallback: load profiler from the Mono default path. This in particular allows users to run mono --profiler=log foo.exe without having to set anuy environment variables 2011-09-07 18:44:22 -04:00
Sebastien Pouliot 64ff652330 Add null-check on 'partDesc'. Fix bug #612 (WCF regression) 2011-09-07 11:17:55 -04:00
Rodrigo Kumpera 75e3ca80bc Let the system figure our permissions instead of doing a poor job at it.
io.c (DeleteFile): We can't forbit a file to be deleted just before
	it's mask is not u+w. We should just call unlink and let the kernel
	figure out permissions.

	We are not SAMBA.

	We're not in the job of trying to mingle windows and unix permissions
	models so we just let the kernel figure it out and translate the appropriate
	errno value to UnauthorizedAccessException.
2011-09-06 19:36:00 -03:00
Jérémie Laval aa48b6f714 Use a TaskCompletionSource in non-generic ContinueWhenAny case. Fix #647. 2011-09-06 23:55:01 +02:00
Rodrigo Kumpera 2603a2e4fd Improve exception message. 2011-09-06 14:53:00 -03:00
Rodrigo Kumpera 05550e7c66 Add collection logging to sgen. 2011-09-06 14:52:59 -03:00
Gonzalo Paniagua Javier 99349445b1 Display more debugging info when epoll fails 2011-09-05 21:13:07 -04:00
Gonzalo Paniagua Javier d768dd0125 Fallback to poll() if epoll_create() fails
From a patch by Zoltan in bug #705190.
2011-09-05 20:51:10 -04:00
Zoltan Varga e376d9156b Handle threads which die without detaching. 2011-09-06 04:24:21 +02:00
Zoltan Varga 85349b801f Implement AppDomain.ResourceResolve. Fixes #579. 2011-09-04 03:20:22 +02:00
Mark Probst 41d1be9f34 [sgen] Break tracking weak references as early as possible.
Our tracking references code aimed to transform tracking references
into normal weak references the first time their targets became
unreachable.  It was implemented incorrectly though, and is not the
right thing to do in the first place anyway, because tracking
references have to keep tracking if the target is re-registered for
finalization.  The incorrect implementation inadvertently handled
re-registration correctly, but it kept the reference intact for one
garbage collection cycle too many.
2011-09-02 11:14:27 -03:00
Rodrigo Kumpera ac19d5bfaf Handle finalizable objects pointed by bridge objects. (cont...)
* sgen-fin-weak-hash.c:
	* sgen-gc.c: Bridge objects are used to represent objects
	that have references outside of sgen's control. They are
	kept around until the embedder figures out it's ok to
	collect them.
	Until those bridge objects turn externally unreachable,
	they must be kept around. Up to now, the expected pattern
	was to resurrect them during finalization.
	The problem with this approach is that if they hold references
	to other finalizable, non-bridge objects those will be finalized
	and we will resurrect objects that point to dead ones.

	Think of this:

	class BridgeObject {
 		FileStream stream;
	}

	The bridge object is resurrected on the finalizer and so will
	stream, disposing its native handle and been permanently unusable.

	The solution is to process brige objects before we do ordinary
	finalization. We record all dead bridges and copy/mark them.
	We drain the gray queue on the end, which makes sure all other
	finalizable objects that transitively reachable are too.

	Finally, we introduce a breaking change to the bridge API.
	The bridge must set to NULL the first object of all SCC
	entries that remain alive. Other entries will be considered
	dead and will be subject to regular finalization.

	This way, sgen knows when a given bridge object is completely
	unreachable and provides adequate finalization semantics to
	them and referenced objects.

	This fixes bxc #375
2011-09-01 20:13:06 -03:00
Atsushi Eno ae7d005dfc DiffLoader didn't handle encoded name and caused mismatch between .NET. 2011-08-31 17:53:04 -07:00
Atsushi Eno 04427d962d Fix invalid path check for Windows regarding ':'. 2011-08-31 14:12:51 -07:00
Atsushi Eno 57bc2f6ffb Add test for bug #545. 2011-08-31 14:12:42 -07:00
Atsushi Eno 059a6a685b EncoderReplacementFallbackBuffer.Reset() did not really reset its internals. 2011-08-31 14:03:10 -07:00
Chris Toshok 4ac77ca819 prepend $(CURDIR) to jay input files so that the debugging info references the right .jay 2011-08-30 17:06:50 -07:00
Jonathan Pryor d703e86b4b Don't use vasprintf on PLATFORM_ANDROID.
This allows sanely using g_log() within signal handlers.
2011-08-30 15:44:17 -04:00
Atsushi Eno 6870a59952 Implement IXmlLineInfo on XLinq node reader. 2011-08-30 23:13:36 +09:00
Atsushi Eno 721dadd34b LineInfo on namespace nodes were missing. 2011-08-30 20:22:01 +09:00
Sebastien Pouliot b7061d3e57 Fix build. Adding #if MOBILE is just not enough ;-) 2011-08-29 09:53:23 -04:00
Sebastien Pouliot 2f4099863e Fix bug #380. Patch from bnc#605795 were not committed to master but part of MonoTouch 3.x (ended up missing in MT4) 2011-08-29 08:57:30 -04:00
Hin-Tak Leung 96e0c59371 Fix mingw32 cross-build on a git no-branch checkout. Fixes #698446. 2011-08-29 01:25:19 +02:00
Zoltan Varga 1e910229a8 Allow pointers to structures to be passed in pinvoke, MS seems to allow this at least in some cases. Fixes bxc #158.
This partially reverts c4d9097c57.
2011-08-28 17:52:05 +02:00
Jérémie Laval c74031105a Check that CancellationToken coming from OperationCanceledException isn't None. Fix #472. 2011-08-28 14:50:12 +02:00
Atsushi Eno 279678d726 Revert GET switch for serializing requests. BodyWriter handles it better. 2011-08-24 18:13:04 -07:00
Atsushi Eno 46db32524d for GET request, just skip the member. It does not contain xml for null. 2011-08-24 16:48:46 -07:00
Atsushi Eno 0563034987 Skip serialization when the return type is void.
This batch should fix bug #206.
2011-08-24 12:20:23 -07:00
Atsushi Eno 0baf32151f Do not try to output empty message body to logs. 2011-08-24 12:20:13 -07:00
Atsushi Eno 8bd9eebf1f When there is void return, the common message formatter should ignore it.
This case occurs when MessageContract is used and there is no member for
the return value.
2011-08-24 12:20:02 -07:00
Atsushi Eno b9a5b85c16 ReturnValue in MessageDescription was missing when there was MessageContract. 2011-08-24 12:19:52 -07:00
Atsushi Eno c98be1ad12 Differentiate GET query parameter binding from another request binding.
This is one core of the bugfix for #206.
2011-08-24 12:19:42 -07:00
Atsushi Eno 67b1fcec06 When there was no path parameter, it ignored the whole path part. 2011-08-24 12:19:31 -07:00
Atsushi Eno 4643f66d1a This filter should ignore port, and should not filter out anonymous URIs. 2011-08-24 12:19:21 -07:00
Atsushi Eno e3aa857b74 UriTemplate should not be mandatory, make it optional. Fix unit test. 2011-08-23 11:43:56 -07:00
98 changed files with 3129 additions and 938 deletions

No files matched your search

+2 -2
View File
@@ -57,11 +57,11 @@ function setup ()
CROSS_DLL_DIR="$CROSS_DIR/bin"
PATH=$CROSS_BIN_DIR:$PATH
MONO_VERSION=`grep AM_INIT_AUTOMAKE configure.in | cut -d ',' -f 2|tr -d '\)'`
MONO_VERSION=`grep AM_INIT_AUTOMAKE configure.in | cut -d ',' -f 2|tr -d '\)'|tr -d '\('`
if [ -d ./.git ]; then
MONO_GIT_COMMIT="`git log -1 --format=format:%t`"
MONO_GIT_BRANCH="`git branch|grep '\*'|cut -d ' ' -f 2`"
MONO_GIT_BRANCH="`git branch|grep '\*'|cut -d ' ' -f 2|tr -d '\)'|tr -d '\('`"
MONO_RELEASE="$MONO_VERSION-$MONO_GIT_BRANCH-$MONO_GIT_COMMIT"
else
MONO_RELEASE="$MONO_VERSION"
+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.10.5)
AM_INIT_AUTOMAKE(mono,2.10.6)
AM_MAINTAINER_MODE
API_VER=2.0
+7 -9
View File
@@ -112,28 +112,26 @@ g_log_set_fatal_mask (const gchar *log_domain, GLogLevelFlags fatal_mask)
void
g_logv (const gchar *log_domain, GLogLevelFlags log_level, const gchar *format, va_list args)
{
#if PLATFORM_ANDROID
__android_log_vprint (to_android_priority (log_level), log_domain, format, args);
#else
char *msg;
vasprintf (&msg, format, args);
#if PLATFORM_ANDROID
__android_log_print (to_android_priority (log_level),
/* TODO: provide a proper app name */
"mono", "%s%s%s",
log_domain != NULL ? log_domain : "",
log_domain != NULL ? ": " : "",
msg);
#else
printf ("%s%s%s\n",
log_domain != NULL ? log_domain : "",
log_domain != NULL ? ": " : "",
msg);
#endif
free (msg);
if (log_level & fatal){
fflush (stdout);
fflush (stderr);
abort ();
}
#endif
if (log_level & fatal){
abort ();
}
}
void
+2
View File
@@ -26,6 +26,8 @@ PLATFORM_MAKE_CORLIB_CMP = yes
PLATFORM_CHANGE_SEPARATOR_CMD=tr '/' '\\\\'
PLATFORM_PATH_SEPARATOR = ;
override CURDIR:=$(shell cygpath -m $(CURDIR))
## not so simple :-)
#PLATFORM_AOT_SUFFIX = .dll
+1 -1
View File
@@ -22,7 +22,7 @@ EXTRA_DISTFILES = \
$(RESOURCE_FILES)
Commons.Xml.Relaxng.Rnc/RncParser.cs: Commons.Xml.Relaxng.Rnc/RncParser.jay $(topdir)/jay/skeleton.cs
$(topdir)/jay/jay -ctv < $(topdir)/jay/skeleton.cs Commons.Xml.Relaxng.Rnc/RncParser.jay > Commons.Xml.Relaxng.Rnc/RncParser.cs
$(topdir)/jay/jay -ctv < $(topdir)/jay/skeleton.cs $(CURDIR)/Commons.Xml.Relaxng.Rnc/RncParser.jay > Commons.Xml.Relaxng.Rnc/RncParser.cs
BUILT_SOURCES = Commons.Xml.Relaxng.Rnc/RncParser.cs
+2 -2
View File
@@ -28,13 +28,13 @@ Mono.Xml.XPath2/XQueryParser.jay: Mono.Xml.XPath2/ParserBase.jay $(SKELETON)
Mono.Xml.XPath2/XPath2Parser.cs: Mono.Xml.XPath2/XPath2Parser.jay
echo "#define XPATH2_PARSER" > $@
echo "#if NET_2_0" >> $@
$(topdir)/jay/jay -ct < $(SKELETON) $< >>$@
$(topdir)/jay/jay -ct < $(SKELETON) $(CURDIR)/$< >>$@
echo "#endif" >> $@
Mono.Xml.XPath2/XQueryParser.cs: Mono.Xml.XPath2/XQueryParser.jay $(SKELETON)
echo "#define XQUERY_PARSER" > $@
echo "#if NET_2_0" >> $@
$(topdir)/jay/jay -ct < $(SKELETON) $< >>$@
$(topdir)/jay/jay -ct < $(SKELETON) $(CURDIR)/$< >>$@
echo "#endif" >> $@
Mono.Xml.XPath2/XPath2Tokenizer.cs: Mono.Xml.XPath2/TokenizerBase.cs
@@ -329,6 +329,9 @@ namespace System
#if MONODROID
return ZoneInfoDB.GetTimeZone (id);
#elif LIBC
// Local requires special logic that already exists in the Local property (bug #326)
if (id == "Local")
return Local;
string filepath = Path.Combine (TimeZoneDirectory, id);
return FindSystemTimeZoneByFileName (id, filepath);
#else
@@ -540,6 +540,20 @@ namespace MonoTests.System
TimeZoneInfo vatican = TimeZoneInfo.FindSystemTimeZoneById ("Europe/Vatican");
Assert.IsTrue (rome.HasSameRules (vatican));
}
[Test]
public void FindSystemTimeZoneById_Local_Roundtrip ()
{
Assert.AreEqual (TimeZoneInfo.Local.Id, TimeZoneInfo.FindSystemTimeZoneById (TimeZoneInfo.Local.Id).Id);
}
[Test]
public void Test326 ()
{
DateTime utc = DateTime.UtcNow;
DateTime local = TimeZoneInfo.ConvertTime (utc, TimeZoneInfo.Utc, TimeZoneInfo.FindSystemTimeZoneById (TimeZoneInfo.Local.Id));
Assert.AreEqual (local, utc + TimeZoneInfo.Local.GetUtcOffset (utc), "ConvertTime/Local");
}
#if SLOW_TESTS
[Test]
+1 -1
View File
@@ -63,7 +63,7 @@ EXTRA_DISTFILES = \
BUILT_SOURCES = Mono.Data.SqlExpressions/Parser.cs
Mono.Data.SqlExpressions/Parser.cs: Mono.Data.SqlExpressions/Parser.jay $(topdir)/jay/skeleton.cs
$(topdir)/jay/jay -ct < $(topdir)/jay/skeleton.cs $< >$@
$(topdir)/jay/jay -vct < $(topdir)/jay/skeleton.cs $(CURDIR)/$< >$@
include ../../build/library.make
@@ -6,6 +6,7 @@
// Juraj Skripsky ([email protected])
//
// (C) 2004 HotFeet GmbH (http://www.hotfeet.ch)
// Copyright 2011 Xamarin Inc (http://www.xamarin.com)
//
using System;
@@ -190,6 +191,7 @@ LiteralValue
| NumberLiteral { $$ = new Literal ($1); }
| DateLiteral { $$ = new Literal ($1); }
| BoolLiteral
| NULL { $$ = new Literal (null); }
;
BoolLiteral
@@ -271,28 +273,20 @@ AggFunctionName
;
StringExpr
: PAROPEN StringExpr PARCLOSE
{
$$ = (IExpression)$2;
}
| SingleColumnValue
: SingleColumnValue
| StringLiteral { $$ = new Literal ($1); }
| StringFunction
| Function
;
StringFunction
: TRIM PAROPEN StringExpr PARCLOSE
: TRIM PAROPEN ArithExpr PARCLOSE
{
$$ = new TrimFunction ((IExpression)$3);
}
| SUBSTRING PAROPEN StringExpr COMMA ArithExpr COMMA ArithExpr PARCLOSE
| SUBSTRING PAROPEN ArithExpr COMMA ArithExpr COMMA ArithExpr PARCLOSE
{
$$ = new SubstringFunction ((IExpression)$3, (IExpression)$5, (IExpression)$7);
}
| StringExpr PLUS StringExpr
{
$$ = new ConcatFunction ((IExpression)$1, (IExpression)$3);
}
;
CalcFunction
@@ -55,42 +55,6 @@ namespace Mono.Data.SqlExpressions {
}
}
internal class ConcatFunction : StringFunction
{
readonly IExpression _add;
public ConcatFunction (IExpression e, IExpression add)
: base (e)
{
_add = add;
}
public override bool Equals(object obj)
{
if (!base.Equals (obj))
return false;
if (!(obj is ConcatFunction))
return false;
ConcatFunction other = (ConcatFunction) obj;
return _add.Equals (other._add);
}
public override int GetHashCode()
{
int hashCode = base.GetHashCode ();
hashCode ^= _add.GetHashCode ();
return hashCode;
}
override public object Eval (DataRow row) {
string str = (string) base.Eval (row);
string x = (string) _add.Eval (row);
return str + x;
}
}
internal class SubstringFunction : StringFunction {
IExpression start;
IExpression len;
+48 -41
View File
@@ -17,6 +17,7 @@
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
// Copyright (C) 2011 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -475,43 +476,53 @@ namespace System.Data {
if (value == null)
value = String.Empty;
if (value != String.Empty) {
if (AutoIncrement || Unique)
throw new ArgumentException ("Cannot create an expression on a column that has AutoIncrement or Unique.");
CompileExpression (value);
_expression = value;
}
}
if (Table != null) {
for (int i = 0; i < Table.Constraints.Count; i++) {
if (Table.Constraints [i].IsColumnContained (this))
throw new ArgumentException (
String.Format (
"Cannot set Expression property on column {0}, because it is a part of a constraint.",
ColumnName));
}
}
internal void CompileExpression ()
{
CompileExpression (_expression);
}
Parser parser = new Parser ();
IExpression compiledExpression = parser.Compile (value);
internal void CompileExpression (string expression)
{
if (expression != String.Empty) {
if (AutoIncrement || Unique)
throw new ArgumentException ("Cannot create an expression on a column that has AutoIncrement or Unique.");
if (Table != null) {
if (compiledExpression.DependsOn (this))
throw new ArgumentException ("Cannot set Expression property due to circular reference in the expression.");
// Check if expression is ok
if (Table.Rows.Count == 0)
compiledExpression.Eval (Table.NewRow ());
else
compiledExpression.Eval (Table.Rows [0]);
}
ReadOnly = true;
_compiledExpression = compiledExpression;
} else {
_compiledExpression = null;
if (Table != null) {
int defaultValuesRowIndex = Table.DefaultValuesRowIndex;
if (defaultValuesRowIndex != -1)
DataContainer.FillValues (defaultValuesRowIndex);
if (Table != null) {
for (int i = 0; i < Table.Constraints.Count; i++) {
if (Table.Constraints [i].IsColumnContained (this))
throw new ArgumentException (
String.Format (
"Cannot set Expression property on column {0}, because it is a part of a constraint.",
ColumnName));
}
}
_expression = value;
Parser parser = new Parser ();
IExpression compiledExpression = parser.Compile (expression);
if (Table != null) {
if (compiledExpression.DependsOn (this))
throw new ArgumentException ("Cannot set Expression property due to circular reference in the expression.");
// Check if expression is ok
if (Table.Rows.Count == 0)
compiledExpression.Eval (Table.NewRow ());
else
compiledExpression.Eval (Table.Rows [0]);
}
ReadOnly = true;
_compiledExpression = compiledExpression;
} else {
_compiledExpression = null;
if (Table != null) {
int defaultValuesRowIndex = Table.DefaultValuesRowIndex;
if (defaultValuesRowIndex != -1)
DataContainer.FillValues (defaultValuesRowIndex);
}
}
}
@@ -701,16 +712,12 @@ namespace System.Data {
//Copy.Container
copy.DataType = DataType;
copy._defaultValue = _defaultValue;
// Use the property to set the expression as it updates compiledExpression, if any.
copy.Expression = _expression;
// Do not use the Expression property to set the expression, the caller of Clone
// must explicitly call CompileExpression on the returned DataColumn to update compiledExpression (if any).
copy._expression = _expression;
//Copy.ExtendedProperties
if (_extendedProperties.Count > 0) {
Array extPropArray = Array.CreateInstance (typeof (object), _extendedProperties.Count);
_extendedProperties.CopyTo (extPropArray, 0);
for (var i = 0; i < _extendedProperties.Count; i++)
copy.ExtendedProperties.Add (extPropArray.GetValue(i),
ExtendedProperties[extPropArray.GetValue(i)]);
}
foreach (object key in _extendedProperties.Keys)
copy.ExtendedProperties.Add (key, ExtendedProperties[key]);
copy._maxLength = _maxLength;
copy._nameSpace = _nameSpace;
copy._prefix = _prefix;
@@ -880,6 +880,8 @@ namespace System.Data {
if (isEmpty || !Copy.Columns.Contains (column.ColumnName))
Copy.Columns.Add (column.Clone ());
}
foreach (DataColumn column in Copy.Columns)
column.CompileExpression ();
CopyConstraints (Copy);
// add primary key to the copy
@@ -351,6 +351,7 @@ namespace System.Data {
DataTable GetTable (string name)
{
name = XmlConvert.DecodeName (name);
if (DSet != null)
return DSet.Tables [name];
else if (name == table.TableName)
@@ -10,9 +10,10 @@
// (C) Copyright 2002 Rodrigo Moya
// (C) Copyright 2003 Daniel Morgan
// (C) Copyright 2003 Martin Willemoes Hansen
//
// (C) Copyright 2011 Xamarin Inc
//
// Copyright 2011 Xamarin Inc (http://www.xamarin.com)
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
@@ -913,5 +914,46 @@ namespace MonoTests.System.Data
Assert.Fail ("SetOrdinalTest failed");
}
}
[Test]
public void Xamarin665 ()
{
var t = new DataTable() ;
var c1 = t.Columns.Add ("c1");
var c2 = t.Columns.Add ("c2");
c2.Expression = "TRIM(ISNULL(c1,' '))";
c2.Expression = "SUBSTRING(ISNULL(c1,' '), 1, 10)";
}
DataColumn MakeColumn (string col, string test)
{
return new DataColumn () {
ColumnName = col,
Expression = test
};
}
#if false
// Check Windows output for the row [0] value
[Test]
public void NullStrings ()
{
var a = MakeColumn ("nullbar", "null+'bar'");
var b = MakeColumn ("barnull", "'bar'+null");
var c = MakeColumn ("foobar", "'foo'+'bar'");
var table = new DataTable();
table.Columns.Add(a);
table.Columns.Add(b);
table.Columns.Add(c);
var row = table.NewRow();
table.Rows.Add(row);
Assert.AreEqual (row [0], DBNull.Value, "#1");
Assert.AreEqual (row [1], DBNull.Value, "#2");
Assert.AreEqual (row [2], "foobar", "#3");
}
#endif
}
}
@@ -2563,6 +2563,30 @@ namespace MonoTests.System.Data
Assert.AreEqual (2, dsLoad.Tables[2].Columns.Count, "T3-Columns");
}
[Test]
public void ReadDiff ()
{
DataSet dsTest = new DataSet ("MonoTouchTest");
var dt = new DataTable ("123");
dt.Columns.Add (new DataColumn ("Value1"));
dt.Columns.Add (new DataColumn ("Value2"));
dsTest.Tables.Add (dt);
dsTest.ReadXml (new StringReader (@"
<diffgr:diffgram
xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'
xmlns:diffgr='urn:schemas-microsoft-com:xml-diffgram-v1'>
<MonoTouchTest>
<_x0031_23 diffgr:id='1231' msdata:rowOrder='0'>
<Value1>Row1Value1</Value1>
<Value2>Row1Value2</Value2>
</_x0031_23>
</MonoTouchTest>
</diffgr:diffgram>
"));
Assert.AreEqual ("123", dsTest.Tables [0].TableName, "#1");
Assert.AreEqual (1, dsTest.Tables [0].Rows.Count, "#2");
}
private void CompareTables (DataSet dsLoad) {
Assert.AreEqual (ds.Tables.Count, dsLoad.Tables.Count, "NumTables");
for (int tc = 0; tc < dsLoad.Tables.Count; tc++) {
@@ -11,6 +11,7 @@
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
// Copyright (C) 2011 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -1043,6 +1044,43 @@ namespace MonoTests.System.Data
Assert.AreEqual ("Table#1", copyTable.TableName, "#A30");
}
[Test]
public void CloneExtendedProperties ()
{
// bug 668
DataTable t1 = new DataTable ("t1");
DataColumn c1 = t1.Columns.Add ("c1");
c1.ExtendedProperties.Add ("Company", "Xamarin");
DataTable t2 = t1.Clone ();
Assert.AreEqual ("Xamarin", t1.Columns["c1"].ExtendedProperties["Company"], "CEP1");
Assert.AreEqual ("Xamarin", t2.Columns["c1"].ExtendedProperties["Company"], "CEP2");
}
[Test]
[ExpectedException (typeof (EvaluateException))]
public void CloneExtendedProperties1 ()
{
// Xamarin bug 666
DataTable table1 = new DataTable("Table1") ;
DataColumn c1 = table1.Columns.Add("c1", typeof(string), "'hello ' + c2") ; /* Should cause an exception */
}
[Test]
public void CloneExtendedProperties2 ()
{
// Xamarin bug 666
DataTable table1 = new DataTable("Table1") ;
DataColumn c1 = table1.Columns.Add("c1") ;
DataColumn c2 = table1.Columns.Add("c2") ;
c1.Expression = "'hello ' + c2";
DataTable t2 = table1.Clone(); // this should not cause an exception
}
[Test]
public void LoadDataException ()
{
@@ -3,8 +3,10 @@
//
// Author:
// Atsushi Enomoto <[email protected]>
// Atsushi Enomoto <[email protected]>
//
// Copyright (C) 2008,2009 Novell, Inc (http://www.novell.com)
// Copyright (C) 2011 Xamarin, Inc (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -45,6 +47,24 @@ using XmlObjectSerializer = System.Object;
namespace System.ServiceModel.Dispatcher
{
// This set of classes is to work as message formatters for
// WebHttpBehavior. There are couple of aspects to differentiate
// implementations:
// - request/reply and client/server
// by WebMessageFormatter hierarchy
// - WebClientMessageFormatter - for client
// - RequestClientFormatter - for request
// - ReplyClientFormatter - for response
// - WebDispatchMessageFormatter - for server
// - RequestDispatchFormatter - for request
// - ReplyDispatchFormatter - for response
//
// FIXME: below items need more work
// - HTTP method differences
// - GET (WebGet)
// - POST (other way)
// - output format: Stream, JSON, XML ...
internal abstract class WebMessageFormatter
{
OperationDescription operation;
@@ -182,6 +202,9 @@ namespace System.ServiceModel.Dispatcher
protected XmlObjectSerializer GetSerializer (WebContentFormat msgfmt, bool isWrapped, MessagePartDescription part)
{
if (part.Type == typeof (void))
return null; // no serialization should be done.
switch (msgfmt) {
case WebContentFormat.Xml:
if (xml_serializer == null)
@@ -208,6 +231,9 @@ namespace System.ServiceModel.Dispatcher
// FIXME: handle ref/out parameters
var reader = message.GetReaderAtBodyContents ();
reader.MoveToContent ();
bool wasEmptyElement = reader.IsEmptyElement;
if (isWrapped) {
if (fmt == WebContentFormat.Json)
@@ -216,9 +242,9 @@ namespace System.ServiceModel.Dispatcher
reader.ReadStartElement (md.Body.WrapperName, md.Body.WrapperNamespace);
}
var ret = ReadObjectBody (serializer, reader);
var ret = (serializer == null) ? null : ReadObjectBody (serializer, reader);
if (isWrapped)
if (isWrapped && !wasEmptyElement)
reader.ReadEndElement ();
return ret;
@@ -291,6 +317,8 @@ namespace System.ServiceModel.Dispatcher
internal abstract class WebClientMessageFormatter : WebMessageFormatter, IClientMessageFormatter
{
IClientMessageFormatter default_formatter;
protected WebClientMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
: base (operation, endpoint, converter, behavior)
{
@@ -306,11 +334,11 @@ namespace System.ServiceModel.Dispatcher
MessageDescription md = GetMessageDescription (MessageDirection.Input);
if (parameters.Length != md.Body.Parts.Count)
throw new ArgumentException ("Parameter array length does not match the number of message body parts");
Message ret;
Uri to;
object msgpart = null;
for (int i = 0; i < parameters.Length; i++) {
var p = md.Body.Parts [i];
string name = p.Name.ToUpper (CultureInfo.InvariantCulture);
@@ -325,10 +353,9 @@ namespace System.ServiceModel.Dispatcher
throw new NotImplementedException (String.Format ("More than one parameters including {0} that are not contained in the URI template {1} was found.", p.Name, UriTemplate));
}
}
ret = Message.CreateMessage (messageVersion, (string) null, msgpart);
Uri to = UriTemplate.BindByName (Endpoint.Address.Uri, c);
Message ret = Message.CreateMessage (messageVersion, (string) null, msgpart);
to = UriTemplate.BindByName (Endpoint.Address.Uri, c);
ret.Headers.To = to;
var hp = new HttpRequestMessageProperty ();
@@ -546,11 +573,8 @@ namespace System.ServiceModel.Dispatcher
var fmt = wp != null ? wp.Format : WebContentFormat.Xml;
Uri to = message.Headers.To;
UriTemplateMatch match = UriTemplate.Match (Endpoint.Address.Uri, to);
if (match == null)
// not sure if it could happen
throw new SystemException (String.Format ("INTERNAL ERROR: UriTemplate does not match with the request: {0} / {1}", UriTemplate, to));
if (iwc != null)
UriTemplateMatch match = to == null ? null : UriTemplate.Match (Endpoint.Address.Uri, to);
if (match != null && iwc != null)
iwc.UriTemplateMatch = match;
MessageDescription md = GetMessageDescription (MessageDirection.Input);
@@ -558,15 +582,20 @@ namespace System.ServiceModel.Dispatcher
for (int i = 0; i < parameters.Length; i++) {
var p = md.Body.Parts [i];
string name = p.Name.ToUpperInvariant ();
var str = match.BoundVariables [name];
if (str != null)
parameters [i] = Converter.ConvertStringToValue (str, p.Type);
else if (fmt == WebContentFormat.Raw && p.Type == typeof (Stream)) {
if (fmt == WebContentFormat.Raw && p.Type == typeof (Stream)) {
var rmsg = (RawMessage) message;
parameters [i] = rmsg.Stream;
} else {
var serializer = GetSerializer (fmt, IsRequestBodyWrapped, p);
parameters [i] = DeserializeObject (serializer, message, md, IsRequestBodyWrapped, fmt);
var str = match.BoundVariables [name];
if (str != null)
parameters [i] = Converter.ConvertStringToValue (str, p.Type);
else {
if (info.Method != "GET") {
var serializer = GetSerializer (fmt, IsRequestBodyWrapped, p);
parameters [i] = DeserializeObject (serializer, message, md, IsRequestBodyWrapped, fmt);
}
// for GET Uri template parameters, there is no <anyType xsi:nil='true' />. So just skip the member.
}
}
}
}
@@ -163,6 +163,15 @@ namespace System
void BindByName (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults, bool query)
{
if (query) {
int idx = template.IndexOf ('?', src);
if (idx > 0) {
sb.Append (template.Substring (src, idx - src));
src = idx;
// note that it doesn't append '?'. It is added only when there is actual parameter binding.
}
}
foreach (string name in names) {
int s = template.IndexOf ('{', src);
int e = template.IndexOf ('}', s + 1);
@@ -173,18 +182,19 @@ namespace System
#endif
if (dic != null)
dic.TryGetValue (name, out value);
if (query) {
if (value != null || (!omitDefaults && Defaults.TryGetValue (name, out value))) {
sb.Append (template.Substring (src, s - src));
sb.Append (value);
}
} else
if (value == null && (omitDefaults || !Defaults.TryGetValue(name, out value)))
throw new ArgumentException(string.Format("The argument name value collection does not contain non-nul vaalue for '{0}'", name), "parameters");
else {
sb.Append (template.Substring (src, s - src));
sb.Append (value);
}
} else {
if (value == null && (omitDefaults || !Defaults.TryGetValue (name, out value)))
throw new ArgumentException (string.Format("The argument name value collection does not contain non-null value for '{0}'", name), "parameters");
sb.Append (template.Substring (src, s - src));
sb.Append (value);
}
src = e + 1;
}
}
@@ -0,0 +1,321 @@
//
// This code was partly auto-generated by slsvcutil, version 4.0.60310.0
//
namespace DHIWebService
{
using System.Runtime.Serialization;
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="ClientLoginData", Namespace="http://schemas.datacontract.org/2004/07/Domain.Models")]
public partial class ClientLoginData : object
{
private int CompanyNumberField;
private string InstitutionIdField;
private string PasswordField;
private string UserNameField;
[System.Runtime.Serialization.DataMemberAttribute()]
public int CompanyNumber
{
get
{
return this.CompanyNumberField;
}
set
{
this.CompanyNumberField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string InstitutionId
{
get
{
return this.InstitutionIdField;
}
set
{
this.InstitutionIdField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public string Password
{
get
{
return this.PasswordField;
}
set
{
this.PasswordField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public string UserName
{
get
{
return this.UserNameField;
}
set
{
this.UserNameField = value;
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="Login", Namespace="http://schemas.datacontract.org/2004/07/Domain.Models")]
public partial class Login : object
{
private int CompanyNumberField;
private string InstitutionIdField;
private string PasswordField;
private string UserNameField;
[System.Runtime.Serialization.DataMemberAttribute()]
public int CompanyNumber
{
get
{
return this.CompanyNumberField;
}
set
{
this.CompanyNumberField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string InstitutionId
{
get
{
return this.InstitutionIdField;
}
set
{
this.InstitutionIdField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public string Password
{
get
{
return this.PasswordField;
}
set
{
this.PasswordField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public string UserName
{
get
{
return this.UserNameField;
}
set
{
this.UserNameField = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace="IBEWebSvc", ConfigurationName="DHIWebService.IDHIService")]
public interface IDHIService
{
[System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="IBEWebSvc/IDHIService/Login", ReplyAction="IBEWebSvc/IDHIService/LoginResponse")]
// FIXME: uncommenting this results in cryptic error message. We should tell what could be wrong here.
// [System.ServiceModel.Web.WebInvoke(BodyStyle=System.ServiceModel.Web.WebMessageBodyStyle.Wrapped)]
System.IAsyncResult BeginLogin(DHIWebService.LoginRequest request, System.AsyncCallback callback, object asyncState);
DHIWebService.LoginResponse EndLogin(System.IAsyncResult result);
[System.ServiceModel.OperationContractAttribute(Action="IBEWebSvc/IDHIService/Login", ReplyAction="IBEWebSvc/IDHIService/LoginResponse")]
[System.ServiceModel.Web.WebInvoke(BodyStyle=System.ServiceModel.Web.WebMessageBodyStyle.Wrapped)]
DHIWebService.LoginResponse Login(DHIWebService.LoginRequest request);
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.MessageContractAttribute(WrapperName="Login", WrapperNamespace="IBEWebSvc", IsWrapped=true)]
public partial class LoginRequest
{
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="IBEWebSvc", Order=0)]
public DHIWebService.ClientLoginData clientLoginData;
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="IBEWebSvc", Order=1)]
public DHIWebService.Login credentials;
public LoginRequest()
{
}
public LoginRequest(DHIWebService.ClientLoginData clientLoginData, DHIWebService.Login credentials)
{
this.clientLoginData = clientLoginData;
this.credentials = credentials;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.MessageContractAttribute(WrapperName="LoginResponse", WrapperNamespace="IBEWebSvc", IsWrapped=true)]
public partial class LoginResponse
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IDHIServiceChannel : DHIWebService.IDHIService, System.ServiceModel.IClientChannel
{
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class LoginCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
public LoginCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState)
{
this.results = results;
}
public DHIWebService.LoginResponse Result
{
get
{
base.RaiseExceptionIfNecessary();
return ((DHIWebService.LoginResponse)(this.results[0]));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class DHIServiceClient : System.ServiceModel.ClientBase<DHIWebService.IDHIService>, DHIWebService.IDHIService
{
private BeginOperationDelegate onBeginLoginDelegate;
private EndOperationDelegate onEndLoginDelegate;
private System.Threading.SendOrPostCallback onLoginCompletedDelegate;
public DHIServiceClient()
{
}
public DHIServiceClient(string endpointConfigurationName) :
base(endpointConfigurationName)
{
}
public DHIServiceClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress)
{
}
public DHIServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress)
{
}
public DHIServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress)
{
}
public event System.EventHandler<LoginCompletedEventArgs> LoginCompleted;
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.IAsyncResult DHIWebService.IDHIService.BeginLogin(DHIWebService.LoginRequest request, System.AsyncCallback callback, object asyncState)
{
return base.Channel.BeginLogin(request, callback, asyncState);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
DHIWebService.LoginResponse DHIWebService.IDHIService.EndLogin(System.IAsyncResult result)
{
return base.Channel.EndLogin(result);
}
private System.IAsyncResult OnBeginLogin(object[] inValues, System.AsyncCallback callback, object asyncState)
{
DHIWebService.LoginRequest request = ((DHIWebService.LoginRequest)(inValues[0]));
return ((DHIWebService.IDHIService)(this)).BeginLogin(request, callback, asyncState);
}
private object[] OnEndLogin(System.IAsyncResult result)
{
DHIWebService.LoginResponse retVal = ((DHIWebService.IDHIService)(this)).EndLogin(result);
return new object[] {
retVal};
}
private void OnLoginCompleted(object state)
{
if ((this.LoginCompleted != null))
{
InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
this.LoginCompleted(this, new LoginCompletedEventArgs(e.Results, e.Error, e.Cancelled, e.UserState));
}
}
public void LoginAsync(DHIWebService.LoginRequest request)
{
this.LoginAsync(request, null);
}
public void LoginAsync(DHIWebService.LoginRequest request, object userState)
{
if ((this.onBeginLoginDelegate == null))
{
this.onBeginLoginDelegate = new BeginOperationDelegate(this.OnBeginLogin);
}
if ((this.onEndLoginDelegate == null))
{
this.onEndLoginDelegate = new EndOperationDelegate(this.OnEndLogin);
}
if ((this.onLoginCompletedDelegate == null))
{
this.onLoginCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnLoginCompleted);
}
base.InvokeAsync(this.onBeginLoginDelegate, new object[] {
request}, this.onEndLoginDelegate, this.onLoginCompletedDelegate, userState);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
DHIWebService.LoginResponse DHIWebService.IDHIService.Login (DHIWebService.LoginRequest request)
{
return base.Channel.Login(request);
}
}
}
@@ -241,7 +241,6 @@ namespace MonoTests.System.ServiceModel.Description
var se = new ServiceEndpoint (cd, new WebHttpBinding (), new EndpointAddress ("http://localhost:8080/"));
var wmebe = new WebMessageEncodingBindingElement ();
var wme = wmebe.CreateMessageEncoderFactory ().Encoder;
Console.WriteLine (wme.MediaType);
var msg = wme.ReadMessage (ms, 100, null); // "application/xml" causes error.
var formatter = new WebHttpBehaviorExt ().DoGetRequestDispatchFormatter (od, se);
object [] pars = new object [1];
@@ -256,6 +256,7 @@ namespace MonoTests.System.ServiceModel.Dispatcher
{
var host = new WebServiceHost (typeof (Hello));
host.AddServiceEndpoint (typeof (IHello), new WebHttpBinding (), "http://localhost:37564/");
host.Description.Behaviors.Find<ServiceDebugBehavior> ().IncludeExceptionDetailInFaults = true;
host.Open ();
try {
// run client
@@ -228,6 +228,15 @@ namespace MonoTests.System
Assert.AreEqual ("http://localhost/x/value2/value1", u.ToString ());
}
[Test]
public void BindByName3 ()
{
var t = new UriTemplate ("Login?clientLoginData={clientLoginData}&credentials={credentials}");
var n = new NameValueCollection ();
var u = t.BindByName (new Uri ("http://localhost"), n);
Assert.AreEqual ("http://localhost/Login", u.ToString (), "#1");
}
[Test]
public void BindByNameManySlashes ()
{
@@ -3,8 +3,10 @@
//
// Author:
// Atsushi Enomoto <[email protected]>
// Atsushi Enomoto <[email protected]>
//
// Copyright (C) 2005-2007 Novell, Inc. http://www.novell.com
// Copyright (C) 2011 Xamarin, Inc. http://xamarin.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -413,9 +415,21 @@ namespace System.ServiceModel.Description
cd.Namespace.Length == 0 ? "urn:" : cd.Namespace.EndsWith ("/") ? "" : "/", cd.Name, "/",
od.Name, isRequest ? String.Empty : "Response");
MessageDescription md;
if (mca != null)
return CreateMessageDescription (messageType, cd.Namespace, action, isRequest, isCallback, mca);
return CreateMessageDescription (oca, plist, od.Name, cd.Namespace, action, isRequest, isCallback, retType, mi.ReturnTypeCustomAttributes);
md = CreateMessageDescription (messageType, cd.Namespace, action, isRequest, isCallback, mca);
else
md = CreateMessageDescription (oca, plist, od.Name, cd.Namespace, action, isRequest, isCallback, retType);
// ReturnValue
if (!isRequest) {
MessagePartDescription mp = CreatePartCore (GetMessageParameterAttribute (mi.ReturnTypeCustomAttributes), od.Name + "Result", md.Body.WrapperNamespace);
mp.Index = 0;
mp.Type = mca != null ? typeof (void) : retType;
md.Body.ReturnValue = mp;
}
return md;
}
public static MessageDescription CreateMessageDescription (
@@ -456,6 +470,13 @@ namespace System.ServiceModel.Description
pd.MemberInfo = bmi;
md.Headers.Add (pd);
}
var mpa = bmi.GetCustomAttribute<MessagePropertyAttribute> (false);
if (mpa != null) {
var pd = new MessagePropertyDescription (mpa.Name ?? mname);
pd.Type = MessageFilterOutByRef (mtype);
pd.MemberInfo = bmi;
md.Properties.Add (pd);
}
var mba = GetMessageBodyMemberAttribute (bmi);
if (mba != null) {
var pd = CreatePartCore (mba, mname, defaultNamespace);
@@ -467,12 +488,11 @@ namespace System.ServiceModel.Description
}
}
// FIXME: fill headers and properties.
return md;
}
public static MessageDescription CreateMessageDescription (
OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, bool isCallback, Type retType, ICustomAttributeProvider retTypeAttributes)
OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, bool isCallback, Type retType)
{
var dir = isRequest ^ isCallback ? MessageDirection.Input : MessageDirection.Output;
MessageDescription md = new MessageDescription (action, dir) { IsRequest = isRequest };
@@ -505,16 +525,6 @@ namespace System.ServiceModel.Description
mb.Parts.Add (pd);
}
// ReturnValue
if (!isRequest) {
MessagePartDescription mp = CreatePartCore (GetMessageParameterAttribute (retTypeAttributes), name + "Result", mb.WrapperNamespace);
mp.Index = 0;
mp.Type = retType;
mb.ReturnValue = mp;
}
// FIXME: fill properties.
return md;
}
@@ -306,8 +306,9 @@ namespace System.ServiceModel.Dispatcher
foreach (MessagePartDescription partDesc in l)
if (partDesc.MemberInfo is FieldInfo)
((FieldInfo) partDesc.MemberInfo).SetValue (msgObject, parts [partDesc.Index]);
else
else if (partDesc.MemberInfo is PropertyInfo)
((PropertyInfo) partDesc.MemberInfo).SetValue (msgObject, parts [partDesc.Index], null);
// otherwise, it could be null (in case of undefined return value in MessageContract)
}
void MessageObjectToParts (MessageDescription md, object msgObject, Dictionary<MessageHeaderDescription,object> headers, object [] parts)
@@ -68,8 +68,12 @@ namespace System.ServiceModel.Dispatcher
public override bool Match (Message message)
{
Uri to = message.Headers.To;
bool path = ((CultureInfo.InvariantCulture.CompareInfo.IsPrefix (to.AbsolutePath, address.Uri.AbsolutePath, CompareOptions.Ordinal)) &&
(to.Port == address.Uri.Port));
if (to == null)
return false;
if (to.ToString () == Constants.WsaAnonymousUri || to.Equals (EndpointAddress.AnonymousUri) || to.Equals (EndpointAddress.NoneUri))
return true;
bool path = CultureInfo.InvariantCulture.CompareInfo.IsPrefix (to.AbsolutePath, address.Uri.AbsolutePath, CompareOptions.Ordinal);
bool host = IncludeHostNameInComparison
? (String.CompareOrdinal (to.Host, address.Uri.Host) == 0)
: true;
@@ -7,6 +7,7 @@
//
// Copyright (C) 2005-2010 Novell, Inc. http://www.novell.com
// Copyright (C) 2008 Mainsoft Co. http://www.mainsoft.com
// Copyright (C) 2011 Xamarin Inc. http://www.xamarin.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -65,7 +66,7 @@ namespace System.ServiceModel.Dispatcher
m.IsReturnValue = isReturnValue;
m.MemberName = partDesc.Name;
m.MemberType = partDesc.Type;
m.XmlAttributes = new XmlAttributes(partDesc.MemberInfo);
m.XmlAttributes = partDesc.MemberInfo == null ? new XmlAttributes () : new XmlAttributes (partDesc.MemberInfo);
return m;
}
@@ -273,43 +273,26 @@ namespace System.ServiceModel
h.ExtendedProtectionPolicy = Security.Transport.ExtendedProtectionPolicy;
#endif
#if !NET_2_1
switch (Security.Mode) {
case BasicHttpSecurityMode.Transport:
switch (Security.Transport.ClientCredentialType) {
case HttpClientCredentialType.Basic:
h.AuthenticationScheme = AuthenticationSchemes.Basic;
break;
case HttpClientCredentialType.Ntlm:
h.AuthenticationScheme = AuthenticationSchemes.Ntlm;
break;
case HttpClientCredentialType.Windows:
h.AuthenticationScheme = AuthenticationSchemes.Negotiate;
break;
case HttpClientCredentialType.Digest:
h.AuthenticationScheme = AuthenticationSchemes.Digest;
break;
case HttpClientCredentialType.Certificate:
var https = (HttpsTransportBindingElement) h;
https.RequireClientCertificate = true;
break;
}
#if !NET_2_1 || MOBILE
switch (Security.Transport.ClientCredentialType) {
case HttpClientCredentialType.Basic:
h.AuthenticationScheme = AuthenticationSchemes.Basic;
break;
case BasicHttpSecurityMode.TransportCredentialOnly:
switch (Security.Transport.ClientCredentialType) {
case HttpClientCredentialType.Basic:
h.AuthenticationScheme = AuthenticationSchemes.Basic;
case HttpClientCredentialType.Ntlm:
h.AuthenticationScheme = AuthenticationSchemes.Ntlm;
break;
case HttpClientCredentialType.Windows:
h.AuthenticationScheme = AuthenticationSchemes.Negotiate;
break;
case HttpClientCredentialType.Digest:
h.AuthenticationScheme = AuthenticationSchemes.Digest;
break;
case HttpClientCredentialType.Certificate:
switch (Security.Mode) {
case BasicHttpSecurityMode.Transport:
(h as HttpsTransportBindingElement).RequireClientCertificate = true;
break;
case HttpClientCredentialType.Ntlm:
h.AuthenticationScheme = AuthenticationSchemes.Ntlm;
break;
case HttpClientCredentialType.Windows:
h.AuthenticationScheme = AuthenticationSchemes.Negotiate;
break;
case HttpClientCredentialType.Digest:
h.AuthenticationScheme = AuthenticationSchemes.Digest;
break;
case HttpClientCredentialType.Certificate:
case BasicHttpSecurityMode.TransportCredentialOnly:
throw new InvalidOperationException ("Certificate-based client authentication is not supported by 'TransportCredentialOnly' mode.");
}
break;
@@ -25,6 +25,9 @@
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if !MOONLIGHT
using System;
using System.Net.Security;
using System.ServiceModel.Security;
@@ -37,14 +40,16 @@ namespace System.ServiceModel
internal BasicHttpMessageSecurity ()
{
}
#if !MOBILE
SecurityAlgorithmSuite alg = SecurityAlgorithmSuite.Default;
BasicHttpMessageCredentialType ctype;
public SecurityAlgorithmSuite AlgorithmSuite {
get { return alg; }
set { alg = value; }
}
#endif
BasicHttpMessageCredentialType ctype;
public BasicHttpMessageCredentialType ClientCredentialType {
get { return ctype; }
@@ -52,3 +57,5 @@ namespace System.ServiceModel
}
}
}
#endif
@@ -183,7 +183,9 @@ namespace System.ServiceModel
xw.WriteEndAttribute ();
xw.WriteAttributeString ("Source", log.Source.ToString ());
xw.WriteAttributeString ("Type", log.Type.FullName);
log.Message.CreateMessage ().WriteMessage (xw);
var msg = log.Message.CreateMessage ();
if (!msg.IsEmpty)
msg.WriteMessage (xw);
xw.WriteEndElement ();
xw.Close ();
@@ -5,6 +5,7 @@
// Atsushi Enomoto <[email protected]>
//
// Copyright (C) 2005 Novell, Inc. http://www.novell.com
// Copyright (C) 2011 Xamarin, Inc. http://xamarin.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -555,6 +556,24 @@ namespace MonoTests.System.ServiceModel.Description
Assert.IsNotNull (md.Body.ReturnValue, od.Name);
}
[Test]
public void BugX206Contract ()
{
var cd = ContractDescription.GetContract (typeof (BugX206Service));
bool examined = false;
foreach (var md in cd.Operations.First ().Messages) {
if (md.Direction == MessageDirection.Input)
continue;
var pd = md.Body.ReturnValue;
Assert.IsNotNull (pd, "#1");
Assert.AreEqual ("DoWorkResult", pd.Name, "#2");
Assert.IsNull (pd.MemberInfo, "#3");
Assert.AreEqual (typeof (void), pd.Type, "#4");
examined = true;
}
Assert.IsTrue (examined, "end");
}
// It is for testing attribute search in interfaces.
public class Foo : IFoo
{
@@ -916,5 +935,18 @@ namespace MonoTests.System.ServiceModel.Description
[XmlSerializerFormat]
string Echo (string input);
}
[ServiceContract]
public interface BugX206Service
{
[OperationContract]
BugX206Response DoWork ();
}
[MessageContract (IsWrapped = true)]
public partial class BugX206Response
{
}
}
}
@@ -54,7 +54,6 @@ namespace MonoTests.System.ServiceModel.Dispatcher
}
[Test]
[Category ("NotWorking")]
public void Match ()
{
PrefixEndpointAddressMessageFilter f =
@@ -173,7 +173,8 @@ System.ServiceModel.Security/UserNamePasswordClientCredential.cs
System.ServiceModel/ActionNotSupportedException.cs
System.ServiceModel/AllEnums.cs
System.ServiceModel/BasicHttpBinding.cs
System.ServiceModel/BasicHttpSecurity_2_1.cs
System.ServiceModel/BasicHttpSecurity.cs
System.ServiceModel/BasicHttpMessageSecurity.cs
System.ServiceModel/ChannelFactory.cs
System.ServiceModel/ChannelFactory_1.cs
System.ServiceModel/ClientBase.cs
@@ -200,6 +201,7 @@ System.ServiceModel/FaultException.cs
System.ServiceModel/FaultException_1.cs
System.ServiceModel/FaultReason.cs
System.ServiceModel/FaultReasonText.cs
System.ServiceModel/HttpTransportSecurity.cs
System.ServiceModel/IClientChannel.cs
System.ServiceModel/ICommunicationObject.cs
System.ServiceModel/IContextChannel.cs
@@ -146,13 +146,15 @@ namespace System.Web.Compilation
if (NeedsLoadFromBin && _compiler != null)
return LoadTypeFromBin (_compiler, Parser);
// This is not called if compilation failed.
// Returning null makes the caller throw an InvalidCastException
Type type = null;
Assembly assembly = results != null ? results.CompiledAssembly : null;
if (assembly == null)
return null;
return assembly.GetType (GetClassType (_compiler, Parser));
if (assembly != null) {
type = assembly.GetType (GetClassType (_compiler, Parser));
}
if (type == null) {
throw new HttpException (500, String.Format ("Type {0} could not be loaded", GetClassType (_compiler, Parser)));
}
return type;
}
// This is intended to be used by builders which may need to do special processing
+2 -2
View File
@@ -77,14 +77,14 @@ EXTRA_DISTFILES = \
$(nist_dom_files:%=Test/System.Xml/nist_dom/%)
System.Xml.XPath/Parser.cs: System.Xml.XPath/Parser.jay $(topdir)/jay/skeleton.cs
$(topdir)/jay/jay -ct < $(topdir)/jay/skeleton.cs $< >$@
$(topdir)/jay/jay -ct < $(topdir)/jay/skeleton.cs $(CURDIR)/$< >$@
Mono.Xml.Xsl/PatternParser.jay: System.Xml.XPath/Parser.jay $(topdir)/jay/skeleton.cs
sed "s/\%start Expr/\%start Pattern/" $< >$@
Mono.Xml.Xsl/PatternParser.cs: Mono.Xml.Xsl/PatternParser.jay $(topdir)/jay/skeleton.cs
echo "#define XSLT_PATTERN" > $@
$(topdir)/jay/jay -ct $< < $(topdir)/jay/skeleton.cs >>$@
$(topdir)/jay/jay -ct $(CURDIR)/$< < $(topdir)/jay/skeleton.cs >>$@
Mono.Xml.Xsl/PatternTokenizer.cs: System.Xml.XPath/Tokenizer.cs
echo "#define XSLT_PATTERN" > $@
@@ -578,6 +578,10 @@ namespace Mono.Xml.XPath
namespaces [nsIndex].Name = name;
namespaces [nsIndex].Namespace = ns;
namespaces [nsIndex].NextNamespace = nextNs;
if (lineInfo != null && lineInfo.HasLineInfo ()) {
namespaces [nsIndex].LineNumber = lineInfo.LineNumber;
namespaces [nsIndex].LinePosition = lineInfo.LinePosition;
}
}
}
}
@@ -118,14 +118,16 @@ namespace Mono.Xml.XPath
int IXmlLineInfo.LineNumber {
get {
return currentIsAttr ? attributes [currentAttr].LineNumber :
nodes [currentNode].LineNumber;
currentIsNode ? nodes [currentNode].LineNumber :
namespaces [currentNs].LineNumber;
}
}
int IXmlLineInfo.LinePosition {
get {
return currentIsAttr ? attributes [currentAttr].LinePosition :
nodes [currentNode].LinePosition;
currentIsNode ? nodes [currentNode].LinePosition :
namespaces [currentNs].LinePosition;
}
}
@@ -100,5 +100,7 @@ namespace Mono.Xml.XPath
public int NextNamespace;
public int Name;
public int Namespace;
public int LineNumber;
public int LinePosition;
}
}
@@ -111,13 +111,13 @@ namespace System.Xml
public XmlTextReader (string url, XmlNameTable nt)
{
string uriString;
Stream stream = GetStreamFromUrl (url, out uriString);
reader_uri = resolver.ResolveUri (null, url);
string uriString = (reader_uri == null) ? String.Empty : reader_uri.ToString ();
XmlParserContext ctx = new XmlParserContext (nt,
new XmlNamespaceManager (nt),
String.Empty,
XmlSpace.None);
this.InitializeContext (uriString, ctx, new XmlStreamReader (stream), XmlNodeType.Document);
this.InitializeContext (uriString, ctx, null, XmlNodeType.Document);
}
public XmlTextReader (TextReader input, XmlNameTable nt)
@@ -138,6 +138,7 @@ namespace System.Xml
}
this.XmlResolver = resolver;
string uriString;
Stream stream = GetStreamFromUrl (url, out uriString);
this.InitializeContext (uriString, context, new XmlStreamReader (stream), fragType);
}
@@ -180,7 +181,12 @@ namespace System.Xml
InitializeContext (url, context, fragment, fragType);
}
private Stream GetStreamFromUrl (string url, out string absoluteUriString)
Uri ResolveUri (string url)
{
return resolver.ResolveUri (null, url);
}
Stream GetStreamFromUrl (string url, out string absoluteUriString)
{
#if NET_2_1
if (url == null)
@@ -188,7 +194,7 @@ namespace System.Xml
if (url.Length == 0)
throw new ArgumentException ("url");
#endif
Uri uri = resolver.ResolveUri (null, url);
Uri uri = ResolveUri (url);
absoluteUriString = uri != null ? uri.ToString () : String.Empty;
return resolver.GetEntity (uri, null, typeof (Stream)) as Stream;
}
@@ -928,6 +934,7 @@ namespace System.Xml
private StringBuilder valueBuffer;
Uri reader_uri;
private TextReader reader;
private char [] peekChars;
private int peekCharsIndex;
@@ -1239,6 +1246,12 @@ namespace System.Xml
private bool ReadTextReader (int remained)
{
if (reader == null && reader_uri != null) {
Uri uri = reader_uri;
reader_uri = null;
string uriString;
reader = new XmlStreamReader (GetStreamFromUrl (uri.ToString (), out uriString));
}
if (peekCharsLength < 0) { // initialized buffer
peekCharsLength = reader.Read (peekChars, 0, peekChars.Length);
return peekCharsLength > 0;
@@ -31,7 +31,7 @@ using XPI = System.Xml.Linq.XProcessingInstruction;
namespace System.Xml.Linq
{
internal class XNodeReader : XmlReader
internal class XNodeReader : XmlReader, IXmlLineInfo
{
ReadState state = ReadState.Initial;
XNode node, start;
@@ -46,6 +46,24 @@ namespace System.Xml.Linq
start = node;
}
int IXmlLineInfo.LineNumber {
get {
var o = (XObject) GetCurrentAttribute () ?? node;
return o != null ? o.LineNumber : 0;
}
}
int IXmlLineInfo.LinePosition {
get {
var o = (XObject) GetCurrentAttribute () ?? node;
return o != null ? o.LinePosition : 0;
}
}
bool IXmlLineInfo.HasLineInfo ()
{
var o = (XObject) GetCurrentAttribute () ?? node;
return o != null ? ((IXmlLineInfo) o).HasLineInfo () : false;
}
public override int AttributeCount {
get {
if (state != ReadState.Interactive || end_element)
@@ -2,9 +2,10 @@
//
// Authors:
// Marek Habersack ([email protected])
// Gonzalo Paniagua Javier (gonzalo@novell.com)
// Gonzalo Paniagua Javier (gonzalo@xamarin.com)
//
// Copyright (c) 2008,2010 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2011 Xamarin, Inc. (http://xamarin.com)
//
//
@@ -37,6 +38,8 @@ namespace System.Net.Sockets
{
public class SocketAsyncEventArgs : EventArgs, IDisposable
{
bool disposed;
int in_progress;
internal Socket.Worker Worker;
EndPoint remote_ep;
#if MOONLIGHT || NET_4_0
@@ -147,7 +150,11 @@ namespace System.Net.Sockets
void Dispose (bool disposing)
{
disposed = true;
if (disposing) {
if (disposed || Interlocked.CompareExchange (ref in_progress, 0, 0) != 0)
return;
if (Worker != null) {
Worker.Dispose ();
Worker = null;
@@ -171,6 +178,10 @@ namespace System.Net.Sockets
internal void SetLastOperation (SocketAsyncOperation op)
{
if (disposed)
throw new ObjectDisposedException ("System.Net.Sockets.SocketAsyncEventArgs");
if (Interlocked.Exchange (ref in_progress, 1) != 0)
throw new InvalidOperationException ("Operation already in progress");
LastOperation = op;
}
@@ -219,6 +230,8 @@ namespace System.Net.Sockets
static void DispatcherCB (IAsyncResult ares)
{
SocketAsyncEventArgs args = (SocketAsyncEventArgs) ares.AsyncState;
if (Interlocked.Exchange (ref args.in_progress, 0) != 1)
throw new InvalidOperationException ("No operation in progress");
SocketAsyncOperation op = args.LastOperation;
// Notes;
// -SocketOperation.AcceptReceive not used in SocketAsyncEventArgs
@@ -162,7 +162,7 @@ namespace System.Globalization {
public string CultureName {
get {
if (customCultureName == null)
customCultureName = ci.Name;
customCultureName = ci == null ? String.Empty : ci.Name;
return customCultureName;
}
}
+4 -4
View File
@@ -220,7 +220,7 @@ namespace System.IO
}
if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
#if NET_2_1
#if MOONLIGHT
if (anonymous)
throw new IsolatedStorageException ("Enum value for FileAccess was out of legal range.");
else
@@ -229,7 +229,7 @@ namespace System.IO
}
if (share < FileShare.None || share > (FileShare.ReadWrite | FileShare.Delete)) {
#if NET_2_1
#if MOONLIGHT
if (anonymous)
throw new IsolatedStorageException ("Enum value for FileShare was out of legal range.");
else
@@ -275,7 +275,7 @@ namespace System.IO
// don't leak the path information for isolated storage
string msg = Locale.GetText ("Could not find a part of the path \"{0}\".");
string fname = (anonymous) ? dname : Path.GetFullPath (path);
#if NET_2_1
#if MOONLIGHT
// don't use GetSecureFileName for the directory name
throw new IsolatedStorageException (String.Format (msg, fname));
#else
@@ -289,7 +289,7 @@ namespace System.IO
// don't leak the path information for isolated storage
string msg = Locale.GetText ("Could not find file \"{0}\".");
string fname = GetSecureFileName (path);
#if NET_2_1
#if MOONLIGHT
throw new IsolatedStorageException (String.Format (msg, fname));
#else
throw new FileNotFoundException (String.Format (msg, fname), fname);
@@ -256,6 +256,11 @@ namespace System.IO {
throw new ArgumentException ("An empty file name is not valid.");
if (path.IndexOfAny (Path.InvalidPathChars) != -1)
throw new ArgumentException ("Illegal characters in path.");
if (Environment.IsRunningOnWindows) {
int idx = path.IndexOf (':');
if (idx >= 0 && idx != 1)
throw new ArgumentException ("path");
}
}
internal MonoIOStat stat;
+2 -2
View File
@@ -82,7 +82,7 @@ namespace System.IO
// FIXME: add more exception mappings here
case MonoIOError.ERROR_FILE_NOT_FOUND:
message = String.Format ("Could not find file \"{0}\"", path);
#if NET_2_1
#if MOONLIGHT
return new IsolatedStorageException (message);
#else
return new FileNotFoundException (message, path);
@@ -93,7 +93,7 @@ namespace System.IO
case MonoIOError.ERROR_PATH_NOT_FOUND:
message = String.Format ("Could not find a part of the path \"{0}\"", path);
#if NET_2_1
#if MOONLIGHT
return new IsolatedStorageException (message);
#else
return new DirectoryNotFoundException (message);
+5
View File
@@ -841,6 +841,11 @@ namespace System.IO {
throw new ArgumentException (Locale.GetText ("Path is empty"));
if (path.IndexOfAny (Path.InvalidPathChars) != -1)
throw new ArgumentException (Locale.GetText ("Path contains invalid chars"));
if (Environment.IsRunningOnWindows) {
int idx = path.IndexOf (':');
if (idx >= 0 && idx != 1)
throw new ArgumentException (parameterName);
}
#if MOONLIGHT
// On Moonlight (SL4+) there are some limitations in "Elevated Trust"
if (SecurityManager.HasElevatedPermissions) {
@@ -281,8 +281,13 @@ namespace System.Reflection {
"name");
ManifestResourceInfo info = GetManifestResourceInfo (name);
if (info == null)
return null;
if (info == null) {
Assembly a = AppDomain.CurrentDomain.DoResourceResolve (name, this);
if (a != null && a != this)
return a.GetManifestResourceStream (name);
else
return null;
}
if (info.ReferencedAssembly != null)
return info.ReferencedAssembly.GetManifestResourceStream (name);
@@ -8,6 +8,7 @@
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) Tim Coleman, 2004
// Copyright (C) 2004-2007,2011 Novell, Inc (http://www.novell.com)
// Copyright (C) 2011 Xamarin Inc. http://www.xamarin.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -489,6 +490,8 @@ public partial class CryptoConfig {
if (algo == null)
algo = name;
algoClass = Type.GetType (algo);
if (algoClass == null)
return null;
// call the constructor for the type
return Activator.CreateInstance (algoClass, args);
}
@@ -94,6 +94,7 @@ namespace System.Text
public override void Reset ()
{
fallback_assigned = false;
current = 0;
}
}
@@ -31,14 +31,15 @@ using System.Threading;
namespace System.Threading.Tasks
{
public class SynchronizationContextScheduler : TaskScheduler
sealed class SynchronizationContextScheduler : TaskScheduler
{
readonly SynchronizationContext ctx;
static readonly SendOrPostCallback callback = TaskLaunchWrapper;
readonly SendOrPostCallback callback;
public SynchronizationContextScheduler (SynchronizationContext ctx)
{
this.ctx = ctx;
this.callback = TaskLaunchWrapper;
}
protected internal override void QueueTask (Task task)
@@ -46,9 +47,9 @@ namespace System.Threading.Tasks
ctx.Post (callback, task);
}
static void TaskLaunchWrapper (object obj)
void TaskLaunchWrapper (object obj)
{
((Task)obj).Execute (null);
TryExecuteTask ((Task)obj);
}
protected override System.Collections.Generic.IEnumerable<Task> GetScheduledTasks ()
@@ -63,15 +64,8 @@ namespace System.Threading.Tasks
protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
{
if (task.IsCompleted)
return false;
if (task.Status == TaskStatus.WaitingToRun) {
task.Execute (null);
return true;
}
return false;
ctx.Send (callback, task);
return true;
}
public override int MaximumConcurrencyLevel {
+99 -30
View File
@@ -30,8 +30,8 @@ using System.Collections.Concurrent;
namespace System.Threading.Tasks
{
[System.Diagnostics.DebuggerDisplay ("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")]
[System.Diagnostics.DebuggerTypeProxy ("System.Threading.Tasks.SystemThreadingTasks_TaskDebugView")]
[System.Diagnostics.DebuggerDisplay ("Id = {Id}, Status = {Status}")]
[System.Diagnostics.DebuggerTypeProxy (typeof (TaskDebuggerView))]
public class Task : IDisposable, IAsyncResult
{
// With this attribute each thread has its own value so that it's correct for our Schedule code
@@ -57,14 +57,16 @@ namespace System.Threading.Tasks
volatile AggregateException exception;
volatile bool exceptionObserved;
ConcurrentQueue<AggregateException> childExceptions;
TaskStatus status;
Action<object> action;
Action simpleAction;
object state;
AtomicBooleanValue executing;
ConcurrentQueue<EventHandler> completed = new ConcurrentQueue<EventHandler> ();
ConcurrentQueue<EventHandler> completed;
CancellationToken token;
@@ -87,8 +89,13 @@ namespace System.Threading.Tasks
}
public Task (Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this ((o) => { if (action != null) action (); }, null, cancellationToken, creationOptions)
: this (null, null, cancellationToken, creationOptions, current)
{
if (action == null)
throw new ArgumentNullException ("action");
if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
throw new ArgumentOutOfRangeException ("creationOptions");
this.simpleAction = action;
}
public Task (Action<object> action, object state) : this (action, state, TaskCreationOptions.None)
@@ -104,27 +111,35 @@ namespace System.Threading.Tasks
: this (action, state, cancellationToken, TaskCreationOptions.None)
{
}
public Task (Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this (action, state, cancellationToken, creationOptions, current)
{
if (action == null)
throw new ArgumentNullException ("action");
if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
throw new ArgumentOutOfRangeException ("creationOptions");
}
internal Task (Action<object> action,
object state,
CancellationToken cancellationToken,
TaskCreationOptions creationOptions,
Task parent)
{
this.taskCreationOptions = creationOptions;
this.action = action == null ? EmptyFunc : action;
this.action = action;
this.state = state;
this.taskId = Interlocked.Increment (ref id);
this.status = cancellationToken.IsCancellationRequested ? TaskStatus.Canceled : TaskStatus.Created;
this.token = cancellationToken;
this.parent = parent;
// Process taskCreationOptions
if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent)) {
parent = current;
if (parent != null)
parent.AddChild ();
}
if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null)
parent.AddChild ();
}
~Task ()
{
if (exception != null && !exceptionObserved)
@@ -136,10 +151,6 @@ namespace System.Threading.Tasks
return (opt & member) == member;
}
static void EmptyFunc (object o)
{
}
#region Start
public void Start ()
{
@@ -168,9 +179,24 @@ namespace System.Threading.Tasks
public void RunSynchronously (TaskScheduler scheduler)
{
if (scheduler.TryExecuteTask (this))
return;
if (scheduler == null)
throw new ArgumentNullException ("scheduler");
if (Status > TaskStatus.WaitingForActivation)
throw new InvalidOperationException ("The task is not in a valid state to be started");
SetupScheduler (scheduler);
var saveStatus = status;
status = TaskStatus.WaitingToRun;
try {
if (scheduler.RunInline (this))
return;
} catch (Exception inner) {
throw new TaskSchedulerException (inner);
}
status = saveStatus;
Start (scheduler);
Wait ();
}
@@ -199,7 +225,11 @@ namespace System.Threading.Tasks
public Task ContinueWith (Action<Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
Task continuation = new Task ((o) => continuationAction ((Task)o), this, cancellationToken, GetCreationOptions (continuationOptions));
Task continuation = new Task ((o) => continuationAction ((Task)o),
this,
cancellationToken,
GetCreationOptions (continuationOptions),
this);
ContinueWithCore (continuation, continuationOptions, scheduler);
return continuation;
@@ -233,7 +263,11 @@ namespace System.Threading.Tasks
if (scheduler == null)
throw new ArgumentNullException ("scheduler");
Task<TResult> t = new Task<TResult> ((o) => continuationFunction ((Task)o), this, cancellationToken, GetCreationOptions (continuationOptions));
Task<TResult> t = new Task<TResult> ((o) => continuationFunction ((Task)o),
this,
cancellationToken,
GetCreationOptions (continuationOptions),
this);
ContinueWithCore (t, continuationOptions, scheduler);
@@ -275,6 +309,8 @@ namespace System.Threading.Tasks
return;
}
if (completed == null)
Interlocked.CompareExchange (ref completed, new ConcurrentQueue<EventHandler> (), null);
completed.Enqueue (action);
// Retry in case completion was achieved but event adding was too late
@@ -327,7 +363,7 @@ namespace System.Threading.Tasks
void CheckAndSchedule (Task continuation, TaskContinuationOptions options, TaskScheduler scheduler, bool fromCaller)
{
if ((options & TaskContinuationOptions.ExecuteSynchronously) > 0)
continuation.ThreadStart ();
continuation.RunSynchronously (scheduler);
else
continuation.Start (scheduler);
}
@@ -348,7 +384,7 @@ namespace System.Threading.Tasks
#region Internal and protected thingies
internal void Schedule ()
{
{
status = TaskStatus.WaitingToRun;
// If worker is null it means it is a local one, revert to the old behavior
@@ -383,7 +419,7 @@ namespace System.Threading.Tasks
try {
InnerInvoke ();
} catch (OperationCanceledException oce) {
if (oce.CancellationToken == token)
if (token != CancellationToken.None && oce.CancellationToken == token)
CancelReal ();
else
HandleGenericException (oce);
@@ -408,23 +444,31 @@ namespace System.Threading.Tasks
childTasks.AddCount ();
}
internal void ChildCompleted ()
internal void ChildCompleted (AggregateException childEx)
{
childTasks.Signal ();
if (childTasks.IsSet && status == TaskStatus.WaitingForChildrenToComplete) {
if (childEx != null) {
if (childExceptions == null)
Interlocked.CompareExchange (ref childExceptions, new ConcurrentQueue<AggregateException> (), null);
childExceptions.Enqueue (childEx);
}
if (childTasks.Signal () && status == TaskStatus.WaitingForChildrenToComplete) {
status = TaskStatus.RanToCompletion;
ProcessChildExceptions ();
ProcessCompleteDelegates ();
}
}
internal virtual void InnerInvoke ()
{
if (action != null)
if (action == null && simpleAction != null)
simpleAction ();
else if (action != null)
action (state);
// Set action to null so that the GC can collect the delegate and thus
// any big object references that the user might have captured in an anonymous method
action = null;
simpleAction = null;
state = null;
}
@@ -449,17 +493,33 @@ namespace System.Threading.Tasks
TaskScheduler.Current = null;
// Tell parent that we are finished
if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null){
parent.ChildCompleted ();
if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null) {
parent.ChildCompleted (this.Exception);
}
}
void ProcessCompleteDelegates ()
{
if (completed == null)
return;
EventHandler handler;
while (completed.TryDequeue (out handler))
handler (this, EventArgs.Empty);
}
void ProcessChildExceptions ()
{
if (childExceptions == null)
return;
if (exception == null)
exception = new AggregateException ();
AggregateException childEx;
while (childExceptions.TryDequeue (out childEx))
exception.AddChildException (childEx);
}
#endregion
#region Cancel and Wait related method
@@ -477,6 +537,7 @@ namespace System.Threading.Tasks
internal void HandleGenericException (AggregateException e)
{
exception = e;
Thread.MemoryBarrier ();
status = TaskStatus.Faulted;
if (scheduler != null && scheduler.FireUnobservedEvent (exception).Observed)
exceptionObserved = true;
@@ -835,6 +896,14 @@ namespace System.Threading.Tasks
return parent;
}
}
internal string DisplayActionMethod {
get {
Delegate d = simpleAction ?? (Delegate) action;
return d == null ? "<none>" : d.Method.ToString ();
}
}
#endregion
}
}
@@ -1,10 +1,12 @@
//
// TaskCompletionSource.cs
//
// Author:
// Authors:
// Jérémie "Garuma" Laval <[email protected]>
// Marek Safar <[email protected]>
//
// Copyright (c) 2009 Jérémie "Garuma" Laval
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -64,15 +66,18 @@ namespace System.Threading.Tasks
if (!ApplyOperation (source.CancelReal))
ThrowInvalidException ();
}
public void SetException (Exception exception)
{
if (exception == null)
throw new ArgumentNullException ("exception");
SetException (new Exception[] { exception });
}
public void SetException (IEnumerable<Exception> exceptions)
{
if (!ApplyOperation (() => source.HandleGenericException (new AggregateException (exceptions))))
if (!TrySetException (exceptions))
ThrowInvalidException ();
}
@@ -82,7 +87,7 @@ namespace System.Threading.Tasks
ThrowInvalidException ();
}
void ThrowInvalidException ()
static void ThrowInvalidException ()
{
throw new InvalidOperationException ("The underlying Task is already in one of the three final states: RanToCompletion, Faulted, or Canceled.");
}
@@ -94,12 +99,22 @@ namespace System.Threading.Tasks
public bool TrySetException (Exception exception)
{
if (exception == null)
throw new ArgumentNullException ("exception");
return TrySetException (new Exception[] { exception });
}
public bool TrySetException (IEnumerable<Exception> exceptions)
{
return ApplyOperation (() => source.HandleGenericException (new AggregateException (exceptions)));
if (exceptions == null)
throw new ArgumentNullException ("exceptions");
var aggregate = new AggregateException (exceptions);
if (aggregate.InnerExceptions.Count == 0)
throw new ArgumentNullException ("exceptions");
return ApplyOperation (() => source.HandleGenericException (aggregate));
}
public bool TrySetResult (TResult result)
@@ -0,0 +1,86 @@
//
// TaskDebuggerView.cs
//
// Authors:
// Marek Safar <[email protected]>
//
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_4_0 || MOBILE
using System;
using System.Diagnostics;
namespace System.Threading.Tasks
{
//
// Custom debugger type proxy for tasks
//
sealed class TaskDebuggerView
{
readonly Task task;
public TaskDebuggerView (Task task)
{
this.task = task;
}
public object AsyncState {
get {
return task.AsyncState;
}
}
public TaskCreationOptions CreationOptions {
get {
return task.CreationOptions;
}
}
public Exception Exception {
get {
return task.Exception;
}
}
public int Id {
get {
return task.Id;
}
}
public string Method {
get {
return task.DisplayActionMethod;
}
}
public TaskStatus Status {
get {
return task.Status;
}
}
}
}
#endif
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,463 @@
//
// TaskFactory_T.cs
//
// Authors:
// Jérémie "Garuma" Laval <[email protected]>
// Marek Safar <[email protected]>
//
// Copyright (c) 2009 Jérémie "Garuma" Laval
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if NET_4_0 || MOBILE
using System;
using System.Threading;
namespace System.Threading.Tasks
{
public class TaskFactory<TResult>
{
readonly TaskScheduler scheduler;
TaskCreationOptions creationOptions;
TaskContinuationOptions continuationOptions;
CancellationToken cancellationToken;
TaskFactory parent;
const TaskCreationOptions FromAsyncOptionsNotSupported = TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness;
public TaskFactory ()
: this (CancellationToken.None)
{
}
public TaskFactory (TaskScheduler scheduler)
: this (CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, scheduler)
{
}
public TaskFactory (CancellationToken cancellationToken)
: this (cancellationToken, TaskCreationOptions.None, TaskContinuationOptions.None, null)
{
}
public TaskFactory (TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions)
: this (CancellationToken.None, creationOptions, continuationOptions, null)
{
}
public TaskFactory (CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
this.cancellationToken = cancellationToken;
this.scheduler = scheduler;
this.creationOptions = creationOptions;
this.continuationOptions = continuationOptions;
TaskFactory.CheckContinuationOptions (continuationOptions);
this.parent = new TaskFactory (cancellationToken, creationOptions, continuationOptions, scheduler);
}
public TaskScheduler Scheduler {
get {
return scheduler;
}
}
public TaskContinuationOptions ContinuationOptions {
get {
return continuationOptions;
}
}
public TaskCreationOptions CreationOptions {
get {
return creationOptions;
}
}
public CancellationToken CancellationToken {
get {
return cancellationToken;
}
}
#region StartNew for Task<TResult>
public Task<TResult> StartNew (Func<TResult> function)
{
return StartNew (function, cancellationToken, creationOptions, GetScheduler ());
}
public Task<TResult> StartNew (Func<TResult> function, TaskCreationOptions creationOptions)
{
return StartNew (function, cancellationToken, creationOptions, GetScheduler ());
}
public Task<TResult> StartNew (Func<TResult> function, CancellationToken cancellationToken)
{
return StartNew (function, cancellationToken, creationOptions, GetScheduler ());
}
public Task<TResult> StartNew (Func<TResult> function,
CancellationToken cancellationToken,
TaskCreationOptions creationOptions,
TaskScheduler scheduler)
{
return StartNew ((o) => function (), null, cancellationToken, creationOptions, scheduler);
}
public Task<TResult> StartNew (Func<object, TResult> function, object state)
{
return StartNew (function, state, cancellationToken, creationOptions, GetScheduler ());
}
public Task<TResult> StartNew (Func<object, TResult> function, object state, TaskCreationOptions creationOptions)
{
return StartNew (function, state, cancellationToken, creationOptions, GetScheduler ());
}
public Task<TResult> StartNew (Func<object, TResult> function, object state, CancellationToken cancellationToken)
{
return StartNew (function, state, cancellationToken, creationOptions, GetScheduler ());
}
public Task<TResult> StartNew (Func<object, TResult> function, object state,
CancellationToken cancellationToken,
TaskCreationOptions creationOptions,
TaskScheduler scheduler)
{
return parent.StartNew<TResult> (function, state, cancellationToken, creationOptions, scheduler);
}
#endregion
#region Continue
public Task<TResult> ContinueWhenAny (Task[] tasks,
Func<Task, TResult> continuationFunction)
{
return ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAny (Task[] tasks,
Func<Task, TResult> continuationFunction,
CancellationToken cancellationToken)
{
return ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAny (Task[] tasks,
Func<Task, TResult> continuationFunction,
TaskContinuationOptions continuationOptions)
{
return ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAny (Task[] tasks,
Func<Task, TResult> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
return parent.ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, scheduler);
}
public Task<TResult> ContinueWhenAny<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>, TResult> continuationFunction)
{
return ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAny<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>, TResult> continuationFunction,
CancellationToken cancellationToken)
{
return ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAny<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>, TResult> continuationFunction,
TaskContinuationOptions continuationOptions)
{
return ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAny<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>, TResult> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
return parent.ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, scheduler);
}
public Task<TResult> ContinueWhenAll (Task[] tasks, Func<Task[], TResult> continuationFunction)
{
return ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAll (Task[] tasks,
Func<Task[], TResult> continuationFunction,
TaskContinuationOptions continuationOptions)
{
return ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAll (Task[] tasks,
Func<Task[], TResult> continuationFunction,
CancellationToken cancellationToken)
{
return ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAll (Task[] tasks,
Func<Task[], TResult> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
return parent.ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, scheduler);
}
public Task<TResult> ContinueWhenAll<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>[], TResult> continuationFunction)
{
return ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAll<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>[], TResult> continuationFunction,
TaskContinuationOptions continuationOptions)
{
return ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAll<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>[], TResult> continuationFunction,
CancellationToken cancellationToken)
{
return ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAll<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>[], TResult> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
return parent.ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, scheduler);
}
#endregion
#region FromAsync
public Task<TResult> FromAsync (IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod)
{
return FromAsync (asyncResult, endMethod, creationOptions);
}
public Task<TResult> FromAsync (IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod, TaskCreationOptions creationOptions)
{
return FromAsync (asyncResult, endMethod, creationOptions, GetScheduler ());
}
public Task<TResult> FromAsync (IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
return FromIAsyncResult (asyncResult, endMethod, creationOptions, scheduler);
}
internal static Task<TResult> FromIAsyncResult (IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
if (asyncResult == null)
throw new ArgumentNullException ("asyncResult");
if (endMethod == null)
throw new ArgumentNullException ("endMethod");
if (scheduler == null)
throw new ArgumentNullException ("scheduler");
if ((creationOptions & FromAsyncOptionsNotSupported) != 0)
throw new ArgumentOutOfRangeException ("creationOptions");
var source = new CancellationTokenSource ();
var task = new Task<TResult> (l => {
try {
return endMethod (asyncResult);
} catch (OperationCanceledException) {
source.Cancel ();
source.Token.ThrowIfCancellationRequested ();
}
return default (TResult);
}, null, source.Token, creationOptions);
// Take quick path for completed operations
if (asyncResult.IsCompleted) {
task.RunSynchronously (scheduler);
} else {
ThreadPool.RegisterWaitForSingleObject (asyncResult.AsyncWaitHandle,
(s, t) => task.RunSynchronously (scheduler),
null, Timeout.Infinite, true);
}
return task;
}
public Task<TResult> FromAsync (Func<AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
object state)
{
return FromAsync (beginMethod, endMethod, state, creationOptions);
}
public Task<TResult> FromAsync (Func<AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
object state, TaskCreationOptions creationOptions)
{
return FromAsyncBeginEnd (beginMethod, endMethod, state, creationOptions);
}
internal static Task<TResult> FromAsyncBeginEnd (Func<AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
object state, TaskCreationOptions creationOptions)
{
if (beginMethod == null)
throw new ArgumentNullException ("beginMethod");
if (endMethod == null)
throw new ArgumentNullException ("endMethod");
if ((creationOptions & FromAsyncOptionsNotSupported) != 0)
throw new ArgumentOutOfRangeException ("creationOptions");
var tcs = new TaskCompletionSource<TResult> (state, creationOptions);
beginMethod (l => InnerInvoke (tcs, endMethod, l), state);
return tcs.Task;
}
public Task<TResult> FromAsync<TArg1> (Func<TArg1, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, object state)
{
return FromAsync (beginMethod, endMethod, arg1, state, creationOptions);
}
public Task<TResult> FromAsync<TArg1> (Func<TArg1, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, object state, TaskCreationOptions creationOptions)
{
return FromAsyncBeginEnd (beginMethod, endMethod, arg1, state, creationOptions);
}
internal static Task<TResult> FromAsyncBeginEnd<TArg1> (Func<TArg1, AsyncCallback, object, IAsyncResult> beginMethod,
Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, object state, TaskCreationOptions creationOptions)
{
if (beginMethod == null)
throw new ArgumentNullException ("beginMethod");
if (endMethod == null)
throw new ArgumentNullException ("endMethod");
if ((creationOptions & FromAsyncOptionsNotSupported) != 0)
throw new ArgumentOutOfRangeException ("creationOptions");
var tcs = new TaskCompletionSource<TResult> (state, creationOptions);
beginMethod (arg1, l => InnerInvoke (tcs, endMethod, l), state);
return tcs.Task;
}
public Task<TResult> FromAsync<TArg1, TArg2> (Func<TArg1, TArg2, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, TArg2 arg2, object state)
{
return FromAsync (beginMethod, endMethod, arg1, arg2, state, creationOptions);
}
public Task<TResult> FromAsync<TArg1, TArg2> (Func<TArg1, TArg2, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, TArg2 arg2, object state, TaskCreationOptions creationOptions)
{
return FromAsyncBeginEnd (beginMethod, endMethod, arg1, arg2, state, creationOptions);
}
internal static Task<TResult> FromAsyncBeginEnd<TArg1, TArg2> (Func<TArg1, TArg2, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, TArg2 arg2, object state, TaskCreationOptions creationOptions)
{
if (beginMethod == null)
throw new ArgumentNullException ("beginMethod");
if (endMethod == null)
throw new ArgumentNullException ("endMethod");
if ((creationOptions & FromAsyncOptionsNotSupported) != 0)
throw new ArgumentOutOfRangeException ("creationOptions");
var tcs = new TaskCompletionSource<TResult> (state, creationOptions);
beginMethod (arg1, arg2, l => InnerInvoke (tcs, endMethod, l), state);
return tcs.Task;
}
public Task<TResult> FromAsync<TArg1, TArg2, TArg3> (Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, TArg2 arg2, TArg3 arg3, object state)
{
return FromAsync (beginMethod, endMethod, arg1, arg2, arg3, state, creationOptions);
}
public Task<TResult> FromAsync<TArg1, TArg2, TArg3> (Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, TArg2 arg2, TArg3 arg3, object state,
TaskCreationOptions creationOptions)
{
return FromAsyncBeginEnd (beginMethod, endMethod, arg1, arg2, arg3, state, creationOptions);
}
internal static Task<TResult> FromAsyncBeginEnd<TArg1, TArg2, TArg3> (Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, TArg2 arg2, TArg3 arg3, object state, TaskCreationOptions creationOptions)
{
if (beginMethod == null)
throw new ArgumentNullException ("beginMethod");
if (endMethod == null)
throw new ArgumentNullException ("endMethod");
if ((creationOptions & FromAsyncOptionsNotSupported) != 0)
throw new ArgumentOutOfRangeException ("creationOptions");
var tcs = new TaskCompletionSource<TResult> (state, creationOptions);
beginMethod (arg1, arg2, arg3, l => InnerInvoke (tcs, endMethod, l), state);
return tcs.Task;
}
#endregion
TaskScheduler GetScheduler ()
{
return scheduler ?? TaskScheduler.Current;
}
static void InnerInvoke (TaskCompletionSource<TResult> tcs, Func<IAsyncResult, TResult> endMethod, IAsyncResult l)
{
try {
tcs.SetResult (endMethod (l));
} catch (OperationCanceledException) {
tcs.SetCanceled ();
} catch (Exception e) {
tcs.SetException (e);
}
}
}
}
#endif
@@ -35,8 +35,7 @@ namespace System.Threading.Tasks
[System.Diagnostics.DebuggerTypeProxy ("System.Threading.Tasks.TaskScheduler+SystemThreadingTasks_TaskSchedulerDebugView")]
public abstract class TaskScheduler
{
static TaskScheduler defaultScheduler =
Environment.GetEnvironmentVariable ("USE_OLD_TASK_SCHED") != null ? (TaskScheduler)new Scheduler () : (TaskScheduler)new TpScheduler ();
static TaskScheduler defaultScheduler = new TpScheduler ();
SchedulerProxy proxy;
[ThreadStatic]
@@ -53,6 +52,10 @@ namespace System.Threading.Tasks
this.proxy = new SchedulerProxy (this);
}
~TaskScheduler ()
{
}
public static TaskScheduler FromCurrentSynchronizationContext ()
{
var syncCtx = SynchronizationContext.Current;
@@ -125,7 +128,17 @@ namespace System.Threading.Tasks
}
protected abstract bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued);
internal bool RunInline (Task task)
{
if (!TryExecuteTaskInline (task, false))
return false;
if (!task.IsCompleted)
throw new InvalidOperationException ("The TryExecuteTaskInline call to the underlying scheduler succeeded, but the task body was not invoked");
return true;
}
internal UnobservedTaskExceptionEventArgs FireUnobservedEvent (AggregateException e)
{
UnobservedTaskExceptionEventArgs args = new UnobservedTaskExceptionEventArgs (e);
@@ -30,7 +30,7 @@ namespace System.Threading.Tasks
{
public class TaskSchedulerException : Exception
{
const string exceptionDefaultMessage = "TaskScheduler exception";
const string exceptionDefaultMessage = "An exception was thrown by a TaskScheduler";
public TaskSchedulerException () : base (exceptionDefaultMessage)
{
@@ -0,0 +1,212 @@
//
// Task_T.cs
//
// Copyright (c) 2008 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 || MOBILE
using System;
namespace System.Threading.Tasks
{
[System.Diagnostics.DebuggerDisplay ("Id = {Id}, Status = {Status}, Result = {ResultAsString}")]
[System.Diagnostics.DebuggerTypeProxy (typeof (TaskDebuggerView))]
public class Task<TResult>: Task
{
TResult value;
static TaskFactory<TResult> factory = new TaskFactory<TResult> ();
static readonly Action<object> emptyAction = delegate {};
internal Func<object, TResult> function;
object state;
[System.Diagnostics.DebuggerBrowsable (System.Diagnostics.DebuggerBrowsableState.Never)]
public TResult Result {
get {
if (function != null)
Wait ();
else if (Exception != null)
throw Exception;
return value;
}
internal set {
this.value = value;
}
}
string ResultAsString {
get {
if ((Status & (TaskStatus.RanToCompletion)) != 0)
return "" + value;
return "<value not available>";
}
}
public static new TaskFactory<TResult> Factory {
get {
return factory;
}
}
public Task (Func<TResult> function) : this (function, TaskCreationOptions.None)
{
}
public Task (Func<TResult> function, CancellationToken cancellationToken)
: this (function == null ? (Func<object, TResult>)null : (o) => function(), null, cancellationToken, TaskCreationOptions.None)
{
}
public Task (Func<TResult> function, TaskCreationOptions creationOptions)
: this (function == null ? (Func<object, TResult>)null : (o) => function(), null, CancellationToken.None, creationOptions)
{
}
public Task (Func<TResult> function, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this (function == null ? (Func<object, TResult>)null : (o) => function(), null, cancellationToken, creationOptions)
{
}
public Task (Func<object, TResult> function, object state) : this (function, state, TaskCreationOptions.None)
{
}
public Task (Func<object, TResult> function, object state, CancellationToken cancellationToken)
: this (function, state, cancellationToken, TaskCreationOptions.None)
{
}
public Task (Func<object, TResult> function, object state, TaskCreationOptions creationOptions)
: this (function, state, CancellationToken.None, creationOptions)
{
}
public Task (Func<object, TResult> function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: base (emptyAction, state, cancellationToken, creationOptions)
{
this.function = function;
this.state = state;
}
internal Task (Func<object, TResult> function,
object state,
CancellationToken cancellationToken,
TaskCreationOptions creationOptions,
Task parent)
: base (null, state, cancellationToken, creationOptions, parent)
{
this.function = function;
this.state = state;
}
internal override void InnerInvoke ()
{
if (function != null)
value = function (state);
function = null;
state = null;
}
public Task ContinueWith (Action<Task<TResult>> continuationAction)
{
return ContinueWith (continuationAction, TaskContinuationOptions.None);
}
public Task ContinueWith (Action<Task<TResult>> continuationAction, TaskContinuationOptions continuationOptions)
{
return ContinueWith (continuationAction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
}
public Task ContinueWith (Action<Task<TResult>> continuationAction, CancellationToken cancellationToken)
{
return ContinueWith (continuationAction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
}
public Task ContinueWith (Action<Task<TResult>> continuationAction, TaskScheduler scheduler)
{
return ContinueWith (continuationAction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
}
public Task ContinueWith (Action<Task<TResult>> continuationAction, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationAction == null)
throw new ArgumentNullException ("continuationFunction");
if (scheduler == null)
throw new ArgumentNullException ("scheduler");
Task t = new Task ((o) => continuationAction ((Task<TResult>)o),
this,
cancellationToken,
GetCreationOptions (continuationOptions),
this);
ContinueWithCore (t, continuationOptions, scheduler);
return t;
}
public Task<TNewResult> ContinueWith<TNewResult> (Func<Task<TResult>, TNewResult> continuationFunction)
{
return ContinueWith<TNewResult> (continuationFunction, TaskContinuationOptions.None);
}
public Task<TNewResult> ContinueWith<TNewResult> (Func<Task<TResult>, TNewResult> continuationFunction, CancellationToken cancellationToken)
{
return ContinueWith<TNewResult> (continuationFunction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
}
public Task<TNewResult> ContinueWith<TNewResult> (Func<Task<TResult>, TNewResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
return ContinueWith<TNewResult> (continuationFunction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
}
public Task<TNewResult> ContinueWith<TNewResult> (Func<Task<TResult>, TNewResult> continuationFunction, TaskScheduler scheduler)
{
return ContinueWith<TNewResult> (continuationFunction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
}
public Task<TNewResult> ContinueWith<TNewResult> (Func<Task<TResult>, TNewResult> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
Task<TNewResult> t = new Task<TNewResult> ((o) => continuationFunction ((Task<TResult>)o),
this,
cancellationToken,
GetCreationOptions (continuationOptions),
this);
ContinueWithCore (t, continuationOptions, scheduler);
return t;
}
}
}
#endif
@@ -25,7 +25,7 @@
*/
#if NET_4_0
#if NET_4_0 || MOBILE
using System;
using System.Runtime.Serialization;
@@ -34,7 +34,9 @@ using System.Runtime.CompilerServices;
namespace System.Threading
{
[Serializable]
#if !MOBILE
[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
#endif
public class LockRecursionException : Exception
{
public LockRecursionException ()
@@ -22,7 +22,7 @@
//
//
#if NET_4_0
#if NET_4_0 || MOBILE
using System;
using System.Collections.Concurrent;
@@ -121,6 +121,16 @@ namespace System
return innerExceptions.AsReadOnly ();
}
}
internal void AddChildException (AggregateException childEx)
{
if (innerExceptions == null)
innerExceptions = new List<Exception> ();
if (childEx == null)
return;
innerExceptions.Add (childEx);
}
public override string ToString ()
{
+19
View File
@@ -1316,6 +1316,25 @@ namespace System {
}
}
internal Assembly DoResourceResolve (string name, Assembly requesting) {
if (ResourceResolve == null)
return null;
Delegate[] invocation_list = ResourceResolve.GetInvocationList ();
foreach (Delegate eh in invocation_list) {
ResolveEventHandler handler = (ResolveEventHandler) eh;
#if NET_4_0
Assembly assembly = handler (this, new ResolveEventArgs (name, requesting));
#else
Assembly assembly = handler (this, new ResolveEventArgs (name));
#endif
if (assembly != null)
return assembly;
}
return null;
}
private void DoDomainUnload ()
{
if (DomainUnload != null)
@@ -40,7 +40,7 @@ namespace MonoTests.System.Collections.Generic
public class ComparerTest
{
#if !NET_4_0 // FIXME: the blob contains the 2.0 mscorlib version
#if !NET_4_0 && !NET_2_1 // FIXME: the blob contains the 2.0 mscorlib version
[Test] // bug #80929
public void SerializeDefault ()
@@ -337,7 +337,7 @@ namespace MonoTests.System.Collections.Generic {
Assert.AreEqual (- (l.Count + 1), l.BinarySearch (int.MaxValue));
}
#if !NET_4_0 // FIXME: the blob contains the 2.0 mscorlib version
#if !NET_4_0 && !NET_2_1 // FIXME: the blob contains the 2.0 mscorlib version
[Test]
[Category ("TargetJvmNotWorking")]
@@ -127,12 +127,14 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly ();
Assert.AreEqual (Int64.MaxValue, isf.MaximumSize, "MaximumSize");
Assert.AreEqual (IsolatedStorageScope.User | IsolatedStorageScope.Assembly, isf.Scope, "Scope");
#if !NET_2_1
Assert.IsTrue ((isf.AssemblyIdentity is Url), "AssemblyIdentity");
// note: mono transforms the CodeBase into uppercase
// for net 1.1 which uses file:// and not file:///
string codebase = Assembly.GetExecutingAssembly ().CodeBase.ToUpper ().Substring (8);
Assert.IsTrue ((isf.AssemblyIdentity.ToString ().ToUpper ().IndexOf (codebase) > 0), "Url");
Assert.IsTrue ((isf.AssemblyIdentity.ToString ().ToUpper ().IndexOf (codebase) > 0), "Url");
#endif
Assert.IsTrue ((isf.CurrentSize >= 0), "CurrentSize");
}
@@ -160,6 +162,7 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForDomain ();
Assert.AreEqual (Int64.MaxValue, isf.MaximumSize, "MaximumSize");
Assert.AreEqual (IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, isf.Scope, "Scope");
#if !NET_2_1
Assert.IsTrue ((isf.AssemblyIdentity is Url), "AssemblyIdentity");
// note: mono transforms the CodeBase into uppercase
// for net 1.1 which uses file:// and not file:///
@@ -170,6 +173,7 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
// so we're using the first parameter to GetCommandLineArgs
string exe = Environment.GetCommandLineArgs ()[0].Replace ("\\", "/").ToUpper ();
Assert.IsTrue ((isf.DomainIdentity.ToString ().ToUpper ().IndexOf (exe) > 0), exe + "\n" + isf.DomainIdentity.ToString ().ToUpper ()); //"Url - Domain");
#endif
Assert.IsTrue ((isf.CurrentSize >= 0), "CurrentSize");
}
@@ -196,12 +200,15 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication ();
Assert.AreEqual (Int64.MaxValue, isf.MaximumSize, "MaximumSize");
#if !NET_2_1
Assert.AreEqual (IsolatedStorageScope.User | IsolatedStorageScope.Assembly, isf.Scope, "Scope");
Assert.IsTrue ((isf.AssemblyIdentity is Url), "AssemblyIdentity");
Assert.IsTrue ((isf.AssemblyIdentity.ToString ().IndexOf (Assembly.GetExecutingAssembly ().CodeBase) > 0), "Url");
#endif
Assert.IsTrue ((isf.CurrentSize >= 0), "CurrentSize");
}
#if !NET_2_1
[Test]
[ExpectedException (typeof (IsolatedStorageException))]
public void GetUserStoreForApplication_AssemblyIdentity ()
@@ -218,6 +225,7 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
object o = isf.DomainIdentity;
}
#endif
#endif
#if NET_4_0
// This is supposed to be working only in SL.
@@ -235,11 +243,13 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
IsolatedStorageScope scope = IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly;
IsolatedStorageFile isf = IsolatedStorageFile.GetStore (scope, typeof (Zone), typeof (Zone));
Assert.AreEqual (Int64.MaxValue, isf.MaximumSize, "MaximumSize");
#if !NET_2_1
Assert.AreEqual (IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, isf.Scope, "Scope");
Assert.IsTrue ((isf.AssemblyIdentity is Zone), "AssemblyIdentity");
Assert.IsTrue ((isf.AssemblyIdentity.ToString ().IndexOf ("MyComputer") > 0), "Zone - Assembly");
Assert.IsTrue ((isf.DomainIdentity is Zone), "DomainIdentity");
Assert.IsTrue ((isf.DomainIdentity.ToString ().IndexOf ("MyComputer") > 0), "Zone - Domain");
#endif
Assert.IsTrue ((isf.CurrentSize >= 0), "CurrentSize");
}
@@ -258,12 +268,14 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
IsolatedStorageFile isf = IsolatedStorageFile.GetStore (scope, typeof (StrongName), typeof (Url));
Assert.AreEqual (Int64.MaxValue, isf.MaximumSize, "MaximumSize");
Assert.AreEqual (scope, isf.Scope, "Scope");
#if !NET_2_1
Assert.IsTrue ((isf.AssemblyIdentity is Url), "AssemblyIdentity");
// note: mono transforms the CodeBase into uppercase
// for net 1.1 which uses file:// and not file:///
string codebase = Assembly.GetExecutingAssembly ().CodeBase.ToUpper ().Substring (8);
Assert.IsTrue ((isf.AssemblyIdentity.ToString ().ToUpper ().IndexOf (codebase) > 0), "Url");
// DomainIdentity throws a InvalidOperationException
#endif
Assert.IsTrue ((isf.CurrentSize >= 0), "CurrentSize");
}
@@ -348,10 +360,12 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
// Maximum size for Internet isn't (by default) Int64.MaxValue
Assert.AreEqual (scope, isf.Scope, "Scope");
#if !NET_2_1
Assert.IsTrue ((isf.AssemblyIdentity is Zone), "AssemblyIdentity");
Assert.IsTrue ((isf.AssemblyIdentity.ToString ().IndexOf ("Intranet") > 0), "Zone - Assembly");
Assert.IsTrue ((isf.DomainIdentity is Zone), "DomainIdentity");
Assert.IsTrue ((isf.DomainIdentity.ToString ().IndexOf ("Internet") > 0), isf.DomainIdentity.ToString ()); //"Zone - Domain");
#endif
Assert.IsTrue ((isf.CurrentSize >= 0), "CurrentSize");
}
@@ -439,7 +453,7 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
try {
isf.CreateDirectory (path);
}
#if NET_4_0
#if NET_4_0 || NET_2_1
catch (IsolatedStorageException ex) {
Assert.IsFalse (ex.Message.IndexOf (path) >= 0, "Message");
Assert.IsNull (ex.InnerException, "InnerException");
@@ -480,7 +494,7 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
}
[Test]
#if NET_4_0
#if NET_4_0 || NET_2_1
[ExpectedException (typeof (ArgumentException))]
#else
[ExpectedException (typeof (SecurityException))]
@@ -580,8 +594,10 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
{
IsolatedStorageScope scope = IsolatedStorageScope.User | IsolatedStorageScope.Roaming | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain;
IsolatedStorageFile isf = IsolatedStorageFile.GetStore (scope, null, null);
#if !NET_2_1
Assert.AreEqual (typeof (Url), isf.AssemblyIdentity.GetType (), "AssemblyIdentity");
Assert.AreEqual (typeof (Url), isf.DomainIdentity.GetType (), "DomainIdentity");
#endif
}
[Test]
@@ -12,6 +12,7 @@
using NUnit.Framework;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace MonoTests.System.IO
@@ -21,6 +22,10 @@ namespace MonoTests.System.IO
{
string TempFolder = Path.Combine (Path.GetTempPath (), "MonoTests.System.IO.Tests");
static readonly char DSC = Path.DirectorySeparatorChar;
static bool MacOSX = false;
[DllImport ("libc")]
static extern int uname (IntPtr buf);
[TearDown]
public void TearDown ()
@@ -36,6 +41,12 @@ namespace MonoTests.System.IO
Directory.Delete (TempFolder, true);
Directory.CreateDirectory (TempFolder);
// from XplatUI.cs
IntPtr buf = Marshal.AllocHGlobal (8192);
if (uname (buf) == 0)
MacOSX = Marshal.PtrToStringAnsi (buf) == "Darwin";
Marshal.FreeHGlobal (buf);
}
public void TestCtr ()
@@ -102,6 +113,9 @@ namespace MonoTests.System.IO
Assert.Fail ("#B1");
} catch (FileNotFoundException ex) {
Assert.AreEqual (typeof (FileNotFoundException), ex.GetType (), "#B2");
// under OSX 'var' is a symlink to 'private/var'
if (MacOSX)
path = "/private" + path;
Assert.AreEqual (path, ex.FileName, "#B3");
Assert.IsNull (ex.InnerException, "#B4");
Assert.IsNotNull (ex.Message, "#B5");
@@ -147,6 +161,9 @@ namespace MonoTests.System.IO
Assert.Fail ("#B1");
} catch (FileNotFoundException ex) {
Assert.AreEqual (typeof (FileNotFoundException), ex.GetType (), "#B2");
// under OSX 'var' is a symlink to 'private/var'
if (MacOSX)
path = "/private" + path;
Assert.AreEqual (path, ex.FileName, "#B3");
Assert.IsNull (ex.InnerException, "#B4");
Assert.IsNotNull (ex.Message, "#B5");
@@ -658,7 +658,7 @@ namespace MonoTests.System.Reflection.Emit
Assert.AreEqual ("FOO", ((ObsoleteAttribute) attrs [0]).Message, "#B3");
}
}
#if !NET_2_1
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void TestAddDeclarativeSecurityAlreadyCreated ()
@@ -717,7 +717,7 @@ namespace MonoTests.System.Reflection.Emit
mb.AddDeclarativeSecurity (SecurityAction.Demand, set);
mb.AddDeclarativeSecurity (SecurityAction.Demand, set);
}
#endif
[AttributeUsage (AttributeTargets.Parameter)]
class ParamAttribute : Attribute
{
@@ -69,12 +69,12 @@ namespace MonoTests.System.Reflection.Emit
#if NET_4_0
Assert.AreEqual ("foo.type[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", inst.FullName, "#3");
Assert.AreEqual ("foo.type[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], MonoTests.System.Reflection.Emit.MonoGenericClassTest, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", inst.AssemblyQualifiedName, "#4");
#elif NET_2_1
Assert.AreEqual ("foo.type[[System.Double, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", inst.FullName, "#3");
Assert.AreEqual ("foo.type[[System.Double, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], MonoTests.System.Reflection.Emit.MonoGenericClassTest, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", inst.AssemblyQualifiedName, "#4");
#else
Assert.AreEqual ("foo.type[[System.Double, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", inst.FullName, "#3");
Assert.AreEqual ("foo.type[[System.Double, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], MonoTests.System.Reflection.Emit.MonoGenericClassTest, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", inst.AssemblyQualifiedName, "#4");
#endif
Assert.AreEqual ("foo.type[System.Double,System.String]", inst.ToString (), "#5");
}
@@ -73,7 +73,7 @@ namespace MonoTests.System.Reflection
}
}
#if NET_2_0
#if NET_2_0 && !NET_2_1
public enum ParamEnum {
None = 0,
Foo = 1,
@@ -55,6 +55,9 @@ namespace MonoTests.System.Runtime.InteropServices {
}
[Test]
#if NET_2_1
[Ignore ("There's no GAC for the NET_2_1 based profiles (Moonlight, MonoTouch and Mono for Android")]
#endif
public void FromGlobalAccessCache ()
{
Assembly corlib = typeof (int).Assembly;
@@ -103,6 +103,9 @@ namespace MonoTests.System.Security.Cryptography.X509Certificates {
}
[Test]
#if NET_2_1
[Ignore ("This constructor always throw a NotSupportedException under NET_2_1 and is useless without CryptoAPI (i.e. outside Windows)")]
#endif
public void ConstructorIntPtr ()
{
byte[] cert = { 0x30,0x82,0x01,0xFF,0x30,0x82,0x01,0x6C,0x02,0x05,0x02,0x72,0x00,0x06,0xE8,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x02,0x05,0x00,0x30,0x5F,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x20,0x30,0x1E,0x06,0x03,0x55,0x04,0x0A,0x13,0x17,0x52,0x53,0x41,0x20,0x44,0x61,0x74,0x61,0x20,0x53,0x65,0x63,0x75,0x72,0x69,0x74,0x79,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x2E,0x30,0x2C,0x06,0x03,0x55,0x04,0x0B,0x13,0x25,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x53,0x65,0x72,0x76,
@@ -136,6 +136,9 @@ public class CryptoConfigTest {
// additional names (URL) used for XMLDSIG (System.Security.Cryptography.Xml)
// URL taken from http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/
[Test]
#if NET_2_1
[Ignore ("System.Security.dll is not part of Moonlight, MonoTouch and Mono for Android")]
#endif
public void CreateFromURL ()
{
// URL used in SignatureMethod element
@@ -26,7 +26,8 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
// NET_2_1 profile lacks some (of the few) CAS features required to execute those tests
#if NET_2_0 && !NET_2_1
using NUnit.Framework;
using System;
@@ -2,9 +2,10 @@
// EncoderReplacementFallbackBuffer.cs
//
// Author:
// Atsushi Enomoto <[email protected]>
// Atsushi Enomoto <[email protected]> <[email protected]>
//
// Copyright (C) 2005 Novell, Inc. http://www.novell.com
// Copyright (C) 2011 Xamain, Inc. http://xamarin.com
//
#if NET_2_0
@@ -85,6 +86,13 @@ namespace MonoTests.System.Text
Assert.IsFalse (b.MovePrevious (), "#8");
// Assert.AreEqual ('?', b.GetNextChar (), "#9");
}
[Test]
public void Reset ()
{
// Xamarin bug #545
Encoding.UTF8.GetBytes ("\uDE7E\uDE7E");
}
}
}
@@ -66,7 +66,7 @@ namespace MonoTests.System.Threading.Tasks
static Task<int> CreateNestedFuture(int level)
{
if (level == 0)
return Task.Factory.StartNew(() => { Thread.Sleep (10); return 1; });
return Task.Factory.StartNew(() => { Thread.Sleep (1); return 1; });
var t = CreateNestedFuture(level - 1);
return Task.Factory.StartNew(() => t.Result + 1);
@@ -75,14 +75,15 @@ namespace MonoTests.System.Threading.Tasks
[Test]
public void NestedFutureTest ()
{
var t = CreateNestedFuture(10);
var t2 = CreateNestedFuture(100);
var t3 = CreateNestedFuture(100);
var t4 = CreateNestedFuture(100);
Assert.AreEqual (11, t.Result);
Assert.AreEqual (101, t2.Result);
Assert.AreEqual (101, t3.Result);
Assert.AreEqual (101, t4.Result);
ParallelTestHelper.Repeat (delegate {
var t = CreateNestedFuture(10);
var t2 = CreateNestedFuture(100);
var t3 = CreateNestedFuture(100);
Assert.AreEqual (11, t.Result);
Assert.AreEqual (101, t2.Result);
Assert.AreEqual (101, t3.Result);
}, 50);
}
[Test]
@@ -1,4 +1,3 @@
#if NET_4_0
//
// TaskCompletionSourceTests.cs
//
@@ -25,6 +24,8 @@
// 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.Threading;
using System.Threading.Tasks;
@@ -96,6 +97,24 @@ namespace MonoTests.System.Threading.Tasks
Assert.IsFalse (completionSource.TrySetCanceled (), "#8");
Assert.AreEqual (TaskStatus.Faulted, completionSource.Task.Status, "#9");
}
[Test]
public void SetExceptionInvalid ()
{
try {
completionSource.TrySetException (new ApplicationException[0]);
Assert.Fail ("#1");
} catch (ArgumentException) {
}
try {
completionSource.TrySetException (new [] { new ApplicationException (), null });
Assert.Fail ("#2");
} catch (ArgumentException) {
}
Assert.AreEqual (TaskStatus.WaitingForActivation, completionSource.Task.Status, "r1");
}
[Test, ExpectedException (typeof (InvalidOperationException))]
public void SetResultExceptionTest ()
@@ -1,7 +1,12 @@
#if NET_4_0
//
// TaskFactoryTest.cs
//
// Authors:
// Jérémie "Garuma" Laval <[email protected]>
// Marek Safar <[email protected]>
//
// Copyright (c) 2010 Jérémie "Garuma" Laval
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -23,9 +28,12 @@
//
//
#if NET_4_0 || MOBILE
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using NUnit.Framework;
@@ -34,14 +42,98 @@ namespace MonoTests.System.Threading.Tasks
[TestFixture]
public class TaskFactoryTests
{
class CompletedAsyncResult : IAsyncResult
{
public object AsyncState
{
get { throw new NotImplementedException (); }
}
public WaitHandle AsyncWaitHandle
{
get { throw new NotImplementedException (); }
}
public bool CompletedSynchronously
{
get { throw new NotImplementedException (); }
}
public bool IsCompleted
{
get { return true; }
}
}
class TestAsyncResult : IAsyncResult
{
WaitHandle wh = new ManualResetEvent (true);
public object AsyncState
{
get { throw new NotImplementedException (); }
}
public WaitHandle AsyncWaitHandle
{
get
{
return wh;
}
}
public bool CompletedSynchronously
{
get { throw new NotImplementedException (); }
}
public bool IsCompleted
{
get { return false; }
}
}
class TestScheduler : TaskScheduler
{
public bool ExecutedInline { get; set; }
protected override void QueueTask (Task task)
{
throw new NotImplementedException ();
}
protected override bool TryDequeue (Task task)
{
throw new NotImplementedException ();
}
protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
{
if (taskWasPreviouslyQueued)
throw new ArgumentException ("taskWasPreviouslyQueued");
if (task.Status != TaskStatus.WaitingToRun)
throw new ArgumentException ("task.Status");
ExecutedInline = true;
return TryExecuteTask (task);
}
protected override IEnumerable<Task> GetScheduledTasks ()
{
throw new NotImplementedException ();
}
}
TaskFactory factory;
[SetUp]
public void Setup ()
{
this.factory = Task.Factory;
}
[Test]
public void StartNewTest ()
{
@@ -49,62 +141,86 @@ namespace MonoTests.System.Threading.Tasks
factory.StartNew (() => result = true).Wait ();
Assert.IsTrue (result);
}
[Test]
public void NoDefaultScheduler ()
{
Assert.IsNull (factory.Scheduler, "#1");
}
[Test]
public void ContinueWhenAllTest ()
{
bool r1 = false, r2 = false, r3 = false;
Task[] tasks = new Task[3];
tasks[0] = new Task (() => { Thread.Sleep (100); r1 = true; });
tasks[1] = new Task (() => { Thread.Sleep (500); r2 = true; });
tasks[2] = new Task (() => { Thread.Sleep (300); r3 = true; });
bool result = false;
Task cont = factory.ContinueWhenAll (tasks, (ts) => { if (r1 && r2 && r3) result = true; });
foreach (Task t in tasks)
t.Start ();
cont.Wait ();
Assert.IsTrue (r1, "#1");
Assert.IsTrue (r2, "#2");
Assert.IsTrue (r3, "#3");
Assert.IsTrue (result, "#4");
}
[Test]
public void ContinueWhenAnyTest ()
{
bool r = false, result = false, finished = false;
Task[] tasks = new Task[2];
tasks[0] = new Task (() => { Thread.Sleep (300); r = true; });
tasks[1] = new Task (() => { SpinWait sw; while (!finished) sw.SpinOnce (); });
tasks[1] = new Task (() => { SpinWait sw = new SpinWait (); while (!finished) sw.SpinOnce (); });
//tasks[2] = new Task (() => { SpinWait sw; while (!finished) sw.SpinOnce (); });
Task cont = factory.ContinueWhenAny (tasks, (t) => { if (r) result = t == tasks[0]; finished = true; });
foreach (Task t in tasks)
t.Start ();
cont.Wait ();
Assert.IsTrue (r, "#1");
Assert.IsTrue (result, "#2");
Assert.IsTrue (finished, "#3");
}
[Test]
public void FromAsyncWithBeginTest ()
public void FromAsyncBeginInvoke_WithResult ()
{
bool result = false;
Func<int, int> func = (i) => {
Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread);
result = true; return i + 3;
};
var task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, "state", TaskCreationOptions.AttachedToParent);
Assert.IsTrue (task.Wait (5000), "#1");
Assert.IsTrue (result, "#2");
Assert.AreEqual (4, task.Result, "#3");
Assert.AreEqual ("state", (string) task.AsyncState, "#4");
Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#5");
}
[Test]
public void FromAsyncBeginMethod_DirectResult ()
{
bool result = false;
bool continuationTest = false;
Func<int, int> func = (i) => { result = true; return i + 3; };
Task<int> task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, null);
Task<int> task = factory.FromAsync<int> (func.BeginInvoke (1, delegate { }, null), func.EndInvoke);
var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
task.Wait ();
cont.Wait ();
@@ -115,24 +231,7 @@ namespace MonoTests.System.Threading.Tasks
}
[Test]
public void FromAsyncWithDirectAsyncResultTest ()
{
bool result = false;
bool continuationTest = false;
Func<int, int> func = (i) => { result = true; return i + 3; };
Task<int> task = factory.FromAsync<int> (func.BeginInvoke (1, delegate {}, null), func.EndInvoke);
var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
task.Wait ();
cont.Wait ();
Assert.IsTrue (result);
Assert.IsTrue (continuationTest);
Assert.AreEqual (4, task.Result);
}
[Test]
public void FromAsyncWithBeginAndExceptionTest ()
public void FromAsyncBeginMethod_Exception ()
{
bool result = false;
bool continuationTest = false;
@@ -142,7 +241,7 @@ namespace MonoTests.System.Threading.Tasks
var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
try {
task.Wait ();
} catch {}
} catch { }
cont.Wait ();
Assert.IsTrue (result);
@@ -151,6 +250,215 @@ namespace MonoTests.System.Threading.Tasks
var agg = task.Exception;
Assert.AreEqual (1, agg.InnerExceptions.Count);
Assert.IsInstanceOfType (typeof (ApplicationException), agg.InnerExceptions[0]);
Assert.AreEqual (TaskStatus.Faulted, task.Status);
try {
var a = task.Result;
Assert.Fail ();
} catch (AggregateException) {
}
}
[Test]
public void FromAsync_ArgumentsCheck ()
{
var result = new CompletedAsyncResult ();
try {
factory.FromAsync (null, l => { });
Assert.Fail ("#1");
} catch (ArgumentNullException) {
}
try {
factory.FromAsync (result, null);
Assert.Fail ("#2");
} catch (ArgumentNullException) {
}
try {
factory.FromAsync (result, l => { }, TaskCreationOptions.LongRunning);
Assert.Fail ("#3");
} catch (ArgumentOutOfRangeException) {
}
try {
factory.FromAsync (result, l => { }, TaskCreationOptions.PreferFairness);
Assert.Fail ("#4");
} catch (ArgumentOutOfRangeException) {
}
try {
factory.FromAsync (result, l => { }, TaskCreationOptions.None, null);
Assert.Fail ("#5");
} catch (ArgumentNullException) {
}
try {
factory.FromAsync (null, l => { }, null, TaskCreationOptions.None);
Assert.Fail ("#6");
} catch (ArgumentNullException) {
}
try {
factory.FromAsync ((a, b) => null, l => { }, null, TaskCreationOptions.LongRunning);
Assert.Fail ("#7");
} catch (ArgumentOutOfRangeException) {
}
}
[Test]
public void FromAsync_Completed ()
{
var completed = new CompletedAsyncResult ();
bool? valid = null;
Action<IAsyncResult> end = l => {
Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#2");
valid = l == completed;
};
Task task = factory.FromAsync (completed, end);
Assert.IsTrue (valid == true, "#1");
}
[Test]
public void FromAsync_CompletedWithException ()
{
var completed = new CompletedAsyncResult ();
Action<IAsyncResult> end = l => {
throw new ApplicationException ();
};
Task task = factory.FromAsync (completed, end);
Assert.AreEqual (TaskStatus.Faulted, task.Status, "#1");
}
[Test]
public void FromAsync_CompletedCanceled ()
{
var completed = new CompletedAsyncResult ();
Action<IAsyncResult> end = l => {
throw new OperationCanceledException ();
};
Task task = factory.FromAsync (completed, end);
Assert.AreEqual (TaskStatus.Canceled, task.Status, "#1");
Assert.IsNull (task.Exception, "#2");
}
[Test]
public void FromAsync_SimpleAsyncResult ()
{
var result = new TestAsyncResult ();
bool called = false;
var task = factory.FromAsync (result, l => {
called = true;
});
Assert.IsTrue (task.Wait (1000), "#1");
Assert.IsTrue (called, "#2");
}
[Test]
public void FromAsync_ResultException ()
{
var result = new TestAsyncResult ();
var task = factory.FromAsync (result, l => {
throw new ApplicationException ();
});
try {
Assert.IsFalse (task.Wait (1000), "#1");
} catch (AggregateException) {
}
Assert.AreEqual (TaskStatus.Faulted, task.Status, "#2");
}
[Test]
public void FromAsync_ReturnInt ()
{
var result = new TestAsyncResult ();
bool called = false;
var task = factory.FromAsync<int> (result, l => {
called = true;
return 4;
});
Assert.IsTrue (task.Wait (1000), "#1");
Assert.IsTrue (called, "#2");
Assert.AreEqual (4, task.Result, "#3");
}
[Test]
public void FromAsync_Scheduler_Explicit ()
{
var result = new TestAsyncResult ();
bool called = false;
var scheduler = new TestScheduler ();
var task = factory.FromAsync (result, l => {
called = true;
}, TaskCreationOptions.None, scheduler);
Assert.IsTrue (task.Wait (5000), "#1");
Assert.IsTrue (called, "#2");
Assert.IsTrue (scheduler.ExecutedInline, "#3");
}
[Test]
public void FromAsync_Scheduler_Implicit ()
{
var result = new TestAsyncResult ();
bool called = false;
var scheduler = new TestScheduler ();
factory = new TaskFactory (scheduler);
Task task = factory.FromAsync (result, l => {
Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread, "#6");
called = true;
}, TaskCreationOptions.AttachedToParent);
Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#1");
Assert.IsNull (task.AsyncState, "#2");
Assert.IsTrue (task.Wait (5000), "#3");
Assert.IsTrue (called, "#4");
Assert.IsTrue (scheduler.ExecutedInline, "#5");
}
[Test]
public void FromAsync_BeginCallback ()
{
bool called = false;
bool called2 = false;
var task = factory.FromAsync (
(a, b, c) => {
if (a != "h")
Assert.Fail ("#10");
if ((TaskCreationOptions) c != TaskCreationOptions.AttachedToParent)
Assert.Fail ("#11");
Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#12");
called2 = true;
b.Invoke (null);
return null;
},
l => {
called = true;
},
"h", TaskCreationOptions.AttachedToParent);
Assert.AreEqual (TaskCreationOptions.None, task.CreationOptions, "#1");
Assert.AreEqual (TaskCreationOptions.AttachedToParent, (TaskCreationOptions) task.AsyncState, "#2");
Assert.IsTrue (task.Wait (5000), "#3");
Assert.IsTrue (called, "#4");
Assert.IsTrue (called2, "#5");
}
}
}
@@ -0,0 +1,184 @@
//
// TaskFactory_T_Test.cs
//
// Author:
// Marek Safar <marek.safargmail.com>
//
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
#if NET_4_0 || MOBILE
using System;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
namespace MonoTests.System.Threading.Tasks
{
[TestFixture]
public class TaskFactory_T_Tests
{
class CompletedAsyncResult : IAsyncResult
{
public object AsyncState
{
get { throw new NotImplementedException (); }
}
public WaitHandle AsyncWaitHandle
{
get { throw new NotImplementedException (); }
}
public bool CompletedSynchronously
{
get { throw new NotImplementedException (); }
}
public bool IsCompleted
{
get { return true; }
}
}
class TestAsyncResult : IAsyncResult
{
WaitHandle wh = new ManualResetEvent (true);
public object AsyncState
{
get { throw new NotImplementedException (); }
}
public WaitHandle AsyncWaitHandle
{
get
{
return wh;
}
}
public bool CompletedSynchronously
{
get { throw new NotImplementedException (); }
}
public bool IsCompleted
{
get { return false; }
}
}
[SetUp]
public void Setup ()
{
}
[Test]
public void ConstructorTest ()
{
try {
new TaskFactory<int> (TaskCreationOptions.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.LongRunning);
Assert.Fail ("#1");
} catch (ArgumentOutOfRangeException) {
}
try {
new TaskFactory<int> (TaskCreationOptions.None, TaskContinuationOptions.OnlyOnRanToCompletion);
Assert.Fail ("#2");
} catch (ArgumentOutOfRangeException) {
}
try {
new TaskFactory<int> (TaskCreationOptions.None, TaskContinuationOptions.NotOnRanToCompletion);
Assert.Fail ("#3");
} catch (ArgumentOutOfRangeException) {
}
}
[Test]
public void NoDefaultScheduler ()
{
var tf = new TaskFactory<object> ();
Assert.IsNull (tf.Scheduler, "#1");
}
[Test]
public void FromAsync_ArgumentsCheck ()
{
var factory = new TaskFactory<object> ();
var result = new CompletedAsyncResult ();
try {
factory.FromAsync (null, l => 1);
Assert.Fail ("#1");
} catch (ArgumentNullException) {
}
try {
factory.FromAsync (result, null);
Assert.Fail ("#2");
} catch (ArgumentNullException) {
}
try {
factory.FromAsync (result, l => 1, TaskCreationOptions.LongRunning);
Assert.Fail ("#3");
} catch (ArgumentOutOfRangeException) {
}
try {
factory.FromAsync (result, l => 1, TaskCreationOptions.PreferFairness);
Assert.Fail ("#4");
} catch (ArgumentOutOfRangeException) {
}
try {
factory.FromAsync (result, l => 1, TaskCreationOptions.None, null);
Assert.Fail ("#5");
} catch (ArgumentNullException) {
}
try {
factory.FromAsync (null, l => 1, null, TaskCreationOptions.None);
Assert.Fail ("#6");
} catch (ArgumentNullException) {
}
}
[Test]
public void FromAsync_SimpleAsyncResult ()
{
var result = new TestAsyncResult ();
var factory = new TaskFactory<int> ();
var task = factory.FromAsync (result, l => 5);
Assert.IsTrue (task.Wait (1000), "#1");
Assert.AreEqual (5, task.Result, "#2");
}
}
}
#endif
@@ -0,0 +1,113 @@
// TaskSchedulerTest.cs
//
// Copyright (c) 2008 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
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using NUnit.Framework;
namespace MonoTests.System.Threading.Tasks
{
[TestFixture]
public class TaskSchedulerTests
{
[Test]
public void BasicRunSynchronouslyTest ()
{
bool ran = false;
var t = new Task (() => ran = true);
t.RunSynchronously ();
Assert.IsTrue (t.IsCompleted);
Assert.IsFalse (t.IsFaulted);
Assert.IsFalse (t.IsCanceled);
Assert.IsTrue (ran);
}
class LazyCatScheduler : TaskScheduler
{
public TaskStatus ExecuteInlineStatus {
get;
set;
}
protected override void QueueTask (Task task)
{
throw new NotImplementedException ();
}
protected override bool TryDequeue (Task task)
{
throw new NotImplementedException ();
}
protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
{
ExecuteInlineStatus = task.Status;
return true;
}
protected override IEnumerable<Task> GetScheduledTasks ()
{
throw new NotImplementedException ();
}
}
[Test]
public void RunSynchronouslyButNoExecutionTest ()
{
TaskSchedulerException ex = null;
var ts = new LazyCatScheduler ();
Task t = new Task (() => {});
try {
t.RunSynchronously (ts);
} catch (TaskSchedulerException e) {
ex = e;
}
Assert.IsNotNull (ex);
Assert.IsNotNull (ex.InnerException);
Assert.IsInstanceOfType (typeof (InvalidOperationException), ex.InnerException);
}
[Test]
public void RunSynchronouslyTaskStatusTest ()
{
var ts = new LazyCatScheduler ();
var t = new Task (() => { });
try {
t.RunSynchronously (ts);
} catch {}
Assert.AreEqual (TaskStatus.WaitingToRun, ts.ExecuteInlineStatus);
}
}
}
#endif
@@ -1,4 +1,4 @@
#if NET_4_0
//
// TaskTest.cs
//
// Copyright (c) 2008 Jérémie "Garuma" Laval
@@ -23,6 +23,8 @@
//
//
#if NET_4_0
using System;
using System.Threading;
using System.Threading.Tasks;
@@ -286,6 +288,17 @@ namespace MonoTests.System.Threading.Tasks
Assert.AreEqual (1, val);
}
[Test]
public void RunSynchronouslyArgumentChecks ()
{
Task t = new Task (() => { });
try {
t.RunSynchronously (null);
Assert.Fail ("#1");
} catch (ArgumentNullException) {
}
}
[Test]
public void UnobservedExceptionOnFinalizerThreadTest ()
{
@@ -319,6 +332,18 @@ namespace MonoTests.System.Threading.Tasks
var t = new Task (() => { });
t.Dispose ();
}
[Test]
public void ThrowingUnrelatedCanceledExceptionTest ()
{
Task t = new Task (() => {
throw new TaskCanceledException ();
});
t.RunSynchronously ();
Assert.IsTrue (t.IsFaulted);
Assert.IsFalse (t.IsCanceled);
}
}
}
#endif
@@ -3237,6 +3237,21 @@ namespace MonoTests.System
asm.GetTypes();
}
[Test]
public void ResourceResolve ()
{
bool called = false;
ResolveEventHandler del = delegate (object sender, ResolveEventArgs args) {
called = true;
return null;
};
AppDomain.CurrentDomain.ResourceResolve += del;
Stream st = Assembly.GetExecutingAssembly ().GetManifestResourceStream ("NOT_EXISTING");
Assert.IsTrue (called);
AppDomain.CurrentDomain.ResourceResolve -= del;
}
private static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
return Assembly.ReflectionOnlyLoad(args.Name);
@@ -128,7 +128,7 @@ namespace MonoTests.System
Assert.IsFalse (d.IsSynchronized, "IsSynchronized");
}
#if NET_2_0 && !TARGET_JVM
#if NET_2_0 && !TARGET_JVM && !NET_2_1
[Test] // bug #333740
public void GetEnvironmentVariables_NewlySet ()
{
@@ -151,7 +151,7 @@ namespace MonoTests.System
Assert.IsNotNull (args [0], "application");
}
#if NET_2_0
#if NET_2_0 && !NET_2_1
[Test]
[ExpectedException (typeof (ArgumentException))]
public void GetEnvironmentVariable_Target_Invalid ()
+4 -4
View File
@@ -794,7 +794,7 @@ public class TimeSpanTest {
ParseHelper (" 13:45:15 ",false, false, "13:45:15");
ParseHelper (" -1:2:3 ", false, false, "-01:02:03");
#if NET_4_0
#if NET_4_0 || NET_2_1
// In 4.0 when the first part is out of range, it parses it as day.
ParseHelper (" 25:11:12 ", false, false, "25.11:12:00");
ParseHelper (" 24:11:12 ", false, false, "24.11:12:00");
@@ -811,14 +811,14 @@ public class TimeSpanTest {
ParseHelper ("24:60:60", false, true, "dontcare");
ParseHelper ("0001:0002:0003.12 ", false, false, "01:02:03.1200000");
#if NET_4_0
#if NET_4_0 || NET_2_1
// In 4.0 when a section has more than 7 digits an OverflowException is thrown.
ParseHelper (" 1:2:3:12345678 ", false, true, "dontcare");
#else
ParseHelper (" 1:2:3:12345678 ", true, false, "dontcare");
#endif
#if NET_4_0
#if NET_4_0 || NET_2_1
ParseHelper ("10:11:12:13", false, false, "10.11:12:13"); // Days using : instead of . as separator
ParseHelper ("10.11", true, false, "dontcare"); // days+hours is invalid
@@ -894,7 +894,7 @@ public class TimeSpanTest {
{
// hours should be between 0 and 23 but format is also invalid (too many dots)
// In 2.0 overflow as precedence over format, but not in 4.0
#if NET_4_0
#if NET_4_0 || NET_2_1
try {
TimeSpan.Parse ("0.99.99.0");
Assert.Fail ("#A1");
+3 -1
View File
@@ -1531,6 +1531,7 @@ System/Predicate.cs
System.Collections.Generic/Comparer.cs
System.Threading.Tasks/TaskFactory.cs
System.Threading.Tasks/TaskFactory_T.cs
System.Threading.Tasks/TaskStatus.cs
System.Threading.Tasks/TaskCreationOptions.cs
System.Threading.Tasks/ThreadWorker.cs
@@ -1540,8 +1541,9 @@ System.Threading.Tasks/CyclicDeque.cs
System.Threading.Tasks/TaskScheduler.cs
System.Threading.Tasks/TaskContinuationOptions.cs
System.Threading.Tasks/TaskCanceledException.cs
System.Threading.Tasks/Future.cs
System.Threading.Tasks/Task_T.cs
System.Threading.Tasks/Task.cs
System.Threading.Tasks/TaskDebuggerView.cs
System.Threading.Tasks/TaskCompletionSource.cs
System.Threading.Tasks/TaskSchedulerException.cs
System.Collections.Concurrent/OrderablePartitioner.cs
+1 -1
View File
@@ -16,7 +16,7 @@ EXTRA_DISTFILES = \
$(wildcard tests/*.il)
ILParser.cs: parser/ILParser.jay $(topdir)/jay/skeleton.cs
$(topdir)/jay/jay -ct < $(topdir)/jay/skeleton.cs $< >$@
$(topdir)/jay/jay -ct < $(topdir)/jay/skeleton.cs $(CURDIR)/$< >$@
include ../build/executable.make
+1
View File
@@ -815,6 +815,7 @@ namespace Mono.CSharp {
break;
case "xterm-color":
case "xterm-256color":
xterm_colors = true;
break;
}
+1
View File
@@ -195,6 +195,7 @@ namespace Mono.XBuild.CommandLine {
break;
case "xterm-color":
case "xterm-256color":
xterm_colors = true;
break;
}
-9
View File
@@ -1738,15 +1738,6 @@ gboolean DeleteFile(const gunichar2 *name)
return(FALSE);
}
if (attrs & FILE_ATTRIBUTE_READONLY) {
#ifdef DEBUG
g_message ("%s: file %s is readonly", __func__, filename);
#endif
SetLastError (ERROR_ACCESS_DENIED);
g_free (filename);
return(FALSE);
}
#if 0
/* Check to make sure sharing allows us to open the file for
* writing. See bug 323389.
+7 -1
View File
@@ -2806,7 +2806,13 @@ ves_icall_InternalInvoke (MonoReflectionMethod *method, MonoObject *this, MonoAr
if (this) {
if (!mono_object_isinst (this, m->klass)) {
mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Object does not match target type."));
char *this_name = mono_type_get_full_name (mono_object_get_class (this));
char *target_name = mono_type_get_full_name (m->klass);
char *msg = g_strdup_printf ("Object of type '%s' doesn't match target type '%s'", this_name, target_name);
mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", msg));
g_free (msg);
g_free (target_name);
g_free (this_name);
return NULL;
}
m = mono_object_get_virtual_method (this, m);
+3
View File
@@ -7878,10 +7878,13 @@ emit_marshal_ptr (EmitMarshalContext *m, int argnum, MonoType *t,
switch (action) {
case MARSHAL_ACTION_CONV_IN:
/* MS seems to allow this in some cases, ie. bxc #158 */
/*
if (MONO_TYPE_ISSTRUCT (t->data.type) && !mono_class_from_mono_type (t->data.type)->blittable) {
char *msg = g_strdup_printf ("Can not marshal 'parameter #%d': Pointers can not reference marshaled structures. Use byref instead.", argnum + 1);
mono_mb_emit_exception_marshal_directive (m->mb, msg);
}
*/
break;
case MARSHAL_ACTION_PUSH:
+37 -27
View File
@@ -10,6 +10,7 @@
#include "config.h"
#include "mono/metadata/profiler-private.h"
#include "mono/metadata/assembly.h"
#include "mono/metadata/debug-helpers.h"
#include "mono/metadata/mono-debug.h"
#include "mono/metadata/debug-mono-symfile.h"
@@ -1029,6 +1030,38 @@ mono_profiler_coverage_get (MonoProfiler *prof, MonoMethod *method, MonoProfileC
typedef void (*ProfilerInitializer) (const char*);
#define INITIALIZER_NAME "mono_profiler_startup"
static gboolean
load_profiler_from_directory (const char *directory, const char *libname, const char *desc)
{
MonoDl *pmodule = NULL;
char* path;
char *err;
void *iter;
iter = NULL;
err = NULL;
while ((path = mono_dl_build_path (directory, libname, &iter))) {
g_free (err);
pmodule = mono_dl_open (path, MONO_DL_LAZY, &err);
if (pmodule) {
ProfilerInitializer func;
if ((err = mono_dl_symbol (pmodule, INITIALIZER_NAME, (gpointer *)&func))) {
g_warning ("Cannot find initializer function %s in profiler module: %s (%s)", INITIALIZER_NAME, libname, err);
g_free (err);
err = NULL;
} else {
func (desc);
}
g_free (path);
return TRUE;
}
g_free (path);
}
return FALSE;
}
/**
* mono_profiler_load:
* @desc: arguments to configure the profiler
@@ -1074,13 +1107,9 @@ mono_profiler_load (const char *desc)
desc = cdesc = g_string_free (str, FALSE);
}
{
MonoDl *pmodule = NULL;
const char* col = strchr (desc, ':');
char* libname;
char* path;
char *mname;
char *err;
void *iter;
if (col != NULL) {
mname = g_memdup (desc, col - desc + 1);
mname [col - desc] = 0;
@@ -1088,31 +1117,12 @@ mono_profiler_load (const char *desc)
mname = g_strdup (desc);
}
libname = g_strdup_printf ("mono-profiler-%s", mname);
iter = NULL;
err = NULL;
while ((path = mono_dl_build_path (NULL, libname, &iter))) {
g_free (err);
pmodule = mono_dl_open (path, MONO_DL_LAZY, &err);
if (pmodule) {
ProfilerInitializer func;
if ((err = mono_dl_symbol (pmodule, INITIALIZER_NAME, (gpointer *)&func))) {
g_warning ("Cannot find initializer function %s in profiler module: %s (%s)", INITIALIZER_NAME, libname, err);
g_free (err);
err = NULL;
} else {
func (desc);
}
break;
}
g_free (path);
}
if (!pmodule) {
g_warning ("Error loading profiler module '%s': %s", libname, err);
g_free (err);
}
if (!load_profiler_from_directory (NULL, libname, desc))
if (!load_profiler_from_directory (mono_assembly_getrootdir (), libname, desc))
g_warning ("Error loading profiler module '%s'", libname);
g_free (libname);
g_free (mname);
g_free (path);
}
g_free (cdesc);
}
+155 -3
View File
@@ -42,6 +42,9 @@
#include "sgen-gc.h"
#include "sgen-bridge.h"
#include "utils/mono-logger-internal.h"
#include "utils/mono-time.h"
typedef struct {
int size;
@@ -175,6 +178,77 @@ dyn_array_append (DynArray *dst, DynArray *src)
dst->size += src->size;
}
static DynArray merge_array;
static void
dyn_array_int_merge (DynArray *dst, DynArray *src)
{
int i, j;
dyn_array_ensure_capacity (&merge_array, dst->size + src->size);
merge_array.size = 0;
for (i = j = 0; i < dst->size || j < src->size; ) {
if (i < dst->size && j < src->size) {
int a = DYN_ARRAY_INT_REF (dst, i);
int b = DYN_ARRAY_INT_REF (src, j);
if (a < b) {
dyn_array_int_add (&merge_array, a);
++i;
} else if (a == b) {
dyn_array_int_add (&merge_array, a);
++i;
++j;
} else {
dyn_array_int_add (&merge_array, b);
++j;
}
} else if (i < dst->size) {
dyn_array_int_add (&merge_array, DYN_ARRAY_INT_REF (dst, i));
++i;
} else {
dyn_array_int_add (&merge_array, DYN_ARRAY_INT_REF (src, j));
++j;
}
}
if (merge_array.size > dst->size) {
dyn_array_ensure_capacity (dst, merge_array.size);
memcpy (DYN_ARRAY_REF (dst, 0), DYN_ARRAY_REF (&merge_array, 0), merge_array.size * merge_array.elem_size);
dst->size = merge_array.size;
}
}
static void
dyn_array_int_merge_one (DynArray *array, int value)
{
int i;
int tmp;
int end = array->size;
for (i = 0; i < end; ++i) {
if (DYN_ARRAY_INT_REF (array, i) == value)
return;
else if (DYN_ARRAY_INT_REF (array, i) > value)
break;
}
dyn_array_ensure_capacity (array, array->size + 1);
if (i < end) {
tmp = DYN_ARRAY_INT_REF (array, i);
for (; i <= end; ++i) {
DYN_ARRAY_INT_REF (array, i) = value;
value = tmp;
tmp = DYN_ARRAY_INT_REF (array, i + 1);
}
DYN_ARRAY_INT_REF (array, end + 1) = tmp;
} else {
DYN_ARRAY_INT_REF (array, end) = value;
}
++array->size;
}
/*
* FIXME: Optimizations:
*
@@ -341,6 +415,7 @@ free_data (void)
num_hash_entries = 0;
hash_table = NULL;
dyn_array_uninit (&merge_array);
//g_print ("total srcs %d - max %d\n", total_srcs, max_srcs);
}
@@ -375,6 +450,9 @@ object_is_live (MonoObject **objp)
static DynArray dfs_stack;
static int dsf1_passes, dsf2_passes;
#undef HANDLE_PTR
#define HANDLE_PTR(ptr,obj) do { \
MonoObject *dst = (MonoObject*)*(ptr); \
@@ -395,6 +473,7 @@ dfs1 (HashEntry *obj_entry, HashEntry *src)
do {
MonoObject *obj;
char *start;
++dsf1_passes;
obj_entry = dyn_array_ptr_pop (&dfs_stack);
if (obj_entry) {
@@ -438,11 +517,10 @@ scc_add_xref (SCC *src, SCC *dst)
if (dyn_array_int_contains (&dst->xrefs, src->index))
return;
if (src->num_bridge_entries) {
dyn_array_int_add (&dst->xrefs, src->index);
dyn_array_int_merge_one (&dst->xrefs, src->index);
} else {
int i;
// FIXME: uniq here
dyn_array_append (&dst->xrefs, &src->xrefs);
dyn_array_int_merge (&dst->xrefs, &src->xrefs);
for (i = 0; i < dst->xrefs.size; ++i)
g_assert (DYN_ARRAY_INT_REF (&dst->xrefs, i) != dst->index);
}
@@ -471,6 +549,7 @@ dfs2 (HashEntry *entry)
do {
entry = dyn_array_ptr_pop (&dfs_stack);
++dsf2_passes;
if (entry->scc_index >= 0) {
if (entry->scc_index != current_scc->index)
@@ -493,6 +572,12 @@ compare_hash_entries (const void *ep1, const void *ep2)
return e2->finishing_time - e1->finishing_time;
}
gboolean
mono_sgen_is_bridge_object (MonoObject *obj)
{
return bridge_callbacks.is_bridge_object (obj);
}
void
mono_sgen_bridge_processing (int num_objs, MonoObject **objs)
{
@@ -503,6 +588,15 @@ mono_sgen_bridge_processing (int num_objs, MonoObject **objs)
int i;
MonoGCBridgeSCC **api_sccs;
MonoGCBridgeXRef *api_xrefs;
SGEN_TV_DECLARE (atv);
SGEN_TV_DECLARE (btv);
int hash_table_size, sccs_size;
unsigned long step_1, step_2, step_3, step_4, step_5, step_6, step_7, step_8;
int fist_pass_links = 0, second_pass_links = 0, sccs_links = 0;
int max_sccs_links = 0;
dsf1_passes = dsf2_passes = 0;
SGEN_TV_GETTIME (atv);
g_assert (mono_sgen_need_bridge_processing ());
@@ -520,16 +614,23 @@ mono_sgen_bridge_processing (int num_objs, MonoObject **objs)
}
num_objs = j;
SGEN_TV_GETTIME (btv);
step_1 = SGEN_TV_ELAPSED (atv, btv);
//g_print ("%d bridge objects\n", num_objs);
/* first DFS pass */
dyn_array_ptr_init (&dfs_stack);
dyn_array_int_init (&merge_array);
current_time = 0;
for (i = 0; i < num_objs; ++i)
dfs1 (get_hash_entry (objs [i]), NULL);
SGEN_TV_GETTIME (atv);
step_2 = SGEN_TV_ELAPSED (btv, atv);
//g_print ("%d entries - hash size %d\n", num_hash_entries, hash_size);
/* alloc and fill array of all entries */
@@ -545,11 +646,13 @@ mono_sgen_bridge_processing (int num_objs, MonoObject **objs)
g_assert (entry->finishing_time >= 0);
all_entries [j++] = entry;
++length;
fist_pass_links += entry->srcs.size;
}
if (length > max_entries)
max_entries = length;
}
g_assert (j == num_hash_entries);
hash_table_size = num_hash_entries;
//g_print ("max hash bucket length %d\n", max_entries);
@@ -557,6 +660,9 @@ mono_sgen_bridge_processing (int num_objs, MonoObject **objs)
qsort (all_entries, num_hash_entries, sizeof (HashEntry*), compare_hash_entries);
SGEN_TV_GETTIME (btv);
step_3 = SGEN_TV_ELAPSED (atv, btv);
/* second DFS pass */
dyn_array_init (&sccs, sizeof (SCC));
@@ -574,6 +680,16 @@ mono_sgen_bridge_processing (int num_objs, MonoObject **objs)
}
}
sccs_size = sccs.size;
for (i = 0; i < num_hash_entries; ++i) {
HashEntry *entry = all_entries [i];
second_pass_links += entry->srcs.size;
}
SGEN_TV_GETTIME (atv);
step_4 = SGEN_TV_ELAPSED (btv, atv);
//g_print ("%d sccs\n", sccs.size);
dyn_array_uninit (&dfs_stack);
@@ -586,6 +702,8 @@ mono_sgen_bridge_processing (int num_objs, MonoObject **objs)
g_assert (scc->index == i);
if (scc->num_bridge_entries)
++num_sccs;
sccs_links += scc->xrefs.size;
max_sccs_links = MAX (max_sccs_links, scc->xrefs.size);
}
api_sccs = mono_sgen_alloc_internal_dynamic (sizeof (MonoGCBridgeSCC*) * num_sccs, INTERNAL_MEM_BRIDGE_DATA);
@@ -632,6 +750,9 @@ mono_sgen_bridge_processing (int num_objs, MonoObject **objs)
}
}
SGEN_TV_GETTIME (btv);
step_5 = SGEN_TV_ELAPSED (atv, btv);
/* free data */
j = 0;
@@ -653,12 +774,26 @@ mono_sgen_bridge_processing (int num_objs, MonoObject **objs)
free_data ();
SGEN_TV_GETTIME (atv);
step_6 = SGEN_TV_ELAPSED (btv, atv);
//g_print ("%d sccs containing bridges - %d max bridge objects - %d max xrefs\n", j, max_entries, max_xrefs);
/* callback */
bridge_callbacks.cross_references (num_sccs, api_sccs, num_xrefs, api_xrefs);
SGEN_TV_GETTIME (btv);
step_7 = SGEN_TV_ELAPSED (atv, btv);
/*Release for finalization those objects we no longer care. */
for (i = 0; i < num_sccs; ++i) {
if (!api_sccs [i]->objs [0])
continue;
for (j = 0; j < api_sccs [i]->num_objs; ++j)
mono_sgen_mark_bridge_object (api_sccs [i]->objs [j]);
}
/* free callback data */
for (i = 0; i < num_sccs; ++i) {
@@ -669,6 +804,23 @@ mono_sgen_bridge_processing (int num_objs, MonoObject **objs)
mono_sgen_free_internal_dynamic (api_sccs, sizeof (MonoGCBridgeSCC*) * num_sccs, INTERNAL_MEM_BRIDGE_DATA);
mono_sgen_free_internal_dynamic (api_xrefs, sizeof (MonoGCBridgeXRef) * num_xrefs, INTERNAL_MEM_BRIDGE_DATA);
SGEN_TV_GETTIME (atv);
step_8 = SGEN_TV_ELAPSED (btv, atv);
mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_BRIDGE num-objects %d num_hash_entries %d sccs size %d init %.2fms df1 %.2fms sort %.2fms dfs2 %.2fms setup-cb %.2fms free-data %.2fms user-cb %.2fms clenanup %.2fms links %d/%d/%d/%d dfs passes %d/%d",
num_objs, hash_table_size, sccs.size,
step_1 / 1000.0f,
step_2 / 1000.0f,
step_3 / 1000.0f,
step_4 / 1000.0f,
step_5 / 1000.0f,
step_6 / 1000.0f,
step_7 / 1000.0f,
step_8 / 1000.f,
fist_pass_links, second_pass_links, sccs_links, max_sccs_links,
dsf1_passes, dsf2_passes);
}
static gboolean
+205 -40
View File
@@ -216,6 +216,7 @@
#include "utils/mono-semaphore.h"
#include "utils/mono-counters.h"
#include "utils/mono-proclib.h"
#include "utils/mono-logger-internal.h"
#include <mono/utils/memcheck.h>
@@ -521,6 +522,12 @@ static mword memory_pressure = 0;
static mword minor_collection_allowance;
static int minor_collection_sections_alloced = 0;
/* GC Logging stats */
static int last_major_num_sections = 0;
static int last_los_memory_usage = 0;
static gboolean major_collection_hapenned = FALSE;
static GCMemSection *nursery_section = NULL;
static mword lowest_heap_address = ~(mword)0;
static mword highest_heap_address = 0;
@@ -816,6 +823,25 @@ typedef SgenGrayQueue GrayQueue;
typedef void (*CopyOrMarkObjectFunc) (void**, GrayQueue*);
typedef char* (*ScanObjectFunc) (char*, GrayQueue*);
static inline MonoObject*
finalize_entry_get_object (FinalizeEntry *entry)
{
return (MonoObject*)(((mword)entry->object) & ~(mword)0x1);
}
static inline gboolean
finalize_entry_get_bridge_bit (FinalizeEntry *entry)
{
return (((mword)entry->object) & 0x1);
}
static inline void
finalize_entry_set_object (FinalizeEntry *entry, MonoObject *object, gboolean bridge_bit)
{
entry->object = (MonoObject*)((mword)object | (mword)bridge_bit);
}
/* forward declarations */
static int stop_world (int generation);
static int restart_world (int generation);
@@ -827,6 +853,7 @@ static void report_finalizer_roots (void);
static void report_registered_roots (void);
static void find_pinning_ref_from_thread (char *obj, size_t size);
static void update_current_thread_stack (void *start);
static void collect_bridge_objects (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation, GrayQueue *queue);
static void finalize_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation, GrayQueue *queue);
static void add_or_remove_disappearing_link (MonoObject *obj, void **link, gboolean track, int generation);
static void null_link_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation, gboolean before_finalization, GrayQueue *queue);
@@ -2280,9 +2307,10 @@ report_finalizer_roots_list (FinalizeEntry *list)
report.count = 0;
for (fin = list; fin; fin = fin->next) {
if (!fin->object)
MonoObject *object = finalize_entry_get_object (fin);
if (!object)
continue;
add_profile_gc_root (&report, fin->object, MONO_PROFILE_GC_ROOT_FINALIZER, 0);
add_profile_gc_root (&report, object, MONO_PROFILE_GC_ROOT_FINALIZER, 0);
}
notify_gc_roots (&report);
}
@@ -2378,10 +2406,14 @@ scan_finalizer_entries (CopyOrMarkObjectFunc copy_func, FinalizeEntry *list, Gra
FinalizeEntry *fin;
for (fin = list; fin; fin = fin->next) {
if (!fin->object)
void *object = finalize_entry_get_object (fin);
gboolean bridge_bit = finalize_entry_get_bridge_bit (fin);
if (!object)
continue;
DEBUG (5, fprintf (gc_debug_file, "Scan of fin ready object: %p (%s)\n", fin->object, safe_name (fin->object)));
copy_func (&fin->object, queue);
DEBUG (5, fprintf (gc_debug_file, "Scan of fin ready object: %p (%s)\n", object, safe_name (object)));
copy_func (&object, queue);
finalize_entry_set_object (fin, object, bridge_bit);
}
}
@@ -2533,6 +2565,12 @@ finish_gray_stack (char *start_addr, char *end_addr, int generation, GrayQueue *
++ephemeron_rounds;
} while (!done_with_ephemerons);
if (mono_sgen_need_bridge_processing ()) {
collect_bridge_objects (copy_func, start_addr, end_addr, generation, queue);
if (generation == GENERATION_OLD)
collect_bridge_objects (copy_func, nursery_start, nursery_real_end, GENERATION_NURSERY, queue);
}
fin_ready = num_ready_finalizers;
finalize_in_range (copy_func, start_addr, end_addr, generation, queue);
if (generation == GENERATION_OLD)
@@ -3403,6 +3441,7 @@ major_collection (const char *reason)
return;
}
major_collection_hapenned = TRUE;
current_collection_generation = GENERATION_OLD;
major_do_collection (reason);
current_collection_generation = -1;
@@ -4037,7 +4076,7 @@ is_critical_finalizer (FinalizeEntry *entry)
if (!mono_defaults.critical_finalizer_object)
return FALSE;
obj = entry->object;
obj = finalize_entry_get_object (entry);
class = ((MonoVTable*)LOAD_VTABLE (obj))->klass;
return mono_class_has_parent (class, mono_defaults.critical_finalizer_object);
@@ -4069,7 +4108,7 @@ rehash_fin_table (FinalizeEntryHashTable *hash_table)
new_hash = mono_sgen_alloc_internal_dynamic (new_size * sizeof (FinalizeEntry*), INTERNAL_MEM_FIN_TABLE);
for (i = 0; i < finalizable_hash_size; ++i) {
for (entry = finalizable_hash [i]; entry; entry = next) {
hash = mono_object_hash (entry->object) % new_size;
hash = mono_object_hash (finalize_entry_get_object (entry)) % new_size;
next = entry->next;
entry->next = new_hash [hash];
new_hash [hash] = entry;
@@ -4088,6 +4127,101 @@ rehash_fin_table_if_necessary (FinalizeEntryHashTable *hash_table)
rehash_fin_table (hash_table);
}
/* LOCKING: requires that the GC lock is held */
void
mono_sgen_mark_bridge_object (MonoObject *obj)
{
FinalizeEntryHashTable *hash_table = get_finalize_entry_hash_table (ptr_in_nursery (obj) ? GENERATION_NURSERY : GENERATION_OLD);
FinalizeEntry **finalizable_hash = hash_table->table;
FinalizeEntry *entry;
unsigned int hash;
hash = mono_object_hash (obj);
hash %= hash_table->size;
for (entry = finalizable_hash [hash]; entry; entry = entry->next) {
if (finalize_entry_get_object (entry) == obj)
finalize_entry_set_object (entry, obj, TRUE);
}
}
/* LOCKING: requires that the GC lock is held */
static void
collect_bridge_objects (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation, GrayQueue *queue)
{
FinalizeEntryHashTable *hash_table = get_finalize_entry_hash_table (generation);
FinalizeEntry *entry, *prev;
int i;
FinalizeEntry **finalizable_hash = hash_table->table;
mword finalizable_hash_size = hash_table->size;
if (no_finalize)
return;
for (i = 0; i < finalizable_hash_size; ++i) {
prev = NULL;
for (entry = finalizable_hash [i]; entry;) {
MonoObject *object = finalize_entry_get_object (entry);
gboolean ignore_obj = finalize_entry_get_bridge_bit (entry);
char *copy;
/* Bridge code told us to ignore this one */
if (ignore_obj)
goto next_step;
/* Object is a bridge object and major heap says it's dead */
if (!((char*)object >= start && (char*)object < end && !major_collector.is_object_live ((char*)object)))
goto next_step;
/* Nursery says the object is dead. */
if (!object_is_fin_ready (object))
goto next_step;
if (!mono_sgen_is_bridge_object (object))
goto next_step;
copy = (char*)object;
copy_func ((void**)&copy, queue);
bridge_register_finalized_object ((MonoObject*)copy);
if (hash_table == &minor_finalizable_hash && !ptr_in_nursery (copy)) {
FinalizeEntry *next = entry->next;
unsigned int major_hash;
/* remove from the list */
if (prev)
prev->next = entry->next;
else
finalizable_hash [i] = entry->next;
hash_table->num_registered--;
finalize_entry_set_object (entry, (MonoObject*)copy, ignore_obj);
/* insert it into the major hash */
rehash_fin_table_if_necessary (&major_finalizable_hash);
major_hash = mono_object_hash ((MonoObject*) copy) %
major_finalizable_hash.size;
entry->next = major_finalizable_hash.table [major_hash];
major_finalizable_hash.table [major_hash] = entry;
major_finalizable_hash.num_registered++;
entry = next;
continue;
} else {
/* update pointer */
finalize_entry_set_object (entry, (MonoObject*)copy, ignore_obj);
}
next_step:
prev = entry;
entry = entry->next;
}
}
drain_gray_stack (queue);
}
/* LOCKING: requires that the GC lock is held */
static void
finalize_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation, GrayQueue *queue)
@@ -4103,16 +4237,19 @@ finalize_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int g
for (i = 0; i < finalizable_hash_size; ++i) {
prev = NULL;
for (entry = finalizable_hash [i]; entry;) {
if ((char*)entry->object >= start && (char*)entry->object < end && !major_collector.is_object_live (entry->object)) {
gboolean is_fin_ready = object_is_fin_ready (entry->object);
char *copy = entry->object;
MonoObject *object = finalize_entry_get_object (entry);
gboolean bridge_bit = finalize_entry_get_bridge_bit (entry);
if ((char*)object >= start && (char*)object < end && !major_collector.is_object_live ((char*)object)) {
gboolean is_fin_ready = object_is_fin_ready (object);
char *copy = (char*)object;
copy_func ((void**)&copy, queue);
if (is_fin_ready) {
char *from;
FinalizeEntry *next;
/* Make it survive */
from = entry->object;
entry->object = copy;
from = (char*)object;
finalize_entry_set_object (entry, (MonoObject*)copy, bridge_bit);
/* remove and put in fin_ready_list */
if (prev)
prev->next = entry->next;
@@ -4122,12 +4259,11 @@ finalize_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int g
num_ready_finalizers++;
hash_table->num_registered--;
queue_finalization_entry (entry);
bridge_register_finalized_object ((MonoObject*)copy);
DEBUG (5, fprintf (gc_debug_file, "Queueing object for finalization: %p (%s) (was at %p) (%d/%d)\n", entry->object, safe_name (entry->object), from, num_ready_finalizers, hash_table->num_registered));
DEBUG (5, fprintf (gc_debug_file, "Queueing object for finalization: %p (%s) (was at %p) (%d/%d)\n", object, safe_name (object), from, num_ready_finalizers, hash_table->num_registered));
entry = next;
continue;
} else {
char *from = entry->object;
char *from = (char*)object;
if (hash_table == &minor_finalizable_hash && !ptr_in_nursery (copy)) {
FinalizeEntry *next = entry->next;
unsigned int major_hash;
@@ -4138,7 +4274,7 @@ finalize_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int g
finalizable_hash [i] = entry->next;
hash_table->num_registered--;
entry->object = copy;
finalize_entry_set_object (entry, (MonoObject*)copy, bridge_bit);
/* insert it into the major hash */
rehash_fin_table_if_necessary (&major_finalizable_hash);
@@ -4154,8 +4290,8 @@ finalize_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int g
continue;
} else {
/* update pointer */
DEBUG (5, fprintf (gc_debug_file, "Updating object for finalization: %p (%s) (was at %p)\n", entry->object, safe_name (entry->object), from));
entry->object = copy;
DEBUG (5, fprintf (gc_debug_file, "Updating object for finalization: %p (%s) (was at %p)\n", object, safe_name (object), from));
finalize_entry_set_object (entry, (MonoObject*)copy, bridge_bit);
}
}
}
@@ -4359,6 +4495,16 @@ null_link_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int
for (entry = disappearing_link_hash [i]; entry;) {
char *object;
gboolean track = DISLINK_TRACK (entry);
/*
* Tracked references are processed after
* finalization handling whereas standard weak
* references are processed before. If an
* object is still not marked after finalization
* handling it means that it either doesn't have
* a finalizer or the finalizer has already run,
* so we must null a tracking reference.
*/
if (track == before_finalization) {
prev = entry;
entry = entry->next;
@@ -4368,7 +4514,7 @@ null_link_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int
object = DISLINK_OBJECT (entry);
if (object >= start && object < end && !major_collector.is_object_live (object)) {
if (!track && object_is_fin_ready (object)) {
if (object_is_fin_ready (object)) {
void **p = entry->link;
DisappearingLink *old;
*p = NULL;
@@ -4415,14 +4561,7 @@ null_link_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int
continue;
} else {
/* We set the track resurrection bit to
* FALSE if the object is to be finalized
* so that the object can be collected in
* the next cycle (i.e. after it was
* finalized).
*/
*entry->link = HIDE_POINTER (copy,
object_is_fin_ready (object) ? FALSE : track);
*entry->link = HIDE_POINTER (copy, track);
DEBUG (5, fprintf (gc_debug_file, "Updated dislink at %p to %p\n", entry->link, DISLINK_OBJECT (entry)));
}
}
@@ -4486,7 +4625,8 @@ finalizers_for_domain (MonoDomain *domain, MonoObject **out_array, int out_size,
for (i = 0; i < finalizable_hash_size; ++i) {
prev = NULL;
for (entry = finalizable_hash [i]; entry;) {
if (mono_object_domain (entry->object) == domain) {
MonoObject *object = finalize_entry_get_object (entry);
if (mono_object_domain (object) == domain) {
FinalizeEntry *next;
/* remove and put in out_array */
if (prev)
@@ -4495,8 +4635,8 @@ finalizers_for_domain (MonoDomain *domain, MonoObject **out_array, int out_size,
finalizable_hash [i] = entry->next;
next = entry->next;
hash_table->num_registered--;
out_array [count ++] = entry->object;
DEBUG (5, fprintf (gc_debug_file, "Collecting object for finalization: %p (%s) (%d/%d)\n", entry->object, safe_name (entry->object), num_ready_finalizers, hash_table->num_registered));
out_array [count ++] = object;
DEBUG (5, fprintf (gc_debug_file, "Collecting object for finalization: %p (%s) (%d/%d)\n", object, safe_name (object), num_ready_finalizers, hash_table->num_registered));
entry = next;
if (count == out_size)
return count;
@@ -4557,7 +4697,7 @@ register_for_finalization (MonoObject *obj, void *user_data, int generation)
hash %= finalizable_hash_size;
prev = NULL;
for (entry = finalizable_hash [hash]; entry; entry = entry->next) {
if (entry->object == obj) {
if (finalize_entry_get_object (entry) == obj) {
if (!user_data) {
/* remove from the list */
if (prev)
@@ -4579,7 +4719,7 @@ register_for_finalization (MonoObject *obj, void *user_data, int generation)
return;
}
entry = mono_sgen_alloc_internal (INTERNAL_MEM_FINALIZE_ENTRY);
entry->object = obj;
finalize_entry_set_object (entry, obj, FALSE);
entry->next = finalizable_hash [hash];
finalizable_hash [hash] = entry;
hash_table->num_registered++;
@@ -4716,21 +4856,21 @@ mono_gc_invoke_finalizers (void)
}
/* Now look for the first non-null entry. */
for (entry = fin_ready_list; entry && !entry->object; entry = entry->next)
for (entry = fin_ready_list; entry && !finalize_entry_get_object (entry); entry = entry->next)
;
if (entry) {
entry_is_critical = FALSE;
} else {
entry_is_critical = TRUE;
for (entry = critical_fin_list; entry && !entry->object; entry = entry->next)
for (entry = critical_fin_list; entry && !finalize_entry_get_object (entry); entry = entry->next)
;
}
if (entry) {
g_assert (entry->object);
obj = finalize_entry_get_object (entry);
g_assert (obj);
num_ready_finalizers--;
obj = entry->object;
entry->object = NULL;
finalize_entry_set_object (entry, NULL, FALSE);
DEBUG (7, fprintf (gc_debug_file, "Finalizing object %p (%s)\n", obj, safe_name (obj)));
}
@@ -4739,7 +4879,7 @@ mono_gc_invoke_finalizers (void)
if (!entry)
break;
g_assert (entry->object == NULL);
g_assert (finalize_entry_get_object (entry) == NULL);
count++;
/* the object is on the stack so it is pinned */
/*g_print ("Calling finalizer for object: %p (%s)\n", entry->object, safe_name (entry->object));*/
@@ -5198,6 +5338,10 @@ stop_world (int generation)
g_assert (count >= 0);
DEBUG (3, fprintf (gc_debug_file, "world stopped %d thread(s)\n", count));
mono_profiler_gc_event (MONO_GC_EVENT_POST_STOP_WORLD, generation);
last_major_num_sections = major_collector.get_num_major_sections ();
last_los_memory_usage = los_memory_usage;
major_collection_hapenned = FALSE;
return count;
}
@@ -5205,10 +5349,11 @@ stop_world (int generation)
static int
restart_world (int generation)
{
int count, i;
int count, i, num_major_sections;
SgenThreadInfo *info;
TV_DECLARE (end_sw);
unsigned long usec;
TV_DECLARE (end_bridge);
unsigned long usec, bridge_usec;
/* notify the profiler of the leftovers */
if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_GC_MOVES)) {
@@ -5233,6 +5378,26 @@ restart_world (int generation)
max_pause_usec = MAX (usec, max_pause_usec);
DEBUG (2, fprintf (gc_debug_file, "restarted %d thread(s) (pause time: %d usec, max: %d)\n", count, (int)usec, (int)max_pause_usec));
mono_profiler_gc_event (MONO_GC_EVENT_POST_START_WORLD, generation);
TV_GETTIME (end_bridge);
bridge_usec = TV_ELAPSED (end_sw, end_bridge);
num_major_sections = major_collector.get_num_major_sections ();
if (major_collection_hapenned)
mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MAJOR: %s pause %.2fms, bridge %.2fms major %dK/%dK los %dK/%dK",
generation ? "" : "(minor overflow)",
(int)usec / 1000.0f, (int)bridge_usec / 1000.0f,
major_collector.section_size * num_major_sections / 1024,
major_collector.section_size * last_major_num_sections / 1024,
los_memory_usage / 1024,
last_los_memory_usage / 1024);
else
mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MINOR: pause %.2fms, bridge %.2fms promoted %dK major %dK los %dK",
(int)usec / 1000.0f, (int)bridge_usec / 1000.0f,
(num_major_sections - last_major_num_sections) * major_collector.section_size / 1024,
major_collector.section_size * num_major_sections / 1024,
los_memory_usage / 1024);
return count;
}
+2 -1
View File
@@ -803,6 +803,8 @@ gboolean mono_sgen_object_is_live (void *obj) MONO_INTERNAL;
gboolean mono_sgen_need_bridge_processing (void) MONO_INTERNAL;
void mono_sgen_bridge_processing (int num_objs, MonoObject **objs) MONO_INTERNAL;
gboolean mono_sgen_is_bridge_object (MonoObject *obj) MONO_INTERNAL;
void mono_sgen_mark_bridge_object (MonoObject *obj) MONO_INTERNAL;
enum {
SPACE_MAJOR,
@@ -830,7 +832,6 @@ struct _LOSObject {
extern LOSObject *los_object_list;
extern mword los_memory_usage;
extern mword last_los_memory_usage;
void mono_sgen_los_free_object (LOSObject *obj) MONO_INTERNAL;
void* mono_sgen_los_alloc_large_inner (MonoVTable *vtable, size_t size) MONO_INTERNAL;
+7 -1
View File
@@ -481,8 +481,14 @@ static void
init_event_system (SocketIOData *data)
{
#ifdef HAVE_EPOLL
if (data->event_system == EPOLL_BACKEND)
if (data->event_system == EPOLL_BACKEND) {
data->event_data = tp_epoll_init (data);
if (data->event_data == NULL) {
if (g_getenv ("MONO_DEBUG"))
g_message ("Falling back to poll()");
data->event_system = POLL_BACKEND;
}
}
#elif defined(HAVE_KQUEUE)
if (data->event_system == KQUEUE_BACKEND)
data->event_data = tp_kqueue_init (data);
+11 -1
View File
@@ -19,8 +19,18 @@ tp_epoll_init (SocketIOData *data)
result->epollfd = epoll_create (256); /* The number does not really matter */
fcntl (result->epollfd, F_SETFD, FD_CLOEXEC);
#endif
if (result->epollfd == -1)
if (result->epollfd == -1) {
int err = errno;
if (g_getenv ("MONO_DEBUG")) {
#ifdef EPOLL_CLOEXEC
g_message ("epoll_create1(EPOLL_CLOEXEC) failed: %d %s", err, g_strerror (err));
#else
g_message ("epoll_create(256) failed: %d %s", err, g_strerror (err));
#endif
}
return NULL;
}
data->shutdown = tp_epoll_shutdown;
data->modify = tp_epoll_modify;
+7 -1
View File
@@ -2125,6 +2125,7 @@ notify_thread (gpointer key, gpointer value, gpointer user_data)
MonoInternalThread *thread = key;
DebuggerTlsData *tls = value;
gsize tid = thread->tid;
int res;
if (GetCurrentThreadId () == tid || tls->terminated)
return;
@@ -2153,7 +2154,12 @@ notify_thread (gpointer key, gpointer value, gpointer user_data)
#ifdef HOST_WIN32
QueueUserAPC (notify_thread_apc, thread->handle, NULL);
#else
mono_thread_kill (thread, mono_thread_get_abort_signal ());
res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
if (res)
/*
* Attached thread which died without detaching.
*/
tls->terminated = TRUE;
#endif
}
+3
View File
@@ -1300,6 +1300,8 @@ public class Tests {
* Pointers to structures can not be passed
*/
/* This seems to be allowed by MS in some cases */
/*
public struct CharInfo {
public char Character;
public short Attributes;
@@ -1321,6 +1323,7 @@ public class Tests {
}
return 1;
}
*/
/*
* LPWStr marshalling