[Pkg-mono-svn-commits] [SCM] mono branch, upstream-experimental, updated. upstream/2.8-1-gf85b0b1

Jo Shields directhex at apebox.org
Tue Nov 23 16:41:20 UTC 2010


The following commit has been merged in the upstream-experimental branch:
commit f85b0b1a56036469a3217c34b1090f68b118972e
Author: Jo Shields <directhex at apebox.org>
Date:   Tue Nov 23 16:32:50 2010 +0000

    Imported Upstream version 2.8.1

diff --git a/ChangeLog b/ChangeLog
index 4661eaa..405fe9f 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,7 @@
+2010-10-21  Andrew Jorgensen  <ajorgensen at novell.com>
+
+	Bump version to 2.8.1
+
 2010-09-23  Andrew Jorgensen  <ajorgensen at novell.com>
 
 	move DynamicData to mvc because it depends on Extensions
diff --git a/configure b/configure
index 96f02c1..891253a 100755
--- a/configure
+++ b/configure
@@ -2764,7 +2764,7 @@ fi
 
 # Define the identity of the package.
  PACKAGE=mono
- VERSION=2.8
+ VERSION=2.8.1
 
 
 cat >>confdefs.h <<_ACEOF
diff --git a/configure.in b/configure.in
index 84488de..4c0d4cb 100644
--- a/configure.in
+++ b/configure.in
@@ -6,7 +6,7 @@ AC_CANONICAL_SYSTEM
 m4_ifdef([_A][M_PROG_TAR],[_A][M_SET_OPTION([tar-ustar])])
 
 AM_CONFIG_HEADER(config.h)
-AM_INIT_AUTOMAKE(mono,2.8)
+AM_INIT_AUTOMAKE(mono,2.8.1)
 AM_MAINTAINER_MODE
 
 API_VER=2.0
diff --git a/data/ChangeLog b/data/ChangeLog
index c1cf92a..4e91007 100644
--- a/data/ChangeLog
+++ b/data/ChangeLog
@@ -1,3 +1,9 @@
+2010-11-02  Andrew Jorgensen  <ajorgensen at novell.com>
+
+	Map libcups for mac
+
+	Fixes bnc#649994
+
 2010-08-30  Andrew Jorgensen  <ajorgensen at novell.com>
 
 	Remove obsolete Microsoft.Vsa and Microsoft.JScript
diff --git a/data/config.in b/data/config.in
index a56f7d1..ecc7692 100644
--- a/data/config.in
+++ b/data/config.in
@@ -18,6 +18,7 @@
 	<dllmap dll="libX11" target="@X11@" os="!windows" />
 	<dllmap dll="libcairo-2.dll" target="libcairo.so.2" os="!windows"/>
 	<dllmap dll="libcups" target="libcups.so.2" os="!windows"/>
+	<dllmap dll="libcups" target="libcups.dylib" os="osx"/>
 	<dllmap dll="i:kernel32.dll">
 		<dllentry dll="__Internal" name="CopyMemory" target="mono_win32_compat_CopyMemory"/>
 		<dllentry dll="__Internal" name="FillMemory" target="mono_win32_compat_FillMemory"/>
diff --git a/eglib/ChangeLog b/eglib/ChangeLog
index 89b624f..3a4e1e5 100644
--- a/eglib/ChangeLog
+++ b/eglib/ChangeLog
@@ -1,3 +1,26 @@
+2010-10-23  Zoltan Varga  <vargaz at gmail.com>
+
+	Use int 3 as G_BREAKPOINT on x86-64 too. Hopefully fixes #648838.
+
+2010-10-22  Zoltan Varga  <vargaz at gmail.com>
+
+	Use locale_charset() from iconv which will use nl_langinfo
+	(CODESET) anyways but it will do canonicalization so we will get
+	the correct charset name, because nl_langinfo (CODESET) can return
+	different things on different systems. This at least fixes
+	OpenBSD.
+
+2010-09-04  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Fix return value of items_read
+
+	items_read was not being initialized and it was not being set in
+	the fast common case of g_utf8_to_utf16().
+
+2010-10-14  Zoltan Varga  <vargaz at gmail.com>
+
+	Avoid a crash in g_convert () if iconv_open () fails.
+
 2010-09-10  Miguel de Icaza  <miguel at gnome.org>
 
 	[Fix] Correct fix for the g_shell_parse_argv bug
diff --git a/eglib/config.h.in b/eglib/config.h.in
index 1cd57fb..10b4188 100644
--- a/eglib/config.h.in
+++ b/eglib/config.h.in
@@ -21,6 +21,9 @@
 /* Define to 1 if you have the <langinfo.h> header file. */
 #undef HAVE_LANGINFO_H
 
+/* Define to 1 if you have the <localcharset.h> header file. */
+#undef HAVE_LOCALCHARSET_H
+
 /* Define to 1 if you have the <memory.h> header file. */
 #undef HAVE_MEMORY_H
 
diff --git a/eglib/configure b/eglib/configure
index 1f45ba5..8cdeaa3 100755
--- a/eglib/configure
+++ b/eglib/configure
@@ -11103,9 +11103,8 @@ BREAKPOINT="G_STMT_START { raise (SIGTRAP); } G_STMT_END"
 if test x$GCC = xyes; then
    GNUC_UNUSED='__attribute__((__unused__))'
    GNUC_NORETURN='__attribute__((__noreturn__))'
-   echo target_cpu=$target_cpu
    case $target_cpu in
-     i*86) BREAKPOINT="G_STMT_START { __asm__ (\"int \$03\"); } G_STMT_END" ;;
+     i*86|x86_64) BREAKPOINT="G_STMT_START { __asm__ (\"int \$03\"); } G_STMT_END" ;;
    esac
 fi
 
@@ -12939,7 +12938,8 @@ fi
 
 
 
-for ac_header in getopt.h sys/time.h sys/wait.h pwd.h langinfo.h iconv.h
+
+for ac_header in getopt.h sys/time.h sys/wait.h pwd.h langinfo.h iconv.h localcharset.h
 do
 as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
 if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
diff --git a/eglib/configure.ac b/eglib/configure.ac
index 51e448d..5b614b1 100644
--- a/eglib/configure.ac
+++ b/eglib/configure.ac
@@ -14,9 +14,8 @@ BREAKPOINT="G_STMT_START { raise (SIGTRAP); } G_STMT_END"
 if test x$GCC = xyes; then
    GNUC_UNUSED='__attribute__((__unused__))'
    GNUC_NORETURN='__attribute__((__noreturn__))'
-   echo target_cpu=$target_cpu
    case $target_cpu in
-     i*86) BREAKPOINT="G_STMT_START { __asm__ (\"int \$03\"); } G_STMT_END" ;;
+     i*86|x86_64) BREAKPOINT="G_STMT_START { __asm__ (\"int \$03\"); } G_STMT_END" ;;
    esac
 fi
 AC_SUBST(GNUC_PRETTY)
@@ -110,7 +109,7 @@ if test "x$have_iso_varargs" = "xyes"; then
 fi
 AC_SUBST(G_HAVE_ISO_VARARGS)
 
-AC_CHECK_HEADERS(getopt.h sys/time.h sys/wait.h pwd.h langinfo.h iconv.h)
+AC_CHECK_HEADERS(getopt.h sys/time.h sys/wait.h pwd.h langinfo.h iconv.h localcharset.h)
 
 if test $ac_cv_sizeof_void_p != $ac_cv_sizeof_int; then
    GPOINTER_TO_INT="((gint)(long) (ptr))"
diff --git a/eglib/src/eglib-config.h b/eglib/src/eglib-config.h
index 9b7d9b0..589185f 100644
--- a/eglib/src/eglib-config.h
+++ b/eglib/src/eglib-config.h
@@ -12,7 +12,7 @@
 #define G_SEARCHPATH_SEPARATOR   ':'
 #define G_DIR_SEPARATOR          '/'
 #define G_DIR_SEPARATOR_S        "/"
-#define G_BREAKPOINT()           G_STMT_START { raise (SIGTRAP); } G_STMT_END
+#define G_BREAKPOINT()           G_STMT_START { __asm__ ("int $03"); } G_STMT_END
 #define G_OS_UNIX
 #define GPOINTER_TO_INT(ptr)   ((gint)(long) (ptr))
 #define GPOINTER_TO_UINT(ptr)  ((guint)(long) (ptr))
diff --git a/eglib/src/gunicode.c b/eglib/src/gunicode.c
index af11774..2c1d424 100644
--- a/eglib/src/gunicode.c
+++ b/eglib/src/gunicode.c
@@ -53,6 +53,9 @@
 #    ifdef HAVE_ICONV_H
 #       include <iconv.h>
 #    endif
+#    ifdef HAVE_LOCALCHARSET_H
+#       include <localcharset.h>
+#    endif
 #endif
 
 static char *my_charset;
@@ -217,8 +220,10 @@ g_convert (const gchar *str, gssize len,
 	
 	convertor = iconv_open (to_codeset, from_codeset);
 	if (convertor == (iconv_t) -1){
-		*bytes_written = 0;
-		*bytes_read = 0;
+		if (bytes_written)
+			*bytes_written = 0;
+		if (bytes_read)
+			*bytes_read = 0;
 		return NULL;
 	}
 
@@ -303,7 +308,9 @@ g_get_charset (G_CONST_RETURN char **charset)
 #else
 	if (my_charset == NULL){
 		/* These shouldn't be heap allocated */
-#if HAVE_LANGINFO_H
+#if HAVE_LOCALCHARSET_H
+		my_charset = locale_charset ();
+#elif defined(HAVE_LANGINFO_H)
 		my_charset = nl_langinfo (CODESET);
 #else
 		my_charset = "UTF-8";
diff --git a/eglib/src/gutf8.c b/eglib/src/gutf8.c
index 3f1fab4..6abd703 100644
--- a/eglib/src/gutf8.c
+++ b/eglib/src/gutf8.c
@@ -74,8 +74,11 @@ utf8_to_utf16_len (const gchar *str, glong len, glong *items_read, GError **erro
 	for (in_pos = 0; in_pos < len && str [in_pos] < 0x80; in_pos++)
 		ret ++;
 
-	if (in_pos == len)
+	if (in_pos == len) {
+		if (items_read)
+			*items_read = in_pos;
 		return ret;
+	}
 
 	mb_size = 0;
 	mb_remain = 0;
@@ -214,6 +217,8 @@ g_utf8_to_utf16 (const gchar *str, glong len, glong *items_read, glong *items_wr
 	if (len < 0)
 		len = strlen (str);
 
+	if (items_read)
+		*items_read = 0;
 	if (items_written)
 		*items_written = 0;
 	utf16_len = utf8_to_utf16_len (str, len, items_read, error);
@@ -311,6 +316,8 @@ g_utf16_to_utf8 (const gunichar2 *str, glong len, glong *items_read, glong *item
 	out_pos = 0;
 	surrogate = FALSE;
 
+	if (items_read)
+		*items_read = 0;
 	if (items_written)
 		*items_written = 0;
 	utf8_len = utf16_to_utf8_len (str, len, items_read, error);
diff --git a/libgc/ChangeLog b/libgc/ChangeLog
index 02b4098..bc3e262 100644
--- a/libgc/ChangeLog
+++ b/libgc/ChangeLog
@@ -1,3 +1,8 @@
+2010-10-18  Zoltan Varga  <vargaz at gmail.com>
+
+	Avoid calling sem_post on a uninitialized semaphore during thread
+	attach, it works under linux, but fails under *bsd. Fixes #647248.
+
 2010-08-26  Zoltan Varga  <vargaz at gmail.com>
 
 	Avoid warnings on machines with cpus > 16.
diff --git a/libgc/pthread_support.c b/libgc/pthread_support.c
index f013204..29c39f7 100644
--- a/libgc/pthread_support.c
+++ b/libgc/pthread_support.c
@@ -1341,7 +1341,8 @@ void * GC_start_routine_head(void * arg, void *base_addr,
     if (start) *start = si -> start_routine;
     if (start_arg) *start_arg = si -> arg;
 
-    sem_post(&(si -> registered));	/* Last action on si.	*/
+	if (!(si->flags & FOREIGN_THREAD))
+		sem_post(&(si -> registered));	/* Last action on si.	*/
     					/* OK to deallocate.	*/
 #   if defined(THREAD_LOCAL_ALLOC) && !defined(DBG_HDRS_ALL)
  	LOCK();
diff --git a/man/ChangeLog b/man/ChangeLog
index 2ee9a51..4670bf3 100644
--- a/man/ChangeLog
+++ b/man/ChangeLog
@@ -1,3 +1,7 @@
+2010-10-21  Miguel de Icaza  <miguel at gnome.org>
+
+	Document server option to --debugger-agent
+
 2010-09-02  Ankit Jain  <radical at corewars.org>
 
 	[xbuild] Update man page to add "/tv:" option.
diff --git a/man/mono.1 b/man/mono.1
index 3b2974a..b8b2d22 100644
--- a/man/mono.1
+++ b/man/mono.1
@@ -220,6 +220,13 @@ Specifies the diagnostics log level for
 .Sp
 Used to specify the file where the log will be stored, it defaults to
 standard output.
+.TP
+.I server=[y/n]
+Defaults to no, with the default option Mono will actively connect to the
+host/port configured with the \fBaddress\fR option.  If you set it to 'y', it 
+instructs the Mono runtime to start debugging in server mode, where Mono
+actively waits for the debugger front end to connect to the Mono process.  
+Mono will print out to stdout the IP address and port where it is listening.
 .ne
 .RE
 .TP
diff --git a/mcs/build/common/Consts.cs b/mcs/build/common/Consts.cs
index 0e61c18..4912dd5 100644
--- a/mcs/build/common/Consts.cs
+++ b/mcs/build/common/Consts.cs
@@ -34,7 +34,7 @@ static class Consts
 	// Use these assembly version constants to make code more maintainable.
 	//
 
-	public const string MonoVersion = "2.8.0.0";
+	public const string MonoVersion = "2.8.1.0";
 	public const string MonoCompany = "MONO development team";
 	public const string MonoProduct = "MONO Common language infrastructure";
 	public const string MonoCopyright = "(c) various MONO Authors";
diff --git a/mcs/class/Managed.Windows.Forms/Assembly/AssemblyInfo.cs b/mcs/class/Managed.Windows.Forms/Assembly/AssemblyInfo.cs
index c24fc73..7a2cbb4 100644
--- a/mcs/class/Managed.Windows.Forms/Assembly/AssemblyInfo.cs
+++ b/mcs/class/Managed.Windows.Forms/Assembly/AssemblyInfo.cs
@@ -37,24 +37,14 @@ using System.Diagnostics;
 [assembly: AssemblyDelaySign (true)]
 [assembly: AssemblyKeyFile("../ecma.pub")]
 
-#if NET_2_0
-	[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
-	[assembly: Debuggable (DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
-	[assembly: CompilationRelaxations (CompilationRelaxations.NoStringInterning)]
-	[assembly: Dependency ("System.Drawing,", LoadHint.Always)]
-	[assembly: Dependency ("System,", LoadHint.Always)]
-	[assembly: StringFreezing]
-	[assembly: ComCompatibleVersion (1, 0, 3300, 0)]
-#elif NET_1_1
-	[assembly: AssemblyTrademark ("")]
-	[assembly: AssemblyConfiguration ("")]
-	[assembly: ComCompatibleVersion (1, 0, 3300, 0)]
-	[assembly: TypeLibVersion (1, 10)]
-#elif NET_1_0
-	[assembly: AssemblyTrademark ("")]
-	[assembly: AssemblyConfiguration ("")]
-#endif
-
-#if NET_2_0
-	[assembly: InternalsVisibleTo("UIAutomationWinforms, PublicKey=00240000048000009400000006020000002400005253413100040000110000004bb98b1af6c1df0df8c02c380e116b7a7f0c8c827aecfccddc6e29b7c754cd608b49dfcef4df9699ad182e50f66afa4e68dabc7b6aeeec0aa4719a5f8e0aae8c193080a706adc3443a8356b1f254142034995532ac176398e12a30f6a74a119a89ac47672c9ae24d7e90de686557166e3b873cd707884431a0451d9d6f7fe795")]
-#endif
+[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+[assembly: Debuggable (DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
+[assembly: CompilationRelaxations (CompilationRelaxations.NoStringInterning)]
+[assembly: Dependency ("System.Drawing,", LoadHint.Always)]
+[assembly: Dependency ("System,", LoadHint.Always)]
+[assembly: StringFreezing]
+[assembly: ComCompatibleVersion (1, 0, 3300, 0)]
+
+[assembly: InternalsVisibleTo("UIAutomationWinforms, PublicKey=00240000048000009400000006020000002400005253413100040000110000004bb98b1af6c1df0df8c02c380e116b7a7f0c8c827aecfccddc6e29b7c754cd608b49dfcef4df9699ad182e50f66afa4e68dabc7b6aeeec0aa4719a5f8e0aae8c193080a706adc3443a8356b1f254142034995532ac176398e12a30f6a74a119a89ac47672c9ae24d7e90de686557166e3b873cd707884431a0451d9d6f7fe795")]
+[assembly: InternalsVisibleTo("Mono.WinformsSupport, PublicKey=00240000048000009400000006020000002400005253413100040000110000004bb98b1af6c1df0df8c02c380e116b7a7f0c8c827aecfccddc6e29b7c754cd608b49dfcef4df9699ad182e50f66afa4e68dabc7b6aeeec0aa4719a5f8e0aae8c193080a706adc3443a8356b1f254142034995532ac176398e12a30f6a74a119a89ac47672c9ae24d7e90de686557166e3b873cd707884431a0451d9d6f7fe795")]
+
diff --git a/mcs/class/Managed.Windows.Forms/Assembly/ChangeLog b/mcs/class/Managed.Windows.Forms/Assembly/ChangeLog
index 979a5c4..47538a2 100644
--- a/mcs/class/Managed.Windows.Forms/Assembly/ChangeLog
+++ b/mcs/class/Managed.Windows.Forms/Assembly/ChangeLog
@@ -1,3 +1,7 @@
+2010-10-31  Miguel de Icaza  <miguel at gnome.org>
+
+	Expose some of our internals to the Mono.Winforms assembly
+
 2008-09-03  Mario Carrion  <mcarrion at novell.com>
 
 	* AssemblyInfo.cs: Added InternalsVisibleTo attribute to support 
diff --git a/mcs/class/Managed.Windows.Forms/Assembly/ChangeLog b/mcs/class/Managed.Windows.Forms/Assembly/ChangeLog.old
similarity index 100%
copy from mcs/class/Managed.Windows.Forms/Assembly/ChangeLog
copy to mcs/class/Managed.Windows.Forms/Assembly/ChangeLog.old
diff --git a/mcs/class/Managed.Windows.Forms/System.Windows.Forms/ChangeLog b/mcs/class/Managed.Windows.Forms/System.Windows.Forms/ChangeLog
index adcfad4..98e1523 100644
--- a/mcs/class/Managed.Windows.Forms/System.Windows.Forms/ChangeLog
+++ b/mcs/class/Managed.Windows.Forms/System.Windows.Forms/ChangeLog
@@ -1,3 +1,15 @@
+2010-10-31  Miguel de Icaza  <miguel at gnome.org>
+
+	Expose some of our internals to the Mono.Winforms assembly
+
+2010-10-31  Miguel de Icaza  <miguel at gnome.org>
+
+	Fix broken patch
+
+2010-10-31  Miguel de Icaza  <miguel at gnome.org>
+
+	Allow this file to expose its types as public if needed
+
 2010-08-16  Carlos Alberto Cortez  <calberto.cortez at gmail.com>
 
 	* DataGridView.cs: When refreshing the scrolling info, set the
diff --git a/mcs/class/Managed.Windows.Forms/System.Windows.Forms/XplatUIStructs.cs b/mcs/class/Managed.Windows.Forms/System.Windows.Forms/XplatUIStructs.cs
index d9fe8d0..9a27be4 100644
--- a/mcs/class/Managed.Windows.Forms/System.Windows.Forms/XplatUIStructs.cs
+++ b/mcs/class/Managed.Windows.Forms/System.Windows.Forms/XplatUIStructs.cs
@@ -30,9 +30,19 @@ using System;
 using System.Drawing;
 using System.Runtime.InteropServices;
 
-namespace System.Windows.Forms {
+#if PUBLIC_TYPES
+namespace Mono.Winforms 
+#else
+namespace System.Windows.Forms
+#endif
+{
 	[Flags]
-	internal enum WindowStyles : int {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum WindowStyles : int {
 		WS_OVERLAPPED		= 0x00000000,
 		WS_POPUP		= unchecked((int)0x80000000),
 		WS_CHILD		= 0x40000000,
@@ -63,7 +73,12 @@ namespace System.Windows.Forms {
 	}
 
 	[Flags]
-	internal enum WindowExStyles : int {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum WindowExStyles : int {
 		// Extended Styles
 		WS_EX_DLGMODALFRAME	= 0x00000001,
 		WS_EX_DRAGDETECT	= 0x00000002,
@@ -99,14 +114,24 @@ namespace System.Windows.Forms {
 	}
 
 	[Flags]
-	internal enum ToolBarStyles : int {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum ToolBarStyles : int {
 		TBSTYLE_TOOLTIPS    = 0x100,
 		TBSTYLE_FLAT        = 0x800,
 		TBSTYLE_LIST        = 0x1000,
 		TBSTYLE_TRANSPARENT = 0x8000
 	}
-	
-	internal enum Msg {
+
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum Msg {
 		WM_NULL                   = 0x0000,
 		WM_CREATE                 = 0x0001,
 		WM_DESTROY                = 0x0002,
@@ -358,7 +383,12 @@ namespace System.Windows.Forms {
 		NIN_BALLOONUSERCLICK      = WM_USER + 0x0005 
 	}
 
-	internal enum MsgButtons {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum MsgButtons {
 		MK_LBUTTON		= 0x0001,
 		MK_RBUTTON		= 0x0002,
 		MK_SHIFT		= 0x0004,
@@ -367,8 +397,13 @@ namespace System.Windows.Forms {
 		MK_XBUTTON1		= 0x0020,
 		MK_XBUTTON2		= 0x0040,
 	}
-	
-	internal enum MsgUIState {
+
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum MsgUIState {
 		UIS_SET        = 1,
 		UIS_CLEAR      = 2,
 		UIS_INITIALIZE = 3,
@@ -378,17 +413,22 @@ namespace System.Windows.Forms {
 	}
 
 	[StructLayout(LayoutKind.Sequential)]
-	internal struct POINT {
-		internal int x;
-		internal int y;
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	struct POINT {
+		public int x;
+		public int y;
 
-		internal POINT (int x, int y)
+		public POINT (int x, int y)
 		{
 			this.x = x;
 			this.y = y;
 		}
 
-		internal Point ToPoint ()
+		public Point ToPoint ()
 		{
 			return new Point (x, y);
 		}
@@ -400,7 +440,12 @@ namespace System.Windows.Forms {
 	}
 	
 	[StructLayout(LayoutKind.Sequential)] 
-	internal struct MSG {
+#if PUBLIC_TYPES
+        public
+#else
+	internal
+#endif
+	struct MSG {
 		internal IntPtr	hwnd;
 		internal Msg	message;
 		internal IntPtr	wParam; 
@@ -416,26 +461,46 @@ namespace System.Windows.Forms {
 	}
 
 	[Flags]
-	internal enum TransparencySupport {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum TransparencySupport {
 		None = 0x00,
 		Get = 0x01,
 		Set = 0x02,
 		GetSet = 0x03
 	}
 
-	internal enum WindowActiveFlags {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum WindowActiveFlags {
 		WA_INACTIVE		= 0,
 		WA_ACTIVE		= 1,
 		WA_CLICKACTIVE		= 2
 	}
 
-	internal enum KeybdEventFlags {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum KeybdEventFlags {
 		None			= 0,
 		ExtendedKey		= 0x0001,
 		KeyUp			= 0x0002
 	}
 
-	internal enum VirtualKeys {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum VirtualKeys {
 		VK_LBUTTON		= 0x01,
 		VK_RBUTTON              = 0x02,
 		VK_CANCEL		= 0x03,
@@ -590,7 +655,12 @@ namespace System.Windows.Forms {
 		VK_OEM_CLEAR		= 0xFE,
 	}
 
-	internal enum TtyKeys {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum TtyKeys {
 		XK_BackSpace		= 0xff08,  /* Back space, back char */
 		XK_Tab			= 0xff09,
 		XK_Linefeed		= 0xff0a,  /* Linefeed, LF */
@@ -603,7 +673,12 @@ namespace System.Windows.Forms {
 		XK_Delete		= 0xffff  /* Delete, rubout */
 	}
 
-	internal enum MiscKeys {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum MiscKeys {
 		XK_ISO_Lock             = 0xfe01,
 		XK_ISO_Last_Group_Lock	= 0xfe0f,
 		XK_Select		= 0xff60,
@@ -622,7 +697,12 @@ namespace System.Windows.Forms {
 		XK_Num_Lock		= 0xff7f
 	}
 
-	internal enum KeypadKeys {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum KeypadKeys {
 		XK_KP_Space		= 0xff80,
 		XK_KP_Tab		= 0xff89,
 		XK_KP_Enter		= 0xff8d,  /* Enter */
@@ -663,7 +743,12 @@ namespace System.Windows.Forms {
 		XK_KP_9			= 0xffb9
 	}
 
-        internal enum DeadKeys {
+#if PUBLIC_TYPES
+	public
+#else
+        internal
+#endif
+	enum DeadKeys {
                 XK_dead_grave           = 0xfe50,
                 XK_dead_acute           = 0xfe51,
                 XK_dead_circumflex      = 0xfe52,
@@ -687,7 +772,12 @@ namespace System.Windows.Forms {
         }
 
 	[StructLayout(LayoutKind.Sequential)]
-	internal struct HELPINFO {
+#if PUBLIC_TYPES
+	 public
+#else
+	internal
+#endif
+	struct HELPINFO {
 		internal uint		cbSize;
 		internal int		iContextType;
 		internal int		iCtrlId;
@@ -696,13 +786,23 @@ namespace System.Windows.Forms {
 		internal POINT		MousePos;
 	}
 
-	internal enum PeekMessageFlags {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum PeekMessageFlags {
 		PM_NOREMOVE			= 0x00000000,
 		PM_REMOVE			= 0x00000001,
 		PM_NOYIELD			= 0x00000002
 	}
 
-	internal enum StdCursor {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum StdCursor {
 		Default				= 0,
 		AppStarting			= 1,
 		Arrow				= 2,
@@ -733,7 +833,12 @@ namespace System.Windows.Forms {
 		WaitCursor			= 27
 	}
 
-	internal enum HitTest {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum HitTest {
 		HTERROR				= -2,
 		HTTRANSPARENT			= -1,
 		HTNOWHERE			= 0,
@@ -765,14 +870,24 @@ namespace System.Windows.Forms {
 		HTHELP				= 21
 	}
 
-	internal enum TitleStyle {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum TitleStyle {
 		None				= 0,
 		Normal				= 1,
 		Tool				= 2
 	}
 
 	[StructLayout(LayoutKind.Sequential)]
-	internal struct BITMAPINFOHEADER {
+#if PUBLIC_TYPES
+	 public
+#else
+	internal
+#endif
+	struct BITMAPINFOHEADER {
 		internal uint     biSize;
 		internal int      biWidth;
 		internal int      biHeight;
@@ -786,7 +901,12 @@ namespace System.Windows.Forms {
 		internal uint     biClrImportant;
 	}
 
-	internal enum ClipboardFormats : ushort {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum ClipboardFormats : ushort {
 		CF_TEXT				= 1,
 		CF_BITMAP           		= 2,
 		CF_METAFILEPICT     		= 3,
@@ -807,7 +927,12 @@ namespace System.Windows.Forms {
 	}
 
 	[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
-	internal struct MINMAXINFO {
+#if PUBLIC_TYPES
+	 public
+#else
+	internal
+#endif
+	struct MINMAXINFO {
 		internal POINT			ptReserved;
 		internal POINT			ptMaxSize;
 		internal POINT			ptMaxPosition;
@@ -816,7 +941,12 @@ namespace System.Windows.Forms {
 	}
 
 	[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
-	internal struct KeyFilterData {
+#if PUBLIC_TYPES
+	 public
+#else
+	internal
+#endif
+	struct KeyFilterData {
 			internal bool Down;
 			internal int keycode;
 			internal int keysym;
@@ -824,7 +954,12 @@ namespace System.Windows.Forms {
 			internal String str;
 		}
 
-	internal enum ScrollBarCommands {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum ScrollBarCommands {
 		SB_LINEUP		= 0,
 		SB_LINELEFT		= 0,
 		SB_LINEDOWN		= 1,
@@ -842,7 +977,12 @@ namespace System.Windows.Forms {
 		SB_ENDSCROLL		= 8
 	}
 
-	internal enum ClipCombineMode {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum ClipCombineMode {
 		RGN_AND = 1,
 		RGN_OR,
 		RGN_XOR,
@@ -853,7 +993,12 @@ namespace System.Windows.Forms {
 		RGN_MAX = RGN_COPY
 	}
 
-	internal enum SystemCommands {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum SystemCommands {
 		SC_SIZE         = 0xF000,
 		SC_MOVE         = 0xF010,
 		SC_MINIMIZE     = 0xF020,
@@ -875,7 +1020,12 @@ namespace System.Windows.Forms {
 		SC_CONTEXTHELP  = 0xF180
 	}
 
-	internal enum AlertType {
+#if PUBLIC_TYPES
+	public
+#else
+	internal
+#endif
+	enum AlertType {
 		Default		= 1,
 		Error		= 2,
 		Question	= 3,
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildTask.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildTask.cs
index 38bdad8..b57dfd7 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildTask.cs
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildTask.cs
@@ -84,36 +84,38 @@ namespace Microsoft.Build.BuildEngine {
 		[MonoTODO]
 		public bool Execute ()
 		{
-			bool		result;
+			bool		result = false;
 			TaskEngine	taskEngine;
 
 			LogTaskStarted ();
 			ITask task = null;
 
 			try {
-				task = InitializeTask ();
-			} catch (Exception e) {
-				LogError ("Error initializing task {0}: {1}", taskElement.LocalName, e.Message);
-				LogMessage (MessageImportance.Low, "Error initializing task {0}: {1}",
-						taskElement.LocalName, e.ToString ());
-				return false;
-			}
+				try {
+					task = InitializeTask ();
+				} catch (Exception e) {
+					LogError ("Error initializing task {0}: {1}", taskElement.LocalName, e.Message);
+					LogMessage (MessageImportance.Low, "Error initializing task {0}: {1}",
+							taskElement.LocalName, e.ToString ());
+					return false;
+				}
 
-			try {
-				taskEngine = new TaskEngine (parentTarget.Project);		
-				taskEngine.Prepare (task, this.taskElement, GetParameters (), this.Type);
-				result = taskEngine.Execute ();
-				if (result)
-					taskEngine.PublishOutput ();
-			} catch (Exception e) {
-				task_logger.LogError ("Error executing task {0}: {1}", taskElement.LocalName, e.Message);
-				task_logger.LogMessage (MessageImportance.Low,
-						"Error executing task {0}: {1}", taskElement.LocalName, e.ToString ());
-				result = false;
+				try {
+					taskEngine = new TaskEngine (parentTarget.Project);
+					taskEngine.Prepare (task, this.taskElement, GetParameters (), this.Type);
+					result = taskEngine.Execute ();
+					if (result)
+						taskEngine.PublishOutput ();
+				} catch (Exception e) {
+					task_logger.LogError ("Error executing task {0}: {1}", taskElement.LocalName, e.Message);
+					task_logger.LogMessage (MessageImportance.Low,
+							"Error executing task {0}: {1}", taskElement.LocalName, e.ToString ());
+					result = false;
+				}
+			} finally {
+				LogTaskFinished (result);
 			}
 
-			LogTaskFinished (result);
-		
 			return result;
 		}
 
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ChangeLog b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ChangeLog
index 8874704..ca872f3 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ChangeLog
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ChangeLog
@@ -1,3 +1,49 @@
+2010-10-13  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Reset cache of built targets, on a new project build.
+
+	All targets that get built are tracked by the engine, to avoid
+	unnecessary builds of targets. This should be reset on
+	engine.Build, unless it is explicitly requested *not to* reset it,
+	via BuildFlags.
+
+2010-10-13  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Reset ConsoleLogger when a build finishes.
+
+	MSBuild hosts like monodevelop, which use the same logger for
+	multiple builds, get errors/warnings from older builds. So, reset
+	them whenever the BuildFinished event is raised.
+
+	ILogger.Shutdown () is invoked when the host is about to quit,
+	according to msdn, so can't use that.
+
+2010-10-11  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Log TaskFinished even when task fails to initialize.
+
+2010-09-12  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Fix ConsoleLogger's output, extra blank lines etc.
+
+2010-09-11  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Reduce ConsoleLogger's unnecessary output.
+
+	ConsoleLogger was emitting target names, even if they didn't have
+	any useful output, which resulted in lots of "Target foo:" in the
+	output, with no other related msgs.
+
+	Target Foo: Target Bar: Target Xyz:
+
+	Emit project/target/task headers only if they result in a message,
+	error or warning. This results in much cleaner output.
+
+2010-09-11  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Log default msg for TargetSkipped if @reason is null or
+	empty.
+
 2010-09-02  Ankit Jain  <radical at corewars.org>
 
 	[xbuild] Unsubscribe events on ConsoleLogger.Shutdown ()
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConsoleLogger.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConsoleLogger.cs
index 6f5f280..2834998 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConsoleLogger.cs
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConsoleLogger.cs
@@ -59,7 +59,7 @@ namespace Microsoft.Build.BuildEngine {
 		bool no_message_color, use_colors;
 		bool noItemAndPropertyList;
 
-		List<BuildStatusEventArgs> events;
+		List<BuildEvent> events;
 		Dictionary<string, List<string>> errorsTable;
 		Dictionary<string, List<string>> warningsTable;
 		SortedDictionary<string, PerfInfo> targetPerfTable, tasksPerfTable;
@@ -96,7 +96,7 @@ namespace Microsoft.Build.BuildEngine {
 			this.colorSet = colorSet;
 			this.colorReset = colorReset;
 
-			events = new List<BuildStatusEventArgs> ();
+			events = new List<BuildEvent> ();
 			errorsTable = new Dictionary<string, List<string>> ();
 			warningsTable = new Dictionary<string, List<string>> ();
 			targetPerfTable = new SortedDictionary<string, PerfInfo> ();
@@ -205,19 +205,23 @@ namespace Microsoft.Build.BuildEngine {
 		{
 			this.eventSource = eventSource;
 
-                        eventSource.BuildStarted +=  new BuildStartedEventHandler (BuildStartedHandler);
-                        eventSource.BuildFinished += new BuildFinishedEventHandler (BuildFinishedHandler);
-                        eventSource.ProjectStarted += new ProjectStartedEventHandler (ProjectStartedHandler);
-                        eventSource.ProjectFinished += new ProjectFinishedEventHandler (ProjectFinishedHandler);
-                        eventSource.TargetStarted += new TargetStartedEventHandler (TargetStartedHandler);
-                        eventSource.TargetFinished += new TargetFinishedEventHandler (TargetFinishedHandler);
-                        eventSource.TaskStarted += new TaskStartedEventHandler (TaskStartedHandler);
-                        eventSource.TaskFinished += new TaskFinishedEventHandler (TaskFinishedHandler);
-                        eventSource.MessageRaised += new BuildMessageEventHandler (MessageHandler);
-                        eventSource.WarningRaised += new BuildWarningEventHandler (WarningHandler);
-                        eventSource.ErrorRaised += new BuildErrorEventHandler (ErrorHandler);
+			eventSource.BuildStarted += BuildStartedHandler;
+			eventSource.BuildFinished += BuildFinishedHandler;
+
+			eventSource.ProjectStarted += PushEvent;
+			eventSource.ProjectFinished += PopEvent;
+
+			eventSource.TargetStarted += PushEvent;
+			eventSource.TargetFinished += PopEvent;
+
+			eventSource.TaskStarted += PushEvent;
+			eventSource.TaskFinished += PopEvent;
+
+			eventSource.MessageRaised += MessageHandler;
+			eventSource.WarningRaised += WarningHandler;
+			eventSource.ErrorRaised += ErrorHandler;
 		}
-		
+
 		public void BuildStartedHandler (object sender, BuildStartedEventArgs args)
 		{
 			if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Normal)) {
@@ -232,8 +236,27 @@ namespace Microsoft.Build.BuildEngine {
 		
 		public void BuildFinishedHandler (object sender, BuildFinishedEventArgs args)
 		{
+			BuildFinishedHandlerActual (args);
+
+			// Reset
+			events.Clear ();
+			errorsTable.Clear ();
+			warningsTable.Clear ();
+			targetPerfTable.Clear ();
+			tasksPerfTable.Clear ();
+			errors.Clear ();
+			warnings.Clear ();
+
+			indent = 0;
+			errorCount = 0;
+			warningCount = 0;
+			projectFailed = false;
+		}
+
+		void BuildFinishedHandlerActual (BuildFinishedEventArgs args)
+		{
 			if (!IsVerbosityGreaterOrEqual (LoggerVerbosity.Normal)) {
-				PopEvent ();
+				PopEvent (args);
 				return;
 			}
 
@@ -288,8 +311,9 @@ namespace Microsoft.Build.BuildEngine {
 				WriteLine (String.Format ("\t {0} Error(s)", errorCount));
 				WriteLine (String.Empty);
 				WriteLine (String.Format ("Time Elapsed {0}", timeElapsed));
-			} 
-			PopEvent ();
+			}
+
+			PopEvent (args);
 		}
 
 		public void ProjectStartedHandler (object sender, ProjectStartedEventArgs args)
@@ -299,11 +323,9 @@ namespace Microsoft.Build.BuildEngine {
 				WriteLine (String.Format ("Project \"{0}\" ({1} target(s)):", args.ProjectFile,
 							String.IsNullOrEmpty (args.TargetNames) ? "default" : args.TargetNames));
 				ResetColor ();
-				WriteLine (String.Empty);
 				DumpProperties (args.Properties);
 				DumpItems (args.Items);
 			}
-			PushEvent (args);
 		}
 		
 		public void ProjectFinishedHandler (object sender, ProjectFinishedEventArgs args)
@@ -320,8 +342,6 @@ namespace Microsoft.Build.BuildEngine {
 			if (!projectFailed)
 				// no project has failed yet, so update the flag
 				projectFailed = !args.Succeeded;
-
-			PopEvent ();
 		}
 		
 		public void TargetStartedHandler (object sender, TargetStartedEventArgs args)
@@ -329,10 +349,10 @@ namespace Microsoft.Build.BuildEngine {
 			if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Normal)) {
 				indent++;
 				SetColor (eventColor);
+				WriteLine (String.Empty);
 				WriteLine (String.Format ("Target {0}:",args.TargetName));
 				ResetColor ();
 			}
-			PushEvent (args);
 		}
 		
 		public void TargetFinishedHandler (object sender, TargetFinishedEventArgs args)
@@ -347,19 +367,16 @@ namespace Microsoft.Build.BuildEngine {
 				WriteLine (String.Empty);
 			}
 			indent--;
-
-			PopEvent ();
 		}
 		
 		public void TaskStartedHandler (object sender, TaskStartedEventArgs args)
 		{
-			if (this.verbosity == LoggerVerbosity.Detailed) {
+			if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Detailed)) {
 				SetColor (eventColor);
 				WriteLine (String.Format ("Task \"{0}\"",args.TaskName));
 				ResetColor ();
 			}
 			indent++;
-			PushEvent (args);
 		}
 		
 		public void TaskFinishedHandler (object sender, TaskFinishedEventArgs args)
@@ -374,15 +391,16 @@ namespace Microsoft.Build.BuildEngine {
 					WriteLine (String.Format ("Task \"{0}\" execution -- FAILED", args.TaskName));
 				ResetColor ();
 			}
-			PopEvent ();
 		}
 		
 		public void MessageHandler (object sender, BuildMessageEventArgs args)
 		{
 			if (IsMessageOk (args)) {
 				if (no_message_color) {
+					ExecutePendingEventHandlers ();
 					WriteLine (args.Message);
 				} else {
+					ExecutePendingEventHandlers ();
 					SetColor (args.Importance == MessageImportance.High ? highMessageColor : messageColor);
 					WriteLine (args.Message);
 					ResetColor ();
@@ -394,6 +412,7 @@ namespace Microsoft.Build.BuildEngine {
 		{
 			string msg = FormatWarningEvent (args);
 			if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Quiet)) {
+				ExecutePendingEventHandlers ();
 				SetColor (warningColor);
 				WriteLineWithoutIndent (msg);
 				ResetColor ();
@@ -412,6 +431,7 @@ namespace Microsoft.Build.BuildEngine {
 		{
 			string msg = FormatErrorEvent (args);
 			if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Quiet)) {
+				ExecutePendingEventHandlers ();
 				SetColor (errorColor);
 				WriteLineWithoutIndent (msg);
 				ResetColor ();
@@ -444,16 +464,36 @@ namespace Microsoft.Build.BuildEngine {
 			}
 		}
 
-		void PushEvent (BuildStatusEventArgs args)
+		void PushEvent<T> (object sender, T args) where T: BuildStatusEventArgs
 		{
-			events.Add (args);
+			PushEvent (args);
+		}
+
+		void PushEvent<T> (T args) where T: BuildStatusEventArgs
+		{
+			BuildEvent be = new BuildEvent {
+				EventArgs = args,
+				StartHandlerHasExecuted = false,
+				ConsoleLogger = this
+			};
+
+			events.Add (be);
 			current_events_string = null;
 		}
 
-		void PopEvent ()
+		void PopEvent<T> (object sender, T finished_args) where T: BuildStatusEventArgs
 		{
+			PopEvent (finished_args);
+		}
+
+		void PopEvent<T> (T finished_args) where T: BuildStatusEventArgs
+		{
+			if (events.Count == 0)
+				throw new InvalidOperationException ("INTERNAL ERROR: Trying to pop from an empty events stack");
+
+			BuildEvent be = events [events.Count - 1];
 			if (performanceSummary || verbosity == LoggerVerbosity.Diagnostic) {
-				var args = events [events.Count - 1];
+				var args = be.EventArgs;
 				TargetStartedEventArgs tgt_args = args as TargetStartedEventArgs;
 				if (tgt_args != null) {
 					AddPerfInfo (tgt_args.TargetName, args.Timestamp, targetPerfTable);
@@ -464,17 +504,24 @@ namespace Microsoft.Build.BuildEngine {
 				}
 			}
 
+			be.ExecuteFinishedHandler (finished_args);
 			events.RemoveAt (events.Count - 1);
 			current_events_string = null;
 		}
 
+		void ExecutePendingEventHandlers ()
+		{
+			foreach (var be in events)
+				be.ExecuteStartedHandler ();
+		}
+
 		string EventsToString ()
 		{
 			StringBuilder sb = new StringBuilder ();
 
 			string last_imported_target_file = String.Empty;
 			for (int i = 0; i < events.Count; i ++) {
-				var args = events [i];
+				var args = events [i].EventArgs;
 				ProjectStartedEventArgs pargs = args as ProjectStartedEventArgs;
 				if (pargs != null) {
 					sb.AppendFormat ("{0} ({1}) ->\n", pargs.ProjectFile,
@@ -580,14 +627,18 @@ namespace Microsoft.Build.BuildEngine {
 			if (eventSource == null)
 				return;
 
-			eventSource.BuildStarted -=  BuildStartedHandler;
+			eventSource.BuildStarted -= BuildStartedHandler;
 			eventSource.BuildFinished -= BuildFinishedHandler;
-			eventSource.ProjectStarted -= ProjectStartedHandler;
-			eventSource.ProjectFinished -= ProjectFinishedHandler;
-			eventSource.TargetStarted -= TargetStartedHandler;
-			eventSource.TargetFinished -= TargetFinishedHandler;
-			eventSource.TaskStarted -= TaskStartedHandler;
-			eventSource.TaskFinished -= TaskFinishedHandler;
+
+			eventSource.ProjectStarted -= PushEvent;
+			eventSource.ProjectFinished -= PopEvent;
+
+			eventSource.TargetStarted -= PushEvent;
+			eventSource.TargetFinished -= PopEvent;
+
+			eventSource.TaskStarted -= PushEvent;
+			eventSource.TaskFinished -= PopEvent;
+
 			eventSource.MessageRaised -= MessageHandler;
 			eventSource.WarningRaised -= WarningHandler;
 			eventSource.ErrorRaised -= ErrorHandler;
@@ -673,7 +724,7 @@ namespace Microsoft.Build.BuildEngine {
 				return;
 
 			SetColor (eventColor);
-			WriteLine ("\n");
+			WriteLine (String.Empty);
 			WriteLine ("Initial Properties:");
 			ResetColor ();
 
@@ -686,7 +737,6 @@ namespace Microsoft.Build.BuildEngine {
 
 			foreach (KeyValuePair<string, string> pair in dict)
 				WriteLine (String.Format ("{0} = {1}", pair.Key, pair.Value));
-			WriteLine ("\n");
 		}
 
 		void DumpItems (IEnumerable items)
@@ -695,7 +745,7 @@ namespace Microsoft.Build.BuildEngine {
 				return;
 
 			SetColor (eventColor);
-			WriteLine ("\n");
+			WriteLine (String.Empty);
 			WriteLine ("Initial Items:");
 			ResetColor ();
 			if (items == null)
@@ -717,7 +767,6 @@ namespace Microsoft.Build.BuildEngine {
 					WriteLine (item.ItemSpec);
 				indent--;
 			}
-			WriteLine ("\n");
 		}
 
 		public string Parameters {
@@ -762,6 +811,44 @@ namespace Microsoft.Build.BuildEngine {
 		}
 	}
 
+	class BuildEvent {
+		public BuildStatusEventArgs EventArgs;
+		public bool StartHandlerHasExecuted;
+		public ConsoleLogger ConsoleLogger;
+
+		public void ExecuteStartedHandler ()
+		{
+			if (StartHandlerHasExecuted)
+				return;
+
+			if (EventArgs is ProjectStartedEventArgs)
+				ConsoleLogger.ProjectStartedHandler (null, (ProjectStartedEventArgs)EventArgs);
+			else if (EventArgs is TargetStartedEventArgs)
+				ConsoleLogger.TargetStartedHandler (null, (TargetStartedEventArgs)EventArgs);
+			else if (EventArgs is TaskStartedEventArgs)
+				ConsoleLogger.TaskStartedHandler (null, (TaskStartedEventArgs)EventArgs);
+			else if (!(EventArgs is BuildStartedEventArgs))
+				throw new InvalidOperationException ("Unexpected event on the stack, type: " + EventArgs.GetType ());
+
+			StartHandlerHasExecuted = true;
+		}
+
+		public void ExecuteFinishedHandler (BuildStatusEventArgs finished_args)
+		{
+			if (!StartHandlerHasExecuted)
+				return;
+
+			if (EventArgs is ProjectStartedEventArgs)
+				ConsoleLogger.ProjectFinishedHandler (null, finished_args as ProjectFinishedEventArgs);
+			else if (EventArgs is TargetStartedEventArgs)
+				ConsoleLogger.TargetFinishedHandler (null, finished_args as TargetFinishedEventArgs);
+			else if (EventArgs is TaskStartedEventArgs)
+				ConsoleLogger.TaskFinishedHandler (null, finished_args as TaskFinishedEventArgs);
+			else if (!(EventArgs is BuildStartedEventArgs))
+				throw new InvalidOperationException ("Unexpected event on the stack, type: " + EventArgs.GetType ());
+		}
+	}
+
 	class PerfInfo {
 		public TimeSpan Time;
 		public int NumberOfCalls;
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Engine.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Engine.cs
index fd675a7..3a41134 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Engine.cs
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Engine.cs
@@ -126,6 +126,7 @@ namespace Microsoft.Build.BuildEngine {
 		{
 			if (project == null)
 				throw new ArgumentException ("project");
+			builtTargetsOutputByName.Clear ();
 			return project.Build ();
 		}
 		
@@ -164,6 +165,9 @@ namespace Microsoft.Build.BuildEngine {
 			if (targetNames == null)
 				return false;
 
+			if ((buildFlags & BuildSettings.DoNotResetPreviouslyBuiltTargets) != BuildSettings.DoNotResetPreviouslyBuiltTargets)
+				builtTargetsOutputByName.Clear ();
+
 			if (defaultToolsVersion != null)
 				// it has been explicitly set, xbuild does this..
 				project.ToolsVersion = defaultToolsVersion;
@@ -224,6 +228,9 @@ namespace Microsoft.Build.BuildEngine {
 					      IDictionary targetOutputs,
 					      BuildSettings buildFlags, string toolsVersion)
 		{
+			if ((buildFlags & BuildSettings.DoNotResetPreviouslyBuiltTargets) != BuildSettings.DoNotResetPreviouslyBuiltTargets)
+				builtTargetsOutputByName.Clear ();
+
 			Project project;
 
 			bool newProject = false;
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/TargetBatchingImpl.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/TargetBatchingImpl.cs
index 54aad29..b5bc459 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/TargetBatchingImpl.cs
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/TargetBatchingImpl.cs
@@ -241,8 +241,10 @@ namespace Microsoft.Build.BuildEngine {
 		void LogTargetSkipped (Target target, string reason)
 		{
 			BuildMessageEventArgs bmea;
-			bmea = new BuildMessageEventArgs (reason ?? String.Format ("Skipping target \"{0}\" because its outputs are up-to-date.", target.Name),
-				null, "MSBuild", MessageImportance.Normal);
+			bmea = new BuildMessageEventArgs (String.IsNullOrEmpty (reason)
+								? String.Format ("Skipping target \"{0}\" because its outputs are up-to-date.", target.Name)
+								: reason,
+							null, "MSBuild", MessageImportance.Normal);
 			target.Engine.EventSource.FireMessageRaised (this, bmea);
 		}
 
diff --git a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/ChangeLog b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/ChangeLog
index 9103a15..fe424f5 100644
--- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/ChangeLog
+++ b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/ChangeLog
@@ -1,3 +1,17 @@
+2010-09-16  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Use files referenced by resx for dependency check.
+
+	For .resx resource files, check files referenced by the resx file
+	also, to determine whether to resgen it or not.
+
+	IsResgenRequired () has been taken from MonoDevelop
+	(main/src/core/MonoDevelop.Core/MonoDevelop.Projects.Formats.MD1/MD1DotNetProjectHandler.cs)
+
+2010-09-15  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Add ToolTask.EnvironmentVariables property.
+
 2010-08-31  Ankit Jain  <radical at corewars.org>
 
 	[xbuild] Task 'Touch' should pass even if the file already exists.
diff --git a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/GenerateResource.cs b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/GenerateResource.cs
index 9c1f645..31676af 100644
--- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/GenerateResource.cs
+++ b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/GenerateResource.cs
@@ -5,8 +5,11 @@
 //   Marek Sieradzki (marek.sieradzki at gmail.com)
 //   Paolo Molaro (lupus at ximian.com)
 //   Gonzalo Paniagua Javier (gonzalo at ximian.com)
+//   Lluis Sanchez Gual <lluis at novell.com>
+//   Ankit Jain <jankit at novell.com>
 //
 // (C) 2005 Marek Sieradzki
+// Copyright 2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -36,6 +39,7 @@ using System.Collections;
 using System.Collections.Generic;
 using System.Resources;
 using System.Reflection;
+using System.Xml;
 using Microsoft.Build.Framework;
 using Microsoft.Build.Utilities;
 using Mono.XBuild.Tasks.GenerateResourceInternal;
@@ -73,7 +77,8 @@ namespace Microsoft.Build.Tasks {
 					string sourceFile = source.ItemSpec;
 					string outputFile = Path.ChangeExtension (sourceFile, "resources");
 
-					result &= CompileResourceFile (sourceFile, outputFile);
+					if (IsResgenRequired (sourceFile, outputFile))
+						result &= CompileResourceFile (sourceFile, outputFile);
 
 					ITaskItem newItem = new TaskItem (source);
 					source.ItemSpec = outputFile;
@@ -93,7 +98,8 @@ namespace Microsoft.Build.Tasks {
 						continue;
 					}
 
-					result &= CompileResourceFile (sources [i].ItemSpec, outputResources [i].ItemSpec);
+					if (IsResgenRequired (sources [i].ItemSpec, outputResources [i].ItemSpec))
+						result &= CompileResourceFile (sources [i].ItemSpec, outputResources [i].ItemSpec);
 					temporaryFilesWritten.Add (outputResources [i]);
 				}
 			}
@@ -103,6 +109,78 @@ namespace Microsoft.Build.Tasks {
 			return result;
 		}
 		
+		// true if the resx file or any file referenced
+		// by the resx is newer than the .resources file
+		//
+		// Code taken from monodevelop
+		// main/src/core/MonoDevelop.Core/MonoDevelop.Projects.Formats.MD1/MD1DotNetProjectHandler.cs
+		bool IsResgenRequired (string resx_filename, string resources_filename)
+		{
+			if (IsFileNewerThan (resx_filename, resources_filename)) {
+				Log.LogMessage (MessageImportance.Low,
+						"Resource file '{0}' is newer than the source file '{1}', skipping.",
+						resources_filename, resx_filename);
+				return true;
+			}
+
+			if (String.Compare (Path.GetExtension (resx_filename), ".resx", true) != 0)
+				return true;
+
+			// resx file, check for files referenced from there
+			XmlTextReader xr = null;
+			try {
+				// look for
+				// <data type="System.Resources.ResXFileRef, System.Windows.Forms" ..>
+				//   <value>... filename;.. </value>
+				// </data>
+				xr = new XmlTextReader (resx_filename);
+				string basepath = Path.GetDirectoryName (resx_filename);
+				while (xr.Read ()) {
+					if (xr.NodeType != XmlNodeType.Element ||
+						String.Compare (xr.LocalName, "data") != 0)
+						continue;
+
+					string type = xr.GetAttribute ("type");
+					if (String.IsNullOrEmpty (type))
+						continue;
+
+					if (String.Compare (type, "System.Resources.ResXFileRef, System.Windows.Forms") != 0)
+						continue;
+
+					xr.ReadToDescendant ("value");
+					if (xr.NodeType != XmlNodeType.Element)
+						continue;
+
+					string value = xr.ReadElementContentAsString ();
+
+					string [] parts = value.Split (';');
+					if (parts.Length > 0) {
+						string referenced_filename = Utilities.FromMSBuildPath (
+								Path.Combine (basepath, parts [0]).Trim ());
+						if (File.Exists (referenced_filename) &&
+							IsFileNewerThan (referenced_filename, resources_filename))
+							return true;
+					}
+				}
+			} catch (XmlException) {
+				// Ignore xml errors, let resgen handle it
+				return true;
+			} finally {
+				if (xr != null)
+					xr.Close ();
+			}
+
+			return false;
+		}
+
+		// true if first is newer than second
+		static bool IsFileNewerThan (string first, string second)
+		{
+			FileInfo finfo_first = new FileInfo (first);
+			FileInfo finfo_second = new FileInfo (second);
+			return finfo_first.LastWriteTime > finfo_second.LastWriteTime;
+		}
+
 #if false
 		private IResourceReader GetReader (Stream stream, string name)
 		{
@@ -154,13 +232,6 @@ namespace Microsoft.Build.Tasks {
 				return false;
 			}
 
-			if (File.GetLastWriteTime (sname) <= File.GetLastWriteTime (dname)) {
-				Log.LogMessage (MessageImportance.Low,
-						"Resource file '{0}' is newer than the source file '{1}', skipping.",
-						dname, sname);
-				return true;
-			}
-
 			Resgen resgen = new Resgen ();
 			resgen.BuildEngine = this.BuildEngine;
 			resgen.UseSourcePath = true;
@@ -298,7 +369,7 @@ namespace Microsoft.Build.Tasks {
 		public override bool Execute ()
 		{
 			if (String.IsNullOrEmpty (Environment.GetEnvironmentVariable ("MONO_IOMAP")))
-				EnvironmentOverride ["MONO_IOMAP"] = "drive";
+				EnvironmentVariables = new string [] { "MONO_IOMAP=drive" };
 			return base.Execute ();
 		}
 
diff --git a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Utilities.cs b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Utilities.cs
index e9a5ac5..5a0c56e 100644
--- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Utilities.cs
+++ b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Utilities.cs
@@ -28,6 +28,7 @@
 #if NET_2_0
 
 using System;
+using System.IO;
 
 namespace Microsoft.Build.Tasks {
 	internal static class Utilities {
@@ -42,6 +43,68 @@ namespace Microsoft.Build.Tasks {
 			}
 
 		}
+
+		internal static string FromMSBuildPath (string relPath)
+		{
+			if (relPath == null || relPath.Length == 0)
+				return null;
+
+			bool is_windows = Path.DirectorySeparatorChar == '\\';
+			string path = relPath;
+			if (!is_windows)
+				path = path.Replace ("\\", "/");
+
+			// a path with drive letter is invalid/unusable on non-windows
+			if (!is_windows && char.IsLetter (path [0]) && path.Length > 1 && path[1] == ':')
+				return null;
+
+			if (System.IO.File.Exists (path)){
+				return Path.GetFullPath (path);
+			}
+
+			if (Path.IsPathRooted (path)) {
+
+				// Windows paths are case-insensitive. When mapping an absolute path
+				// we can try to find the correct case for the path.
+
+				string[] names = path.Substring (1).Split ('/');
+				string part = "/";
+
+				for (int n=0; n<names.Length; n++) {
+					string[] entries;
+
+					if (names [n] == ".."){
+						if (part == "/")
+							return ""; // Can go further back. It's not an existing file
+						part = Path.GetFullPath (part + "/..");
+						continue;
+					}
+
+					entries = Directory.GetFileSystemEntries (part);
+
+					string fpath = null;
+					foreach (string e in entries) {
+						if (string.Compare (Path.GetFileName (e), names[n], true) == 0) {
+							fpath = e;
+							break;
+						}
+					}
+					if (fpath == null) {
+						// Part of the path does not exist. Can't do any more checking.
+						part = Path.GetFullPath (part);
+						for (; n < names.Length; n++)
+							part += "/" + names[n];
+						return part;
+					}
+
+					part = fpath;
+				}
+				return Path.GetFullPath (part);
+			} else {
+				return Path.GetFullPath (path);
+			}
+		}
+
 	}
 
 }
diff --git a/mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ChangeLog b/mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ChangeLog
index cae24a5..ee0d380 100644
--- a/mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ChangeLog
+++ b/mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ChangeLog
@@ -1,3 +1,48 @@
+2010-09-16  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Fix case sensitive environment variables for ToolTask.
+
+	Use ProcessStringDictionary in ToolTask for EnvironmentVariables,
+	as this retains the original case of the keys. Without this
+	environment vars would all be passed as lowercase!
+
+	This was removed in a previous patch by mistake.
+
+2010-09-15  Ankit Jain  <radical at corewars.org>
+
+	*
+	class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
+	(EnvironmentVariables): New. (ExecuteTool): Merge
+	EnvironmentVariables with EnvironmentOverride *
+	class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/GenerateResource.cs
+	(Resgen.Execute): Use EnvironmentVariables to set MONO_IOMAP=drive
+	.
+
+2010-09-15  Ankit Jain  <radical at corewars.org>
+
+	*
+	class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
+	(ExecuteTool): When StartProcess returns, the process has already
+	.Start()'ed If we subscribe to the output events after that, then
+	for processes that finish executing before we can subscribe, we
+	won't get the output/error events at all! So, pass the handlers to
+	StartProcess itself, so that they get added before the process is
+	started.
+
+2010-09-15  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Fix handling of tool output.
+
+	The *StreamChanged event for ProcessWrapper may get parts of long
+	lines, so process the complete ones that we have (for matching
+	error/warning), and save rest for processing when the rest of it
+	is received.
+
+	Also, don't ignore empty lines.
+
+	*
+	class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
+
 2010-08-05  Ankit Jain  <radical at corewars.org>
 
 	[xbuild] Handle multi-line output from tool.
diff --git a/mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs b/mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
index 74e1b76..c2ccff4 100644
--- a/mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
+++ b/mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
@@ -46,7 +46,6 @@ namespace Microsoft.Build.Utilities
 {
 	public abstract class ToolTask : Task
 	{
-		SCS.ProcessStringDictionary	environmentOverride;
 		int			exitCode;
 		int			timeout;
 		string			toolPath, toolExe;
@@ -76,7 +75,6 @@ namespace Microsoft.Build.Utilities
 			this.toolPath = MonoLocationHelper.GetBinDir ();
 			this.responseFileEncoding = Encoding.UTF8;
 			this.timeout = Int32.MaxValue;
-			this.environmentOverride = new SCS.ProcessStringDictionary ();
 		}
 
 		[MonoTODO]
@@ -111,11 +109,8 @@ namespace Microsoft.Build.Utilities
 			if (pathToTool == null)
 				throw new ArgumentNullException ("pathToTool");
 
-			string output, error, responseFileName;
-			StreamWriter outwr, errwr;
-
-			outwr = errwr = null;
-			responseFileName = output = error = null;
+			string responseFileName;
+			responseFileName = null;
 			toolOutput = new StringBuilder ();
 
 			try {
@@ -129,11 +124,6 @@ namespace Microsoft.Build.Utilities
 				LogToolCommand (String.Format ("Tool {0} execution started with arguments: {1} {2}",
 						pathToTool, commandLineCommands, responseFileCommands));
 
-				output = Path.GetTempFileName ();
-				error = Path.GetTempFileName ();
-				outwr = new StreamWriter (output);
-				errwr = new StreamWriter (error);
-
 				ProcessStartInfo pinfo = new ProcessStartInfo (pathToTool, arguments);
 				pinfo.WorkingDirectory = GetWorkingDirectory () ?? Environment.CurrentDirectory;
 
@@ -141,15 +131,27 @@ namespace Microsoft.Build.Utilities
 				pinfo.RedirectStandardOutput = true;
 				pinfo.RedirectStandardError = true;
 
+				var pendingLineFragmentOutput = new StringBuilder ();
+				var pendingLineFragmentError = new StringBuilder ();
+				var environmentOverride = GetAndLogEnvironmentVariables ();
 				try {
-					ProcessWrapper pw = ProcessService.StartProcess (pinfo, outwr, errwr, null, environmentOverride);
-					pw.OutputStreamChanged += delegate (object o, string msg) { ProcessLine (msg, StandardOutputLoggingImportance); };
-					pw.ErrorStreamChanged += delegate (object o, string msg) { ProcessLine (msg, StandardErrorLoggingImportance); };
+					// When StartProcess returns, the process has already .Start()'ed
+					// If we subscribe to the events after that, then for processes that
+					// finish executing before we can subscribe, we won't get the output/err
+					// events at all!
+					ProcessWrapper pw = ProcessService.StartProcess (pinfo,
+							(_, msg) => ProcessLine (pendingLineFragmentOutput, msg, StandardOutputLoggingImportance),
+							(_, msg) => ProcessLine (pendingLineFragmentError, msg, StandardErrorLoggingImportance),
+							null,
+							environmentOverride);
+
+					pw.WaitForOutput (timeout == Int32.MaxValue ? Int32.MaxValue : timeout);
+
+					// Process any remaining line
+					ProcessLine (pendingLineFragmentOutput, StandardOutputLoggingImportance, true);
+					ProcessLine (pendingLineFragmentError, StandardErrorLoggingImportance, true);
 
-					pw.WaitForOutput (timeout == Int32.MaxValue ? -1 : timeout);
 					exitCode = pw.ExitCode;
-					outwr.Close();
-					errwr.Close();
 					pw.Dispose ();
 				} catch (System.ComponentModel.Win32Exception e) {
 					Log.LogError ("Error executing tool '{0}': {1}", pathToTool, e.Message);
@@ -159,17 +161,13 @@ namespace Microsoft.Build.Utilities
 				if (typeLoadException)
 					ProcessTypeLoadException ();
 
+				pendingLineFragmentOutput.Length = 0;
+				pendingLineFragmentError.Length = 0;
+
 				Log.LogMessage (MessageImportance.Low, "Tool {0} execution finished.", pathToTool);
 				return exitCode;
 			} finally {
 				DeleteTempFile (responseFileName);
-				if (outwr != null)
-					outwr.Dispose ();
-				if (errwr != null)
-					errwr.Dispose ();
-
-				DeleteTempFile (output);
-				DeleteTempFile (error);
 			}
 		}
 
@@ -192,9 +190,39 @@ namespace Microsoft.Build.Utilities
 			Log.LogError (output_str);
 		}
 
-		void ProcessLine (string line, MessageImportance importance)
+		void ProcessLine (StringBuilder outputBuilder, MessageImportance importance, bool isLastLine)
+		{
+			if (outputBuilder.Length == 0)
+				return;
+
+			if (isLastLine && !outputBuilder.ToString ().EndsWith (Environment.NewLine))
+				// last line, but w/o an trailing newline, so add that
+				outputBuilder.Append (Environment.NewLine);
+
+			ProcessLine (outputBuilder, null, importance);
+		}
+
+		void ProcessLine (StringBuilder outputBuilder, string line, MessageImportance importance)
 		{
-			foreach (string singleLine in line.Split (new string [] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)) {
+			// Add to any line fragment from previous call
+			if (line != null)
+				outputBuilder.Append (line);
+
+			// Don't remove empty lines!
+			var lines = outputBuilder.ToString ().Split (new string [] {Environment.NewLine}, StringSplitOptions.None);
+
+			// Clear the builder. If any incomplete line is found,
+			// then it will get added back
+			outputBuilder.Length = 0;
+			for (int i = 0; i < lines.Length; i ++) {
+				string singleLine = lines [i];
+				if (i == lines.Length - 1 && !singleLine.EndsWith (Environment.NewLine)) {
+					// Last line doesn't end in newline, could be part of
+					// a bigger line. Save for later processing
+					outputBuilder.Append (singleLine);
+					continue;
+				}
+
 				toolOutput.AppendLine (singleLine);
 
 				// in case of typeLoadException, collect all the output
@@ -206,9 +234,10 @@ namespace Microsoft.Build.Utilities
 
 		protected virtual void LogEventsFromTextOutput (string singleLine, MessageImportance importance)
 		{
-			singleLine = singleLine.Trim ();
-			if (singleLine.Length == 0)
+			if (singleLine.Length == 0) {
+				Log.LogMessage (singleLine, importance);
 				return;
+			}
 
 			if (singleLine.StartsWith ("Unhandled Exception: System.TypeLoadException") ||
 			    singleLine.StartsWith ("Unhandled Exception: System.IO.FileNotFoundException")) {
@@ -319,11 +348,50 @@ namespace Microsoft.Build.Utilities
 			}
 		}
 
+		// If EnvironmentVariables is defined, then merge EnvironmentOverride
+		// EnvironmentOverride is Obsolete'd in 4.0
+		//
+		// Returns the final set of environment variables and logs them
+		SCS.StringDictionary GetAndLogEnvironmentVariables ()
+		{
+			var env_vars = GetEnvironmentVariables ();
+			if (env_vars == null)
+				return env_vars;
+
+			Log.LogMessage (MessageImportance.Low, "Environment variables being passed to the tool:");
+			foreach (DictionaryEntry entry in env_vars)
+				Log.LogMessage (MessageImportance.Low, "\t{0}={1}", (string)entry.Key, (string)entry.Value);
+
+			return env_vars;
+		}
+
+		SCS.StringDictionary GetEnvironmentVariables ()
+		{
+			if (EnvironmentVariables == null || EnvironmentVariables.Length == 0)
+				return EnvironmentOverride;
+
+			var env_vars = new SCS.ProcessStringDictionary ();
+			foreach (string pair in EnvironmentVariables) {
+				string [] key_value = pair.Split ('=');
+				if (!String.IsNullOrEmpty (key_value [0]))
+					env_vars [key_value [0]] = key_value.Length > 1 ? key_value [1] : String.Empty;
+			}
+
+			if (EnvironmentOverride != null)
+				foreach (DictionaryEntry entry in EnvironmentOverride)
+					env_vars [(string)entry.Key] = (string)entry.Value;
+
+			return env_vars;
+		}
+
 		protected virtual StringDictionary EnvironmentOverride
 		{
-			get { return environmentOverride; }
+			get { return null; }
 		}
-		
+
+		// Ignore EnvironmentOverride if this is set
+		public string[] EnvironmentVariables { get; set; }
+
 		[Output]
 		public int ExitCode {
 			get { return exitCode; }
diff --git a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/ChangeLog b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/ChangeLog
index fbd23d3..0994bcf 100644
--- a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/ChangeLog
+++ b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/ChangeLog
@@ -1,3 +1,8 @@
+2010-11-03  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix encoding of large strings in the soft debugger api. Fixes
+	#648832.
+
 2010-09-13  Zoltan Varga  <vargaz at gmail.com>
 
 	Bump minor version to 2 to be compatible with the runtime.
diff --git a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs
index 9c25270..0a1999a 100644
--- a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs
+++ b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs
@@ -678,32 +678,48 @@ namespace Mono.Debugger.Soft
 			int offset;
 
 			public PacketWriter () {
-				// FIXME:
 				data = new byte [1024];
 				offset = 0;
 			}
 
+			void MakeRoom (int size) {
+				if (offset + size >= data.Length) {
+					int new_len = data.Length * 2;
+					while (new_len < offset + size) {
+						new_len *= 2;
+					}
+					byte[] new_data = new byte [new_len];
+					Array.Copy (data, new_data, data.Length);
+					data = new_data;
+				}
+			}
+
 			public PacketWriter WriteByte (byte val) {
+				MakeRoom (1);
 				encode_byte (data, val, ref offset);
 				return this;
 			}
 
 			public PacketWriter WriteInt (int val) {
+				MakeRoom (4);
 				encode_int (data, val, ref offset);
 				return this;
 			}
 
 			public PacketWriter WriteId (long id) {
+				MakeRoom (8);
 				encode_id (data, id, ref offset);
 				return this;
 			}
 
 			public PacketWriter WriteLong (long val) {
+				MakeRoom (8);
 				encode_long (data, val, ref offset);
 				return this;
 			}
 
 			public PacketWriter WriteFloat (float f) {
+				MakeRoom (8);
 				byte[] b = DataConverter.GetBytesBE (f);
 				for (int i = 0; i < 4; ++i)
 					data [offset + i] = b [i];
@@ -712,6 +728,7 @@ namespace Mono.Debugger.Soft
 			}
 
 			public PacketWriter WriteDouble (double d) {
+				MakeRoom (8);
 				byte[] b = DataConverter.GetBytesBE (d);
 				for (int i = 0; i < 8; ++i)
 					data [offset + i] = b [i];
@@ -734,6 +751,7 @@ namespace Mono.Debugger.Soft
 			public PacketWriter WriteString (string s) {
 				encode_int (data, s.Length, ref offset);
 				byte[] b = Encoding.UTF8.GetBytes (s);
+				MakeRoom (b.Length);
 				Buffer.BlockCopy (b, 0, data, offset, b.Length);
 				offset += b.Length;
 				return this;
diff --git a/mcs/class/Mono.Debugger.Soft/Test/ChangeLog b/mcs/class/Mono.Debugger.Soft/Test/ChangeLog
index e36de05..0ef327b 100644
--- a/mcs/class/Mono.Debugger.Soft/Test/ChangeLog
+++ b/mcs/class/Mono.Debugger.Soft/Test/ChangeLog
@@ -1,3 +1,17 @@
+2010-11-10  Zoltan Varga  <vargaz at gmail.com>
+
+	When single stepping from a exception throw site, single step to
+	the catch site. Fixes #652590.
+
+2010-11-05  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix gshared support in the soft debugger. Fixes #651251.
+
+2010-11-03  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix encoding of large strings in the soft debugger api. Fixes
+	#648832.
+
 2010-06-17  Zoltan Varga  <vargaz at gmail.com>
 
 	* dtest.cs: Add an EventSet test.
diff --git a/mcs/class/Mono.Debugger.Soft/Test/ChangeLog b/mcs/class/Mono.Debugger.Soft/Test/ChangeLog.old
similarity index 100%
copy from mcs/class/Mono.Debugger.Soft/Test/ChangeLog
copy to mcs/class/Mono.Debugger.Soft/Test/ChangeLog.old
diff --git a/mcs/class/Mono.Debugger.Soft/Test/dtest.cs b/mcs/class/Mono.Debugger.Soft/Test/dtest.cs
index 62d52df..8647a96 100644
--- a/mcs/class/Mono.Debugger.Soft/Test/dtest.cs
+++ b/mcs/class/Mono.Debugger.Soft/Test/dtest.cs
@@ -3,6 +3,7 @@ using System.Collections.Generic;
 using System.Threading;
 using System.Net;
 using System.Reflection;
+using System.Text;
 using Mono.Cecil.Cil;
 using Mono.Debugger.Soft;
 using Diag = System.Diagnostics;
@@ -93,7 +94,7 @@ public class DebuggerTests
 		}
 
 		Assert.IsInstanceOfType (typeof (BreakpointEvent), e);
-		Assert.AreEqual (m, (e as BreakpointEvent).Method);
+		Assert.AreEqual (m.Name, (e as BreakpointEvent).Method.Name);
 
 		return (e as BreakpointEvent);
 	}
@@ -885,7 +886,6 @@ public class DebuggerTests
 	}
 
 	[Test]
-	[Category ("only")]
 	public void Type_SetValue () {
 		var e = run_until ("o1");
 		var frame = e.Thread.GetFrames () [0];
@@ -1319,8 +1319,8 @@ public class DebuggerTests
 		StackFrame frame = e.Thread.GetFrames () [0];
 
 		var locals = frame.Method.GetLocals ();
-		Assert.AreEqual (5, locals.Length);
-		for (int i = 0; i < 5; ++i) {
+		Assert.AreEqual (6, locals.Length);
+		for (int i = 0; i < 6; ++i) {
 			if (locals [i].Name == "args") {
 				Assert.IsTrue (locals [i].IsArg);
 				Assert.AreEqual ("String[]", locals [i].Type.Name);
@@ -1336,6 +1336,10 @@ public class DebuggerTests
 			} else if (locals [i].Name == "s") {
 				Assert.IsFalse (locals [i].IsArg);
 				Assert.AreEqual ("String", locals [i].Type.Name);
+			} else if (locals [i].Name == "t") {
+				// gshared
+				Assert.IsTrue (locals [i].IsArg);
+				Assert.AreEqual ("String", locals [i].Type.Name);
 			} else {
 				Assert.Fail ();
 			}
@@ -1343,6 +1347,7 @@ public class DebuggerTests
 	}
 
 	[Test]
+	[Category ("only")]
 	public void Locals () {
 		var be = run_until ("locals1");
 
@@ -1385,6 +1390,8 @@ public class DebuggerTests
 				AssertValue (42, vals [i]);
 			if (locals [i].Name == "s")
 				AssertValue ("AB", vals [i]);
+			if (locals [i].Name == "t")
+				AssertValue ("ABC", vals [i]);
 		}
 
 		// Argument checking
@@ -1654,6 +1661,12 @@ public class DebuggerTests
 		Assert.AreEqual ("ABC", s.Value);
 		Assert.AreEqual (vm.RootDomain, s.Domain);
 
+		// Long strings
+		StringBuilder sb = new StringBuilder ();
+		for (int i = 0; i < 1024; ++i)
+			sb.Append ('A');
+		s = vm.RootDomain.CreateString (sb.ToString ());
+
 		// Argument checking
 		AssertThrows <ArgumentNullException> (delegate () {
 				s = vm.RootDomain.CreateString (null);
@@ -1661,7 +1674,6 @@ public class DebuggerTests
 	}
 
 	[Test]
-	[Category ("only")]
 	public void CreateBoxedValue () {
 		ObjectMirror o = vm.RootDomain.CreateBoxedValue (new PrimitiveValue (vm, 42));
 
@@ -1975,6 +1987,7 @@ public class DebuggerTests
 	}
 
 	[Test]
+	[Category ("only")]
 	public void Frame_SetValue () {
 		Event e = run_until ("locals2");
 
@@ -2000,6 +2013,11 @@ public class DebuggerTests
 		frame.SetValue (p, vm.CreateValue (7));
 		AssertValue (7, frame.GetValue (p));
 
+		// gshared
+		p = frame.Method.GetParameters ()[2];
+		frame.SetValue (p, vm.RootDomain.CreateString ("DEF"));
+		AssertValue ("DEF", frame.GetValue (p));
+
 		// argument checking
 
 		// variable null
@@ -2117,6 +2135,31 @@ public class DebuggerTests
 		Assert.AreEqual ("NullReferenceException", (e as ExceptionEvent).Exception.Type.Name);
 		req.Disable ();
 
+		// Single stepping after an exception
+		req = vm.CreateExceptionRequest (null);
+		req.Enable ();
+
+		vm.Resume ();
+
+		e = vm.GetNextEvent ();
+		Assert.IsInstanceOfType (typeof (ExceptionEvent), e);
+		Assert.AreEqual ("Exception", (e as ExceptionEvent).Exception.Type.Name);
+		frames = e.Thread.GetFrames ();
+		Assert.AreEqual ("exceptions2", frames [0].Method.Name);
+		req.Disable ();
+
+		var sreq = vm.CreateStepRequest (e.Thread);
+		sreq.Depth = StepDepth.Over;
+		sreq.Size = StepSize.Line;
+		sreq.Enable ();
+
+		vm.Resume ();
+		e = vm.GetNextEvent ();
+		Assert.IsInstanceOfType (typeof (StepEvent), e);
+		frames = e.Thread.GetFrames ();
+		Assert.AreEqual ("exceptions", frames [0].Method.Name);
+		sreq.Disable ();
+
 		// Argument checking
 		AssertThrows<ArgumentException> (delegate {
 				vm.CreateExceptionRequest (e.Thread.Type);
diff --git a/mcs/class/System.Configuration/System.Configuration/ChangeLog b/mcs/class/System.Configuration/System.Configuration/ChangeLog
index 43e7145..c4f69c9 100644
--- a/mcs/class/System.Configuration/System.Configuration/ChangeLog
+++ b/mcs/class/System.Configuration/System.Configuration/ChangeLog
@@ -1,3 +1,19 @@
+2010-10-04  Marek Habersack  <grendel at twistedcode.net>
+
+	[configuration] Part of fix for bug #579837.
+	CommaDelimitedStringCollection must properly note that it was
+	modified.
+
+	When one manipulates the collection as an instance of
+	StringCollection, the 'modified' field will not be set (Add,
+	Remove etc. from the underlying StringCollection type will be
+	used). To work around it a check has to be performed in IsModified
+	whether the contents of the collection changed. It is done by
+	comparing string hash codes of the original vs current string.
+	CommaDelimitedStringCollectionConverter forces string hash code
+	update on the new collection, so that IsModified works correctly
+	on collections converted from comma-delimited strings.
+
 2010-08-09  Laurent Etiemble  <laurent.etiemble at gmail.com>
 
 	*
diff --git a/mcs/class/System.Configuration/System.Configuration/CommaDelimitedStringCollection.cs b/mcs/class/System.Configuration/System.Configuration/CommaDelimitedStringCollection.cs
index b3cb6d4..d2ecc4a 100644
--- a/mcs/class/System.Configuration/System.Configuration/CommaDelimitedStringCollection.cs
+++ b/mcs/class/System.Configuration/System.Configuration/CommaDelimitedStringCollection.cs
@@ -39,9 +39,19 @@ namespace System.Configuration {
 
 		bool modified;
 		bool readOnly;
+		int originalStringHash = 0;
 
 		public bool IsModified {
-			get { return modified; }
+			get { 
+				if (modified)
+					return true;
+
+				string str = ToString ();
+				if (str == null)
+					return false;
+
+				return str.GetHashCode () != originalStringHash;
+			}
 		}
 
 		public new bool IsReadOnly {
@@ -89,6 +99,7 @@ namespace System.Configuration {
 			CopyTo (contents, 0);
 			
 			col.AddRange (contents);
+			col.originalStringHash = originalStringHash;
 
 			return col;
 		}
@@ -125,6 +136,15 @@ namespace System.Configuration {
 
 			return String.Join (",", contents);
 		}
+
+		internal void UpdateStringHash ()
+		{
+			string str = ToString ();
+			if (str == null)
+				originalStringHash = 0;
+			else
+				originalStringHash = str.GetHashCode ();
+		}
 	}
 
 }
diff --git a/mcs/class/System.Configuration/System.Configuration/CommaDelimitedStringCollectionConverter.cs b/mcs/class/System.Configuration/System.Configuration/CommaDelimitedStringCollectionConverter.cs
index 1ce8d3d..5959d1c 100644
--- a/mcs/class/System.Configuration/System.Configuration/CommaDelimitedStringCollectionConverter.cs
+++ b/mcs/class/System.Configuration/System.Configuration/CommaDelimitedStringCollectionConverter.cs
@@ -48,6 +48,7 @@ namespace System.Configuration
 			foreach (string datum in datums)
 				col.Add (datum.Trim());
 
+			col.UpdateStringHash ();
 			return col;
 		}
 
diff --git a/mcs/class/System.Drawing/ChangeLog b/mcs/class/System.Drawing/ChangeLog
index 8eed992..93ec348 100644
--- a/mcs/class/System.Drawing/ChangeLog
+++ b/mcs/class/System.Drawing/ChangeLog
@@ -1,3 +1,11 @@
+2010-10-29  Geoff Norton  <grompf at sublimeintervention.com>
+
+	[OSX] Reintroduce Cocoa System.Drawing support
+
+	The old Cocoa backend for System.Drawing appears to still work.
+	You must pass in a NSView.Handle while in the DrawRect method, or
+	with lockFocus called to prepare the NSGraphicsContext.
+
 2009-07-08  Carlos Alberto Cortez <calberto.cortez at gmail.com>
 
 	* System.Drawing_test.dll.sources: Add PageSourceTest.cs and
diff --git a/mcs/class/System.Drawing/ChangeLog b/mcs/class/System.Drawing/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Drawing/ChangeLog
copy to mcs/class/System.Drawing/ChangeLog.old
diff --git a/mcs/class/System.Drawing/System.Drawing.dll.sources b/mcs/class/System.Drawing/System.Drawing.dll.sources
index 8cc12e3..186f8e2 100755
--- a/mcs/class/System.Drawing/System.Drawing.dll.sources
+++ b/mcs/class/System.Drawing/System.Drawing.dll.sources
@@ -8,7 +8,7 @@ System.Drawing/BufferedGraphics.cs
 System.Drawing/BufferedGraphicsManager.cs
 System.Drawing/BufferedGraphicsContext.cs
 System.Drawing/CharacterRange.cs
-System.Drawing/carbonFunctions.cs
+System.Drawing/macFunctions.cs
 System.Drawing/ColorConverter.cs
 System.Drawing/Color.cs
 System.Drawing/ColorTranslator.cs
diff --git a/mcs/class/System.Drawing/System.Drawing/ChangeLog b/mcs/class/System.Drawing/System.Drawing/ChangeLog
index 3f744aa..7da80be 100644
--- a/mcs/class/System.Drawing/System.Drawing/ChangeLog
+++ b/mcs/class/System.Drawing/System.Drawing/ChangeLog
@@ -1,3 +1,11 @@
+2010-10-29  Geoff Norton  <grompf at sublimeintervention.com>
+
+	[OSX] Reintroduce Cocoa System.Drawing support
+
+	The old Cocoa backend for System.Drawing appears to still work.
+	You must pass in a NSView.Handle while in the DrawRect method, or
+	with lockFocus called to prepare the NSGraphicsContext.
+
 2010-07-19  Sebastien Pouliot  <sebastien at ximian.com>
 
 	* Icon.cs: Remove width==height check when deserializing (uncommon
diff --git a/mcs/class/System.Drawing/System.Drawing/ChangeLog b/mcs/class/System.Drawing/System.Drawing/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Drawing/System.Drawing/ChangeLog
copy to mcs/class/System.Drawing/System.Drawing/ChangeLog.old
diff --git a/mcs/class/System.Drawing/System.Drawing/Graphics.cs b/mcs/class/System.Drawing/System.Drawing/Graphics.cs
index 87b469b..b3153d8 100644
--- a/mcs/class/System.Drawing/System.Drawing/Graphics.cs
+++ b/mcs/class/System.Drawing/System.Drawing/Graphics.cs
@@ -49,7 +49,7 @@ namespace System.Drawing
 #endif
 	{
 		internal IntPtr nativeObject = IntPtr.Zero;
-		internal CarbonContext context;
+		internal IMacContext maccontext;
 		private bool disposed = false;
 		private static float defDpiX = 0;
 		private static float defDpiY = 0;
@@ -190,6 +190,8 @@ namespace System.Drawing
 				CopyFromScreenX11 (sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
 			} else if (GDIPlus.UseCarbonDrawable) {
 				CopyFromScreenMac (sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
+			} else if (GDIPlus.UseCocoaDrawable) {
+				CopyFromScreenMac (sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
 			} else {
 				CopyFromScreenWin32 (sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
 			}
@@ -293,11 +295,11 @@ namespace System.Drawing
 		{
 			Status status;
 			if (! disposed) {
-				if (GDIPlus.UseCarbonDrawable && context.ctx != IntPtr.Zero) {
+				if (GDIPlus.UseCarbonDrawable || GDIPlus.UseCocoaDrawable) {
 					Flush ();
-					Carbon.CGContextSynchronize (context.ctx);
-					Carbon.ReleaseContext (context.port, context.ctx);
+					maccontext.Release ();
 				}
+
 				status = GDIPlus.GdipDeleteGraphics (nativeObject);
 				nativeObject = IntPtr.Zero;
 				GDIPlus.CheckStatus (status);
@@ -1681,8 +1683,9 @@ namespace System.Drawing
 
 			Status status = GDIPlus.GdipFlush (nativeObject, intention);
                         GDIPlus.CheckStatus (status);                    
-			if (GDIPlus.UseCarbonDrawable && context.ctx != IntPtr.Zero)
-				Carbon.CGContextSynchronize (context.ctx);
+
+			if (maccontext != null)
+				maccontext.Synchronize ();
 		}
 
 		[EditorBrowsable (EditorBrowsableState.Advanced)]		
@@ -1714,12 +1717,22 @@ namespace System.Drawing
 		{
 			IntPtr graphics;
 
+			if (GDIPlus.UseCocoaDrawable) {
+				CocoaContext context = MacSupport.GetCGContextForNSView (hwnd);
+				GDIPlus.GdipCreateFromContext_macosx (context.ctx, context.width, context.height, out graphics);
+
+				Graphics g = new Graphics (graphics);
+				g.maccontext = context;
+
+				return g;
+			}
+
 			if (GDIPlus.UseCarbonDrawable) {
-				CarbonContext context = Carbon.GetCGContextForView (hwnd);
+				CarbonContext context = MacSupport.GetCGContextForView (hwnd);
 				GDIPlus.GdipCreateFromContext_macosx (context.ctx, context.width, context.height, out graphics);
 				
 				Graphics g = new Graphics (graphics);
-				g.context = context;
+				g.maccontext = context;
 				
 				return g;
 			}
diff --git a/mcs/class/System.Drawing/System.Drawing/carbonFunctions.cs b/mcs/class/System.Drawing/System.Drawing/carbonFunctions.cs
deleted file mode 100644
index 64a1452..0000000
--- a/mcs/class/System.Drawing/System.Drawing/carbonFunctions.cs
+++ /dev/null
@@ -1,307 +0,0 @@
-//
-// System.Drawing.carbonFunctions.cs
-//
-// Authors:
-//      Geoff Norton (gnorton at customerdna.com>
-//
-// Copyright (C) 2007 Novell, Inc. (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-#undef DEBUG_CLIPPING
-
-using System.Collections;
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Security;
-
-namespace System.Drawing {
-
-	[SuppressUnmanagedCodeSecurity]
-#if NET_2_0
-	internal static class Carbon {
-#else
-	internal sealed class Carbon {
-#endif
-		internal static Hashtable contextReference = new Hashtable ();
-		internal static object lockobj = new object ();
-
-		internal static Delegate hwnd_delegate;
-
-#if DEBUG_CLIPPING
-		internal static float red = 1.0f;
-		internal static float green = 0.0f;
-		internal static float blue = 0.0f;
-		internal static int debug_threshold = 1;
-#endif
-
-		static Carbon () {
-			foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ()) {
-				if (String.Equals (asm.GetName ().Name, "System.Windows.Forms")) {
-					Type driver_type = asm.GetType ("System.Windows.Forms.XplatUICarbon");
-					if (driver_type != null) {
-						hwnd_delegate = (Delegate) driver_type.GetField ("HwndDelegate", BindingFlags.NonPublic | BindingFlags.Static).GetValue (null);
-					}
-				}
-			}
-		}
-
-		internal static CarbonContext GetCGContextForView (IntPtr handle) {
-			IntPtr context = IntPtr.Zero;
-			IntPtr port = IntPtr.Zero;
-			IntPtr window = IntPtr.Zero;
-
-			window = GetControlOwner (handle);
-
-			if (handle == IntPtr.Zero || window == IntPtr.Zero) {
-				// FIXME: Can we actually get a CGContextRef for the desktop?  this makes context IntPtr.Zero
-				port = GetQDGlobalsThePort ();
-				CreateCGContextForPort (port, ref context);
-
-				Rect desktop_bounds = CGDisplayBounds (CGMainDisplayID ());
-
-				return new CarbonContext (port, context, (int)desktop_bounds.size.width, (int)desktop_bounds.size.height);
-			}
-
-			QDRect window_bounds = new QDRect ();
-			Rect view_bounds = new Rect ();
-
-			port = GetWindowPort (window);
-			
-			context = GetContext (port);
-
-			GetWindowBounds (window, 32, ref window_bounds);
-
-			HIViewGetBounds (handle, ref view_bounds);
-
-			HIViewConvertRect (ref view_bounds, handle, IntPtr.Zero);
-			
-			if (view_bounds.size.height < 0) view_bounds.size.height = 0;
-			if (view_bounds.size.width < 0) view_bounds.size.width = 0;
-
-			CGContextTranslateCTM (context, view_bounds.origin.x, (window_bounds.bottom - window_bounds.top) - (view_bounds.origin.y + view_bounds.size.height));
-
-			// Create the original rect path and clip to it
-			Rect rc_clip = new Rect (0, 0, view_bounds.size.width, view_bounds.size.height);
-
-			CGContextSaveGState (context);
-
-			Rectangle [] clip_rectangles = (Rectangle []) hwnd_delegate.DynamicInvoke (new object [] {handle});
-			if (clip_rectangles != null && clip_rectangles.Length > 0) {
-				int length = clip_rectangles.Length;
-				
-				CGContextBeginPath (context);
-				CGContextAddRect (context, rc_clip);
-
-				for (int i = 0; i < length; i++) {
-					CGContextAddRect (context, new Rect (clip_rectangles [i].X, view_bounds.size.height - clip_rectangles [i].Y - clip_rectangles [i].Height, clip_rectangles [i].Width, clip_rectangles [i].Height));
-				}
-				CGContextClosePath (context);
-				CGContextEOClip (context);
-#if DEBUG_CLIPPING
-				if (clip_rectangles.Length >= debug_threshold) {
-					CGContextSetRGBFillColor (context, red, green, blue, 0.5f);
-					CGContextFillRect (context, rc_clip);
-					CGContextFlush (context);
-					System.Threading.Thread.Sleep (500);
-					if (red == 1.0f) { red = 0.0f; blue = 1.0f; } 
-					else if (blue == 1.0f) { blue = 0.0f; green = 1.0f; } 
-					else if (green == 1.0f) { green = 0.0f; red = 1.0f; } 
-				}
-#endif
-			} else {
-				CGContextBeginPath (context);
-				CGContextAddRect (context, rc_clip);
-				CGContextClosePath (context);
-				CGContextClip (context);
-			}
-
-			return new CarbonContext (port, context, (int)view_bounds.size.width, (int)view_bounds.size.height);
-		}
-
-		internal static IntPtr GetContext (IntPtr port) {
-			IntPtr context = IntPtr.Zero;
-
-			lock (lockobj) { 
-#if FALSE
-				if (contextReference [port] != null) {
-					CreateCGContextForPort (port, ref context);
-				} else {
-					QDBeginCGContext (port, ref context);
-					contextReference [port] = context;
-				}
-#else
-				CreateCGContextForPort (port, ref context);
-#endif
-			}
-
-			return context;
-		}
-
-		internal static void ReleaseContext (IntPtr port, IntPtr context) {
-			CGContextRestoreGState (context);
-
-			lock (lockobj) { 
-#if FALSE
-				if (contextReference [port] != null && context == (IntPtr) contextReference [port]) { 
-					QDEndCGContext (port, ref context);
-					contextReference [port] = null;
-				} else {
-					CFRelease (context);
-				}
-#else
-				CFRelease (context);
-#endif
-			}
-		}
-
-		#region Cocoa Methods
-		[DllImport("libobjc.dylib")]
-		public static extern IntPtr objc_getClass(string className); 
-		[DllImport("libobjc.dylib")]
-		public static extern IntPtr objc_msgSend(IntPtr basePtr, IntPtr selector, string argument);  
-		[DllImport("libobjc.dylib")]
-		public static extern IntPtr objc_msgSend(IntPtr basePtr, IntPtr selector);        
-		[DllImport("libobjc.dylib")]
-		public static extern void objc_msgSend_stret(ref Rect arect, IntPtr basePtr, IntPtr selector);        
-		[DllImport("libobjc.dylib")]
-		public static extern IntPtr sel_registerName(string selectorName);         
-		#endregion
-
-		[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern IntPtr CGMainDisplayID ();
-		[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern Rect CGDisplayBounds (IntPtr display);
-
-		[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern int HIViewGetBounds (IntPtr vHnd, ref Rect r);
-		[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern int HIViewConvertRect (ref Rect r, IntPtr a, IntPtr b);
-
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern IntPtr GetControlOwner (IntPtr aView);
-
-		[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern int GetWindowBounds (IntPtr wHnd, uint reg, ref QDRect rect);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern IntPtr GetWindowPort (IntPtr hWnd);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern IntPtr GetQDGlobalsThePort ();
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CreateCGContextForPort (IntPtr port, ref IntPtr context);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CFRelease (IntPtr context);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void QDBeginCGContext (IntPtr port, ref IntPtr context);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void QDEndCGContext (IntPtr port, ref IntPtr context);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern int CGContextClipToRect (IntPtr context, Rect clip);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern int CGContextClipToRects (IntPtr context, Rect [] clip_rects, int count);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextTranslateCTM (IntPtr context, float tx, float ty);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextScaleCTM (IntPtr context, float x, float y);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextFlush (IntPtr context);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextSynchronize (IntPtr context);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern IntPtr CGPathCreateMutable ();
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGPathAddRects (IntPtr path, IntPtr _void, Rect [] rects, int count);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGPathAddRect (IntPtr path, IntPtr _void, Rect rect);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextAddRects (IntPtr context, Rect [] rects, int count);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextAddRect (IntPtr context, Rect rect);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextBeginPath (IntPtr context);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextClosePath (IntPtr context);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextAddPath (IntPtr context, IntPtr path);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextClip (IntPtr context);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextEOClip (IntPtr context);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextEOFillPath (IntPtr context);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextSaveGState (IntPtr context);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextRestoreGState (IntPtr context);
-
-#if DEBUG_CLIPPING
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextSetRGBFillColor (IntPtr context, float red, float green, float blue, float alpha);
-		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
-		internal static extern void CGContextFillRect (IntPtr context, Rect rect);
-#endif
-	}
-
-	internal struct CGSize {
-		public float width;
-		public float height;
-	}
-
-	internal struct CGPoint {
-		public float x;
-		public float y;
-	}
-
-	internal struct Rect {
-		public Rect (float x, float y, float width, float height) {
-			this.origin.x = x;
-			this.origin.y = y;
-			this.size.width = width;
-			this.size.height = height;
-		}
-
-		public CGPoint origin;
-		public CGSize size;
-	}
-
-	internal struct QDRect
-	{
-		public short top;
-		public short left;
-		public short bottom;
-		public short right;
-	}
-
-	internal struct CarbonContext
-	{
-		public IntPtr port;
-		public IntPtr ctx;
-		public int width;
-		public int height;
-
-		public CarbonContext (IntPtr port, IntPtr ctx, int width, int height)
-		{
-			this.port = port;
-			this.ctx = ctx;
-			this.width = width;
-			this.height = height;
-		}
-	}
-}
diff --git a/mcs/class/System.Drawing/System.Drawing/gdipFunctions.cs b/mcs/class/System.Drawing/System.Drawing/gdipFunctions.cs
index ec8839c..cf48ecd 100644
--- a/mcs/class/System.Drawing/System.Drawing/gdipFunctions.cs
+++ b/mcs/class/System.Drawing/System.Drawing/gdipFunctions.cs
@@ -61,6 +61,7 @@ namespace System.Drawing
 		public static IntPtr Display = IntPtr.Zero;
 		public static bool UseX11Drawable = false;
 		public static bool UseCarbonDrawable = false;
+		public static bool UseCocoaDrawable = false;
 
 		#region gdiplus.dll functions
 
@@ -138,12 +139,12 @@ namespace System.Drawing
 
 		static public bool RunningOnWindows ()
 		{
-			return !UseX11Drawable && !UseCarbonDrawable;
+			return !UseX11Drawable && !UseCarbonDrawable && !UseCocoaDrawable;
 		}
 
 		static public bool RunningOnUnix ()
 		{
-			return UseX11Drawable || UseCarbonDrawable;
+			return UseX11Drawable || UseCarbonDrawable || UseCocoaDrawable;
 		}
 		
 		// Copies a Ptr to an array of Points and releases the memory
diff --git a/mcs/class/System.Drawing/System.Drawing/macFunctions.cs b/mcs/class/System.Drawing/System.Drawing/macFunctions.cs
new file mode 100644
index 0000000..5860968
--- /dev/null
+++ b/mcs/class/System.Drawing/System.Drawing/macFunctions.cs
@@ -0,0 +1,356 @@
+//
+// System.Drawing.carbonFunctions.cs
+//
+// Authors:
+//      Geoff Norton (gnorton at customerdna.com>
+//
+// Copyright (C) 2007 Novell, Inc. (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+#undef DEBUG_CLIPPING
+
+using System.Collections;
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Security;
+
+namespace System.Drawing {
+
+	[SuppressUnmanagedCodeSecurity]
+#if NET_2_0
+	internal static class MacSupport {
+#else
+	internal sealed class MacSupport {
+#endif
+		internal static Hashtable contextReference = new Hashtable ();
+		internal static object lockobj = new object ();
+
+		internal static Delegate hwnd_delegate;
+
+#if DEBUG_CLIPPING
+		internal static float red = 1.0f;
+		internal static float green = 0.0f;
+		internal static float blue = 0.0f;
+		internal static int debug_threshold = 1;
+#endif
+
+		static MacSupport () {
+			foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ()) {
+				if (String.Equals (asm.GetName ().Name, "System.Windows.Forms")) {
+					Type driver_type = asm.GetType ("System.Windows.Forms.XplatUICarbon");
+					if (driver_type != null) {
+						hwnd_delegate = (Delegate) driver_type.GetField ("HwndDelegate", BindingFlags.NonPublic | BindingFlags.Static).GetValue (null);
+					}
+				}
+			}
+		}
+
+		internal static CocoaContext GetCGContextForNSView (IntPtr handle) {
+			IntPtr graphicsContext = objc_msgSend (objc_getClass ("NSGraphicsContext"), sel_registerName ("currentContext"));
+			IntPtr ctx = objc_msgSend (graphicsContext, sel_registerName ("graphicsPort"));
+			Rect bounds = new Rect ();
+
+			objc_msgSend_stret (ref bounds, handle, sel_registerName ("bounds"));
+
+			return new CocoaContext (ctx, (int) bounds.size.width, (int) bounds.size.height);
+		}
+
+		internal static CarbonContext GetCGContextForView (IntPtr handle) {
+			IntPtr context = IntPtr.Zero;
+			IntPtr port = IntPtr.Zero;
+			IntPtr window = IntPtr.Zero;
+
+			window = GetControlOwner (handle);
+
+			if (handle == IntPtr.Zero || window == IntPtr.Zero) {
+				// FIXME: Can we actually get a CGContextRef for the desktop?  this makes context IntPtr.Zero
+				port = GetQDGlobalsThePort ();
+				CreateCGContextForPort (port, ref context);
+
+				Rect desktop_bounds = CGDisplayBounds (CGMainDisplayID ());
+
+				return new CarbonContext (port, context, (int)desktop_bounds.size.width, (int)desktop_bounds.size.height);
+			}
+
+			QDRect window_bounds = new QDRect ();
+			Rect view_bounds = new Rect ();
+
+			port = GetWindowPort (window);
+			
+			context = GetContext (port);
+
+			GetWindowBounds (window, 32, ref window_bounds);
+
+			HIViewGetBounds (handle, ref view_bounds);
+
+			HIViewConvertRect (ref view_bounds, handle, IntPtr.Zero);
+			
+			if (view_bounds.size.height < 0) view_bounds.size.height = 0;
+			if (view_bounds.size.width < 0) view_bounds.size.width = 0;
+
+			CGContextTranslateCTM (context, view_bounds.origin.x, (window_bounds.bottom - window_bounds.top) - (view_bounds.origin.y + view_bounds.size.height));
+
+			// Create the original rect path and clip to it
+			Rect rc_clip = new Rect (0, 0, view_bounds.size.width, view_bounds.size.height);
+
+			CGContextSaveGState (context);
+
+			Rectangle [] clip_rectangles = (Rectangle []) hwnd_delegate.DynamicInvoke (new object [] {handle});
+			if (clip_rectangles != null && clip_rectangles.Length > 0) {
+				int length = clip_rectangles.Length;
+				
+				CGContextBeginPath (context);
+				CGContextAddRect (context, rc_clip);
+
+				for (int i = 0; i < length; i++) {
+					CGContextAddRect (context, new Rect (clip_rectangles [i].X, view_bounds.size.height - clip_rectangles [i].Y - clip_rectangles [i].Height, clip_rectangles [i].Width, clip_rectangles [i].Height));
+				}
+				CGContextClosePath (context);
+				CGContextEOClip (context);
+#if DEBUG_CLIPPING
+				if (clip_rectangles.Length >= debug_threshold) {
+					CGContextSetRGBFillColor (context, red, green, blue, 0.5f);
+					CGContextFillRect (context, rc_clip);
+					CGContextFlush (context);
+					System.Threading.Thread.Sleep (500);
+					if (red == 1.0f) { red = 0.0f; blue = 1.0f; } 
+					else if (blue == 1.0f) { blue = 0.0f; green = 1.0f; } 
+					else if (green == 1.0f) { green = 0.0f; red = 1.0f; } 
+				}
+#endif
+			} else {
+				CGContextBeginPath (context);
+				CGContextAddRect (context, rc_clip);
+				CGContextClosePath (context);
+				CGContextClip (context);
+			}
+
+			return new CarbonContext (port, context, (int)view_bounds.size.width, (int)view_bounds.size.height);
+		}
+
+		internal static IntPtr GetContext (IntPtr port) {
+			IntPtr context = IntPtr.Zero;
+
+			lock (lockobj) { 
+#if FALSE
+				if (contextReference [port] != null) {
+					CreateCGContextForPort (port, ref context);
+				} else {
+					QDBeginCGContext (port, ref context);
+					contextReference [port] = context;
+				}
+#else
+				CreateCGContextForPort (port, ref context);
+#endif
+			}
+
+			return context;
+		}
+
+		internal static void ReleaseContext (IntPtr port, IntPtr context) {
+			CGContextRestoreGState (context);
+
+			lock (lockobj) { 
+#if FALSE
+				if (contextReference [port] != null && context == (IntPtr) contextReference [port]) { 
+					QDEndCGContext (port, ref context);
+					contextReference [port] = null;
+				} else {
+					CFRelease (context);
+				}
+#else
+				CFRelease (context);
+#endif
+			}
+		}
+
+		#region Cocoa Methods
+		[DllImport("libobjc.dylib")]
+		public static extern IntPtr objc_getClass(string className); 
+		[DllImport("libobjc.dylib")]
+		public static extern IntPtr objc_msgSend(IntPtr basePtr, IntPtr selector, string argument);  
+		[DllImport("libobjc.dylib")]
+		public static extern IntPtr objc_msgSend(IntPtr basePtr, IntPtr selector);        
+		[DllImport("libobjc.dylib")]
+		public static extern void objc_msgSend_stret(ref Rect arect, IntPtr basePtr, IntPtr selector);        
+		[DllImport("libobjc.dylib")]
+		public static extern IntPtr sel_registerName(string selectorName);         
+		#endregion
+
+		[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern IntPtr CGMainDisplayID ();
+		[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern Rect CGDisplayBounds (IntPtr display);
+
+		[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern int HIViewGetBounds (IntPtr vHnd, ref Rect r);
+		[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern int HIViewConvertRect (ref Rect r, IntPtr a, IntPtr b);
+
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern IntPtr GetControlOwner (IntPtr aView);
+
+		[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern int GetWindowBounds (IntPtr wHnd, uint reg, ref QDRect rect);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern IntPtr GetWindowPort (IntPtr hWnd);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern IntPtr GetQDGlobalsThePort ();
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CreateCGContextForPort (IntPtr port, ref IntPtr context);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CFRelease (IntPtr context);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void QDBeginCGContext (IntPtr port, ref IntPtr context);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void QDEndCGContext (IntPtr port, ref IntPtr context);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern int CGContextClipToRect (IntPtr context, Rect clip);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern int CGContextClipToRects (IntPtr context, Rect [] clip_rects, int count);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextTranslateCTM (IntPtr context, float tx, float ty);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextScaleCTM (IntPtr context, float x, float y);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextFlush (IntPtr context);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextSynchronize (IntPtr context);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern IntPtr CGPathCreateMutable ();
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGPathAddRects (IntPtr path, IntPtr _void, Rect [] rects, int count);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGPathAddRect (IntPtr path, IntPtr _void, Rect rect);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextAddRects (IntPtr context, Rect [] rects, int count);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextAddRect (IntPtr context, Rect rect);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextBeginPath (IntPtr context);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextClosePath (IntPtr context);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextAddPath (IntPtr context, IntPtr path);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextClip (IntPtr context);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextEOClip (IntPtr context);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextEOFillPath (IntPtr context);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextSaveGState (IntPtr context);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextRestoreGState (IntPtr context);
+
+#if DEBUG_CLIPPING
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextSetRGBFillColor (IntPtr context, float red, float green, float blue, float alpha);
+		[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+		internal static extern void CGContextFillRect (IntPtr context, Rect rect);
+#endif
+	}
+
+	internal struct CGSize {
+		public float width;
+		public float height;
+	}
+
+	internal struct CGPoint {
+		public float x;
+		public float y;
+	}
+
+	internal struct Rect {
+		public Rect (float x, float y, float width, float height) {
+			this.origin.x = x;
+			this.origin.y = y;
+			this.size.width = width;
+			this.size.height = height;
+		}
+
+		public CGPoint origin;
+		public CGSize size;
+	}
+
+	internal struct QDRect
+	{
+		public short top;
+		public short left;
+		public short bottom;
+		public short right;
+	}
+
+	internal struct CarbonContext : IMacContext
+	{
+		public IntPtr port;
+		public IntPtr ctx;
+		public int width;
+		public int height;
+
+		public CarbonContext (IntPtr port, IntPtr ctx, int width, int height)
+		{
+			this.port = port;
+			this.ctx = ctx;
+			this.width = width;
+			this.height = height;
+		}
+
+		public void Synchronize ()
+		{
+			MacSupport.CGContextSynchronize (ctx);
+		}
+
+		public void Release ()
+		{
+			MacSupport.ReleaseContext (port, ctx);
+		}
+	}
+
+	internal struct CocoaContext : IMacContext
+	{
+		public IntPtr ctx;
+		public int width;
+		public int height;
+
+		public CocoaContext (IntPtr ctx, int width, int height)
+		{
+			this.ctx = ctx;
+			this.width = width;
+			this.height = height;
+		}
+
+		public void Synchronize ()
+		{
+			MacSupport.CGContextSynchronize (ctx);
+		}
+
+		public void Release ()
+		{
+		}
+	}
+
+	internal interface IMacContext
+	{
+		void Synchronize ();
+		void Release ();
+	}
+}
diff --git a/mcs/class/System.Json/System.Json/ChangeLog b/mcs/class/System.Json/System.Json/ChangeLog
index e1c7496..47e79e8 100644
--- a/mcs/class/System.Json/System.Json/ChangeLog
+++ b/mcs/class/System.Json/System.Json/ChangeLog
@@ -1,3 +1,11 @@
+2010-10-14  Jb Evain  <jbevain at gmail.com>
+
+	Add pretty print support for null values in JsonObjects
+
+2010-10-14  Jb Evain  <jbevain at gmail.com>
+
+	Allow null values in JsonObjects
+
 2010-08-11  Jb Evain  <jbevain at gmail.com>
 
 	[hygiene] simplify the code dealing with internal collections
diff --git a/mcs/class/System.Json/System.Json/JsonObject.cs b/mcs/class/System.Json/System.Json/JsonObject.cs
index 6b6373d..33177b1 100644
--- a/mcs/class/System.Json/System.Json/JsonObject.cs
+++ b/mcs/class/System.Json/System.Json/JsonObject.cs
@@ -66,8 +66,6 @@ namespace System.Json
 		{
 			if (key == null)
 				throw new ArgumentNullException ("key");
-			if (value == null)
-				throw new ArgumentNullException ("value");
 
 			map.Add (key, value);
 		}
@@ -143,7 +141,13 @@ namespace System.Json
 				stream.WriteByte ((byte) '"');
 				stream.WriteByte ((byte) ',');
 				stream.WriteByte ((byte) ' ');
-				pair.Value.Save (stream);
+				if (pair.Value == null) {
+					stream.WriteByte ((byte) 'n');
+					stream.WriteByte ((byte) 'u');
+					stream.WriteByte ((byte) 'l');
+					stream.WriteByte ((byte) 'l');
+				} else
+					pair.Value.Save (stream);
 			}
 			stream.WriteByte ((byte) '}');
 		}
diff --git a/mcs/class/System.Json/System.Json/JsonValue.cs b/mcs/class/System.Json/System.Json/JsonValue.cs
index 7b7d9a3..5ca044b 100644
--- a/mcs/class/System.Json/System.Json/JsonValue.cs
+++ b/mcs/class/System.Json/System.Json/JsonValue.cs
@@ -148,7 +148,10 @@ namespace System.Json
 					w.Write ('\"');
 					w.Write (EscapeString (pair.Key));
 					w.Write ("\": ");
-					pair.Value.SaveInternal (w);
+					if (pair.Value == null)
+						w.Write ("null");
+					else
+						pair.Value.SaveInternal (w);
 					following = true;
 				}
 				w.Write ('}');
diff --git a/mcs/class/System.ServiceModel.Web/System.ServiceModel.Description/ChangeLog b/mcs/class/System.ServiceModel.Web/System.ServiceModel.Description/ChangeLog
index ddf89a1..562b2d5 100644
--- a/mcs/class/System.ServiceModel.Web/System.ServiceModel.Description/ChangeLog
+++ b/mcs/class/System.ServiceModel.Web/System.ServiceModel.Description/ChangeLog
@@ -1,3 +1,21 @@
+2010-10-20  Marek Habersack  <grendel at twistedcode.net>
+
+	[wcf] make /js and /jsdebug dispatchers work.
+
+	There were several issues here:
+
+	- The IChannelDispatcherBoundListener was defined twice, in two
+	different namespaces, and it caused code in
+	ChannelDispatcher.Attach not to set its associated listener's
+	ChannelDispatcher property to the correct value. This, in turn,
+	caused incorrect HttpListenerManagerTable operation, where it
+	would put the "/js" and "/jsdebug" dispatchers in separate
+	HttpListenerManagers, instead of in the main (base) service's one.
+	- After fixing the above, it turned out that SvcHttpHandler
+	selected the manager based on the host's base address, when it
+	should first try to find one whose URL matches the current request
+	exactly.
+
 2010-08-11  Jb Evain  <jbevain at gmail.com>
 
 	fix the net_2_1 build
diff --git a/mcs/class/System.ServiceModel.Web/System.ServiceModel.Description/WebScriptEnablingBehavior.cs b/mcs/class/System.ServiceModel.Web/System.ServiceModel.Description/WebScriptEnablingBehavior.cs
index 1ec0819..4479f21 100644
--- a/mcs/class/System.ServiceModel.Web/System.ServiceModel.Description/WebScriptEnablingBehavior.cs
+++ b/mcs/class/System.ServiceModel.Web/System.ServiceModel.Description/WebScriptEnablingBehavior.cs
@@ -107,8 +107,8 @@ namespace System.ServiceModel.Description
 			var uri = new Uri (String.Concat (baseUriString, baseUriString [baseUriString.Length - 1] == '/' ? String.Empty : "/", subPath));
 			var listener = endpoint.Binding.BuildChannelListener<IReplyChannel> (uri);
 			var cd = new ChannelDispatcher (listener, String.Empty);
-			cd.MessageVersion = MessageVersion.None;
 
+			cd.MessageVersion = MessageVersion.None;
 			cd.Endpoints.Add (new EndpointDispatcher (new EndpointAddress (uri), "InteropScriptService", String.Empty)
 				{ ContractFilter = new MatchAllMessageFilter () });
 
diff --git a/mcs/class/System.ServiceModel/ChangeLog b/mcs/class/System.ServiceModel/ChangeLog
old mode 100755
new mode 100644
index 7934c6b..3a1b24a
--- a/mcs/class/System.ServiceModel/ChangeLog
+++ b/mcs/class/System.ServiceModel/ChangeLog
@@ -1,3 +1,21 @@
+2010-10-20  Marek Habersack  <grendel at twistedcode.net>
+
+	[wcf] make /js and /jsdebug dispatchers work.
+
+	There were several issues here:
+
+	- The IChannelDispatcherBoundListener was defined twice, in two
+	different namespaces, and it caused code in
+	ChannelDispatcher.Attach not to set its associated listener's
+	ChannelDispatcher property to the correct value. This, in turn,
+	caused incorrect HttpListenerManagerTable operation, where it
+	would put the "/js" and "/jsdebug" dispatchers in separate
+	HttpListenerManagers, instead of in the main (base) service's one.
+	- After fixing the above, it turned out that SvcHttpHandler
+	selected the manager based on the host's base address, when it
+	should first try to find one whose URL matches the current request
+	exactly.
+
 2010-07-30  Astushi Enomoto  <atsushi at ximian.com>
 
 	* System.ServiceModel.dll.sources: add 4.0 standard endpoint types.
diff --git a/mcs/class/System.ServiceModel/ChangeLog b/mcs/class/System.ServiceModel/ChangeLog.old
similarity index 100%
copy from mcs/class/System.ServiceModel/ChangeLog
copy to mcs/class/System.ServiceModel/ChangeLog.old
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Channels.Http/ChangeLog b/mcs/class/System.ServiceModel/System.ServiceModel.Channels.Http/ChangeLog
index 1d5da6e..b6234d5 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Channels.Http/ChangeLog
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Channels.Http/ChangeLog
@@ -1,3 +1,35 @@
+2010-10-20  Marek Habersack  <grendel at twistedcode.net>
+
+	[wcf] make /js and /jsdebug dispatchers work.
+
+	There were several issues here:
+
+	- The IChannelDispatcherBoundListener was defined twice, in two
+	different namespaces, and it caused code in
+	ChannelDispatcher.Attach not to set its associated listener's
+	ChannelDispatcher property to the correct value. This, in turn,
+	caused incorrect HttpListenerManagerTable operation, where it
+	would put the "/js" and "/jsdebug" dispatchers in separate
+	HttpListenerManagers, instead of in the main (base) service's one.
+	- After fixing the above, it turned out that SvcHttpHandler
+	selected the manager based on the host's base address, when it
+	should first try to find one whose URL matches the current request
+	exactly.
+
+2010-10-18  Marek Habersack  <grendel at twistedcode.net>
+
+	[wcf] Don't close HTTP response prematurely.
+
+	Service is invoked in the context of the System.Web pipeline and
+	closing the response before the final output stream flush causes
+	the generated response not to ever reach the client. This patch
+	makes sure the System.Web pipeline takes care of all the response
+	housekeeping.
+
+2010-10-01  Atsushi Eno  <atsushi at ximian.com>
+
+	Remove extra call to HttpResponse.Flush() which would crash.
+
 2010-08-30  Atsushi Eno  <atsushi at ximian.com>
 
 	Add not-working code for TransferMode support.
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Channels.Http/HttpChannelListener.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Channels.Http/HttpChannelListener.cs
index 4edaeaf..55b523b 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Channels.Http/HttpChannelListener.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Channels.Http/HttpChannelListener.cs
@@ -40,11 +40,6 @@ using System.Threading;
 
 namespace System.ServiceModel.Channels.Http
 {
-	internal interface IChannelDispatcherBoundListener
-	{
-		ChannelDispatcher ChannelDispatcher { get; set; }
-	}
-
 	internal class HttpChannelListener<TChannel> : InternalChannelListenerBase<TChannel>, IChannelDispatcherBoundListener
 		where TChannel : class, IChannel
 	{
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Channels.Http/HttpContextInfo.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Channels.Http/HttpContextInfo.cs
index 5e21c07..6dad9d9 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Channels.Http/HttpContextInfo.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Channels.Http/HttpContextInfo.cs
@@ -325,14 +325,15 @@ namespace System.ServiceModel.Channels.Http
 		
 		public override void Abort ()
 		{
-			res.Flush ();
-			res.Close ();
+			res.End ();
 		}
 		
 		public override void Close ()
 		{
-			res.Flush ();
-			res.Close ();
+			// We must not close the response here, as everything is taking place in the
+			// HttpApplication's pipeline context and the output is sent to the client
+			// _after_ we leave this method. Closing the response here will stop any
+			// output from reaching the client.
 		}
 		
 		public override void SetLength (long value)
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/ChangeLog b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/ChangeLog
index 11956c9..338daa4 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/ChangeLog
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/ChangeLog
@@ -1,3 +1,25 @@
+2010-10-20  Marek Habersack  <grendel at twistedcode.net>
+
+	[wcf] make /js and /jsdebug dispatchers work.
+
+	There were several issues here:
+
+	- The IChannelDispatcherBoundListener was defined twice, in two
+	different namespaces, and it caused code in
+	ChannelDispatcher.Attach not to set its associated listener's
+	ChannelDispatcher property to the correct value. This, in turn,
+	caused incorrect HttpListenerManagerTable operation, where it
+	would put the "/js" and "/jsdebug" dispatchers in separate
+	HttpListenerManagers, instead of in the main (base) service's one.
+	- After fixing the above, it turned out that SvcHttpHandler
+	selected the manager based on the host's base address, when it
+	should first try to find one whose URL matches the current request
+	exactly.
+
+2010-10-18  Marek Habersack  <grendel at twistedcode.net>
+
+	[wcf] ServiceHost directive can span several lines.
+
 2010-09-29  Alan McGovern  <alan.mcgovern at gmail.com>
 
 	[System.ServiceModel] Fix a few potential exceptions in background
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/ServiceHostParser.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/ServiceHostParser.cs
index c91ef5e..e749fe1 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/ServiceHostParser.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/ServiceHostParser.cs
@@ -99,16 +99,43 @@ namespace System.ServiceModel.Channels {
 				string line;
 				bool directive_found = false;
 				StringBuilder content = new StringBuilder ();
-					
+				StringBuilder directiveBuffer = null;
+
 				while ((line = reader.ReadLine ()) != null) {
 					string trimmed = line.Trim ();
-					if (!directive_found && trimmed == String.Empty)
+					if (!directive_found && trimmed.Length == 0)
 						continue;
-					
+
 					if (trimmed.StartsWith ("<%@")) {
+						int directiveEnd = trimmed.IndexOf ("%>");
+
+						if (directiveEnd == -1) {
+							if (directiveBuffer == null)
+								directiveBuffer = new StringBuilder ();
+							directiveBuffer.Append (line);
+							continue;
+						}
+
 						ParseDirective (trimmed);
 						directive_found = true;
 						continue;
+					} else if (!directive_found && directiveBuffer != null) {
+						int directiveEnd = trimmed.IndexOf ("%>");
+						if (directiveEnd == -1) {
+							directiveBuffer.Append (trimmed);
+							continue;
+						}
+
+						directiveEnd += 2;
+						int tlen = trimmed.Length;
+						if (tlen > directiveEnd)
+							content.Append (trimmed.Substring (directiveEnd) + "\n");
+
+						directiveBuffer.Append (trimmed.Substring (0, directiveEnd));
+						ParseDirective (directiveBuffer.ToString ());
+						directive_found = true;
+						directiveBuffer = null;
+						continue;
 					}
 
 					content.Append (line + "\n");
@@ -119,7 +146,7 @@ namespace System.ServiceModel.Channels {
 					throw new Exception ("No @ServiceHost directive found");
 
 				this.program = content.ToString ().Trim ();
-				if (this.program.Trim () == "")
+				if (this.program.Trim ().Length == 0)
 					this.program = null;
 			}
 
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/SvcHttpHandler.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/SvcHttpHandler.cs
index 54b8233..df75fd2 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/SvcHttpHandler.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/SvcHttpHandler.cs
@@ -75,7 +75,9 @@ namespace System.ServiceModel.Channels
 			EnsureServiceHost ();
 
 			var table = HttpListenerManagerTable.GetOrCreate (host);
-			var manager = table.GetOrCreateManager (host.BaseAddresses [0]);
+			var manager = table.GetOrCreateManager (context.Request.Url);
+			if (manager == null)
+				manager = table.GetOrCreateManager (host.BaseAddresses [0]);
 			var wait = new ManualResetEvent (false);
 			wcf_wait_handles [context] = wait;
 			manager.ProcessNewContext (new System.ServiceModel.Channels.Http.AspNetHttpContextInfo (this, context));
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChangeLog b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChangeLog
index b2fedae..0aa87f3 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChangeLog
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChangeLog
@@ -1,3 +1,21 @@
+2010-10-20  Marek Habersack  <grendel at twistedcode.net>
+
+	[wcf] make /js and /jsdebug dispatchers work.
+
+	There were several issues here:
+
+	- The IChannelDispatcherBoundListener was defined twice, in two
+	different namespaces, and it caused code in
+	ChannelDispatcher.Attach not to set its associated listener's
+	ChannelDispatcher property to the correct value. This, in turn,
+	caused incorrect HttpListenerManagerTable operation, where it
+	would put the "/js" and "/jsdebug" dispatchers in separate
+	HttpListenerManagers, instead of in the main (base) service's one.
+	- After fixing the above, it turned out that SvcHttpHandler
+	selected the manager based on the host's base address, when it
+	should first try to find one whose URL matches the current request
+	exactly.
+
 2010-07-12  Atsushi Enomoto  <atsushi at ximian.com>
 
 	* InputOrReplyProcessor.cs : remove SecurityHandler. WS-Trust must
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChangeLog b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChangeLog.old
similarity index 100%
copy from mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChangeLog
copy to mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChangeLog.old
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChannelDispatcher.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChannelDispatcher.cs
index d71d76d..2b6aa8b 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChannelDispatcher.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChannelDispatcher.cs
@@ -37,11 +37,6 @@ using System.ServiceModel.Description;
 
 namespace System.ServiceModel.Dispatcher
 {
-	internal interface IChannelDispatcherBoundListener
-	{
-		ChannelDispatcher ChannelDispatcher { get; set; }
-	}
-
 	public class ChannelDispatcher : ChannelDispatcherBase
 	{
 		class EndpointDispatcherCollection : SynchronizedCollection<EndpointDispatcher>
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/IChannelDispatcherBoundListener.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/IChannelDispatcherBoundListener.cs
new file mode 100644
index 0000000..71fae23
--- /dev/null
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/IChannelDispatcherBoundListener.cs
@@ -0,0 +1,36 @@
+//
+// ChannelDispatcher.cs
+//
+// Author:
+//	Atsushi Enomoto <atsushi at ximian.com>
+//
+// Copyright (C) 2005-2010 Novell, Inc.  http://www.novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.ServiceModel.Dispatcher
+{
+	internal interface IChannelDispatcherBoundListener
+	{
+		ChannelDispatcher ChannelDispatcher { get; set; }
+	}
+}
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.dll.sources b/mcs/class/System.ServiceModel/System.ServiceModel.dll.sources
index 344ac16..6596809 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.dll.sources
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.dll.sources
@@ -643,6 +643,7 @@ System.ServiceModel.Dispatcher/FaultContractInfo.cs
 System.ServiceModel.Dispatcher/FilterInvalidBodyAccessException.cs
 System.ServiceModel.Dispatcher/FinalizeProcessingHandler.cs
 System.ServiceModel.Dispatcher/ICallContextInitializer.cs
+System.ServiceModel.Dispatcher/IChannelDispatcherBoundListener.cs
 System.ServiceModel.Dispatcher/IChannelInitializer.cs
 System.ServiceModel.Dispatcher/IClientMessageFormatter.cs
 System.ServiceModel.Dispatcher/IClientMessageInspector.cs
diff --git a/mcs/class/System.Web.Extensions/ChangeLog b/mcs/class/System.Web.Extensions/ChangeLog
index fb1db89..fbaf276 100644
--- a/mcs/class/System.Web.Extensions/ChangeLog
+++ b/mcs/class/System.Web.Extensions/ChangeLog
@@ -1,3 +1,8 @@
+2010-10-12  Sebastien Pouliot  <sebastien at ximian.com>
+
+	Adjust System.Web.Extensions[_1.0].dll.sources wrt
+	MachineKeySectionUtils.cs move
+
 2010-04-28  Marek Habersack  <mhabersack at novell.com>
 
 	* Makefile (OTHER_LIB_MCS_FLAGS): added a reference to
diff --git a/mcs/class/System.Web.Extensions/ChangeLog b/mcs/class/System.Web.Extensions/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Web.Extensions/ChangeLog
copy to mcs/class/System.Web.Extensions/ChangeLog.old
diff --git a/mcs/class/System.Web.Extensions/System.Web.Extensions.dll.sources b/mcs/class/System.Web.Extensions/System.Web.Extensions.dll.sources
index 2c8b100..6709235 100644
--- a/mcs/class/System.Web.Extensions/System.Web.Extensions.dll.sources
+++ b/mcs/class/System.Web.Extensions/System.Web.Extensions.dll.sources
@@ -1,7 +1,7 @@
 ../../build/common/Consts.cs
 ../../build/common/Locale.cs
 ../../build/common/MonoTODOAttribute.cs
-../System.Web/System.Web.Configuration_2.0/MachineKeySectionUtils.cs
+../System.Web/System.Web.Util/MachineKeySectionUtils.cs
 ../System.Web/System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs
 ../System.Web/System.Web.Handlers/AssemblyResourceLoader.cs
 ./Assembly/AssemblyInfo.cs
diff --git a/mcs/class/System.Web.Extensions/System.Web.Script.Services/ChangeLog b/mcs/class/System.Web.Extensions/System.Web.Script.Services/ChangeLog
index 9b88d18..0049e6d 100644
--- a/mcs/class/System.Web.Extensions/System.Web.Script.Services/ChangeLog
+++ b/mcs/class/System.Web.Extensions/System.Web.Script.Services/ChangeLog
@@ -1,3 +1,10 @@
+2010-10-20  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net,wcf] WCF proxies are generated using a slightly different
+	mode of operation.
+
+	WCF proxies don't include full namespace of the contract.
+
 2010-01-18  Marek Habersack  <mhabersack at novell.com>
 
 	* LogicalTypeInfo.cs: partial revert of r146546. The 'd' wrapper
diff --git a/mcs/class/System.Web.Extensions/System.Web.Script.Services/ChangeLog b/mcs/class/System.Web.Extensions/System.Web.Script.Services/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Web.Extensions/System.Web.Script.Services/ChangeLog
copy to mcs/class/System.Web.Extensions/System.Web.Script.Services/ChangeLog.old
diff --git a/mcs/class/System.Web.Extensions/System.Web.Script.Services/LogicalTypeInfo.cs b/mcs/class/System.Web.Extensions/System.Web.Script.Services/LogicalTypeInfo.cs
index dcf3981..b31ece2 100644
--- a/mcs/class/System.Web.Extensions/System.Web.Script.Services/LogicalTypeInfo.cs
+++ b/mcs/class/System.Web.Extensions/System.Web.Script.Services/LogicalTypeInfo.cs
@@ -72,11 +72,13 @@ namespace System.Web.Script.Services
 			readonly MethodInfo _methodInfo;
 			internal readonly ParameterInfo [] _params;
 			internal readonly Dictionary<string, int> _paramMap;
+			LogicalTypeInfo _typeInfo;
 
 			protected LogicalMethodInfo (LogicalTypeInfo typeInfo, MethodInfo method)
 			{
 				_methodInfo = method;
 				_params = MethodInfo.GetParameters ();
+				_typeInfo = typeInfo;
 
 				if (HasParameters) {
 					_paramMap = new Dictionary<string, int> (_params.Length, StringComparer.Ordinal);
@@ -101,8 +103,10 @@ namespace System.Web.Script.Services
 			}
 
 			public void GenerateMethod (StringBuilder proxy, bool isPrototype, bool isPage) {
-				string service = isPage ? "PageMethods" : MethodInfo.DeclaringType.FullName;
+				string ns;
+				string service;// = isPage ? "PageMethods" : MethodInfo.DeclaringType.FullName;
 
+				_typeInfo.GetNamespaceAndServiceName (MethodInfo.DeclaringType, isPage, out ns, out service);
 				string useHttpGet = UseHttpGet ? "true" : "false";
 				string paramMap = GenerateParameters (true);
 				string paramList = GenerateParameters (false);
@@ -187,6 +191,12 @@ Type.registerNamespace('{0}');",
 			return name;
 		}
 
+		protected virtual void GetNamespaceAndServiceName (Type type, bool isPage, out string ns, out string service)
+		{
+			ns = isPage ? String.Empty : type.Namespace;
+			service = isPage ? "PageMethods" : type.FullName;
+		}
+
 		// instance members
 
 		internal readonly Type _type;
@@ -205,8 +215,9 @@ Type.registerNamespace('{0}');",
 			for (int i = 0; i < logicalMethods.Count; i++)
 				_methodMap.Add (logicalMethods [i].MethodName, logicalMethods [i]);
 
-			string ns = isPage ? String.Empty : t.Namespace;
-			string service = isPage ? "PageMethods" : t.FullName;
+			string ns;
+			string service;
+			GetNamespaceAndServiceName (t, isPage, out ns, out service);
 			
 			StringBuilder proxy = new StringBuilder ();
 			List<string> registeredNamespaces = new List<string> ();
@@ -616,6 +627,16 @@ var gtc = Sys.Net.WebServiceProxy._generateTypedConstructor;");
 			yield break;
 		}
 
+		protected override void GetNamespaceAndServiceName (Type type, bool isPage, out string ns, out string service)
+		{
+			string name = type.Namespace;
+			int dot = name.LastIndexOf ('.');
+			if (dot > -1)
+				name = name.Substring (dot + 1);
+			ns = name;
+			service = name + "." + type.Name;
+		}
+
 		protected override void GenerateTypeRegistrationScript (StringBuilder proxy, List<string> registeredNamespaces)
 		{
 			bool gtc = false;
diff --git a/mcs/class/System.Web.Extensions_1.0/ChangeLog b/mcs/class/System.Web.Extensions_1.0/ChangeLog
index 62e8641..4388441 100644
--- a/mcs/class/System.Web.Extensions_1.0/ChangeLog
+++ b/mcs/class/System.Web.Extensions_1.0/ChangeLog
@@ -1,3 +1,8 @@
+2010-10-12  Sebastien Pouliot  <sebastien at ximian.com>
+
+	Adjust System.Web.Extensions[_1.0].dll.sources wrt
+	MachineKeySectionUtils.cs move
+
 2008-12-05  Marek Habersack  <mhabersack at novell.com>
 
 	* Makefile (LIB_MCS_FLAGS): do not reference System.Core
diff --git a/mcs/class/System.Web.Extensions_1.0/ChangeLog b/mcs/class/System.Web.Extensions_1.0/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Web.Extensions_1.0/ChangeLog
copy to mcs/class/System.Web.Extensions_1.0/ChangeLog.old
diff --git a/mcs/class/System.Web.Extensions_1.0/System.Web.Extensions_1.0.dll.sources b/mcs/class/System.Web.Extensions_1.0/System.Web.Extensions_1.0.dll.sources
index 96e1476..2ba19ea 100644
--- a/mcs/class/System.Web.Extensions_1.0/System.Web.Extensions_1.0.dll.sources
+++ b/mcs/class/System.Web.Extensions_1.0/System.Web.Extensions_1.0.dll.sources
@@ -3,7 +3,7 @@
 ../../build/common/MonoTODOAttribute.cs
 ../System.Web/System.Web.Handlers/AssemblyResourceLoader.cs
 ../System.Web/System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs
-../System.Web/System.Web.Configuration_2.0/MachineKeySectionUtils.cs
+../System.Web/System.Web.Util/MachineKeySectionUtils.cs
 ../System.Web.Extensions/Assembly/AssemblyInfo.cs
 ../System.Web.Extensions/System.Web.Handlers/ScriptModule.cs
 ../System.Web.Extensions/System.Web.Handlers/ScriptResourceHandler.cs
diff --git a/mcs/class/System.Web.Routing/System.Web.Routing/ChangeLog b/mcs/class/System.Web.Routing/System.Web.Routing/ChangeLog
index cdbb490..bf6d07e 100644
--- a/mcs/class/System.Web.Routing/System.Web.Routing/ChangeLog
+++ b/mcs/class/System.Web.Routing/System.Web.Routing/ChangeLog
@@ -1,3 +1,13 @@
+2010-11-05  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net,routing] Fix for bug #651593. Don't match all-literal
+	routes for URLs with excessive segments.
+
+2010-10-26  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net,routing] Fix for bug #648901. Matching engine must ignore
+	trailing slash in the URLs.
+
 2010-06-05  Marek Habersack  <mhabersack at novell.com>
 
 	* UrlRoutingModule.cs: 4.0 doesn't do the UrlRouting.axd magic, it
diff --git a/mcs/class/System.Web.Routing/System.Web.Routing/ChangeLog b/mcs/class/System.Web.Routing/System.Web.Routing/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Web.Routing/System.Web.Routing/ChangeLog
copy to mcs/class/System.Web.Routing/System.Web.Routing/ChangeLog.old
diff --git a/mcs/class/System.Web.Routing/System.Web.Routing/PatternParser.cs b/mcs/class/System.Web.Routing/System.Web.Routing/PatternParser.cs
index 72692dc..d684a64 100644
--- a/mcs/class/System.Web.Routing/System.Web.Routing/PatternParser.cs
+++ b/mcs/class/System.Web.Routing/System.Web.Routing/PatternParser.cs
@@ -302,8 +302,10 @@ namespace System.Web.Routing
 
 				argSegs = path.Split ('/');
 				argsCount = argSegs.Length;
+
+				if (String.IsNullOrEmpty (argSegs [argsCount - 1]))
+					argsCount--; // path ends with a trailinig '/'
 			}
-			
 			bool haveDefaults = defaults != null && defaults.Count > 0;
 
 			if (argsCount == 1 && String.IsNullOrEmpty (argSegs [0]))
@@ -353,7 +355,8 @@ namespace System.Web.Routing
 					if (!defaults.ContainsKey (tokens [0].Name))
 						return null;
 				}
-			}
+			} else if (!haveSegmentWithCatchAll && argsCount > segmentCount)
+				return null;
 			
 			return AddDefaults (ret, defaults);
 		}
diff --git a/mcs/class/System.Web.Routing/Test/System.Web.Routing/ChangeLog b/mcs/class/System.Web.Routing/Test/System.Web.Routing/ChangeLog
index e47802d..cf2f33e 100644
--- a/mcs/class/System.Web.Routing/Test/System.Web.Routing/ChangeLog
+++ b/mcs/class/System.Web.Routing/Test/System.Web.Routing/ChangeLog
@@ -1,3 +1,13 @@
+2010-11-05  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net,routing] Fix for bug #651593. Don't match all-literal
+	routes for URLs with excessive segments.
+
+2010-10-26  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net,routing] Fix for bug #648901. Matching engine must ignore
+	trailing slash in the URLs.
+
 2009-09-09  Marek Habersack  <mhabersack at novell.com>
 
 	* RouteTest.cs: added two tests for empty and null route URLs (bug
diff --git a/mcs/class/System.Web.Routing/Test/System.Web.Routing/ChangeLog b/mcs/class/System.Web.Routing/Test/System.Web.Routing/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Web.Routing/Test/System.Web.Routing/ChangeLog
copy to mcs/class/System.Web.Routing/Test/System.Web.Routing/ChangeLog.old
diff --git a/mcs/class/System.Web.Routing/Test/System.Web.Routing/RouteTest.cs b/mcs/class/System.Web.Routing/Test/System.Web.Routing/RouteTest.cs
index 8889d23..3f704f1 100644
--- a/mcs/class/System.Web.Routing/Test/System.Web.Routing/RouteTest.cs
+++ b/mcs/class/System.Web.Routing/Test/System.Web.Routing/RouteTest.cs
@@ -908,6 +908,59 @@ namespace MonoTests.System.Web.Routing
 		}
 
 		[Test]
+		public void GetRouteData44 ()
+		{
+			// {} matches and substitutes even at partial state ...
+			var r = new Route ("{foo}/bartes{baz}", null);
+			var hc = new HttpContextStub ("~/x/bartest/", String.Empty);
+			var rd = r.GetRouteData (hc);
+			Assert.IsNotNull (rd, "#1");
+			Assert.AreEqual (r, rd.Route, "#2");
+			Assert.AreEqual (0, rd.DataTokens.Count, "#3");
+			Assert.AreEqual (2, rd.Values.Count, "#4");
+			Assert.AreEqual ("x", rd.Values ["foo"], "#4-1");
+			Assert.AreEqual ("t", rd.Values ["baz"], "#4-2");
+		}
+
+		[Test]
+		public void GetRouteData45 ()
+		{
+			var r = new Route ("{foo}/{bar}", null);
+			var hc = new HttpContextStub ("~/x/y/", String.Empty);
+			var rd = r.GetRouteData (hc);
+			Assert.IsNotNull (rd, "#1");
+			Assert.AreEqual (r, rd.Route, "#2");
+			Assert.AreEqual (0, rd.DataTokens.Count, "#3");
+			Assert.AreEqual (2, rd.Values.Count, "#4");
+			Assert.AreEqual ("x", rd.Values ["foo"], "#4-1");
+			Assert.AreEqual ("y", rd.Values ["bar"], "#4-2");
+		}
+
+		[Test (Description="Bug #651593")]
+		public void GetRouteData46 ()
+		{
+			var r = new Route ("Foo", null) {
+				Defaults = new RouteValueDictionary (new {
+					controller = "Foo",
+					action = "Index"
+				})
+			};
+			var hc = new HttpContextStub ("/Foo/123", String.Empty);
+			var rd = r.GetRouteData (hc);
+			Assert.IsNull (rd, "#1");
+
+			r = new Route ("Foo", null) {
+				Defaults = new RouteValueDictionary (new {
+					controller = "Foo",
+					action = "Index"
+				})
+			};
+			hc = new HttpContextStub ("~/Foo/123", String.Empty);
+			rd = r.GetRouteData (hc);
+			Assert.IsNull (rd, "#2");
+		}
+
+		[Test]
 		[ExpectedException (typeof (ArgumentNullException))]
 		public void GetVirtualPathNullContext ()
 		{
diff --git a/mcs/class/System.Web/ChangeLog b/mcs/class/System.Web/ChangeLog
index f530141..bdf3ee8 100644
--- a/mcs/class/System.Web/ChangeLog
+++ b/mcs/class/System.Web/ChangeLog
@@ -1,3 +1,21 @@
+2010-11-02  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] 4.0-only types don't need the NET_4_0 ifdef and should
+	be in net_4_0_System.Web.dll.sources
+
+2010-10-12  Sebastien Pouliot  <sebastien at ximian.com>
+
+	* Makefile: Compile tests with TEST defined (to include
+	System.Web.Util. MachineKeySectionUtils unit tests) *
+	System.Web.dll.sources: Move MachineKeySectionUtils.cs from
+	System. Web.Configuration_2.0 to System.Web.Util *
+	System.Web_test.dll.sources: Move MachineKeySectionUtilsTest.cs
+	from System.Web.Configuration_2.0 to System.Web.Util
+
+2010-10-08  Sebastien Pouliot  <sebastien at ximian.com>
+
+	Normalization of cryptographic uses in asp.net
+
 2010-08-24  Marek Habersack  <grendel at twistedcode.net>
 
 	[asp.net] Fix for bug #633756. Children processed as properties
diff --git a/mcs/class/System.Web/Makefile b/mcs/class/System.Web/Makefile
index 7327b01..9621c48 100644
--- a/mcs/class/System.Web/Makefile
+++ b/mcs/class/System.Web/Makefile
@@ -287,7 +287,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -doc:$(test_lib:.dll=.xml) -nowarn:219,169,159
 	$(foreach file,$(NUNIT_APP_GLOBALRESOURCES_FILES),$(shell echo $(file) | sed -e 's;\(.*\)/\(.*\);/resource:\1/\2,App_GlobalResources/\2 ;g'))
 
 ifeq (net_2_0, $(PROFILE))
-TEST_MCS_FLAGS += -r:System.Web.Extensions.dll
+TEST_MCS_FLAGS += -r:System.Web.Extensions.dll -d:TEST
 endif
 
 EXTRA_DISTFILES = \
@@ -442,4 +442,4 @@ ifdef STANDALONE_TEST_COMPILABLE_TESTS
 	done
 endif
  
- 
\ No newline at end of file
+ 
diff --git a/mcs/class/System.Web/System.Web.Configuration_2.0/AuthorizationRule.cs b/mcs/class/System.Web/System.Web.Configuration_2.0/AuthorizationRule.cs
index c2e064a..cd53896 100644
--- a/mcs/class/System.Web/System.Web.Configuration_2.0/AuthorizationRule.cs
+++ b/mcs/class/System.Web/System.Web.Configuration_2.0/AuthorizationRule.cs
@@ -49,7 +49,8 @@ namespace System.Web.Configuration {
 		static ConfigurationPropertyCollection properties;
 
 		AuthorizationRuleAction action;
-
+		ConfigurationSaveMode saveMode = ConfigurationSaveMode.Full;
+			
 		static AuthorizationRule ()
 		{
 			rolesProp = new ConfigurationProperty ("roles", typeof (StringCollection), null,
@@ -130,7 +131,10 @@ namespace System.Web.Configuration {
 		[MonoTODO ("Not implemented")]
 		protected override bool IsModified ()
 		{
-			throw new NotImplementedException ();
+			if (((CommaDelimitedStringCollection)Roles).IsModified || ((CommaDelimitedStringCollection)Users).IsModified || ((CommaDelimitedStringCollection)Verbs).IsModified)
+				return true;
+
+			return false;
 		}
 
 		void VerifyData ()
@@ -168,6 +172,9 @@ namespace System.Web.Configuration {
 
 		protected override bool SerializeElement (XmlWriter writer, bool serializeCollectionKey)
 		{
+			if (saveMode != ConfigurationSaveMode.Full && !IsModified ())
+				return true;
+			
 			PreSerialize (writer);
 
 			writer.WriteStartElement (action == AuthorizationRuleAction.Allow ? "allow" : "deny");
@@ -191,6 +198,7 @@ namespace System.Web.Configuration {
 		protected override void Unmerge (ConfigurationElement sourceElement, ConfigurationElement parentElement, ConfigurationSaveMode saveMode)
 		{
 			base.Unmerge (sourceElement, parentElement, saveMode);
+			this.saveMode = saveMode;
 		}
 
 		public AuthorizationRuleAction Action {
diff --git a/mcs/class/System.Web/System.Web.Configuration_2.0/AuthorizationRuleCollection.cs b/mcs/class/System.Web/System.Web.Configuration_2.0/AuthorizationRuleCollection.cs
index 0c1a39d..e824eb4 100644
--- a/mcs/class/System.Web/System.Web.Configuration_2.0/AuthorizationRuleCollection.cs
+++ b/mcs/class/System.Web/System.Web.Configuration_2.0/AuthorizationRuleCollection.cs
@@ -108,9 +108,8 @@ namespace System.Web.Configuration {
 			get { return ConfigurationElementCollectionType.BasicMapAlternate; }
 		}
 
-		[MonoTODO ("is it okay to return a comma delimited string here?")]
 		protected override string ElementName {
-			get { return "allow,deny"; }
+			get { return String.Empty; }
 		}
 
 		public AuthorizationRule this [int index] {
diff --git a/mcs/class/System.Web/System.Web.Configuration_2.0/ChangeLog b/mcs/class/System.Web/System.Web.Configuration_2.0/ChangeLog
index 2cedb1f..ce9e662 100644
--- a/mcs/class/System.Web/System.Web.Configuration_2.0/ChangeLog
+++ b/mcs/class/System.Web/System.Web.Configuration_2.0/ChangeLog
@@ -1,3 +1,66 @@
+2010-11-02  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] 4.0-only types don't need the NET_4_0 ifdef and should
+	be in net_4_0_System.Web.dll.sources
+
+2010-10-12  Sebastien Pouliot  <sebastien at ximian.com>
+
+	* System.Web.Configuration_2.0/MachineKeySection.cs: Adjust using
+	clauses. Uncomment some code. Fix TripleDES versus 3DES for
+	Validation under NET_4_0. Remove 'private' on fields/methods. *
+	System.Web.Handlers/AssemblyResourceLoader.cs: Adjust using
+	clauses * System.Web.Security/MembershipHelper.cs: Adjust using
+	clauses * System.Web.Security/RolePrincipal.cs: Adjust using
+	clauses * System.Web.SessionState_2.0/SessionId.cs: Adjust using
+	clauses * System.Web.UI/LosFormatter.cs: Adjust using clauses. *
+	System.Web.Util/MachineKeySectionUtils.cs: Moved from System.Web.
+	Configuration_2.0. Rename namespace and remove 'internal' on type
+	declaration
+
+2010-10-08  Sebastien Pouliot  <sebastien at ximian.com>
+
+	* System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs:
+	Remove key length check and generic key generation.
+
+	* System.Web.Configuration_2.0/MachineKeySection.cs: Add support
+	for 4.0 ValidationAlgorithm and the use of custom algorithms
+	(validation and decryption). Allow the use of any, valid, key
+	length (based on the algorithm). Let each algorithm creates its
+	own key (e.g. special needs, default length...)
+
+	* System.Web.Configuration_2.0/MachineKeySectionUtils.cs: Remove
+	key generation (from random) code and 192bits key length hack
+	(won't work with custom algorithms). Add support for new (4.0)
+	algorithms, including custom ones. Provide uniform/shared code to
+	Encrypt/Decrypt, Sign/Verify and EncryptSign/VerifyDecrypt using
+	MachineKeySection data.
+
+	* System.Web.Configuration_2.0/MachineKeyValidation.cs: Add new
+	(4.0) values.
+
+	* System.Web.Configuration_2.0/MachineKeyValidationConverter.cs:
+	Add support for new (4.0) algorithms.
+
+	* System.Web.Configuration_2.0/MachineKeyCompatibilityMode.cs:
+	New.
+
+2010-10-26  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] HttpRuntime.AppDomainAppPath may be null during tests,
+	check it before using.
+
+2010-10-24  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Better handling of application's AppDomain restart
+
+2010-10-04  Marek Habersack  <grendel at twistedcode.net>
+
+	* AuthorizationRule.cs: if the configuration save is not Full,
+	SerializeElement checks whether the rule being serialized is
+	modified. If it isn't, validation and serialization are not
+	performed. * AuthorizationRuleCollection.cs: there is no element
+	name for the collection.
+
 2010-09-28  Marek Habersack  <grendel at twistedcode.net>
 
 	[asp.net] Get rid of a possible (although unlikely) race condition
diff --git a/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyCompatibilityMode.cs b/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyCompatibilityMode.cs
new file mode 100644
index 0000000..38c5e55
--- /dev/null
+++ b/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyCompatibilityMode.cs
@@ -0,0 +1,36 @@
+//
+// System.Web.Configuration.MachineKeyCompatibilityMode
+//
+// Authors:
+//	Sebastien Pouliot  <sebastien at ximian.com>
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace System.Web.Configuration {
+
+	public enum MachineKeyCompatibilityMode {
+		Framework20SP1 = 0,
+		Framework20SP2 = 1
+	}
+}
+
diff --git a/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs b/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs
index c6f1d52..52bc5b3 100644
--- a/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs
+++ b/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs
@@ -28,8 +28,6 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-using System;
-using System.Security.Cryptography;
 using Microsoft.Win32;
 
 namespace System.Web.Configuration
@@ -42,9 +40,6 @@ namespace System.Web.Configuration
 			Encryption
 		};
 
-		const int encryptionKeyLength = 64;
-		const int validationKeyLength = 64;
-		
 		static string keyEncryption;
 		static string keyValidation;
 		
@@ -63,30 +58,15 @@ namespace System.Web.Configuration
 		
 		public static byte[] Retrieve (KeyType kt)
 		{
-			byte[] ret = GetKey (kt);
-			if (ret == null) {
-				ret = Generate (kt);
-				if (ret != null)
-					Store (ret, kt);
-			}
-			
-			return ret;
-		}
-
-		static byte[] GetKey (KeyType kt)
-		{
 			string key = null;
-			int len;
 			
 			switch (kt) {
 				case KeyType.Validation:
 					key = keyValidation;
-					len = validationKeyLength;
 					break;
 
 				case KeyType.Encryption:
 					key = keyEncryption;
-					len = validationKeyLength;
 					break;
 
 				default:
@@ -107,11 +87,7 @@ namespace System.Web.Configuration
 
 			if (o == null || o.GetType () != typeof (byte[]))
 				return null;
-			byte[] ret = (byte[])o;
-			if (ret.Length != len)
-				return null;
-
-			return ret;
+			return (byte[]) o;
 		}
 
 		static RegistryKey OpenRegistryKey (string path, bool write)
@@ -134,23 +110,19 @@ namespace System.Web.Configuration
 			return ret;
 		}
 		
-		static void Store (byte[] buf, KeyType kt)
+		public static void Store (byte[] buf, KeyType kt)
 		{
 			if (buf == null)
 				return;
 			
 			string key = null;
-			int len;
-			
 			switch (kt) {
 				case KeyType.Validation:
 					key = keyValidation;
-					len = validationKeyLength;
 					break;
 
 				case KeyType.Encryption:
 					key = keyEncryption;
-					len = validationKeyLength;
 					break;
 
 				default:
@@ -160,9 +132,6 @@ namespace System.Web.Configuration
 			if (key == null)
 				return;
 
-			if (buf.Length != len)
-				throw new ArgumentException ("Key has invalid length");
-
 			try {
 				using (RegistryKey rk = OpenRegistryKey (key, true)) {
 #if NET_2_0
@@ -180,27 +149,5 @@ namespace System.Web.Configuration
 				throw new ApplicationException ("Failed to store encryption key in the registry.", ex);
 			}
 		}
-
-		static byte[] Generate (KeyType kt)
-		{
-			RandomNumberGenerator rng = RandomNumberGenerator.Create ();
-			byte[] ret = null;
-			
-			switch (kt) {
-				case KeyType.Validation:
-					ret = new byte [validationKeyLength];
-					break;
-
-				case KeyType.Encryption:
-					ret = new byte [encryptionKeyLength];
-					break;
-
-				default:
-					throw new ArgumentException ("Unknown key type.");
-			}
-			
-			rng.GetBytes (ret);
-			return ret;
-		}
 	}
 }
diff --git a/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeySection.cs b/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeySection.cs
index 193b9c2..70ce7fd 100644
--- a/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeySection.cs
+++ b/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeySection.cs
@@ -3,8 +3,9 @@
 //
 // Authors:
 //	Chris Toshok (toshok at ximian.com)
+//	Sebastien Pouliot  <sebastien at ximian.com>
 //
-// (c) Copyright 2005 Novell, Inc (http://www.novell.com)
+// (c) Copyright 2005, 2010 Novell, Inc (http://www.novell.com)
 //
 
 //
@@ -28,12 +29,13 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+#if NET_2_0
+
 using System;
 using System.ComponentModel;
 using System.Configuration;
 using System.Security.Cryptography;
-
-#if NET_2_0
+using System.Web.Util;
 
 namespace System.Web.Configuration {
 
@@ -44,6 +46,10 @@ namespace System.Web.Configuration {
 		static ConfigurationProperty validationProp;
 		static ConfigurationProperty validationKeyProp;
 		static ConfigurationPropertyCollection properties;
+		static MachineKeyValidationConverter converter = new MachineKeyValidationConverter ();
+#if NET_4_0
+		MachineKeyValidation validation;
+#endif
 
 		static MachineKeySection ()
 		{
@@ -55,10 +61,17 @@ namespace System.Web.Configuration {
 								       PropertyHelper.WhiteSpaceTrimStringConverter,
 								       PropertyHelper.NonEmptyStringValidator,
 								       ConfigurationPropertyOptions.None);
-			validationProp = new ConfigurationProperty ("validation", typeof (MachineKeyValidation), MachineKeyValidation.SHA1,
-								    new MachineKeyValidationConverter (),
+#if NET_4_0
+			validationProp = new ConfigurationProperty ("validation", typeof (string), "HMACSHA256",
+								    PropertyHelper.WhiteSpaceTrimStringConverter,
+								    PropertyHelper.NonEmptyStringValidator,
+								    ConfigurationPropertyOptions.None);
+#else
+			validationProp = new ConfigurationProperty ("validation", typeof (MachineKeyValidation), 
+								    MachineKeyValidation.SHA1, converter,
 								    PropertyHelper.DefaultValidator,
 								    ConfigurationPropertyOptions.None);
+#endif
 			validationKeyProp = new ConfigurationProperty ("validationKey", typeof (string), "AutoGenerate,IsolateApps",
 								       PropertyHelper.WhiteSpaceTrimStringConverter,
 								       PropertyHelper.NonEmptyStringValidator,
@@ -71,12 +84,30 @@ namespace System.Web.Configuration {
 			properties.Add (validationProp);
 			properties.Add (validationKeyProp);
 
-			MachineKeySectionUtils.AutoGenKeys ();
+			Config.AutoGenerate (MachineKeyRegistryStorage.KeyType.Encryption);
+			Config.AutoGenerate (MachineKeyRegistryStorage.KeyType.Validation);
 		}
 
+#if NET_4_0
+		public MachineKeySection ()
+		{
+			// get DefaultValue from ValidationAlgorithm
+			validation = (MachineKeyValidation) converter.ConvertFrom (null, null, ValidationAlgorithm);
+		}
+
+		[MonoTODO]
+		public MachineKeyCompatibilityMode CompatibilityMode {
+			get; set;
+		}
+#endif
+
 		protected override void Reset (ConfigurationElement parentElement)
 		{
 			base.Reset (parentElement);
+			decryption_key = null;
+			validation_key = null;
+			decryption_template = null;
+			validation_template = null;
 		}
 
 		[TypeConverter (typeof (WhiteSpaceTrimStringConverter))]
@@ -84,7 +115,10 @@ namespace System.Web.Configuration {
 		[ConfigurationProperty ("decryption", DefaultValue = "Auto")]
 		public string Decryption {
 			get { return (string) base [decryptionProp];}
-			set { base[decryptionProp] = value; }
+			set {
+				decryption_template = MachineKeySectionUtils.GetDecryptionAlgorithm (value);
+				base[decryptionProp] = value;
+			}
 		}
 
 		[TypeConverter (typeof (WhiteSpaceTrimStringConverter))]
@@ -94,16 +128,49 @@ namespace System.Web.Configuration {
 			get { return (string) base [decryptionKeyProp];}
 			set {
 				base[decryptionKeyProp] = value;
-				MachineKeySectionUtils.SetDecryptionKey (value);
+				SetDecryptionKey (value);
 			}
 		}
 
+#if NET_4_0
+		// property exists for backward compatibility
+		public MachineKeyValidation Validation {
+			get { return validation; }
+			set {
+				if (value == MachineKeyValidation.Custom)
+					throw new ArgumentException ();
+
+				string algo = value.ToString ();
+				// enum and accept values differs for TripleDES
+				ValidationAlgorithm = (algo == "TripleDES") ? "3DES" : algo;
+			}
+		}
+
+		[StringValidator (MinLength = 1)]
+		[TypeConverter (typeof (WhiteSpaceTrimStringConverter))]
+		[ConfigurationProperty ("validation", DefaultValue = "HMACSHA256")]
+		public string ValidationAlgorithm {
+			get { return (string) base [validationProp];}
+			set {
+				if (value == null)
+					return;
+
+				if (value.StartsWith ("alg:"))
+					validation = MachineKeyValidation.Custom;
+				else
+					validation = (MachineKeyValidation) converter.ConvertFrom (null, null, value);
+
+				base[validationProp] = value;
+			}
+		}
+#else
 		[TypeConverter (typeof (MachineKeyValidationConverter))]
 		[ConfigurationProperty ("validation", DefaultValue = "SHA1")]
 		public MachineKeyValidation Validation {
 			get { return (MachineKeyValidation) base [validationProp];}
 			set { base[validationProp] = value; }
 		}
+#endif
 
 		[TypeConverter (typeof (WhiteSpaceTrimStringConverter))]
 		[StringValidator (MinLength = 1)]
@@ -112,13 +179,142 @@ namespace System.Web.Configuration {
 			get { return (string) base [validationKeyProp];}
 			set {
 				base[validationKeyProp] = value;
-				MachineKeySectionUtils.SetValidationKey (value);
+				SetValidationKey (value);
 			}
 		}
 
 		protected override ConfigurationPropertyCollection Properties {
 			get { return properties; }
 		}
+
+
+		internal static MachineKeySection Config {
+			get { return WebConfigurationManager.GetSection ("system.web/machineKey") as MachineKeySection; }
+		}
+
+		byte[] decryption_key;
+		byte[] validation_key;
+		SymmetricAlgorithm decryption_template;
+		KeyedHashAlgorithm validation_template;
+
+		internal SymmetricAlgorithm GetDecryptionAlgorithm ()
+		{
+			// code location to help with unit testing the code
+			return MachineKeySectionUtils.GetDecryptionAlgorithm (Decryption);
+		}
+
+		// not to be reused outside algorithm and key validation purpose
+		SymmetricAlgorithm DecryptionTemplate {
+			get {
+				if (decryption_template == null)
+					decryption_template = GetDecryptionAlgorithm ();
+				return decryption_template;
+			}
+		}
+
+		internal byte [] GetDecryptionKey ()
+		{
+			if (decryption_key == null)
+				SetDecryptionKey (DecryptionKey);
+			return decryption_key;
+		}
+
+		void SetDecryptionKey (string key)
+		{
+			if ((key == null) || key.StartsWith ("AutoGenerate")) {
+				decryption_key = AutoGenerate (MachineKeyRegistryStorage.KeyType.Encryption);
+			} else {
+				try {
+					decryption_key = MachineKeySectionUtils.GetBytes (key, key.Length);
+					DecryptionTemplate.Key = decryption_key;
+				}
+				catch {
+					decryption_key = null;
+					throw new ArgumentException ("Invalid key length");
+				}
+			}
+		}
+
+		internal KeyedHashAlgorithm GetValidationAlgorithm ()
+		{
+			// code location to help with unit testing the code
+			return MachineKeySectionUtils.GetValidationAlgorithm (this);
+		}
+
+		// not to be reused outside algorithm and key validation purpose
+		KeyedHashAlgorithm ValidationTemplate {
+			get {
+				if (validation_template == null)
+					validation_template = GetValidationAlgorithm ();
+				return validation_template;
+			}
+		}
+
+		internal byte [] GetValidationKey ()
+		{
+			if (validation_key == null)
+				SetValidationKey (ValidationKey);
+			return validation_key;
+		}
+
+		// key can be expended for HMAC - i.e. a small key, e.g. 32 bytes, is still accepted as valid
+		// the HMAC class already deals with keys larger than what it can use (digested to right size)
+		void SetValidationKey (string key)
+		{
+			if ((key == null) || key.StartsWith ("AutoGenerate")) {
+				validation_key = AutoGenerate (MachineKeyRegistryStorage.KeyType.Validation);
+			} else {
+				try {
+					validation_key = MachineKeySectionUtils.GetBytes (key, key.Length);
+					ValidationTemplate.Key = validation_key;
+				}
+				catch (CryptographicException) {
+					// second chance, use the key length that the HMAC really wants
+					try {
+						byte[] expanded_key = new byte [ValidationTemplate.Key.Length];
+						Array.Copy (validation_key, 0, expanded_key, 0, validation_key.Length);
+						ValidationTemplate.Key = expanded_key;
+						validation_key = expanded_key;
+					}
+					catch {
+						validation_key = null;
+						throw new ArgumentException ("Invalid key length");
+					}
+				}
+			}
+		}
+
+		byte[] AutoGenerate (MachineKeyRegistryStorage.KeyType type)
+		{
+			byte[] key = null;
+#if TARGET_J2EE
+			{
+#else
+			try {
+				key = MachineKeyRegistryStorage.Retrieve (type);
+
+				// ensure the stored key is usable with the selection algorithm
+				if (type == MachineKeyRegistryStorage.KeyType.Encryption)
+					DecryptionTemplate.Key = key;
+				else if (type == MachineKeyRegistryStorage.KeyType.Validation)
+					ValidationTemplate.Key = key;
+			} catch (Exception) {
+				key = null;
+			}
+#endif
+			// some algorithms have special needs for key (e.g. length, parity, weak keys...) 
+			// so we better ask them to provide a default key (than to generate/use bad ones)
+			if (key == null) {
+				if (type == MachineKeyRegistryStorage.KeyType.Encryption)
+					key = DecryptionTemplate.Key;
+				else if (type == MachineKeyRegistryStorage.KeyType.Validation)
+					key = ValidationTemplate.Key;
+#if !TARGET_J2EE
+				MachineKeyRegistryStorage.Store (key, type);
+#endif
+			}
+			return key;
+		}
 	}
 }
 
diff --git a/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeySectionUtils.cs b/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeySectionUtils.cs
deleted file mode 100644
index 1f73379..0000000
--- a/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeySectionUtils.cs
+++ /dev/null
@@ -1,187 +0,0 @@
-//
-// System.Web.Configuration.MachineKeySection
-//
-// Authors:
-//	Chris Toshok (toshok at ximian.com)
-//
-// (c) Copyright 2005 Novell, Inc (http://www.novell.com)
-//
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.ComponentModel;
-using System.Configuration;
-using System.Security.Cryptography;
-
-#if NET_2_0
-
-namespace System.Web.Configuration {
-
-	internal static class MachineKeySectionUtils
-	{
-		static byte [] autogenerated;
-		static byte [] autogenerated_decrypt;
-		static byte[] decryption_key;
-		static byte[] decryption_key_192bits;
-		static byte[] validation_key;
-
-		internal static void AutoGenKeys ()
-		{
-#if TARGET_J2EE
-			{
-#else
-			try {
-				if (autogenerated == null)
-					autogenerated = MachineKeyRegistryStorage.Retrieve (
-						MachineKeyRegistryStorage.KeyType.Validation);
-				if (autogenerated_decrypt == null)
-					autogenerated_decrypt = MachineKeyRegistryStorage.Retrieve (
-						MachineKeyRegistryStorage.KeyType.Encryption);
-			} catch (Exception) {
-#endif
-				// Fall back to old method
-				RandomNumberGenerator rng = RandomNumberGenerator.Create ();
-				
-				if (autogenerated == null) {
-					autogenerated = new byte [64];
-					rng.GetBytes (autogenerated);
-				}
-
-				if (autogenerated_decrypt == null) {
-					autogenerated_decrypt = new byte [64];
-					rng.GetBytes (autogenerated_decrypt);
-				}
-			}
-		}
-
-		static byte ToHexValue (char c, bool high)
-		{
-			byte v;
-			if (c >= '0' && c <= '9')
-				v = (byte) (c - '0');
-			else if (c >= 'a' && c <= 'f')
-				v = (byte) (c - 'a' + 10);
-			else if (c >= 'A' && c <= 'F')
-				v = (byte) (c - 'A' + 10);
-			else
-				throw new ArgumentException ("Invalid hex character");
-
-			if (high)
-				v <<= 4;
-
-			return v;
-		}
-		
-		internal static byte [] GetBytes (string key, int len)
-		{
-			byte [] result = new byte [len / 2];
-			for (int i = 0; i < len; i += 2)
-				result [i / 2] = (byte) (ToHexValue (key [i], true) + ToHexValue (key [i + 1], false));
-
-			return result;
-		}
-
-		static byte [] MakeKey (string key, bool decryption) //, out bool isolate)
-		{
-			if (key == null || key.StartsWith ("AutoGenerate")){
-				//isolate = key.IndexOf ("IsolateApps") != 1;
-				AutoGenKeys ();
-				return (decryption) ? autogenerated_decrypt : autogenerated;
-			}
-
-			//isolate = false;
-
-			int len = key.Length;
-			if (len < 40 || len > 128 || (len % 2) == 1)
-				throw new ArgumentException ("Invalid key length");
-
-			return GetBytes (key, len);
-		}
-
-		internal static void SetDecryptionKey (string n)
-		{
-			decryption_key = MakeKey (n, true); //, out isolate_decryption);
-			decryption_key_192bits = new byte [24];
-			int count = 24;
-			if (decryption_key.Length < 24)
-				count = decryption_key.Length;
-			Buffer.BlockCopy (decryption_key, 0, decryption_key_192bits, 0, count);
-		}
-
-		internal static void SetValidationKey (string n)
-		{
-			validation_key = MakeKey (n, false); //, out isolate_validation);
-		}
-
-		static MachineKeySection Config {
-			get { return WebConfigurationManager.GetSection ("system.web/machineKey") as MachineKeySection; }
-		}		
-
-		internal static byte [] ValidationKeyBytes ()
-		{
-			return ValidationKeyBytes (Config);
-		}
-		
-		internal static byte [] ValidationKeyBytes (MachineKeySection section)
-		{
-			if (section == null)
-				throw new ArgumentNullException ("section");
-			
-			if (validation_key == null)
-				SetValidationKey (section.ValidationKey);
-			return validation_key;
-		}
-
-		internal static byte [] DecryptionKeyBytes ()
-		{
-			return DecryptionKeyBytes (Config);
-		}
-		
-		internal static byte [] DecryptionKeyBytes (MachineKeySection section)
-		{
-			if (section == null)
-				throw new ArgumentNullException ("section");
-			
-			if (decryption_key == null)
-				SetDecryptionKey (section.DecryptionKey);
-			return decryption_key;
-		}
-
-		internal static byte [] DecryptionKey192Bits ()
-		{
-			return DecryptionKey192Bits (Config);
-		}
-		
-		internal static byte [] DecryptionKey192Bits (MachineKeySection section)
-		{
-			if (section == null)
-				throw new ArgumentNullException ("section");
-			
-			if (decryption_key_192bits == null)
-				SetDecryptionKey (section.DecryptionKey);
-			return decryption_key_192bits;
-		}
-	}
-}
-
-#endif
diff --git a/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyValidation.cs b/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyValidation.cs
index a7b7515..eb7dfe1 100644
--- a/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyValidation.cs
+++ b/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyValidation.cs
@@ -23,11 +23,9 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004, 2010 Novell, Inc (http://www.novell.com)
 //
 
-using System.Resources;
-
 namespace System.Web.Configuration
 {
 #if NET_2_0
@@ -40,7 +38,13 @@ namespace System.Web.Configuration
 		MD5 = 0,
 		SHA1 = 1,
 		TripleDES = 2,
-		AES = 3
+		AES = 3,
+#if NET_4_0
+		HMACSHA256 = 4,
+		HMACSHA384 = 5,
+		HMACSHA512 = 6,
+		Custom = 7
+#endif
 	}
 }
 
diff --git a/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyValidationConverter.cs b/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyValidationConverter.cs
index 014ca28..698509c 100644
--- a/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyValidationConverter.cs
+++ b/mcs/class/System.Web/System.Web.Configuration_2.0/MachineKeyValidationConverter.cs
@@ -3,8 +3,9 @@
 //
 // Authors:
 //	Chris Toshok (toshok at ximian.com)
+//	Sebastien Pouliot  <sebastien at ximian.com>
 //
-// (c) Copyright 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005, 2010 Novell, Inc (http://www.novell.com)
 //
 
 //
@@ -28,7 +29,6 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-using System;
 using System.ComponentModel;
 using System.Configuration;
 using System.Globalization;
@@ -39,40 +39,76 @@ namespace System.Web.Configuration {
 
 	public sealed class MachineKeyValidationConverter : ConfigurationConverterBase
 	{
+#if NET_4_0
+		const string InvalidValue = "The enumeration value must be one of the following: SHA1, MD5, 3DES, AES, HMACSHA256, HMACSHA384, HMACSHA512."; 
+#else
+		const string InvalidValue = "The enumeration value must be one of the following: SHA1, MD5, 3DES, AES."; 
+#endif
 		public MachineKeyValidationConverter ()
 		{
 		}
 
 		public override object ConvertFrom (ITypeDescriptorContext ctx, CultureInfo ci, object data)
 		{
-			if ((string)data == "MD5")
+			switch ((string) data) {
+			case "MD5":
 				return MachineKeyValidation.MD5;
-			else if ((string)data == "SHA1")
+			case "SHA1":
 				return MachineKeyValidation.SHA1;
-			else if ((string)data == "3DES")
+			case "3DES":
 				return MachineKeyValidation.TripleDES;
-			else if ((string)data == "AES")
+			case "AES":
 				return MachineKeyValidation.AES;
-			else
-				throw new ArgumentException ("The enumeration value must be one of the following: SHA1, MD5, 3DES, AES.");
+#if NET_4_0
+			case "HMACSHA256":
+				return MachineKeyValidation.HMACSHA256;
+			case "HMACSHA384":
+				return MachineKeyValidation.HMACSHA384;
+			case "HMACSHA512":
+				return MachineKeyValidation.HMACSHA512;
+#endif
+			default:
+				throw new ArgumentException (InvalidValue);
+			}
 		}
 
 		public override object ConvertTo (ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type)
 		{
+#if NET_4_0
+			if ((value == null) || (value.GetType () != typeof (MachineKeyValidation)))
+				throw new ArgumentException (InvalidValue);
+#else
 			if (value.GetType () != typeof (MachineKeyValidation)) {
 				/* MS throws this exception on an invalid */
-				throw new FormatException ("invalid validation value");
+				throw new FormatException (InvalidValue);
 			}				
+#endif
 
-			MachineKeyValidation v = (MachineKeyValidation)value;
-
-			if (v == MachineKeyValidation.MD5) return "MD5";
-			else if (v == MachineKeyValidation.SHA1) return "SHA1";
-			else if (v == MachineKeyValidation.TripleDES) return "3DES";
-			else if (v ==  MachineKeyValidation.AES) return "AES";
-			else
+			switch ((MachineKeyValidation) value) {
+			case MachineKeyValidation.MD5:
+				return "MD5";
+			case MachineKeyValidation.SHA1:
+				return "SHA1";
+			case MachineKeyValidation.TripleDES:
+				return "3DES";
+			case MachineKeyValidation.AES:
+				return "AES";
+#if NET_4_0
+			case MachineKeyValidation.HMACSHA256:
+				return "HMACSHA256";
+			case MachineKeyValidation.HMACSHA384:
+				return "HMACSHA384";
+			case MachineKeyValidation.HMACSHA512:
+				return "HMACSHA512";
+			default:
+				// includes MachineKeyValidation.Custom
+				throw new ArgumentException (InvalidValue);
+#else
+			default:
 				/* MS throws this exception on an invalid */
-				throw new FormatException ("invalid validation value");
+				throw new FormatException (InvalidValue);
+#endif
+			}
 		}
 	}
 }
diff --git a/mcs/class/System.Web/System.Web.Configuration_2.0/WebConfigurationManager.cs b/mcs/class/System.Web/System.Web.Configuration_2.0/WebConfigurationManager.cs
index de0790a..27ae1e7 100644
--- a/mcs/class/System.Web/System.Web.Configuration_2.0/WebConfigurationManager.cs
+++ b/mcs/class/System.Web/System.Web.Configuration_2.0/WebConfigurationManager.cs
@@ -63,6 +63,7 @@ namespace System.Web.Configuration {
 		}
 		
 		const int SAVE_LOCATIONS_CHECK_INTERVAL = 6000; // milliseconds
+		const int SECTION_CACHE_LOCK_TIMEOUT = 200; // milliseconds
 
 		static readonly char[] pathTrimChars = { '/' };
 		static readonly object suppressAppReloadLock = new object ();
@@ -585,8 +586,9 @@ namespace System.Web.Configuration {
 			HttpContext ctx = HttpContext.Current;
 			HttpRequest req = ctx != null ? ctx.Request : null;
 			string physPath = req != null ? VirtualPathUtility.AppendTrailingSlash (MapPath (req, path)) : null;
+			string appDomainPath = HttpRuntime.AppDomainAppPath;
 			
-			if (physPath != null && !physPath.StartsWith (HttpRuntime.AppDomainAppPath, StringComparison.Ordinal))
+			if (physPath != null && appDomainPath != null && !physPath.StartsWith (appDomainPath, StringComparison.Ordinal))
 				inAnotherApp = true;
 			
 			string dir;
@@ -685,19 +687,29 @@ namespace System.Web.Configuration {
 			object cachedSection;
 
 			try {
-				sectionCacheLock.EnterUpgradeableReadLock ();
+				if (!sectionCacheLock.TryEnterUpgradeableReadLock (SECTION_CACHE_LOCK_TIMEOUT))
+					return;
 					
 				if (sectionCache.TryGetValue (key, out cachedSection) && cachedSection != null)
 					return;
 
 				try {
-					sectionCacheLock.EnterWriteLock ();
+					if (!sectionCacheLock.TryEnterWriteLock (SECTION_CACHE_LOCK_TIMEOUT))
+						return;
 					sectionCache.Add (key, section);
 				} finally {
-					sectionCacheLock.ExitWriteLock ();
+					try {
+						sectionCacheLock.ExitWriteLock ();
+					} catch (SynchronizationLockException) {
+						// we can ignore it here
+					}
 				}
 			} finally {
-				sectionCacheLock.ExitUpgradeableReadLock ();
+				try {
+					sectionCacheLock.ExitUpgradeableReadLock ();
+				} catch (SynchronizationLockException) {
+					// we can ignore it here
+				}
 			}
 		}
 		
diff --git a/mcs/class/System.Web/System.Web.Handlers/AssemblyResourceLoader.cs b/mcs/class/System.Web/System.Web.Handlers/AssemblyResourceLoader.cs
index d1cab4b..ea07c1f 100644
--- a/mcs/class/System.Web/System.Web.Handlers/AssemblyResourceLoader.cs
+++ b/mcs/class/System.Web/System.Web.Handlers/AssemblyResourceLoader.cs
@@ -34,10 +34,10 @@ using System.Reflection;
 using System.IO;
 using System.Resources;
 using System.Collections;
-using System.Security.Cryptography;
 using System.Text;
 using System.Text.RegularExpressions;
 using System.Web.Configuration;
+using System.Web.Util;
 
 namespace System.Web.Handlers {
 #if SYSTEM_WEB_EXTENSIONS
@@ -58,11 +58,6 @@ namespace System.Web.Handlers {
 		const char QueryParamSeparator = '&';
 
 		static readonly Hashtable _embeddedResources = Hashtable.Synchronized (new Hashtable ());
-#if SYSTEM_WEB_EXTENSIONS
-		static ScriptResourceHandler () {
-			MachineKeySectionUtils.AutoGenKeys ();
-		}
-#endif
 
 		static void InitEmbeddedResourcesUrls (Assembly assembly, Hashtable hashtable)
 		{
@@ -93,67 +88,25 @@ namespace System.Web.Handlers {
 		}
 #endif
 
-		static string GetHexString (byte [] bytes)
-		{
-			const int letterPart = 55;
-			const int numberPart = 48;
-			char [] result = new char [bytes.Length * 2];
-			for (int i = 0; i < bytes.Length; i++) {
-				int tmp = (int) bytes [i];
-				int second = tmp & 15;
-				int first = (tmp >> 4) & 15;
-				result [(i * 2)] = (char) (first > 9 ? letterPart + first : numberPart + first);
-				result [(i * 2) + 1] = (char) (second > 9 ? letterPart + second : numberPart + second);
-			}
-			return new string (result);
-		}
-		
-		static byte[] GetEncryptionKey ()
-		{
-#if NET_2_0
-			return MachineKeySectionUtils.DecryptionKey192Bits ();
-#else
-			MachineKeyConfig config = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig;
-			return config.DecryptionKey192Bits;
-#endif
-		}
-
-		static byte[] GetBytes (string val)
-		{
-#if NET_2_0
-			return MachineKeySectionUtils.GetBytes (val, val.Length);
-#else
-			return MachineKeyConfig.GetBytes (val, val.Length);
-#endif
-		}		
-		
-		static byte [] init_vector = { 0xD, 0xE, 0xA, 0xD, 0xB, 0xE, 0xE, 0xF };
-		
 		static string EncryptAssemblyResource (string asmName, string resName)
 		{
-			byte[] key = GetEncryptionKey ();
 			byte[] bytes = Encoding.UTF8.GetBytes (String.Concat (asmName, ";", resName));
-			string result;
-			
-			ICryptoTransform encryptor = TripleDES.Create ().CreateEncryptor (key, init_vector);
-			result = GetHexString (encryptor.TransformFinalBlock (bytes, 0, bytes.Length));
-			bytes = null;
-
-			return String.Concat ("d=", result.ToLowerInvariant ());
+			bytes = MachineKeySectionUtils.Encrypt (MachineKeySection.Config, bytes);
+			return Convert.ToBase64String (bytes);
 		}
 
 		static void DecryptAssemblyResource (string val, out string asmName, out string resName)
 		{
-			byte[] key = GetEncryptionKey ();
-			byte[] bytes = GetBytes (val);
-			byte[] result;
+			byte[] bytes = Convert.FromBase64String (val);
 
 			asmName = null;
 			resName = null;			
 
-			ICryptoTransform decryptor = TripleDES.Create ().CreateDecryptor (key, init_vector);
-			result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
+			byte[] result = MachineKeySectionUtils.Decrypt (MachineKeySection.Config, bytes);
 			bytes = null;
+			// null will be returned if, for any reason, decryption fails
+			if (result == null)
+				return;
 
 			string data = Encoding.UTF8.GetString (result);
 			result = null;
@@ -201,7 +154,7 @@ namespace System.Web.Handlers {
 			if (apath != String.Empty)
 				atime = String.Concat (QueryParamSeparator, "t=", File.GetLastWriteTimeUtc (apath).Ticks);
 #endif
-			string href = HandlerFileName + "?" + EncryptAssemblyResource (aname, resourceName) + atime + extra;
+			string href = HandlerFileName + "?d=" + EncryptAssemblyResource (aname, resourceName) + atime + extra;
 
 			HttpContext ctx = HttpContext.Current;
 			if (ctx != null && ctx.Request != null) {
@@ -225,7 +178,13 @@ namespace System.Web.Handlers {
 			string asmName;
 			Assembly assembly;
 
-			DecryptAssemblyResource (request.QueryString ["d"], out asmName, out resourceName);
+			// val is URL-decoded, which means every + has been replaced with ' ', we
+			// need to revert that or the base64 conversion will fail.
+			string d = request.QueryString ["d"];
+			if (!String.IsNullOrEmpty (d))
+				d = d.Replace (' ', '+');
+
+			DecryptAssemblyResource (d, out asmName, out resourceName);
 			if (resourceName == null)
 				throw new HttpException (404, "No resource name given");
 
diff --git a/mcs/class/System.Web/System.Web.Handlers/ChangeLog b/mcs/class/System.Web/System.Web.Handlers/ChangeLog
index f043396..c1b9f63 100644
--- a/mcs/class/System.Web/System.Web.Handlers/ChangeLog
+++ b/mcs/class/System.Web/System.Web.Handlers/ChangeLog
@@ -1,3 +1,17 @@
+2010-10-12  Sebastien Pouliot  <sebastien at ximian.com>
+
+	A few moves/changes following previous patch review
+
+2010-10-08  Sebastien Pouliot  <sebastien at ximian.com>
+
+	* System.Web.Handlers/AssemblyResourceLoader.cs: Use the new
+	common cryptographic code and base64 the encrypted data.
+
+2010-10-18  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] make sure the string we pass to DecryptAssemblyResource
+	is a valid Base64 string
+
 2009-07-08 Gonzalo Paniagua Javier <gonzalo at novell.com>
 
 	* AssemblyResourceLoader.cs: send minimal headers set and don't call
diff --git a/mcs/class/System.Web/System.Web.Handlers/ChangeLog b/mcs/class/System.Web/System.Web.Handlers/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Web/System.Web.Handlers/ChangeLog
copy to mcs/class/System.Web/System.Web.Handlers/ChangeLog.old
diff --git a/mcs/class/System.Web/System.Web.Security/ChangeLog b/mcs/class/System.Web/System.Web.Security/ChangeLog
index ec22dc4..bddcfdf 100644
--- a/mcs/class/System.Web/System.Web.Security/ChangeLog
+++ b/mcs/class/System.Web/System.Web.Security/ChangeLog
@@ -1,3 +1,28 @@
+2010-10-04  Sebastien Pouliot  <sebastien at ximian.com>
+
+	* System.Web.Security/FormsAuthentication.cs: Fix typo
+	(MD5->SHA1). I suspect the later is not used very much by mono
+	users
+
+2010-10-12  Sebastien Pouliot  <sebastien at ximian.com>
+
+	A few moves/changes following previous patch review
+
+2010-10-08  Sebastien Pouliot  <sebastien at ximian.com>
+
+	* System.Web.Security/FormsAuthentication.cs: Use the new common
+	cryptographic code and base64 the signed and/or encrypted data.
+
+	* System.Web.Security/MembershipHelper.cs: Use the new common
+	cryptographic code - this should be 100% compatible with existing
+	data.
+
+	* System.Web.Security/RolePrincipal.cs: Use the new common
+	cryptographic code.
+
+	* System.Web.Security/SqliteMembershipProvider.cs: Adapt code for
+	internal API change.
+
 2010-06-19  Marek Habersack  <mhabersack at novell.com>
 
 	* FormsAuthentication.cs: Authenticate must compare stored and
diff --git a/mcs/class/System.Web/System.Web.Security/ChangeLog b/mcs/class/System.Web/System.Web.Security/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Web/System.Web.Security/ChangeLog
copy to mcs/class/System.Web/System.Web.Security/ChangeLog.old
diff --git a/mcs/class/System.Web/System.Web.Security/FormsAuthentication.cs b/mcs/class/System.Web/System.Web.Security/FormsAuthentication.cs
index 227aa96..ac9ec76 100644
--- a/mcs/class/System.Web/System.Web.Security/FormsAuthentication.cs
+++ b/mcs/class/System.Web/System.Web.Security/FormsAuthentication.cs
@@ -45,9 +45,6 @@ namespace System.Web.Security
 	[AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
 	public sealed class FormsAuthentication
 	{
-		const int MD5_hash_size = 16;
-		const int SHA1_hash_size = 20;
-
 		static string authConfigPath = "system.web/authentication";
 		static string machineKeyConfigPath = "system.web/machineKey";
 #if TARGET_J2EE
@@ -56,7 +53,6 @@ namespace System.Web.Security
 		const string Forms_cookiePath = "Forms.cookiePath";
 		const string Forms_timeout = "Forms.timeout";
 		const string Forms_protection = "Forms.protection";
-		const string Forms_init_vector = "Forms.init_vector";
 		static bool initialized
 		{
 			get {
@@ -88,11 +84,6 @@ namespace System.Web.Security
 			get { return (FormsProtectionEnum) AppDomain.CurrentDomain.GetData (Forms_protection); }
 			set { AppDomain.CurrentDomain.SetData (Forms_protection, value); }
 		}
-		static byte [] init_vector
-		{
-			get { return (byte []) AppDomain.CurrentDomain.GetData (Forms_init_vector); }
-			set { AppDomain.CurrentDomain.SetData (Forms_init_vector, value); }
-		}
 		static object locker = new object ();
 #else
 		static bool initialized;
@@ -101,7 +92,6 @@ namespace System.Web.Security
 		static int timeout;
 		static FormsProtectionEnum protection;
 		static object locker = new object ();
-		static byte [] init_vector; // initialization vector used for 3DES
 #endif
 #if NET_1_1
 #if TARGET_J2EE
@@ -230,25 +220,13 @@ namespace System.Web.Security
 				password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
 				break;
 			case FormsAuthPasswordFormat.SHA1:
-				password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
+				password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
 				break;
 			}
 
 			return String.Compare (password, stored, caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0;
 		}
 
-#if NET_2_0
-		static byte [] GetDecryptionKey (MachineKeySection config)
-		{
-			return MachineKeySectionUtils.DecryptionKey192Bits (config);
-		}
-#else
-		static byte [] GetDecryptionKey (MachineKeyConfig config)
-		{
-			return config.DecryptionKey192Bits;
-		}
-#endif
-		
 		static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
 		{
 			if (protection == FormsProtectionEnum.None)
@@ -259,59 +237,14 @@ namespace System.Web.Security
 #else
 			MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
 #endif
-			bool all = (protection == FormsProtectionEnum.All);
-
-			byte [] result = bytes;
-			if (all || protection == FormsProtectionEnum.Encryption) {
-				ICryptoTransform decryptor;
-				decryptor = TripleDES.Create ().CreateDecryptor (GetDecryptionKey (config), init_vector);
-				result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
-				bytes = null;
-			}
-
-			if (all || protection == FormsProtectionEnum.Validation) {
-				int count;
-				MachineKeyValidation validationType;
-
-#if NET_2_0
-				validationType = config.Validation;
-#else
-				validationType = config.ValidationType;
-#endif
-				if (validationType == MachineKeyValidation.MD5)
-					count = MD5_hash_size;
-				else
-					count = SHA1_hash_size; // 3DES and SHA1
-
-#if NET_2_0
-				byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
-#else
-				byte [] vk = config.ValidationKey;
-#endif
-				byte [] mix = new byte [result.Length - count + vk.Length];
-				Buffer.BlockCopy (result, 0, mix, 0, result.Length - count);
-				Buffer.BlockCopy (vk, 0, mix, result.Length - count, vk.Length);
-
-				byte [] hash = null;
-				switch (validationType) {
-				case MachineKeyValidation.MD5:
-					hash = MD5.Create ().ComputeHash (mix);
-					break;
-				// From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
-				case MachineKeyValidation.TripleDES:
-				case MachineKeyValidation.SHA1:
-					hash = SHA1.Create ().ComputeHash (mix);
-					break;
-				}
-
-				if (result.Length < count)
-					throw new ArgumentException ("Error validating ticket (length).", "encryptedTicket");
 
-				int i, k;
-				for (i = result.Length - count, k = 0; k < count; i++, k++) {
-					if (result [i] != hash [k])
-						throw new ArgumentException ("Error validating ticket.", "encryptedTicket");
-				}
+			byte [] result = null;
+			if (protection == FormsProtectionEnum.All) {
+				result = MachineKeySectionUtils.VerifyDecrypt (config, bytes);
+			} else if (protection == FormsProtectionEnum.Encryption) {
+				result = MachineKeySectionUtils.Decrypt (config, bytes);
+			} else if (protection == FormsProtectionEnum.Validation) {
+				result = MachineKeySectionUtils.Verify (config, bytes);
 			}
 
 			return FormsAuthenticationTicket.FromByteArray (result);
@@ -325,11 +258,8 @@ namespace System.Web.Security
 			Initialize ();
 
 			FormsAuthenticationTicket ticket;
-#if NET_2_0
-			byte [] bytes = MachineKeySectionUtils.GetBytes (encryptedTicket, encryptedTicket.Length);
-#else
-			byte [] bytes = MachineKeyConfig.GetBytes (encryptedTicket, encryptedTicket.Length);
-#endif
+			byte [] bytes = Convert.FromBase64String (encryptedTicket);
+
 			try {
 				ticket = Decrypt2 (bytes);
 			} catch (Exception) {
@@ -347,57 +277,23 @@ namespace System.Web.Security
 			Initialize ();
 			byte [] ticket_bytes = ticket.ToByteArray ();
 			if (protection == FormsProtectionEnum.None)
-				return GetHexString (ticket_bytes);
+				return Convert.ToBase64String (ticket_bytes);
 
-			byte [] result = ticket_bytes;
+			byte [] result = null;
 #if NET_2_0
 			MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
 #else
 			MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
 #endif
-			bool all = (protection == FormsProtectionEnum.All);
-			if (all || protection == FormsProtectionEnum.Validation) {
-				byte [] valid_bytes = null;
-#if NET_2_0
-				byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
-#else
-				byte [] vk = config.ValidationKey;
-#endif
-				byte [] mix = new byte [ticket_bytes.Length + vk.Length];
-				Buffer.BlockCopy (ticket_bytes, 0, mix, 0, ticket_bytes.Length);
-				Buffer.BlockCopy (vk, 0, mix, result.Length, vk.Length);
-
-				switch (
-#if NET_2_0
-					config.Validation
-#else
-					config.ValidationType
-#endif
-					) {
-				case MachineKeyValidation.MD5:
-					valid_bytes = MD5.Create ().ComputeHash (mix);
-					break;
-				// From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
-				case MachineKeyValidation.TripleDES:
-				case MachineKeyValidation.SHA1:
-					valid_bytes = SHA1.Create ().ComputeHash (mix);
-					break;
-				}
-
-				int tlen = ticket_bytes.Length;
-				int vlen = valid_bytes.Length;
-				result = new byte [tlen + vlen];
-				Buffer.BlockCopy (ticket_bytes, 0, result, 0, tlen);
-				Buffer.BlockCopy (valid_bytes, 0, result, tlen, vlen);
+			if (protection == FormsProtectionEnum.All) {
+				result = MachineKeySectionUtils.EncryptSign (config, ticket_bytes);
+			} else if (protection == FormsProtectionEnum.Encryption) {
+				result = MachineKeySectionUtils.Encrypt (config, ticket_bytes);
+			} else if (protection == FormsProtectionEnum.Validation) {
+				result = MachineKeySectionUtils.Sign (config, ticket_bytes);
 			}
 
-			if (all || protection == FormsProtectionEnum.Encryption) {
-				ICryptoTransform encryptor;
-				encryptor = TripleDES.Create ().CreateEncryptor (GetDecryptionKey (config), init_vector);
-				result = encryptor.TransformFinalBlock (result, 0, result.Length);
-			}
-
-			return GetHexString (result);
+			return Convert.ToBase64String (result);
 		}
 
 		public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
@@ -478,21 +374,6 @@ namespace System.Web.Security
 			return returnUrl;
 		}
 
-		static string GetHexString (byte [] bytes)
-		{
-			const int letterPart = 55;
-			const int numberPart = 48;
-			char [] result = new char [bytes.Length * 2];
-			for (int i = 0; i < bytes.Length; i++) {
-				int tmp = (int) bytes [i];
-				int second = tmp & 15;
-				int first = (tmp >> 4) & 15;
-				result [(i * 2)] = (char) (first > 9 ? letterPart + first : numberPart + first);
-				result [(i * 2) + 1] = (char) (second > 9 ? letterPart + second : numberPart + second);
-			}
-			return new string (result);
-		}
-
 		static string HashPasswordForStoringInConfigFile (string password, FormsAuthPasswordFormat passwordFormat)
 		{
 			if (password == null)
@@ -512,7 +393,7 @@ namespace System.Web.Security
 					throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
 			}
 
-			return GetHexString (bytes);
+			return MachineKeySectionUtils.GetHexString (bytes);
 		}
 		
 		public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
@@ -580,16 +461,6 @@ namespace System.Web.Security
 				}
 #endif
 
-				// IV is 8 bytes long for 3DES
-				init_vector = new byte [8];
-				int len = cookieName.Length;
-				for (int i = 0; i < 8; i++) {
-					if (i >= len)
-						break;
-
-					init_vector [i] = (byte) cookieName [i];
-				}
-
 				initialized = true;
 			}
 		}
diff --git a/mcs/class/System.Web/System.Web.Security/MembershipHelper.cs b/mcs/class/System.Web/System.Web.Security/MembershipHelper.cs
index 2292db0..5595fa1 100644
--- a/mcs/class/System.Web/System.Web.Security/MembershipHelper.cs
+++ b/mcs/class/System.Web/System.Web.Security/MembershipHelper.cs
@@ -1,5 +1,5 @@
 //
-// System.Web.Security.MembershipEncryptionHelper
+// System.Web.Security.MembershipHelper
 //
 // Authors:
 //	Ben Maurer (bmaurer at users.sourceforge.net)
@@ -27,10 +27,11 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-using System;
+
 using System.Configuration.Provider;
 using System.Security.Cryptography;
 using System.Web.Configuration;
+using System.Web.Util;
 
 namespace System.Web.Security
 {
@@ -49,56 +50,32 @@ namespace System.Web.Security
 			get { return Membership.Providers; }
 		}
 		
-		static SymmetricAlgorithm GetAlg ()
+		static SymmetricAlgorithm GetAlgorithm ()
 		{
-			MachineKeySection section = (MachineKeySection) WebConfigurationManager.GetSection ("system.web/machineKey");
+			MachineKeySection section = MachineKeySection.Config;
 
 			if (section.DecryptionKey.StartsWith ("AutoGenerate"))
 				throw new ProviderException ("You must explicitly specify a decryption key in the <machineKey> section when using encrypted passwords.");
 
-			string alg_type = section.Decryption;
-			if (alg_type == "Auto")
-				alg_type = "AES";
-
-			SymmetricAlgorithm alg = null;
-			if (alg_type == "AES")
-				alg = Rijndael.Create ();
-			else if (alg_type == "3DES")
-				alg = TripleDES.Create ();
-			else
-				throw new ProviderException (String.Format ("Unsupported decryption attribute '{0}' in <machineKey> configuration section", alg_type));
+			SymmetricAlgorithm sa = section.GetDecryptionAlgorithm ();
+			if (sa == null)
+				throw new ProviderException (String.Format ("Unsupported decryption attribute '{0}' in <machineKey> configuration section", section.Decryption));
 
-			alg.Key = MachineKeySectionUtils.DecryptionKey192Bits (section);
-			return alg;
+			sa.Key = section.GetDecryptionKey ();
+			return sa;
 		}
 		
 		public byte [] DecryptPassword (byte [] encodedPassword)
 		{
-			using (SymmetricAlgorithm alg = GetAlg ()) {
-				// alg.Key is set in GetAlg based on web.config
-				// iv is the first part of the encodedPassword
-				byte [] iv = new byte [alg.IV.Length];
-				Array.Copy (encodedPassword, 0, iv, 0, iv.Length);
-				using (ICryptoTransform decryptor = alg.CreateDecryptor (alg.Key, iv)) {
-					return decryptor.TransformFinalBlock (encodedPassword, iv.Length, encodedPassword.Length - iv.Length);
-				}
+			using (SymmetricAlgorithm sa = GetAlgorithm ()) {
+				return MachineKeySectionUtils.Decrypt (sa, encodedPassword, 0, encodedPassword.Length);
 			}
 		}
 
 		public byte[] EncryptPassword (byte[] password)
 		{
-			using (SymmetricAlgorithm alg = GetAlg ()) {
-				// alg.Key is set in GetAlg based on web.config
-				// alg.IV is randomly set (default behavior) and perfect for our needs
-				byte [] iv = alg.IV;
-				using (ICryptoTransform encryptor = alg.CreateEncryptor (alg.Key, iv)) {
-					byte [] encrypted = encryptor.TransformFinalBlock (password, 0, password.Length);
-					byte [] output = new byte [iv.Length + encrypted.Length];
-					// note: the IV can be public, however it should not be based on the password
-					Array.Copy (iv, 0, output, 0, iv.Length);
-					Array.Copy (encrypted, 0, output, iv.Length, encrypted.Length);
-					return output;
-				}
+			using (SymmetricAlgorithm sa = GetAlgorithm ()) {
+				return MachineKeySectionUtils.Encrypt (sa, password);
 			}
 		}
 	}
diff --git a/mcs/class/System.Web/System.Web.Security/RolePrincipal.cs b/mcs/class/System.Web/System.Web.Security/RolePrincipal.cs
index ed23ec7..b210f82 100644
--- a/mcs/class/System.Web/System.Web.Security/RolePrincipal.cs
+++ b/mcs/class/System.Web/System.Web.Security/RolePrincipal.cs
@@ -29,10 +29,10 @@
 //
 
 using System.Collections.Specialized;
-using System.Security.Cryptography;
 using System.Security.Permissions;
 using System.Security.Principal;
 using System.Web.Configuration;
+using System.Web.Util;
 using System.IO;
 using System.Text;
 
@@ -146,42 +146,16 @@ namespace System.Web.Security {
 
 			CookieProtection cookieProtection = RoleManagerConfig.CookieProtection;
 
-			if (cookieProtection == CookieProtection.None)
-				return GetBase64FromBytes (ticket.GetBuffer (), 0, (int) ticket.Position);
-			
-			if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) {
-
-				byte [] hashBytes = null;
-				byte [] validationBytes = MachineKeySectionUtils.ValidationKeyBytes (MachineConfig);
-				writer.Write (validationBytes);
-
-				switch (MachineConfig.Validation) {
-					case MachineKeyValidation.MD5:
-						hashBytes = MD5.Create ().ComputeHash (ticket.GetBuffer (), 0, (int) ticket.Position);
-						break;
-
-					case MachineKeyValidation.TripleDES:
-					case MachineKeyValidation.SHA1:
-						hashBytes = SHA1.Create ().ComputeHash (ticket.GetBuffer (), 0, (int) ticket.Position);
-						break;
-				}
-
-				writer.Seek (-validationBytes.Length, SeekOrigin.Current);
-				writer.Write (hashBytes);
-			}
-
-			byte [] ticketBytes = null;
-			if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) {
-				ICryptoTransform enc;
-				enc = TripleDES.Create ().CreateEncryptor (MachineKeySectionUtils.DecryptionKey192Bits (MachineConfig),
-									   InitVector);
-				ticketBytes = enc.TransformFinalBlock (ticket.GetBuffer (), 0, (int) ticket.Position);
+			byte[] ticket_data = ticket.GetBuffer ();
+			if (cookieProtection == CookieProtection.All) {
+				ticket_data = MachineKeySectionUtils.EncryptSign (MachineConfig, ticket_data);
+			} else if (cookieProtection == CookieProtection.Encryption) {
+				ticket_data = MachineKeySectionUtils.Encrypt (MachineConfig, ticket_data);
+			} else if (cookieProtection == CookieProtection.Validation) {
+				ticket_data = MachineKeySectionUtils.Sign (MachineConfig, ticket_data);
 			}
 
-			if (ticketBytes == null)
-				return GetBase64FromBytes (ticket.GetBuffer (), 0, (int) ticket.Position);
-			else
-				return GetBase64FromBytes (ticketBytes, 0, ticketBytes.Length);
+			return GetBase64FromBytes (ticket_data, 0, ticket_data.Length);
 		}
 
 		void DecryptTicket (string encryptedTicket)
@@ -193,45 +167,18 @@ namespace System.Web.Security {
 			byte [] decryptedTicketBytes = null;
 
 			CookieProtection cookieProtection = RoleManagerConfig.CookieProtection;
-			if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) {
-				ICryptoTransform decryptor;
-				decryptor = TripleDES.Create ().CreateDecryptor (
-					MachineKeySectionUtils.DecryptionKey192Bits (MachineConfig),
-					InitVector);
-				decryptedTicketBytes = decryptor.TransformFinalBlock (ticketBytes, 0, ticketBytes.Length);
-			}
-			else
-				decryptedTicketBytes = ticketBytes;
-
-			if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) {
-				byte [] validationBytes = MachineKeySectionUtils.ValidationKeyBytes (MachineConfig);
-				byte [] rolesWithValidationBytes = null;
-				byte [] tmpValidation = null;
 
-				int hashSize = (MachineConfig.Validation == MachineKeyValidation.MD5) ? 16 : 20; //md5 is 16 bytes, sha1 is 20 bytes
-
-				rolesWithValidationBytes = new byte [decryptedTicketBytes.Length - hashSize + validationBytes.Length];
-
-				Buffer.BlockCopy (decryptedTicketBytes, 0, rolesWithValidationBytes, 0, decryptedTicketBytes.Length - hashSize);
-				Buffer.BlockCopy (validationBytes, 0, rolesWithValidationBytes, decryptedTicketBytes.Length - hashSize, validationBytes.Length);
-
-				switch (MachineConfig.Validation) {
-					case MachineKeyValidation.MD5:
-						tmpValidation = MD5.Create ().ComputeHash (rolesWithValidationBytes);
-						break;
-
-					case MachineKeyValidation.TripleDES:
-					case MachineKeyValidation.SHA1:
-						tmpValidation = SHA1.Create ().ComputeHash (rolesWithValidationBytes);
-						break;
-				}
-				for (int i = 0; i < tmpValidation.Length; i++) {
-					if (i >= decryptedTicketBytes.Length ||
-						tmpValidation [i] != decryptedTicketBytes [i + decryptedTicketBytes.Length - hashSize])
-						throw new HttpException ("ticket validation failed");
-				}
+			if (cookieProtection == CookieProtection.All) {
+				decryptedTicketBytes = MachineKeySectionUtils.VerifyDecrypt (MachineConfig, ticketBytes);
+			} else if (cookieProtection == CookieProtection.Encryption) {
+				decryptedTicketBytes = MachineKeySectionUtils.Decrypt (MachineConfig, ticketBytes);
+			} else if (cookieProtection == CookieProtection.Validation) {
+				decryptedTicketBytes = MachineKeySectionUtils.Verify (MachineConfig, ticketBytes);
 			}
 
+			if (decryptedTicketBytes == null)
+				throw new HttpException ("ticket validation failed");
+
 			MemoryStream ticket = new MemoryStream (decryptedTicketBytes);
 			BinaryReader reader = new BinaryReader (ticket);
 
@@ -276,11 +223,6 @@ namespace System.Web.Security {
 				_cachedRoles.Add (r, r);
 		}
 
-		byte [] InitVector
-		{
-			get { return new byte [] { 1, 2, 3, 4, 5, 6, 7, 8 }; }
-		}
-		
 		public bool CachedListChanged {
 			get { return _listChanged; }
 		}
diff --git a/mcs/class/System.Web/System.Web.Security/SqlMembershipProvider.cs b/mcs/class/System.Web/System.Web.Security/SqlMembershipProvider.cs
index 5242a20..8bfac0a 100644
--- a/mcs/class/System.Web/System.Web.Security/SqlMembershipProvider.cs
+++ b/mcs/class/System.Web/System.Web.Security/SqlMembershipProvider.cs
@@ -1048,11 +1048,22 @@ namespace System.Web.Security {
 
 					MembershipSection section = (MembershipSection) WebConfigurationManager.GetSection ("system.web/membership");
 					string alg_type = section.HashAlgorithmType;
-					if (alg_type == "") {
-						MachineKeySection keysection = (MachineKeySection) WebConfigurationManager.GetSection ("system.web/machineKey");
-						alg_type = keysection.Validation.ToString ();
+					if (alg_type.Length == 0) {
+						alg_type = MachineKeySection.Config.Validation.ToString ();
+#if NET_4_0
+						// support new (4.0) custom algorithms
+						if (alg_type.StartsWith ("alg:"))
+							alg_type = alg_type.Substring (4);
+#endif
 					}
 					using (HashAlgorithm hash = HashAlgorithm.Create (alg_type)) {
+#if NET_4_0
+						// for compatibility (with 2.0) we'll allow MD5 and SHA1 not to map to HMACMD5 and HMACSHA1
+						// but that won't work with new (4.0) algorithms, like HMACSHA256|384|512 or custom, won't work without using the key
+						KeyedHashAlgorithm kha = (hash as KeyedHashAlgorithm);
+						if (kha != null)
+							kha.Key = MachineKeySection.Config.GetValidationKey ();
+#endif
 						hash.TransformFinalBlock (hashBytes, 0, hashBytes.Length);
 						return Convert.ToBase64String (hash.Hash);
 					}
diff --git a/mcs/class/System.Web/System.Web.Security/SqliteMembershipProvider.cs b/mcs/class/System.Web/System.Web.Security/SqliteMembershipProvider.cs
index f7be4be..2acff57 100644
--- a/mcs/class/System.Web/System.Web.Security/SqliteMembershipProvider.cs
+++ b/mcs/class/System.Web/System.Web.Security/SqliteMembershipProvider.cs
@@ -1432,7 +1432,7 @@ namespace System.Web.Security
 				case MembershipPasswordFormat.Hashed:
 					HMACSHA1 hash = new HMACSHA1();
 					if (machineKeyIsAutoGenerated)
-						hash.Key = MachineKeySectionUtils.ValidationKeyBytes ();
+						hash.Key = MachineKeySection.Config.GetValidationKey ();
 					else
 						hash.Key = HexToByte(m_MachineKey.ValidationKey);
 					encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
diff --git a/mcs/class/System.Web/System.Web.SessionState_2.0/ChangeLog b/mcs/class/System.Web/System.Web.SessionState_2.0/ChangeLog
index 562a552..b83e184 100644
--- a/mcs/class/System.Web/System.Web.SessionState_2.0/ChangeLog
+++ b/mcs/class/System.Web/System.Web.SessionState_2.0/ChangeLog
@@ -1,3 +1,11 @@
+2010-10-12  Sebastien Pouliot  <sebastien at ximian.com>
+
+	A few moves/changes following previous patch review
+
+2010-10-08  Sebastien Pouliot  <sebastien at ximian.com>
+
+	Normalization of cryptographic uses in asp.net
+
 2010-08-10  Marek Habersack  <grendel at twistedcode.net>
 
 	[asp.net] Fix for bug #629990 In-Proc session state must remove
diff --git a/mcs/class/System.Web/System.Web.SessionState_2.0/SessionId.cs b/mcs/class/System.Web/System.Web.SessionState_2.0/SessionId.cs
index c1eac4d..aac1ed6 100644
--- a/mcs/class/System.Web/System.Web.SessionState_2.0/SessionId.cs
+++ b/mcs/class/System.Web/System.Web.SessionState_2.0/SessionId.cs
@@ -28,15 +28,12 @@
 
 using System.Text;
 using System.Security.Cryptography;
+using System.Web.Util;
 
 namespace System.Web.SessionState {
 
 	internal class SessionId {
 
-		static char [] allowed = { '0', '1', '2', '3', '4', '5',
-						   '6', '7', '8', '9', 'A', 'B',
-						   'C', 'D', 'E', 'F' };
-
 		internal const int IdLength = 24;
 		const int half_len = IdLength / 2;
 		static RandomNumberGenerator rng = RandomNumberGenerator.Create ();
@@ -48,25 +45,9 @@ namespace System.Web.SessionState {
 			lock (rng) {
 				rng.GetBytes (key);
 			}
-			return Encode (key);
+			return MachineKeySectionUtils.GetHexString (key);
 		}
 
-		internal static string Encode (byte[] key)
-		{
-			if (key == null)
-				throw new ArgumentNullException ("key");
-			if (key.Length != half_len)
-				throw new ArgumentException (String.Concat ("key must be ", half_len.ToString (), " bytes long."));
-
-			// Just a standard hex conversion
-			char[] res = new char [IdLength];
-			for (int i=0; i < half_len; i++) {
-				int b = key [i];
-				res [i * 2] = allowed [b >> 4];
-				res [(i * 2) + 1] = allowed [b & 0xF];
-			}
-			return new String (res);
-		}
 #if !NET_2_0
 		internal static string Lookup (HttpRequest request, bool cookieless)
 		{
diff --git a/mcs/class/System.Web/System.Web.UI/ChangeLog b/mcs/class/System.Web/System.Web.UI/ChangeLog
index 17b5a61..9dbdef9 100644
--- a/mcs/class/System.Web/System.Web.UI/ChangeLog
+++ b/mcs/class/System.Web/System.Web.UI/ChangeLog
@@ -1,3 +1,54 @@
+2010-11-11  Daniel J Sell  <dredd422 at gmail.com>
+
+	[asp.net] Fix for bug #653192. making MasterPageFile handle
+	relative paths
+
+	MasterPageFile should be relative to the file being parsed, not
+	the request path
+
+2010-10-21  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] ObjectStateFormatter.{De}serialize methods taking stream
+	use a magic value to mark the stream.
+
+2010-10-12  Sebastien Pouliot  <sebastien at ximian.com>
+
+	A few moves/changes following previous patch review
+
+2010-10-08  Sebastien Pouliot  <sebastien at ximian.com>
+
+	* System.Web.UI/LosFormatter.cs: Adapt code for internal API
+	change. Fix some small behaviro changes wrt NET_4_0
+
+	* System.Web.UI/ObjectStateFormatter.cs: Use the new common
+	cryptographic code.
+
+	* System.Web.UI/Page.cs: Remove code that is now unneeded (with
+	the new common cryptogrraphic code).
+
+2010-10-29  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Fix for bug #649551. The LosFormatter (bool, string)
+	constructor does not expect a base64-encoded string.
+
+	Telerik controls pass the string "string" as the macKeyModifier
+	parameter to the constructor. Tests show that .NET accepts such
+	input without throwing an error. The passed string is now
+	converted into a byte array and passed to the LosFormatter (bool,
+	byte[]) constructor.
+
+	This is a backport of 19e5207189c6905bd72e31e457450546b662e79d
+
+2010-10-29  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Fix for bug #649034. Control.FindControl continues to
+	search for controls above itself if it's a naming container.
+
+	When a control is a naming container and an attempt to find a
+	control with non-segmented id (e.g. 'myControl') is made, the
+	search continues to the control's naming container if pathOffset
+	is 0, that is we're at the start of the search.
+
 2010-10-05  Marek Habersack  <grendel at twistedcode.net>
 
 	[asp.net] Fix for bug #643298. A typo prevented the
diff --git a/mcs/class/System.Web/System.Web.UI/Control.cs b/mcs/class/System.Web/System.Web.UI/Control.cs
index 7f6ebe8..ac8acb8 100644
--- a/mcs/class/System.Web/System.Web.UI/Control.cs
+++ b/mcs/class/System.Web/System.Web.UI/Control.cs
@@ -1100,8 +1100,18 @@ namespace System.Web.UI
 				return null;
 			
 			int separatorIdx = id.IndexOf (IdSeparator, pathOffset);
-			if (separatorIdx == -1)
-				return LookForControlByName (id.Substring (pathOffset));
+			if (separatorIdx == -1) {
+				if (pathOffset == 0) {
+					namingContainer = NamingContainer;
+					if (namingContainer != null) {
+						Control ctl = namingContainer.FindControl (id);
+						if (ctl != null)
+							return ctl;
+					}
+				}
+
+				return LookForControlByName (pathOffset > 0 ? id.Substring (pathOffset) : id);
+			}
 
 			string idfound = id.Substring (pathOffset, separatorIdx - pathOffset);
 			namingContainer = LookForControlByName (idfound);
diff --git a/mcs/class/System.Web/System.Web.UI/LosFormatter.cs b/mcs/class/System.Web/System.Web.UI/LosFormatter.cs
index ef8c416..2c96543 100644
--- a/mcs/class/System.Web/System.Web.UI/LosFormatter.cs
+++ b/mcs/class/System.Web/System.Web.UI/LosFormatter.cs
@@ -28,10 +28,11 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+using System.Configuration;
 using System.IO;
-using System.Security.Cryptography;
 using System.Security.Permissions;
 using System.Text;
+using System.Web.Util;
 
 namespace System.Web.UI {
 
@@ -46,42 +47,58 @@ namespace System.Web.UI {
 			osf = new ObjectStateFormatter ();
 		}
 
-		public LosFormatter (bool enableMac, string macKeyModifier) : this (enableMac, Convert.FromBase64String (macKeyModifier))
+		public LosFormatter (bool enableMac, string macKeyModifier) : this (enableMac, String.IsNullOrEmpty (macKeyModifier) ? null : Encoding.ASCII.GetBytes (macKeyModifier))
 		{
 		}
 
-		[MonoTODO]
 		public LosFormatter (bool enableMac, byte[] macKeyModifier)
 		{
-			if (enableMac)
-				osf = new ObjectStateFormatter (macKeyModifier);
-			else
-				osf = new ObjectStateFormatter ();
+			osf = new ObjectStateFormatter ();
+			if (enableMac && (macKeyModifier != null)) {
+				SetMacKey (macKeyModifier);
+			}
+		}
+
+		private void SetMacKey (byte[] macKeyModifier)
+		{
+			try {
+				osf.Section.ValidationKey = MachineKeySectionUtils.GetHexString (macKeyModifier);
+			}
+			catch (ArgumentException) {
+			}
+			catch (ConfigurationErrorsException) {
+				// bad key (e.g. size), default key will be used
+			}
 		}
 
 		public object Deserialize (Stream stream)
 		{
 			if (stream == null)
 				throw new ArgumentNullException ("stream");
+#if NET_4_0
+			using (StreamReader sr = new StreamReader (stream)) {
+				return Deserialize (sr.ReadToEnd ());
+			}
+#else
 			long streamLength = -1;
 			if (stream.CanSeek)
 				streamLength = stream.Length;
-			byte [] bytes = new byte [streamLength >= 0 ? streamLength : 2048];
 			MemoryStream ms = null;
 			if (streamLength  != -1 && (stream is MemoryStream) && stream.Position == 0) {
 				// We save allocating a new stream and reading in this case.
 				ms = (MemoryStream) stream;
 			} else {
+				byte [] bytes = new byte [streamLength >= 0 ? streamLength : 2048];
 				ms = new MemoryStream ();
 				int n;
 				while ((n = stream.Read (bytes, 0, bytes.Length)) > 0)
 					ms.Write (bytes, 0, n);
 				streamLength = ms.Length;
 			}
-
 			string b64 = Encoding.ASCII.GetString (ms.GetBuffer (),
 				0, (int) streamLength);
 			return Deserialize (b64);
+#endif
 		}
 
 		public object Deserialize (TextReader input)
@@ -109,7 +126,10 @@ namespace System.Web.UI {
 		{
 			if (stream == null)
 				throw new ArgumentNullException ("stream");
-
+#if NET_4_0
+			if (!stream.CanSeek)
+				throw new NotSupportedException ();
+#endif
 			string b64 = SerializeToBase64 (value);
 			byte [] bytes = Encoding.ASCII.GetBytes (b64);
 			stream.Write (bytes, 0, bytes.Length);
diff --git a/mcs/class/System.Web/System.Web.UI/ObjectStateFormatter.cs b/mcs/class/System.Web/System.Web.UI/ObjectStateFormatter.cs
index 1464636..f4c6a6c 100644
--- a/mcs/class/System.Web/System.Web.UI/ObjectStateFormatter.cs
+++ b/mcs/class/System.Web/System.Web.UI/ObjectStateFormatter.cs
@@ -44,16 +44,16 @@ using System.Text;
 using System.Web.UI.WebControls;
 using System.Web.Util;
 using System.Diagnostics;
-using System.Security.Cryptography;
 using System.Web.Configuration;
 
 namespace System.Web.UI
 {
 	public sealed class ObjectStateFormatter : IFormatter, IStateFormatter
 	{
+		const ushort SERIALIZED_STREAM_MAGIC = 0x01FF;
+
 		Page page;
-		HashAlgorithm algo;
-		byte [] vkey;
+		MachineKeySection section;
 
 		public ObjectStateFormatter ()
 		{
@@ -64,65 +64,40 @@ namespace System.Web.UI
 			this.page = page;
 		}
 
-		internal ObjectStateFormatter (byte [] vkey)
-		{
-			this.vkey = vkey;
-		}
-		
-		internal bool EnableMac {
+		bool EnableMac {
 			get {
-				if (page == null) {
-					if (vkey == null)
-						return false;
-					return true;
-				} else				
-					return page.EnableViewStateMac;
+				return (page == null) ? (section != null) : page.EnableViewStateMac;
 			}
 		}
 
-		internal HashAlgorithm GetAlgo ()
-		{
-			if (algo != null)
-				return algo;
-			if (!EnableMac)
-				return null;
-			
-			byte [] algoKey;
-			if (page != null) {
-				MachineKeySection mconfig = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection ("system.web/machineKey");
-				algoKey = MachineKeySectionUtils.ValidationKeyBytes (mconfig);
-			} else
-				algoKey = vkey;
-
-			algo = new HMACSHA1 (algoKey);
-			return algo;
+		bool NeedViewStateEncryption {
+			get {
+				return (page == null) ? false : page.NeedViewStateEncryption;
+			}
 		}
 
-		static int ValidateInput (HashAlgorithm algo, byte [] data, int offset, int size)
-		{
-			if (algo == null)
-				throw new HttpException ("Unable to validate data.");
-			
-			int hash_size = algo.HashSize / 8;
-			if (size != 0 && size < hash_size)
-				throw new HttpException ("Unable to validate data.");
-
-			int data_length = size - hash_size;
-			MemoryStream data_stream = new MemoryStream (data, offset, data_length, false, false);
-			byte [] hash = algo.ComputeHash (data_stream);
-			for (int i = 0; i < hash_size; i++) {
-				if (hash [i] != data [data_length + i])
-					throw new HttpException ("Unable to validate data.");
-			}
-			return data_length;
+		internal MachineKeySection Section {
+			get {
+				if (section == null)
+					section = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection ("system.web/machineKey");
+				return section;
+			}
+			set {
+				section = value;
+			}
 		}
-		
+
 		public object Deserialize (Stream inputStream)
 		{
 			if (inputStream == null)
 				throw new ArgumentNullException ("inputStream");
 
-			return DeserializeObject (new BinaryReader (inputStream));
+			BinaryReader reader = new BinaryReader (inputStream);
+			short magic = reader.ReadInt16 ();
+			if (magic != SERIALIZED_STREAM_MAGIC)
+				throw new ArgumentException ("The serialized data is invalid");
+
+			return DeserializeObject (reader);
 		}
 		
 		public object Deserialize (string inputString)
@@ -132,45 +107,50 @@ namespace System.Web.UI
 			if (inputString.Length == 0)
 				throw new ArgumentNullException ("inputString");
 
-			byte [] buffer = Convert.FromBase64String (inputString);
-			int length;
-			if (buffer == null || (length = buffer.Length) == 0)
+			byte [] data = Convert.FromBase64String (inputString);
+			if (data == null || (data.Length) == 0)
 				throw new ArgumentNullException ("inputString");
-			if (page != null && EnableMac)
-				length = ValidateInput (GetAlgo (), buffer, 0, length);
 
-			bool isEncrypted = ((int)buffer [--length] == 1)? true : false;
-			Stream ms = new MemoryStream (buffer, 0, length, false, false);
-			if (isEncrypted)
-				ms = new CryptoStream (ms, page.GetCryptoTransform (CryptoStreamMode.Read), CryptoStreamMode.Read);
-			return Deserialize (ms);
+			if (NeedViewStateEncryption) {
+				if (EnableMac) {
+					data = MachineKeySectionUtils.VerifyDecrypt (Section, data);
+				} else {
+					data = MachineKeySectionUtils.Decrypt (Section, data);
+				}
+			} else if (EnableMac) {
+				data = MachineKeySectionUtils.Verify (Section, data);
+			}
+
+			if (data == null)
+				throw new HttpException ("Unable to validate data.");
+
+			using (MemoryStream ms = new MemoryStream (data)) {
+				return Deserialize (ms);
+			}
 		}
 		
 		public string Serialize (object stateGraph)
 		{
 			if (stateGraph == null)
 				return String.Empty;
-			
-			MemoryStream ms = new MemoryStream ();
-			Stream output = ms;
-			bool needEncryption = page == null ? false : page.NeedViewStateEncryption;
-			if (needEncryption){
-				output = new CryptoStream (output, page.GetCryptoTransform (CryptoStreamMode.Write), CryptoStreamMode.Write);
-			}
-			Serialize (output, stateGraph);
-			ms.WriteByte((byte)(needEncryption? 1 : 0));			
-#if TRACE
-			ms.WriteTo (File.OpenWrite (Path.GetTempFileName ()));
-#endif
-			if (EnableMac && ms.Length > 0) {
-				HashAlgorithm algo = GetAlgo ();
-				if (algo != null) {
-					byte [] hash = algo.ComputeHash (ms.GetBuffer (), 0, (int) ms.Length);
-					ms.Write (hash, 0, hash.Length);
+
+			byte[] data = null;
+			using (MemoryStream ms = new MemoryStream ()) {
+				Serialize (ms, stateGraph);
+				data = ms.GetBuffer ();
+			}
+
+			if (NeedViewStateEncryption) {
+				if (EnableMac) {
+					data = MachineKeySectionUtils.EncryptSign (Section, data);
+				} else {
+					data = MachineKeySectionUtils.Encrypt (Section, data);
 				}
-				
+			} else if (EnableMac) {
+				data = MachineKeySectionUtils.Sign (Section, data);
 			}
-			return Convert.ToBase64String (ms.GetBuffer (), 0, (int) ms.Length);
+			
+			return Convert.ToBase64String (data, 0, data.Length);
 		}
 		
 		public void Serialize (Stream outputStream, object stateGraph)
@@ -181,7 +161,10 @@ namespace System.Web.UI
 			if (stateGraph == null)
 				throw new ArgumentNullException ("stateGraph");
 
-			SerializeValue (new BinaryWriter (outputStream), stateGraph);
+			BinaryWriter writer = new BinaryWriter (outputStream);
+			writer.Write (SERIALIZED_STREAM_MAGIC);
+
+			SerializeValue (writer, stateGraph);
 		}
 		
 		void SerializeValue (BinaryWriter w, object o)
diff --git a/mcs/class/System.Web/System.Web.UI/Page.cs b/mcs/class/System.Web/System.Web.UI/Page.cs
index fa6159c..b44b318 100644
--- a/mcs/class/System.Web/System.Web.UI/Page.cs
+++ b/mcs/class/System.Web/System.Web.UI/Page.cs
@@ -39,7 +39,6 @@ using System.ComponentModel.Design;
 using System.ComponentModel.Design.Serialization;
 using System.Globalization;
 using System.IO;
-using System.Security.Cryptography;
 using System.Security.Permissions;
 using System.Security.Principal;
 using System.Text;
@@ -2375,74 +2374,6 @@ public partial class Page : TemplateControl, IHttpHandler
 		controlRegisteredForViewStateEncryption = true;
 	}
 
-	static byte [] AES_IV = null;
-	static byte [] TripleDES_IV = null;
-	static object locker = new object ();
-	static bool isEncryptionInitialized = false;
-
-	static void InitializeEncryption () 
-	{
-		if (isEncryptionInitialized)
-			return;
-
-		lock (locker) {
-			if (isEncryptionInitialized)
-				return;
-
-			string iv_string = "0BA48A9E-736D-40f8-954B-B2F62241F282";
-			AES_IV = new byte [16];
-			TripleDES_IV = new byte [8];
-
-			int i;
-			for (i = 0; i < AES_IV.Length; i++) {
-				AES_IV [i] = (byte) iv_string [i];
-			}
-
-			for (i = 0; i < TripleDES_IV.Length; i++) {
-				TripleDES_IV [i] = (byte) iv_string [i];
-			}
-
-			isEncryptionInitialized = true;
-		}
-	}
-
-	internal ICryptoTransform GetCryptoTransform (CryptoStreamMode cryptoStreamMode) 
-	{
-		ICryptoTransform transform = null;
-		MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
-		byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
-
-		switch (config.Validation) {
-			case MachineKeyValidation.SHA1:
-				transform = SHA1.Create ();
-				break;
-
-			case MachineKeyValidation.MD5:
-				transform = MD5.Create ();
-				break;
-
-			case MachineKeyValidation.AES:
-				InitializeEncryption ();
-				if (cryptoStreamMode == CryptoStreamMode.Read){
-					transform = Rijndael.Create().CreateDecryptor(vk, AES_IV);
-				} else {
-					transform = Rijndael.Create().CreateEncryptor(vk, AES_IV);
-				}
-				break;
-
-			case MachineKeyValidation.TripleDES:
-				InitializeEncryption ();
-				if (cryptoStreamMode == CryptoStreamMode.Read){
-					transform = TripleDES.Create().CreateDecryptor(vk, TripleDES_IV);
-				} else {
-					transform = TripleDES.Create().CreateEncryptor(vk, TripleDES_IV);
-				}
-				break;
-		}
-
-		return transform;
-	}
-
 	internal bool NeedViewStateEncryption {
 		get {
 			return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
diff --git a/mcs/class/System.Web/System.Web.UI/PageParser.cs b/mcs/class/System.Web/System.Web.UI/PageParser.cs
index 6f92e3c..82769d3 100644
--- a/mcs/class/System.Web/System.Web.UI/PageParser.cs
+++ b/mcs/class/System.Web/System.Web.UI/PageParser.cs
@@ -404,6 +404,7 @@ namespace System.Web.UI
 			value = GetString (atts, "MasterPageFile", masterPage != null ? masterPage.Value : null);
 			if (!String.IsNullOrEmpty (value)) {
 				if (!BaseParser.IsExpression (value)) {
+					value = System.Web.VirtualPathUtility.Combine(BaseVirtualDir, value);
 					if (!HostingEnvironment.VirtualPathProvider.FileExists (value))
 						ThrowParseFileNotFound (value);
 					AddDependency (value);
diff --git a/mcs/class/System.Web/System.Web.Util/ChangeLog b/mcs/class/System.Web/System.Web.Util/ChangeLog
index a8db970..83871f2 100644
--- a/mcs/class/System.Web/System.Web.Util/ChangeLog
+++ b/mcs/class/System.Web/System.Web.Util/ChangeLog
@@ -1,3 +1,7 @@
+2010-10-12  Sebastien Pouliot  <sebastien at ximian.com>
+
+	A few moves/changes following previous patch review
+
 2010-06-04  Jb Evain  <jbevain at novell.com>
 
 	* HttpEncoder.cs: only net_4_0 uses System.Web.Configuration.
diff --git a/mcs/class/System.Web/System.Web.Util/ChangeLog b/mcs/class/System.Web/System.Web.Util/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Web/System.Web.Util/ChangeLog
copy to mcs/class/System.Web/System.Web.Util/ChangeLog.old
diff --git a/mcs/class/System.Web/System.Web.Util/MachineKeySectionUtils.cs b/mcs/class/System.Web/System.Web.Util/MachineKeySectionUtils.cs
new file mode 100644
index 0000000..313bb43
--- /dev/null
+++ b/mcs/class/System.Web/System.Web.Util/MachineKeySectionUtils.cs
@@ -0,0 +1,315 @@
+//
+// System.Web.Util.MachineKeySectionUtils
+//
+// Authors:
+//	Chris Toshok (toshok at ximian.com)
+//	Sebastien Pouliot  <sebastien at ximian.com>
+//
+// (c) Copyright 2005, 2010 Novell, Inc (http://www.novell.com)
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.ComponentModel;
+using System.Configuration;
+using System.Configuration.Provider;
+using System.Security.Cryptography;
+using System.Text;
+using System.Web.Configuration;
+
+#if NET_2_0
+
+namespace System.Web.Util {
+
+	static class MachineKeySectionUtils {
+		static byte ToHexValue (char c, bool high)
+		{
+			byte v;
+			if (c >= '0' && c <= '9')
+				v = (byte) (c - '0');
+			else if (c >= 'a' && c <= 'f')
+				v = (byte) (c - 'a' + 10);
+			else if (c >= 'A' && c <= 'F')
+				v = (byte) (c - 'A' + 10);
+			else
+				throw new ArgumentException ("Invalid hex character");
+
+			if (high)
+				v <<= 4;
+
+			return v;
+		}
+
+		internal static byte [] GetBytes (string key, int len)
+		{
+			byte [] result = new byte [len / 2];
+			for (int i = 0; i < len; i += 2)
+				result [i / 2] = (byte) (ToHexValue (key [i], true) + ToHexValue (key [i + 1], false));
+
+			return result;
+		}
+
+		static public string GetHexString (byte [] bytes)
+		{
+			StringBuilder sb = new StringBuilder (bytes.Length * 2);
+			int letterPart = 55;
+			const int numberPart = 48;
+			for (int i = 0; i < bytes.Length; i++) {
+				int tmp = (int) bytes [i];
+				int second = tmp & 15;
+				int first = (tmp >> 4) & 15;
+				sb.Append ((char) (first > 9 ? letterPart + first : numberPart + first));
+				sb.Append ((char) (second > 9 ? letterPart + second : numberPart + second));
+			}
+			return sb.ToString ();
+		}
+
+
+		// decryption="Auto" [Auto | DES | 3DES | AES | alg:algorithm_name]
+		// http://msdn.microsoft.com/en-us/library/w8h3skw9.aspx
+		public static SymmetricAlgorithm GetDecryptionAlgorithm (string name)
+		{
+			SymmetricAlgorithm sa = null;
+			switch (name) {
+			case "AES":
+			case "Auto":
+				sa = Rijndael.Create ();
+				break;
+			case "DES":
+				sa = DES.Create ();
+				break;
+			case "3DES":
+				sa = TripleDES.Create ();
+				break;
+			default:
+#if NET_4_0
+				if (name.StartsWith ("alg:"))
+					sa = SymmetricAlgorithm.Create (name.Substring (4));
+				else
+#endif
+					throw new ConfigurationErrorsException ();
+				break;
+			}
+			return sa;
+		}
+
+		// validation="HMACSHA256" [SHA1 | MD5 | 3DES | AES | HMACSHA256 | HMACSHA384 | HMACSHA512 | alg:algorithm_name]
+		// [1] http://msdn.microsoft.com/en-us/library/system.web.configuration.machinekeyvalidation.aspx
+		// [2] http://msdn.microsoft.com/en-us/library/w8h3skw9.aspx
+		public static KeyedHashAlgorithm GetValidationAlgorithm (MachineKeySection section)
+		{
+			KeyedHashAlgorithm kha = null;
+			switch (section.Validation) {
+			case MachineKeyValidation.MD5:
+				kha = new HMACMD5 ();
+				break;
+			case MachineKeyValidation.AES:		// see link [1] or [2]
+			case MachineKeyValidation.TripleDES:	// see link [2]
+			case MachineKeyValidation.SHA1:
+				kha = new HMACSHA1 ();
+				break;
+#if NET_4_0
+			case MachineKeyValidation.HMACSHA256:
+				kha = new HMACSHA256 ();
+				break;
+			case MachineKeyValidation.HMACSHA384:
+				kha = new HMACSHA384 ();
+				break;
+			case MachineKeyValidation.HMACSHA512:
+				kha = new HMACSHA512 ();
+				break;
+			case MachineKeyValidation.Custom:
+				// remove the "alg:" from the start of the string
+				string algo = section.ValidationAlgorithm;
+				if (algo.StartsWith ("alg:"))
+					kha = KeyedHashAlgorithm.Create (algo.Substring (4));
+				break;
+#endif
+			}
+			return kha;
+		}
+
+		// helpers to ease unit testing of the cryptographic code
+#if TEST
+		static byte [] decryption_key;
+		static byte [] validation_key;
+
+		static SymmetricAlgorithm GetDecryptionAlgorithm (MachineKeySection section)
+		{
+			return GetDecryptionAlgorithm (section.Decryption);
+		}
+
+		static byte [] GetDecryptionKey (MachineKeySection section)
+		{
+			if (decryption_key == null)
+				decryption_key = GetDecryptionAlgorithm (section).Key;
+			return decryption_key;
+		}
+
+		static byte [] GetValidationKey (MachineKeySection section)
+		{
+			if (validation_key == null)
+				validation_key = GetValidationAlgorithm (section).Key;
+			return validation_key;
+		}
+#else
+		static SymmetricAlgorithm GetDecryptionAlgorithm (MachineKeySection section)
+		{
+			return section.GetDecryptionAlgorithm ();
+		}
+
+		static byte[] GetDecryptionKey (MachineKeySection section)
+		{
+			return section.GetDecryptionKey ();
+		}
+
+		static byte [] GetValidationKey (MachineKeySection section)
+		{
+			return section.GetValidationKey ();
+		}
+#endif
+
+		static public byte [] Decrypt (MachineKeySection section, byte [] encodedData)
+		{
+			return Decrypt (section, encodedData, 0, encodedData.Length);
+		}
+
+		static byte [] Decrypt (MachineKeySection section, byte [] encodedData, int offset, int length)
+		{
+			using (SymmetricAlgorithm sa = GetDecryptionAlgorithm (section)) {
+				sa.Key = GetDecryptionKey (section);
+				return Decrypt (sa, encodedData, offset, length);
+			}
+		}
+
+		static public byte [] Decrypt (SymmetricAlgorithm alg, byte [] encodedData, int offset, int length)
+		{
+			// alg.IV is randomly set (default behavior) and perfect for our needs
+			// iv is the first part of the encodedPassword
+			byte [] iv = new byte [alg.IV.Length];
+			Array.Copy (encodedData, 0, iv, 0, iv.Length);
+			using (ICryptoTransform decryptor = alg.CreateDecryptor (alg.Key, iv)) {
+				try {
+					return decryptor.TransformFinalBlock (encodedData, iv.Length + offset, length - iv.Length);
+				}
+				catch (CryptographicException) {
+					return null;
+				}
+			}
+		}
+
+		static public byte [] Encrypt (MachineKeySection section, byte [] data)
+		{
+			using (SymmetricAlgorithm sa = GetDecryptionAlgorithm (section)) {
+				sa.Key = GetDecryptionKey (section);
+				return Encrypt (sa, data);
+			}
+		}
+
+		static public byte [] Encrypt (SymmetricAlgorithm alg, byte [] data)
+		{
+			// alg.IV is randomly set (default behavior) and perfect for our needs
+			byte [] iv = alg.IV;
+			using (ICryptoTransform encryptor = alg.CreateEncryptor (alg.Key, iv)) {
+				byte [] encrypted = encryptor.TransformFinalBlock (data, 0, data.Length);
+				byte [] output = new byte [iv.Length + encrypted.Length];
+				// note: the IV can be public, however it should not be based on the password
+				Array.Copy (iv, 0, output, 0, iv.Length);
+				Array.Copy (encrypted, 0, output, iv.Length, encrypted.Length);
+				return output;
+			}
+		}
+
+		// in		[data]
+		// return	[data][signature]
+		public static byte [] Sign (MachineKeySection section, byte [] data)
+		{
+			return Sign (section, data, 0, data.Length);
+		}
+
+		static byte [] Sign (MachineKeySection section, byte [] data, int offset, int length)
+		{
+			using (KeyedHashAlgorithm kha = GetValidationAlgorithm (section)) {
+				kha.Key = GetValidationKey (section);
+				byte [] signature = kha.ComputeHash (data, offset, length);
+				byte [] block = new byte [length + signature.Length];
+				Array.Copy (data, block, length);
+				Array.Copy (signature, 0, block, length, signature.Length);
+				return block;
+			}
+		}
+
+		public static byte [] Verify (MachineKeySection section, byte [] data)
+		{
+			byte [] unsigned_data = null;
+			bool valid = true;
+			using (KeyedHashAlgorithm kha = GetValidationAlgorithm (section)) {
+				kha.Key = GetValidationKey (section);
+				int signlen = kha.HashSize >> 3; // bits to bytes
+				byte [] signature = Sign (section, data, 0, data.Length - signlen);
+				for (int i = 0; i < signature.Length; i++) {
+					if (signature [i] != data [data.Length - signature.Length + i])
+						valid = false; // do not return (timing attack)
+				}
+				unsigned_data = new byte [data.Length - signlen];
+				Array.Copy (data, 0, unsigned_data, 0, unsigned_data.Length);
+			}
+			return valid ? unsigned_data : null;
+		}
+
+		// do NOT sign then encrypt
+
+		public static byte [] EncryptSign (MachineKeySection section, byte [] data)
+		{
+			byte [] encdata = Encrypt (section, data);
+			return Sign (section, encdata);
+		}
+
+		// note: take no shortcut (timing attack) while verifying or decrypting
+		public static byte [] VerifyDecrypt (MachineKeySection section, byte [] block)
+		{
+			bool valid = true;
+			int signlen;
+
+			using (KeyedHashAlgorithm kha = GetValidationAlgorithm (section)) {
+				kha.Key = GetValidationKey (section);
+				signlen = kha.HashSize >> 3; // bits to bytes
+				byte [] signature = Sign (section, block, 0, block.Length - signlen);
+				for (int i = 0; i < signature.Length; i++) {
+					if (signature [i] != block [block.Length - signature.Length + i])
+						valid = false; // do not return (timing attack)
+				}
+			}
+
+			// whatever the signature continue with decryption
+			try {
+				byte [] decdata = Decrypt (section, block, 0, block.Length - signlen);
+				return valid ? decdata : null;
+			}
+			catch {
+				return null;
+			}
+		}
+	}
+}
+
+#endif
diff --git a/mcs/class/System.Web/System.Web.dll.sources b/mcs/class/System.Web/System.Web.dll.sources
index 211af52..d270d69 100644
--- a/mcs/class/System.Web/System.Web.dll.sources
+++ b/mcs/class/System.Web/System.Web.dll.sources
@@ -182,7 +182,6 @@ System.Web.Configuration_2.0/IRemoteWebConfigurationHostServer.cs
 System.Web.Configuration_2.0/LowerCaseStringConverter.cs
 System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs
 System.Web.Configuration_2.0/MachineKeySection.cs
-System.Web.Configuration_2.0/MachineKeySectionUtils.cs
 System.Web.Configuration_2.0/MachineKeyValidation.cs
 System.Web.Configuration_2.0/MachineKeyValidationConverter.cs
 System.Web.Configuration_2.0/MembershipSection.cs
@@ -1165,6 +1164,7 @@ System.Web.Util/HttpEncoder.cs
 System.Web.Util/ICalls.cs
 System.Web.Util/IWebObjectFactory.cs
 System.Web.Util/IWebPropertyAccessor.cs
+System.Web.Util/MachineKeySectionUtils.cs
 System.Web.Util/RuntimeHelpers.cs
 System.Web.Util/SearchPattern.cs
 System.Web.Util/SerializationHelper.cs
diff --git a/mcs/class/System.Web/System.Web/ChangeLog b/mcs/class/System.Web/System.Web/ChangeLog
index 60da51b..6485424 100644
--- a/mcs/class/System.Web/System.Web/ChangeLog
+++ b/mcs/class/System.Web/System.Web/ChangeLog
@@ -1,3 +1,29 @@
+2010-11-11  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Don't cache child nodes when security trimming is enabled.
+
+	When SecurityTrimmingEnabled is set to true for the node, the
+	cached children collection also depends on the IPrincipal set for
+	the current context.
+
+	Fixes bug #641449.
+
+2010-10-24  Marek Habersack  <grendel at twistedcode.net>
+
+	* HttpRuntime.cs: disable filesystem watchers on appdomain
+	shutdown and refuse to process requests while the current
+	AppDomain is unloading * HttpApplicationFactory.cs: if the current
+	AppDomain is unloading, ignore FileSystemWatcher notifications *
+	WebConfigurationManager.cs: work around a deadlock issue when
+	entering a ReaderWriterLockSlim upgradeable read lock very early
+	during ASP.NET runtime/AppDomain initialization. Every few runs
+	the attempt would lock up and since adding a section to cache is
+	not a critical operation we can afford timing the lock out in this
+	case. The lockup is probably due to the fact that RWLS is using
+	thread local storage to store the current thread's lock status and
+	it may happen that the TLS is not cleared during thread object
+	finalization (see metadata/threads.c, the start_wrapper function)
+
 2010-08-27  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
 
 	Call SetEndOfSendNotification
diff --git a/mcs/class/System.Web/System.Web/HttpApplicationFactory.cs b/mcs/class/System.Web/System.Web/HttpApplicationFactory.cs
index d7e0866..6a34f2d 100644
--- a/mcs/class/System.Web/System.Web/HttpApplicationFactory.cs
+++ b/mcs/class/System.Web/System.Web/HttpApplicationFactory.cs
@@ -712,6 +712,8 @@ namespace System.Web
 
 	        static void OnFileChanged(object sender, FileSystemEventArgs args)
 	        {
+			if (HttpRuntime.DomainUnloading)
+				return;
 			string name = args.Name;
 			bool isConfig = false;
 
diff --git a/mcs/class/System.Web/System.Web/HttpRuntime.cs b/mcs/class/System.Web/System.Web/HttpRuntime.cs
index eaf8296..63e56e7 100644
--- a/mcs/class/System.Web/System.Web/HttpRuntime.cs
+++ b/mcs/class/System.Web/System.Web/HttpRuntime.cs
@@ -441,6 +441,11 @@ namespace System.Web
 		
 		static void RealProcessRequest (object o)
 		{
+			if (domainUnloading) {
+				Console.Error.WriteLine ("Domain is unloading, not processing the request.");
+				return;
+			}
+
 			HttpWorkerRequest req = (HttpWorkerRequest) o;
 			bool started_internally = req.StartedInternally;
 			do {
@@ -584,6 +589,7 @@ namespace System.Web
 			// TODO: call ReleaseResources
 			//
 			domainUnloading = true;
+			HttpApplicationFactory.DisableWatchers ();
 			ThreadPool.QueueUserWorkItem (delegate {
 				try {
 					ShutdownAppDomain ();
diff --git a/mcs/class/System.Web/System.Web/SiteMapNode.cs b/mcs/class/System.Web/System.Web/SiteMapNode.cs
index e1fb520..b1660b8 100644
--- a/mcs/class/System.Web/System.Web/SiteMapNode.cs
+++ b/mcs/class/System.Web/System.Web/SiteMapNode.cs
@@ -35,6 +35,7 @@ using System.Web.UI;
 using System.Web.UI.WebControls;
 using System.ComponentModel;
 using System.Resources;
+using System.Security.Principal;
 
 namespace System.Web {
 	public class SiteMapNode : IHierarchyData, INavigateUIData, ICloneable {
@@ -177,12 +178,20 @@ namespace System.Web {
 
 		public virtual SiteMapNodeCollection ChildNodes {
 			get {
-				if (childNodes == null)
+				if (provider.SecurityTrimmingEnabled) {
+					IPrincipal p = HttpContext.Current.User;
+					if ((user == null && user != p) || user != null && user != p) {
+						user = p;
+						childNodes = provider.GetChildNodes (this);
+					}
+				} else if (childNodes == null) {
 					childNodes = provider.GetChildNodes (this);
+				}
 				return childNodes;
 			} 
 			set {
 				CheckWritable ();
+				user = null;
 				childNodes = value;
 			}
 		}
@@ -439,6 +448,7 @@ namespace System.Web {
 		string resourceKey;
 		SiteMapNode parent;
 		SiteMapNodeCollection childNodes;
+		IPrincipal user;
 		#endregion
 		
 	}
diff --git a/mcs/class/System.Web/System.Web_test.dll.sources b/mcs/class/System.Web/System.Web_test.dll.sources
index 8e5a166..780edc4 100644
--- a/mcs/class/System.Web/System.Web_test.dll.sources
+++ b/mcs/class/System.Web/System.Web_test.dll.sources
@@ -88,6 +88,7 @@ System.Web.Configuration/CustomErrorCollectionTest.cs
 System.Web.Configuration/DeploymentSectionTest.cs
 System.Web.Configuration/GlobalizationSectionTest.cs
 System.Web.Configuration/HostingEnvironmentSectionTest.cs
+System.Web.Configuration/MachineKeySectionTest.cs
 System.Web.Configuration/MachineKeyValidationConverterTest.cs
 System.Web.Configuration/NullableStringValidatorTest.cs
 System.Web.Configuration/ProfilePropertySettingsTest.cs
@@ -549,6 +550,7 @@ System.Web.UI.WebControls/WebControlCas.cs
 System.Web.UI.WebControls/XmlCas.cs
 System.Web.UI.WebControls/XmlDataSourceCas.cs
 System.Web.Util/HttpEncoderTest.cs
+System.Web.Util/MachineKeySectionUtilsTest.cs
 System.Web.Util/RequestValidatorTest.cs
 System.Web.Util/TransactionsCas.cs
 System.Web.Util/UrlUtilsTest.cs
diff --git a/mcs/class/System.Web/Test/System.Web.Configuration/ChangeLog b/mcs/class/System.Web/Test/System.Web.Configuration/ChangeLog
index 686972c..f6ab72e 100644
--- a/mcs/class/System.Web/Test/System.Web.Configuration/ChangeLog
+++ b/mcs/class/System.Web/Test/System.Web.Configuration/ChangeLog
@@ -1,3 +1,13 @@
+2010-10-12  Sebastien Pouliot  <sebastien at ximian.com>
+
+	A few moves/changes following previous patch review
+
+2010-10-08  Sebastien Pouliot  <sebastien at ximian.com>
+
+	*
+	Test/System.Web.Configuration/MachineKeyValidationConverterTest.cs:
+	Add more, mostly 4.0, test cases.
+
 2008-12-23  Marek Habersack  <mhabersack at novell.com>
 
 	* WebConfigurationManagerTest.cs: added new test.
diff --git a/mcs/class/System.Web/Test/System.Web.Configuration/ChangeLog b/mcs/class/System.Web/Test/System.Web.Configuration/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Web/Test/System.Web.Configuration/ChangeLog
copy to mcs/class/System.Web/Test/System.Web.Configuration/ChangeLog.old
diff --git a/mcs/class/System.Web/Test/System.Web.Configuration/MachineKeySectionTest.cs b/mcs/class/System.Web/Test/System.Web.Configuration/MachineKeySectionTest.cs
new file mode 100644
index 0000000..7b1b941
--- /dev/null
+++ b/mcs/class/System.Web/Test/System.Web.Configuration/MachineKeySectionTest.cs
@@ -0,0 +1,178 @@
+//
+// Unit tests for MachineKeySection
+//
+// Author:
+//	Sebastien Pouliot  <sebastien at ximian.com>
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Configuration;
+using System.Web.Configuration;
+using NUnit.Framework;
+
+namespace MonoTests.System.Web.Configuration {
+
+	[TestFixture]
+	public class MachineKeySectionTest {
+
+		[Test]
+		public void DefaultValues ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+#if NET_4_0
+			Assert.AreEqual (MachineKeyCompatibilityMode.Framework20SP1, section.CompatibilityMode, "CompatibilityMode");
+#endif
+			Assert.AreEqual ("Auto", section.Decryption, "Decryption");
+			Assert.AreEqual ("AutoGenerate,IsolateApps", section.DecryptionKey, "DecryptionKey");
+#if NET_4_0
+			Assert.AreEqual (MachineKeyValidation.HMACSHA256, section.Validation, "Validation");
+			Assert.AreEqual ("HMACSHA256", section.ValidationAlgorithm, "ValidationAlgorithm");
+#else
+			Assert.AreEqual (MachineKeyValidation.SHA1, section.Validation, "Validation");
+#endif
+			Assert.AreEqual ("AutoGenerate,IsolateApps", section.ValidationKey, "ValidationKey");
+		}
+
+		[Test]
+#if NET_4_0
+		[ExpectedException (typeof (NullReferenceException))]
+#else
+		[ExpectedException (typeof (ConfigurationErrorsException))]
+#endif
+		public void Decryption_Null ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Decryption = null;
+		}
+
+		[Test]
+		[ExpectedException (typeof (ConfigurationErrorsException))]
+		public void Decryption_Empty ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Decryption = String.Empty;
+		}
+#if NET_4_0
+		[Test]
+		public void Decryption_RC2 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			Assert.AreEqual ("Auto", section.Decryption, "before");
+
+			section.Decryption = "alg:RC2";
+			Assert.AreEqual ("alg:RC2", section.Decryption, "after");
+		}
+
+		[Test]
+		public void Decryption_InvalidName ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			Assert.AreEqual ("Auto", section.Decryption, "before");
+
+			section.Decryption = "alg:UnexistingType";
+			// looks like the problem is found (much) later
+			Assert.AreEqual ("alg:UnexistingType", section.Decryption, "Decryption");
+		}
+
+		[Test]
+		public void ValidationAlgorithm_Null ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.ValidationAlgorithm = null;
+			Assert.AreEqual ("HMACSHA256", section.ValidationAlgorithm, "ValidationAlgorithm");
+		}
+
+		[Test]
+		[ExpectedException (typeof (ArgumentException))]
+		public void ValidationAlgorithm_Empty ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.ValidationAlgorithm = String.Empty;
+		}
+
+		[Test]
+		[ExpectedException (typeof (ArgumentException))]
+		public void Validation_Custom ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.Custom;
+			// cannot be set directly
+		}
+
+		[Test]
+		public void Validation ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.AES;
+			Assert.AreEqual ("AES", section.ValidationAlgorithm, "AES");
+			section.Validation = MachineKeyValidation.HMACSHA256;
+			Assert.AreEqual ("HMACSHA256", section.ValidationAlgorithm, "HMACSHA256");
+			section.Validation = MachineKeyValidation.HMACSHA384;
+			Assert.AreEqual ("HMACSHA384", section.ValidationAlgorithm, "HMACSHA384");
+			section.Validation = MachineKeyValidation.HMACSHA512;
+			Assert.AreEqual ("HMACSHA512", section.ValidationAlgorithm, "HMACSHA512");
+			section.Validation = MachineKeyValidation.MD5;
+			Assert.AreEqual ("MD5", section.ValidationAlgorithm, "MD5");
+			section.Validation = MachineKeyValidation.SHA1;
+			Assert.AreEqual ("SHA1", section.ValidationAlgorithm, "SHA1");
+			// special case, enum value and algorithm names differs
+			section.Validation = MachineKeyValidation.TripleDES;
+			Assert.AreEqual ("3DES", section.ValidationAlgorithm, "3DES");
+		}
+
+		[Test]
+		[ExpectedException (typeof (ArgumentException))]
+		public void ValidationAlgorithm ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.ValidationAlgorithm = "HMACRIPEMD160";
+			// syntax is: alg:something-deriving-from-KeyedHashAlgorithm
+		}
+
+		[Test]
+		public void ValidationAlgorithm_RIPEMD160 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			Assert.AreEqual (MachineKeyValidation.HMACSHA256, section.Validation, "before");
+
+			section.ValidationAlgorithm = "alg:HMACRIPEMD160";
+			Assert.AreEqual (MachineKeyValidation.Custom, section.Validation, "after");
+			Assert.AreEqual ("alg:HMACRIPEMD160", section.ValidationAlgorithm, "ValidationAlgorithm");
+		}
+
+		[Test]
+		public void ValidationAlgorithm_InvalidName ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			Assert.AreEqual (MachineKeyValidation.HMACSHA256, section.Validation, "before");
+
+			section.ValidationAlgorithm = "alg:UnexistingType";
+			// looks like the problem is found (much) later
+			Assert.AreEqual (MachineKeyValidation.Custom, section.Validation, "after");
+			Assert.AreEqual ("alg:UnexistingType", section.ValidationAlgorithm, "ValidationAlgorithm");
+		}
+#endif
+	}
+}
+
diff --git a/mcs/class/System.Web/Test/System.Web.Configuration/MachineKeyValidationConverterTest.cs b/mcs/class/System.Web/Test/System.Web.Configuration/MachineKeyValidationConverterTest.cs
index 0ed9243..3df6feb 100644
--- a/mcs/class/System.Web/Test/System.Web.Configuration/MachineKeyValidationConverterTest.cs
+++ b/mcs/class/System.Web/Test/System.Web.Configuration/MachineKeyValidationConverterTest.cs
@@ -2,10 +2,11 @@
 // System.Web.Configuration.MachineKeyValidationConverterTest.cs - Unit tests
 // for System.Web.Configuration.MachineKeyValidationConverter.
 //
-// Author:
+// Authors:
 //	Chris Toshok  <toshok at ximian.com>
+//	Sebastien Pouliot  <sebastien at ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005, 2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -35,8 +36,7 @@ using NUnit.Framework;
 
 namespace MonoTests.System.Web.Configuration {
 	[TestFixture]
-	public class MachineKeyValidationConverterTest
-	{
+	public class MachineKeyValidationConverterTest {
 		[Test]
 		public void CanConvertFrom ()
 		{
@@ -66,10 +66,46 @@ namespace MonoTests.System.Web.Configuration {
 			object o;
 
 			o = cv.ConvertFrom (null, null, "MD5");
-			Assert.AreEqual (typeof (MachineKeyValidation), o.GetType(), "A1");
-			Assert.AreEqual ("MD5", o.ToString(), "A2");
+			Assert.AreEqual (typeof (MachineKeyValidation), o.GetType (), "typeof");
+			Assert.AreEqual ("MD5", o.ToString (), "MD5");
+
+			o = cv.ConvertFrom (null, null, "SHA1");
+			Assert.AreEqual ("SHA1", o.ToString (), "SHA1");
+
+			// 3DES in, TripleDES out
+			o = cv.ConvertFrom (null, null, "3DES");
+			Assert.AreEqual ("TripleDES", o.ToString (), "3DES");
+
 			o = cv.ConvertFrom (null, null, "AES");
-			Assert.AreEqual ("AES", o.ToString(), "A3");
+			Assert.AreEqual ("AES", o.ToString (), "AES");
+#if NET_4_0
+			o = cv.ConvertFrom (null, null, "HMACSHA256");
+			Assert.AreEqual ("HMACSHA256", o.ToString (), "HMACSHA256");
+
+			o = cv.ConvertFrom (null, null, "HMACSHA384");
+			Assert.AreEqual ("HMACSHA384", o.ToString (), "HMACSHA384");
+
+			o = cv.ConvertFrom (null, null, "HMACSHA512");
+			Assert.AreEqual ("HMACSHA512", o.ToString (), "HMACSHA512");
+#endif
+		}
+
+#if NET_4_0
+		[Test]
+		[ExpectedException (typeof (ArgumentException))]
+		public void ConvertFrom_Custom ()
+		{
+			MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
+			cv.ConvertFrom (null, null, "Custom");
+		}
+#endif
+
+		[Test]
+		[ExpectedException (typeof (ArgumentException))]
+		public void ConvertFrom_CaseSensitive ()
+		{
+			MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
+			cv.ConvertFrom (null, null, "sha1");
 		}
 
 		[Test]
@@ -91,10 +127,29 @@ namespace MonoTests.System.Web.Configuration {
 			Assert.AreEqual ("MD5", cv.ConvertTo (null, null, MachineKeyValidation.MD5, typeof (string)), "A1");
 			Assert.AreEqual ("SHA1", cv.ConvertTo (null, null, MachineKeyValidation.SHA1, typeof (string)), "A2");
 			Assert.AreEqual ("3DES", cv.ConvertTo (null, null, MachineKeyValidation.TripleDES, typeof (string)), "A3");
+#if NET_4_0
+			Assert.AreEqual ("HMACSHA256", cv.ConvertTo (null, null, MachineKeyValidation.HMACSHA256, typeof (string)), "HMACSHA256");
+			Assert.AreEqual ("HMACSHA384", cv.ConvertTo (null, null, MachineKeyValidation.HMACSHA384, typeof (string)), "HMACSHA384");
+			Assert.AreEqual ("HMACSHA512", cv.ConvertTo (null, null, MachineKeyValidation.HMACSHA512, typeof (string)), "HMACSHA512");
+#endif
+		}
+
+#if NET_4_0
+		[Test]
+		[ExpectedException (typeof (ArgumentException))]
+		public void ConvertTo_Custom ()
+		{
+			MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
+			cv.ConvertTo (null, null, MachineKeyValidation.Custom, typeof (string));
 		}
+#endif
 
 		[Test]
+#if NET_4_0
+		[ExpectedException (typeof (ArgumentException))]
+#else
 		[ExpectedException (typeof (NullReferenceException))]
+#endif
 		public void ConvertTo_NullError ()
 		{
 			MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
@@ -103,7 +158,11 @@ namespace MonoTests.System.Web.Configuration {
 		}
 
 		[Test]
+#if NET_4_0
+		[ExpectedException (typeof (ArgumentException))]
+#else
 		[ExpectedException (typeof (FormatException))]
+#endif
 		public void ConvertTo_TypeError1 ()
 		{
 			MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
@@ -120,6 +179,17 @@ namespace MonoTests.System.Web.Configuration {
 			Assert.AreEqual ("MD5", cv.ConvertTo (null, null, MachineKeyValidation.MD5, null), "A2");
 		}
 
+		[Test]
+#if NET_4_0
+		[ExpectedException (typeof (ArgumentException))]
+#else
+		[ExpectedException (typeof (FormatException))]
+#endif
+		public void ConvertTo_TypeError3 ()
+		{
+			MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
+			cv.ConvertTo (null, null, (MachineKeyValidation)Int32.MinValue, typeof (string));
+		}
 	}
 }
 
diff --git a/mcs/class/System.Web/Test/System.Web.Security/ChangeLog b/mcs/class/System.Web/Test/System.Web.Security/ChangeLog
index 3504756..f1dff97 100644
--- a/mcs/class/System.Web/Test/System.Web.Security/ChangeLog
+++ b/mcs/class/System.Web/Test/System.Web.Security/ChangeLog
@@ -1,3 +1,14 @@
+2010-10-04  Sebastien Pouliot  <sebastien at ximian.com>
+
+	* Test/System.Web.Security/FormsAuthenticationTest.cs: Small
+	change to make sure the hash name is not case sensitive
+
+2010-10-08  Sebastien Pouliot  <sebastien at ximian.com>
+
+	* Test/System.Web.Security/FormsAuthenticationTest.cs: Add test
+	case to ensure HashPasswordForStoringInConfigFile is not case
+	sensitive.
+
 2010-02-11  Marek Habersack  <mhabersack at novell.com>
 
 	* RolesTest.cs: added a test for IsUserInRole. Patch from Tiaan
diff --git a/mcs/class/System.Web/Test/System.Web.Security/ChangeLog b/mcs/class/System.Web/Test/System.Web.Security/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Web/Test/System.Web.Security/ChangeLog
copy to mcs/class/System.Web/Test/System.Web.Security/ChangeLog.old
diff --git a/mcs/class/System.Web/Test/System.Web.Security/FormsAuthenticationTest.cs b/mcs/class/System.Web/Test/System.Web.Security/FormsAuthenticationTest.cs
index b31d721..63b9c46 100644
--- a/mcs/class/System.Web/Test/System.Web.Security/FormsAuthenticationTest.cs
+++ b/mcs/class/System.Web/Test/System.Web.Security/FormsAuthenticationTest.cs
@@ -87,7 +87,7 @@ namespace MonoTests.System.Web.Security
 
 			// ä (C3-A4)
 			s = Encoding.UTF8.GetString (new byte [2] { 0xC3, 0xA4 });
-			Assert.AreEqual ("8419B71C87A225A2C70B50486FBEE545", FormsAuthentication.HashPasswordForStoringInConfigFile (s, "MD5"));
+			Assert.AreEqual ("8419B71C87A225A2C70B50486FBEE545", FormsAuthentication.HashPasswordForStoringInConfigFile (s, "md5"));
 		}
 
 		[Test]
@@ -99,7 +99,7 @@ namespace MonoTests.System.Web.Security
 
 			// ä (C3-A4)
 			s = Encoding.UTF8.GetString (new byte [2] { 0xC3, 0xA4 });
-			Assert.AreEqual ("961FA22F61A56E19F3F5F8867901AC8CF5E6D11F", FormsAuthentication.HashPasswordForStoringInConfigFile (s, "SHA1"));
+			Assert.AreEqual ("961FA22F61A56E19F3F5F8867901AC8CF5E6D11F", FormsAuthentication.HashPasswordForStoringInConfigFile (s, "sha1"));
 		}
 
 		[Test]
@@ -129,6 +129,16 @@ namespace MonoTests.System.Web.Security
 		{
 			FormsAuthentication.RedirectToLoginPage (String.Empty);
 		}
+
+		[Test]
+		[Category ("NotWorking")] // works on .net
+		public void Authenticate ()
+		{
+			Assert.IsFalse (FormsAuthentication.Authenticate (null, "password"), "null,string");
+			Assert.IsFalse (FormsAuthentication.Authenticate ("user", null), "string,null");
+			// not throwing
+			Assert.IsFalse (FormsAuthentication.Authenticate ("user", "password"), "string,string");
+		}
 #endif
 
 		[TestFixtureTearDown]
diff --git a/mcs/class/System.Web/Test/System.Web.Security/RolePrincipalTest.cs b/mcs/class/System.Web/Test/System.Web.Security/RolePrincipalTest.cs
index 0c6e069..67de9b9 100644
--- a/mcs/class/System.Web/Test/System.Web.Security/RolePrincipalTest.cs
+++ b/mcs/class/System.Web/Test/System.Web.Security/RolePrincipalTest.cs
@@ -1,6 +1,6 @@
 //
-// MembershipUserCollectionTest.cs
-//	- Unit tests for System.Web.Security.MembershipUserCollection
+// RolePrincipalTest.cs
+//	- Unit tests for System.Web.Security.RolePrincipal
 //
 // Author:
 //	Sebastien Pouliot  <sebastien at ximian.com>
diff --git a/mcs/class/System.Web/Test/System.Web.UI/ChangeLog b/mcs/class/System.Web/Test/System.Web.UI/ChangeLog
index 2c4b89c..0689632 100644
--- a/mcs/class/System.Web/Test/System.Web.UI/ChangeLog
+++ b/mcs/class/System.Web/Test/System.Web.UI/ChangeLog
@@ -1,3 +1,8 @@
+2010-10-08  Sebastien Pouliot  <sebastien at ximian.com>
+
+	* Test/System.Web.UI/LosFormatterTest.cs: Add some rountrip test
+	cases with the different ctors
+
 2010-04-07  Marek Habersack  <mhabersack at novell.com>
 
 	* ControlTest.cs: added test for bug #594238
diff --git a/mcs/class/System.Web/Test/System.Web.UI/ChangeLog b/mcs/class/System.Web/Test/System.Web.UI/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Web/Test/System.Web.UI/ChangeLog
copy to mcs/class/System.Web/Test/System.Web.UI/ChangeLog.old
diff --git a/mcs/class/System.Web/Test/System.Web.UI/LosFormatterTest.cs b/mcs/class/System.Web/Test/System.Web.UI/LosFormatterTest.cs
index 2889591..f1d9b08 100644
--- a/mcs/class/System.Web/Test/System.Web.UI/LosFormatterTest.cs
+++ b/mcs/class/System.Web/Test/System.Web.UI/LosFormatterTest.cs
@@ -1,10 +1,12 @@
 //
 // LosFormatterTest.cs - Unit tests for System.Web.UI.LosFormatter
 //
-// Author:
+// Authors:
 //	Gert Driesen  <drieseng at users.sourceforge.net>
+//	Sebastien Pouliot  <sebastien at ximian.com>
 //
 // Copyright (C) 2007 Gert Driesen
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -38,6 +40,145 @@ namespace MonoTests.System.Web.UI
 	[TestFixture]
 	public class LosFormatterTest
 	{
+		static byte [] Empty = new byte [0];
+
+		string Serialize (LosFormatter lf, object value)
+		{
+			StringWriter sw = new StringWriter ();
+			lf.Serialize (sw, value);
+			return sw.ToString ();
+		}
+
+		object Deserialize (LosFormatter lf, string serializedData)
+		{
+			return lf.Deserialize (serializedData);
+		}
+
+		string NoKeyRoundTrip (LosFormatter lf, string assertionMessage)
+		{
+			string serializedData = Serialize (lf, "Mono");
+			Assert.AreEqual ("Mono", (string) Deserialize (lf, serializedData), assertionMessage);
+			return serializedData;
+		}
+
+		[Test]
+		public void Ctor_BoolByteArray ()
+		{
+			LosFormatter lf1 = new LosFormatter (false, (byte []) null);
+			string expected = NoKeyRoundTrip (lf1, "false, null");
+
+			LosFormatter lf2 = new LosFormatter (true, (byte []) null);
+			Assert.AreEqual (expected, NoKeyRoundTrip (lf2, "true, null"), "2");
+
+			LosFormatter lf3 = new LosFormatter (false, Empty);
+			Assert.AreEqual (expected, NoKeyRoundTrip (lf3, "false, empty"), "3");
+
+			// an empty key is still a key - a signature is appended
+			LosFormatter lf4 = new LosFormatter (true, Empty);
+			string signed = NoKeyRoundTrip (lf4, "true, empty");
+			Assert.AreNotEqual (expected, signed, "4");
+
+			byte [] data = Convert.FromBase64String (expected);
+			byte [] signed_data = Convert.FromBase64String (signed);
+			Assert.IsTrue (BitConverter.ToString (signed_data).StartsWith (BitConverter.ToString (data)), "4 / same data");
+#if NET_4_0
+			// 32 bytes == 256 bits -> match HMACSHA256 as default
+			Assert.AreEqual (32, signed_data.Length - data.Length, "signature length");
+#else
+			// 20 bytes == 160 bits -> match HMACSHA1 as default
+			Assert.AreEqual (20, signed_data.Length - data.Length, "signature length");
+#endif
+		}
+
+		[Test]
+		public void Ctor_BoolString ()
+		{
+			LosFormatter lf1 = new LosFormatter (false, (string) null);
+			string expected = NoKeyRoundTrip (lf1, "false, null");
+
+			LosFormatter lf2 = new LosFormatter (true, (string) null);
+			Assert.AreEqual (expected, NoKeyRoundTrip (lf2, "true, null"), "2");
+
+			LosFormatter lf3 = new LosFormatter (false, String.Empty);
+			Assert.AreEqual (expected, NoKeyRoundTrip (lf3, "false, empty"), "3");
+
+			// an empty string is not an empty key!
+			LosFormatter lf4 = new LosFormatter (true, String.Empty);
+			Assert.AreEqual (expected, NoKeyRoundTrip (lf4, "true, empty"), "4");
+
+			byte [] key = new byte [32];
+			LosFormatter lf5 = new LosFormatter (true, Convert.ToBase64String (key));
+			string signed = NoKeyRoundTrip (lf5, "true, b64");
+			Assert.AreNotEqual (expected, signed, "5");
+
+			byte [] data = Convert.FromBase64String (expected);
+			byte [] signed_data = Convert.FromBase64String (signed);
+			Assert.IsTrue (BitConverter.ToString (signed_data).StartsWith (BitConverter.ToString (data)), "5 / same data");
+#if NET_4_0
+			// 32 bytes == 256 bits -> match HMACSHA256 as default
+			Assert.AreEqual (32, signed_data.Length - data.Length, "signature length");
+#else
+			// 20 bytes == 160 bits -> match HMACSHA1 as default
+			Assert.AreEqual (20, signed_data.Length - data.Length, "signature length");
+#endif
+		}
+
+		string SerializeOverloads (LosFormatter lf, string message)
+		{
+			string stream_ser;
+			using (MemoryStream ms = new MemoryStream ()) {
+				lf.Serialize (ms, String.Empty);
+				stream_ser = Convert.ToBase64String (ms.ToArray ());
+			}
+
+			string tw_ser;
+			using (MemoryStream ms = new MemoryStream ()) {
+				using (TextWriter tw = new StreamWriter (ms)) {
+					lf.Serialize (tw, String.Empty);
+				}
+				tw_ser = Convert.ToBase64String (ms.ToArray ());
+			}
+
+			Assert.AreEqual (stream_ser, tw_ser, message);
+			return stream_ser;
+		}
+
+		[Test]
+		public void SerializeOverloads ()
+		{
+			LosFormatter lf1 = new LosFormatter (false, (string) null);
+			string r1 = SerializeOverloads (lf1, "false, null");
+
+			LosFormatter lf2 = new LosFormatter (true, (string) null);
+			string r2 = SerializeOverloads (lf2, "true, null");
+			Assert.AreEqual (r1, r2, "r1-r2");
+
+			LosFormatter lf3 = new LosFormatter (false, String.Empty);
+			string r3 = SerializeOverloads (lf3, "false, empty");
+			Assert.AreEqual (r2, r3, "r2-r3");
+
+			// an empty string is not an empty key!
+			LosFormatter lf4 = new LosFormatter (true, String.Empty);
+			string r4 = SerializeOverloads (lf4, "true, empty");
+			Assert.AreEqual (r3, r4, "r3-r4");
+
+			byte [] key = new byte [32];
+			LosFormatter lf5 = new LosFormatter (true, Convert.ToBase64String (key));
+			string r5 = SerializeOverloads (lf5, "false, b64");
+			Assert.AreNotEqual (r4, r5, "r4-r5");
+		}
+
+#if NET_4_0
+		[Test]
+		[ExpectedException (typeof (NotSupportedException))]
+		public void Deserialize_Stream_NonSeekable ()
+		{
+			string s1 = "Hello world";
+			NonSeekableStream ns = new NonSeekableStream ();
+			LosFormatter lf = new LosFormatter ();
+			lf.Serialize (ns, s1);
+		}
+#else
 		[Test] // bug #411115
 		public void Deserialize_Stream_NonSeekable ()
 		{
@@ -49,7 +190,7 @@ namespace MonoTests.System.Web.UI
 			string s2 = lf.Deserialize (ns) as string;
 			Assert.AreEqual (s1, s2);
 		}
-
+#endif
 		[Test] // bug #324526
 		public void Serialize ()
 		{
diff --git a/mcs/class/System.Web/Test/System.Web.UI/ObjectStateFormatterTest.cs b/mcs/class/System.Web/Test/System.Web.UI/ObjectStateFormatterTest.cs
index 58f99e6..5b3faea 100644
--- a/mcs/class/System.Web/Test/System.Web.UI/ObjectStateFormatterTest.cs
+++ b/mcs/class/System.Web/Test/System.Web.UI/ObjectStateFormatterTest.cs
@@ -30,6 +30,7 @@
 
 #if NET_2_0
 using System;
+using System.IO;
 using System.Reflection;
 using System.Web;
 using System.Web.UI;
@@ -115,6 +116,20 @@ namespace MonoTests.System.Web.UI
 
 			HtmlDiff.AssertAreEqual (originalHtml, renderedHtml, "#A1");
 		}
+#if false
+		[Test]
+		public void SerializeOverloads ()
+		{
+			ObjectStateFormatter osf = new ObjectStateFormatter ();
+			string s1 = osf.Serialize (String.Empty);
+			string s2;
+			using (MemoryStream ms = new MemoryStream ()) {
+				osf.Serialize (ms, String.Empty);
+				s2 = Convert.ToBase64String (ms.ToArray ());
+			}
+			Assert.AreEqual (s1, s2, "identical");
+		}
+#endif
 	}
 }
-#endif
\ No newline at end of file
+#endif
diff --git a/mcs/class/System.Web/Test/System.Web.Util/ChangeLog b/mcs/class/System.Web/Test/System.Web.Util/ChangeLog
index 38c22d2..608c86c 100644
--- a/mcs/class/System.Web/Test/System.Web.Util/ChangeLog
+++ b/mcs/class/System.Web/Test/System.Web.Util/ChangeLog
@@ -1,3 +1,9 @@
+2010-10-12  Sebastien Pouliot  <sebastien at ximian.com>
+
+	* Test/System.Web.Util/MachineKeySectionUtilsTest.cs: Moved from
+	Test/ System.Web.Configuration/MachineKeySectionTest.cs. Add test
+	case for TripleDES versus 3DES
+
 2010-03-06  Marek Habersack  <mhabersack at novell.com>
 
 	* RequestValidatorTest.cs: added
diff --git a/mcs/class/System.Web/Test/System.Web.Util/ChangeLog b/mcs/class/System.Web/Test/System.Web.Util/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Web/Test/System.Web.Util/ChangeLog
copy to mcs/class/System.Web/Test/System.Web.Util/ChangeLog.old
diff --git a/mcs/class/System.Web/Test/System.Web.Util/MachineKeySectionUtilsTest.cs b/mcs/class/System.Web/Test/System.Web.Util/MachineKeySectionUtilsTest.cs
new file mode 100644
index 0000000..2beebff
--- /dev/null
+++ b/mcs/class/System.Web/Test/System.Web.Util/MachineKeySectionUtilsTest.cs
@@ -0,0 +1,310 @@
+//
+// Unit tests for MachineKeySectionUtils (internals)
+//
+// Author:
+//	Sebastien Pouliot  <sebastien at ximian.com>
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.IO;
+using System.Web.Configuration;
+using System.Web.Util;
+using NUnit.Framework;
+
+namespace MonoTests.System.Web.Util {
+
+	[TestFixture]
+	public class MachineKeySectionUtilsTest {
+
+		public void Encrypt_RoundTrip (MachineKeySection section)
+		{
+			byte [] data = new byte [14];
+			byte [] encdata = MachineKeySectionUtils.Encrypt (section, data);
+			byte [] decdata = MachineKeySectionUtils.Decrypt (section, encdata);
+			Assert.AreEqual (data, decdata, "roundtrip");
+
+			// changing length (missing first byte)
+			byte [] cut = new byte [encdata.Length - 1];
+			Array.Copy (encdata, 1, cut, 0, cut.Length);
+			Assert.IsNull (MachineKeySectionUtils.Decrypt (section, cut), "bad length");
+
+			// changing last byte (padding)
+			byte be = encdata [encdata.Length - 1];
+			encdata [encdata.Length - 1] ^= (byte) (be + 1);
+			Assert.IsNull (MachineKeySectionUtils.Decrypt (section, encdata), "bad padding");
+		}
+
+		[Test]
+		public void Encrypt_RoundTrip_Default ()
+		{
+			Encrypt_RoundTrip (new MachineKeySection ());
+		}
+
+		[Test]
+		public void Encrypt_RoundTrip_AES ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.AES;
+			Encrypt_RoundTrip (section);
+		}
+
+		[Test]
+		public void Encrypt_RoundTrip_TripleDES ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.TripleDES;
+			Encrypt_RoundTrip (section);
+		}
+
+		[Test]
+		public void Encrypt_RoundTrip_MD5 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.MD5;
+			Encrypt_RoundTrip (section);
+		}
+
+		[Test]
+		public void Encrypt_RoundTrip_SHA1 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.SHA1;
+			Encrypt_RoundTrip (section);
+		}
+#if NET_4_0
+		[Test]
+		public void Encrypt_RoundTrip_HMACSHA256 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.HMACSHA256;
+			EncryptSign_RoundTrip (section);
+		}
+
+		[Test]
+		public void Encrypt_RoundTrip_HMACSHA384 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.HMACSHA384;
+			EncryptSign_RoundTrip (section);
+		}
+
+		[Test]
+		public void Encrypt_RoundTrip_HMACSHA512 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.HMACSHA512;
+			EncryptSign_RoundTrip (section);
+		}
+
+		[Test]
+		public void Encrypt_RoundTrip_Custom_RIPEMD160 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.ValidationAlgorithm = "alg:HMACRIPEMD160";
+			EncryptSign_RoundTrip (section);
+		}
+#endif
+		public void EncryptSign_RoundTrip (MachineKeySection section)
+		{
+			byte [] data = new byte [14];
+			byte [] block = MachineKeySectionUtils.EncryptSign (section, data);
+			byte [] decdata = MachineKeySectionUtils.VerifyDecrypt (section, block);
+			Assert.AreEqual (data, decdata, "roundtrip");
+
+			// changing a byte of the data
+			byte b0 = block [0];
+			block [0] ^= b0;
+			Assert.IsNull (MachineKeySectionUtils.VerifyDecrypt (section, block), "bad data");
+			block [0] = b0;
+
+			// changing a byte of the signature
+			byte be = block [block.Length - 1];
+			block [block.Length - 1] ^= (byte) (be + 1);
+			Assert.IsNull (MachineKeySectionUtils.VerifyDecrypt (section, block), "bad signature");
+		}
+
+		[Test]
+		public void EncryptSign_RoundTrip_Default ()
+		{
+			EncryptSign_RoundTrip (new MachineKeySection ());
+		}
+
+		[Test]
+		public void EncryptSign_RoundTrip_AES ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.AES;
+			EncryptSign_RoundTrip (section);
+		}
+
+		[Test]
+		public void EncryptSign_RoundTrip_TripleDES ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.TripleDES;
+			EncryptSign_RoundTrip (section);
+		}
+
+		[Test]
+		public void EncryptSign_RoundTrip_MD5 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.MD5;
+			EncryptSign_RoundTrip (section);
+		}
+
+		[Test]
+		public void EncryptSign_RoundTrip_SHA1 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.SHA1;
+			EncryptSign_RoundTrip (section);
+		}
+#if NET_4_0
+		[Test]
+		public void EncryptSign_RoundTrip_HMACSHA256 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.HMACSHA256;
+			EncryptSign_RoundTrip (section);
+		}
+
+		[Test]
+		public void EncryptSign_RoundTrip_HMACSHA384 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.HMACSHA384;
+			EncryptSign_RoundTrip (section);
+		}
+
+		[Test]
+		public void EncryptSign_RoundTrip_HMACSHA512 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.HMACSHA512;
+			EncryptSign_RoundTrip (section);
+		}
+
+		[Test]
+		public void EncryptSign_RoundTrip_Custom_RIPEMD160 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.ValidationAlgorithm = "alg:HMACRIPEMD160";
+			EncryptSign_RoundTrip (section);
+		}
+#endif
+		public void Validation_RoundTrip (MachineKeySection section)
+		{
+			byte [] data = new byte [] { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 };
+			byte [] block = MachineKeySectionUtils.Sign (section, data);
+			Assert.AreEqual (data, MachineKeySectionUtils.Verify (section, block), "OK");
+
+			// changing last byte
+			for (int i = 0; i < data.Length; i++) {
+				byte b = block [i];
+				block [i] ^= 0xFF;
+				Assert.IsNull (MachineKeySectionUtils.Verify (section, block), "bad-" + i.ToString ());
+				block [i] = b;
+			}
+		}
+
+		[Test]
+		public void Validation_RoundTrip_Default ()
+		{
+			Validation_RoundTrip (new MachineKeySection ());
+		}
+
+		[Test]
+		public void Validation_RoundTrip_AES ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.AES;
+			Validation_RoundTrip (section);
+		}
+
+		[Test]
+		public void Validation_RoundTrip_TripleDES ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.TripleDES;
+			Validation_RoundTrip (section);
+		}
+
+		[Test]
+		public void Validation_RoundTrip_MD5 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.MD5;
+			Validation_RoundTrip (section);
+		}
+
+		[Test]
+		public void Validation_RoundTrip_SHA1 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.SHA1;
+			Validation_RoundTrip (section);
+		}
+
+#if NET_4_0
+		[Test]
+		public void Validation_RoundTrip_HMACSHA256 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.HMACSHA256;
+			Validation_RoundTrip (section);
+		}
+
+		[Test]
+		public void Validation_RoundTrip_HMACSHA384 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.HMACSHA384;
+			Validation_RoundTrip (section);
+		}
+
+		[Test]
+		public void Validation_RoundTrip_HMACSHA512 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.Validation = MachineKeyValidation.HMACSHA512;
+			Validation_RoundTrip (section);
+		}
+
+		[Test]
+		public void Validation_RoundTrip_Custom_RIPEMD160 ()
+		{
+			MachineKeySection section = new MachineKeySection ();
+			section.ValidationAlgorithm = "alg:HMACRIPEMD160";
+			Validation_RoundTrip (section);
+		}
+#endif
+		[Test]
+		public void GetHexString ()
+		{
+			Assert.AreEqual ("DEADC0DE", MachineKeySectionUtils.GetHexString (new byte [] { 0xde, 0xad, 0xc0, 0xde }), "deadcode");
+		}
+	}
+}
+
diff --git a/mcs/class/System.Web/net_4_0_System.Web.dll.sources b/mcs/class/System.Web/net_4_0_System.Web.dll.sources
index 71cc818..dee93c1 100644
--- a/mcs/class/System.Web/net_4_0_System.Web.dll.sources
+++ b/mcs/class/System.Web/net_4_0_System.Web.dll.sources
@@ -13,6 +13,7 @@ System.Web.Caching/OutputCacheProviderCollection.cs
 System.Web.Caching/ResponseElement.cs
 System.Web.Caching/SubstitutionResponseElement.cs
 System.Web.Configuration_2.0/VersionConverter.cs
+System.Web.Configuration_2.0/MachineKeyCompatibilityMode.cs
 System.Web.Compilation/FolderLevelBuildProviderAppliesTo.cs
 System.Web.Compilation/FolderLevelBuildProviderAppliesToAttribute.cs
 System.Web.Compilation/RouteUrlExpressionBuilder.cs
diff --git a/mcs/class/System/System.Net.Configuration/ChangeLog b/mcs/class/System/System.Net.Configuration/ChangeLog
index 2f5518d..f62b5c1 100644
--- a/mcs/class/System/System.Net.Configuration/ChangeLog
+++ b/mcs/class/System/System.Net.Configuration/ChangeLog
@@ -1,3 +1,9 @@
+2010-10-08  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Add support for EnableSsl in smtp config.
+
+	Ditto. Fixes bug #644816.
+
 2009-12-11  Miguel de Icaza  <miguel at novell.com>
 
 	* SmtpNetworkElement.cs: Add new "targetName" property for smtp. 
diff --git a/mcs/class/System/System.Net.Configuration/ChangeLog b/mcs/class/System/System.Net.Configuration/ChangeLog.old
similarity index 100%
copy from mcs/class/System/System.Net.Configuration/ChangeLog
copy to mcs/class/System/System.Net.Configuration/ChangeLog.old
diff --git a/mcs/class/System/System.Net.Configuration/SmtpNetworkElement.cs b/mcs/class/System/System.Net.Configuration/SmtpNetworkElement.cs
index ffa3361..777ebd8 100644
--- a/mcs/class/System/System.Net.Configuration/SmtpNetworkElement.cs
+++ b/mcs/class/System/System.Net.Configuration/SmtpNetworkElement.cs
@@ -72,7 +72,13 @@ namespace System.Net.Configuration {
 			get { return (string) base ["targetName"]; }
 			set { base ["targetName"] = value; }
                 }
-		
+#if NET_4_0
+		[ConfigurationPropertyAttribute("enableSsl", DefaultValue = false)]
+		public bool EnableSsl {
+			get { return (bool) base ["enableSsl"]; }
+			set { base ["enableSsl"] = value; }
+		}
+#endif
 		protected override ConfigurationPropertyCollection Properties {
 			// what to do here?
 			get { return base.Properties; }
diff --git a/mcs/class/System/System.Net.Mail/ChangeLog b/mcs/class/System/System.Net.Mail/ChangeLog
index f38a933..feb06ed 100644
--- a/mcs/class/System/System.Net.Mail/ChangeLog
+++ b/mcs/class/System/System.Net.Mail/ChangeLog
@@ -1,3 +1,9 @@
+2010-10-08  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Add support for EnableSsl in smtp config.
+
+	Ditto. Fixes bug #644816.
+
 2010-08-04  Raja R Harinath  <harinath at hurrynot.org>
 
 	* System.Net.Mail/SmtpClient.cs (SendCore): Compute envelope
diff --git a/mcs/class/System/System.Net.Mail/SmtpClient.cs b/mcs/class/System/System.Net.Mail/SmtpClient.cs
index 68bdc9b..d525660 100644
--- a/mcs/class/System/System.Net.Mail/SmtpClient.cs
+++ b/mcs/class/System/System.Net.Mail/SmtpClient.cs
@@ -118,6 +118,9 @@ namespace System.Net.Mail {
 			if (cfg != null) {
 				this.host = cfg.Network.Host;
 				this.port = cfg.Network.Port;
+#if NET_4_0
+				this.enableSsl = cfg.Network.EnableSsl;
+#endif
 				TargetName = cfg.Network.TargetName;
 				if (this.TargetName == null)
 					TargetName = "SMTPSVC/" + (host != null ? host : "");
diff --git a/mcs/class/System/System.Net.Sockets/ChangeLog b/mcs/class/System/System.Net.Sockets/ChangeLog
index f23dfe3..8f507f9 100644
--- a/mcs/class/System/System.Net.Sockets/ChangeLog
+++ b/mcs/class/System/System.Net.Sockets/ChangeLog
@@ -1,3 +1,25 @@
+2010-09-09  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	UDP sockets allow connections to Any
+
+	UDP sockets that call Connect() to set a default address for
+	datagrams sent, can call Connect() again with IPv6Any or Any to
+	'disconnect'.
+
+	Fixes bug #639098.
+
+2010-10-20  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Handle special case when disposing a socket.
+
+	When disposing a socket that has more than one asynchronous
+	read/write pending, one of the callbacks could call
+	DisposeAllOnClose() while another one is waiting on the lock. Once
+	the lock is acquired, queue.Count will be 0 and Dequeue would
+	fail. This is fixed now.
+
+	Fixes bug #645675.
+
 2010-09-30  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
 
 	Invoke the callback in separate threads
diff --git a/mcs/class/System/System.Net.Sockets/Socket.cs b/mcs/class/System/System.Net.Sockets/Socket.cs
index 2c6186b..af02ac3 100644
--- a/mcs/class/System/System.Net.Sockets/Socket.cs
+++ b/mcs/class/System/System.Net.Sockets/Socket.cs
@@ -184,7 +184,11 @@ namespace System.Net.Sockets
 					SocketAsyncCall sac = null;
 					SocketAsyncResult req = null;
 					lock (queue) {
-						queue.Dequeue (); // remove ourselves
+						// queue.Count will only be 0 if the socket is closed while receive/send
+						// operation(s) are pending and at least one call to this method is
+						// waiting on the lock while another one calls CompleteAllOnDispose()
+						if (queue.Count > 0)
+							queue.Dequeue (); // remove ourselves
 						if (queue.Count > 0) {
 							req = (SocketAsyncResult) queue.Peek ();
 							if (!Sock.disposed) {
diff --git a/mcs/class/System/System.Net.Sockets/Socket_2_1.cs b/mcs/class/System/System.Net.Sockets/Socket_2_1.cs
index af54044..2f27e2e 100644
--- a/mcs/class/System/System.Net.Sockets/Socket_2_1.cs
+++ b/mcs/class/System/System.Net.Sockets/Socket_2_1.cs
@@ -485,7 +485,7 @@ namespace System.Net.Sockets {
 				throw new ArgumentNullException ("remoteEP");
 
 			IPEndPoint ep = remoteEP as IPEndPoint;
-			if (ep != null)
+			if (ep != null && socket_type != SocketType.Dgram) /* Dgram uses Any to 'disconnect' */
 				if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
 					throw new SocketException ((int) SocketError.AddressNotAvailable);
 
@@ -516,7 +516,8 @@ namespace System.Net.Sockets {
 			if (error != 0)
 				throw new SocketException (error);
 
-			connected=true;
+			if (socket_type != SocketType.Dgram)
+				connected=true;
 
 #if NET_2_0
 			isbound = true;
diff --git a/mcs/class/System/System.Net/ChangeLog b/mcs/class/System/System.Net/ChangeLog
index e0ded47..51a0fa3 100644
--- a/mcs/class/System/System.Net/ChangeLog
+++ b/mcs/class/System/System.Net/ChangeLog
@@ -1,3 +1,16 @@
+2010-11-01  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Avoid killing the thread if socket already null
+
+	In some weird cases socket is null when we try to close it.
+
+2010-10-04  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Set have_response
+
+	Set have_response to true when there's a protocol error or a
+	previous exception for POST/PUT. Patch by Bassam Tabbara.
+
 2010-09-30  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
 
 	Invoke the callback in separate threads
diff --git a/mcs/class/System/System.Net/HttpConnection.cs b/mcs/class/System/System.Net/HttpConnection.cs
index 02283c6..927c03f 100644
--- a/mcs/class/System/System.Net/HttpConnection.cs
+++ b/mcs/class/System/System.Net/HttpConnection.cs
@@ -119,7 +119,7 @@ namespace System.Net {
 			try {
 				stream.BeginRead (buffer, 0, BufferSize, OnRead, this);
 			} catch {
-				sock.Close (); // stream disposed
+				CloseSocket ();
 			}
 		}
 
@@ -167,14 +167,14 @@ namespace System.Net {
 				if (ms != null && ms.Length > 0)
 					SendError ();
 				if (sock != null)
-					sock.Close ();
+					CloseSocket ();
 				return;
 			}
 
 			if (nread == 0) {
 				//if (ms.Length > 0)
 				//	SendError (); // Why bother?
-				sock.Close ();
+				CloseSocket ();
 				return;
 			}
 
@@ -343,6 +343,19 @@ namespace System.Net {
 			Close (false);
 		}
 
+		void CloseSocket ()
+		{
+			if (sock == null)
+				return;
+
+			try {
+				sock.Close ();
+			} catch {
+			} finally {
+				sock = null;
+			}
+		}
+
 		internal void Close (bool force_close)
 		{
 			if (sock != null) {
@@ -381,10 +394,12 @@ namespace System.Net {
 				Socket s = sock;
 				sock = null;
 				try {
-					s.Shutdown (SocketShutdown.Both);
+					if (s != null)
+						s.Shutdown (SocketShutdown.Both);
 				} catch {
 				} finally {
-					s.Close ();
+					if (s != null)
+						s.Close ();
 				}
 				Unbind ();
 				return;
diff --git a/mcs/class/System/System.Net/HttpWebRequest.cs b/mcs/class/System/System.Net/HttpWebRequest.cs
index 6764954..fcad9f2 100644
--- a/mcs/class/System/System.Net/HttpWebRequest.cs
+++ b/mcs/class/System/System.Net/HttpWebRequest.cs
@@ -1240,6 +1240,7 @@ namespace System.Net
 
 			if (r != null) {
 				if (wexc != null) {
+					haveResponse = true;
 					r.SetCompleted (false, wexc);
 					r.DoCallback ();
 					return;
diff --git a/mcs/class/System/System.Security.Cryptography.X509Certificates/ChangeLog b/mcs/class/System/System.Security.Cryptography.X509Certificates/ChangeLog
index bfbae00..f25192c 100644
--- a/mcs/class/System/System.Security.Cryptography.X509Certificates/ChangeLog
+++ b/mcs/class/System/System.Security.Cryptography.X509Certificates/ChangeLog
@@ -1,3 +1,10 @@
+2010-10-05  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	X509Chain always uses the LM store
+
+	X509Chain will now add the LM store certificates always, even when
+	the CU store is selected.
+
 2010-06-11 Jonathan Chambers  <joncham at gmail.com>
 
 	* X509Certificate2Collection.cs: Add {} around default switch case.
diff --git a/mcs/class/System/System.Security.Cryptography.X509Certificates/ChangeLog b/mcs/class/System/System.Security.Cryptography.X509Certificates/ChangeLog.old
similarity index 100%
copy from mcs/class/System/System.Security.Cryptography.X509Certificates/ChangeLog
copy to mcs/class/System/System.Security.Cryptography.X509Certificates/ChangeLog.old
diff --git a/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Chain.cs b/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Chain.cs
index b95fe86..c892907 100644
--- a/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Chain.cs
+++ b/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Chain.cs
@@ -205,14 +205,24 @@ namespace System.Security.Cryptography.X509Certificates {
 				status = null;
 			if (elements.Count > 0)
 				elements.Clear ();
-			if (roots != null) {
-				roots.Close ();
-				roots = null;
+			if (user_root_store != null) {
+				user_root_store.Close ();
+				user_root_store = null;
 			}
-			if (cas != null) {
-				cas.Close ();
-				cas = null;
+			if (root_store != null) {
+				root_store.Close ();
+				root_store = null;
 			}
+			if (user_ca_store != null) {
+				user_ca_store.Close ();
+				user_ca_store = null;
+			}
+			if (ca_store != null) {
+				ca_store.Close ();
+				ca_store = null;
+			}
+			roots = null;
+			cas = null;
 			collection = null;
 			bce_restriction = null;
 			working_public_key = null;
@@ -227,29 +237,92 @@ namespace System.Security.Cryptography.X509Certificates {
 
 		// private stuff
 
-		private X509Store roots;
-		private X509Store cas;
+		private X509Certificate2Collection roots;
+		private X509Certificate2Collection cas;
+		private X509Store root_store;
+		private X509Store ca_store;
+		private X509Store user_root_store;
+		private X509Store user_ca_store;
 
-		private X509Store Roots {
+		private X509Certificate2Collection Roots {
 			get {
 				if (roots == null) {
-					roots = new X509Store (StoreName.Root, location);
-					roots.Open (OpenFlags.ReadOnly);
+					X509Certificate2Collection c = new X509Certificate2Collection ();
+					X509Store store = LMRootStore;
+					if (location == StoreLocation.CurrentUser)
+						c.AddRange (UserRootStore.Certificates);
+					c.AddRange (store.Certificates);
+					roots = c;
 				}
 				return roots;
 			}
 		}
 
-		private X509Store CertificateAuthorities {
+		private X509Certificate2Collection CertificateAuthorities {
 			get {
 				if (cas == null) {
-					cas = new X509Store (StoreName.CertificateAuthority, location);
-					cas.Open (OpenFlags.ReadOnly);
+					X509Certificate2Collection c = new X509Certificate2Collection ();
+					X509Store store = LMCAStore;
+					if (location == StoreLocation.CurrentUser)
+						c.AddRange (UserCAStore.Certificates);
+					c.AddRange (store.Certificates);
+					cas = c;
 				}
 				return cas;
 			}
 		}
 
+		private X509Store LMRootStore {
+			get {
+				if (root_store == null) {
+					root_store = new X509Store (StoreName.Root, StoreLocation.LocalMachine);
+					try {
+						root_store.Open (OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
+					} catch {
+					}
+				}
+				return root_store;
+			}
+		}
+
+		private X509Store UserRootStore {
+			get {
+				if (user_root_store == null) {
+					user_root_store = new X509Store (StoreName.Root, StoreLocation.CurrentUser);
+					try {
+						user_root_store.Open (OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
+					} catch {
+					}
+				}
+				return user_root_store;
+			}
+		}
+
+		private X509Store LMCAStore {
+			get {
+				if (ca_store == null) {
+					ca_store = new X509Store (StoreName.CertificateAuthority, StoreLocation.LocalMachine);
+					try {
+						ca_store.Open (OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
+					} catch {
+					}
+				}
+				return ca_store;
+			}
+		}
+
+		private X509Store UserCAStore {
+			get {
+				if (user_ca_store == null) {
+					user_ca_store = new X509Store (StoreName.CertificateAuthority, StoreLocation.CurrentUser);
+					try {
+						user_ca_store.Open (OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
+					} catch {
+					}
+				}
+				return user_ca_store;
+			}
+		}
 		// *** certificate chain/path building stuff ***
 
 		private X509Certificate2Collection collection;
@@ -260,10 +333,8 @@ namespace System.Security.Cryptography.X509Certificates {
 			get {
 				if (collection == null) {
 					collection = new X509Certificate2Collection (ChainPolicy.ExtraStore);
-					if (Roots.Certificates.Count > 0)
-						collection.AddRange (Roots.Certificates);
-					if (CertificateAuthorities.Certificates.Count > 0)
-						collection.AddRange (CertificateAuthorities.Certificates);
+					collection.AddRange (Roots);
+					collection.AddRange (CertificateAuthorities);
 				}
 				return collection;
 			}
@@ -295,7 +366,7 @@ namespace System.Security.Cryptography.X509Certificates {
 
 			// roots may be supplied (e.g. in the ExtraStore) so we need to confirm their
 			// trustiness (what a cute word) in the trusted root collection
-			if (!Roots.Certificates.Contains (certificate))
+			if (!Roots.Contains (certificate))
 				elements [elements.Count - 1].StatusFlags |= X509ChainStatusFlags.UntrustedRoot;
 
 			return X509ChainStatusFlags.NoError;
@@ -637,18 +708,18 @@ namespace System.Security.Cryptography.X509Certificates {
 		}
 
 		// System.dll v2 doesn't have a class to deal with the AuthorityKeyIdentifier extension
-		private string GetAuthorityKeyIdentifier (X509Certificate2 certificate)
+		static string GetAuthorityKeyIdentifier (X509Certificate2 certificate)
 		{
 			return GetAuthorityKeyIdentifier (certificate.MonoCertificate.Extensions ["2.5.29.35"]);
 		}
 
 		// but anyway System.dll v2 doesn't expose CRL in any way so...
-		private string GetAuthorityKeyIdentifier (MX.X509Crl crl)
+		static string GetAuthorityKeyIdentifier (MX.X509Crl crl)
 		{
 			return GetAuthorityKeyIdentifier (crl.Extensions ["2.5.29.35"]);
 		}
 
-		private string GetAuthorityKeyIdentifier (MX.X509Extension ext)
+		static string GetAuthorityKeyIdentifier (MX.X509Extension ext)
 		{
 			if (ext == null)
 				return String.Empty;
@@ -804,21 +875,34 @@ namespace System.Security.Cryptography.X509Certificates {
 			return X509ChainStatusFlags.NoError;
 		}
 
+		static MX.X509Crl CheckCrls (string subject, string ski, ArrayList crls)
+		{
+			foreach (MX.X509Crl crl in crls) {
+				if (crl.IssuerName == subject && (ski.Length == 0 || ski == GetAuthorityKeyIdentifier (crl)))
+					return crl;
+			}
+			return null; // No CRL found
+		}
+
 		private MX.X509Crl FindCrl (X509Certificate2 caCertificate)
 		{
 			string subject = caCertificate.SubjectName.Decode (X500DistinguishedNameFlags.None);
 			string ski = GetSubjectKeyIdentifier (caCertificate);
-			foreach (MX.X509Crl crl in CertificateAuthorities.Store.Crls) {
-				if (crl.IssuerName == subject) {
-					if ((ski.Length == 0) || (ski == GetAuthorityKeyIdentifier (crl)))
-						return crl;
-				}
-			}
-			foreach (MX.X509Crl crl in Roots.Store.Crls) {
-				if (crl.IssuerName == subject) {
-					if ((ski.Length == 0) || (ski == GetAuthorityKeyIdentifier (crl)))
-						return crl;
-				}
+			MX.X509Crl result = CheckCrls (subject, ski, LMCAStore.Store.Crls);
+			if (result != null)
+				return result;
+			if (location == StoreLocation.CurrentUser) {
+				result = CheckCrls (subject, ski, UserCAStore.Store.Crls);
+				if (result != null)
+					return result;
+			}
+			result = CheckCrls (subject, ski, LMRootStore.Store.Crls);
+			if (result != null)
+				return result;
+			if (location == StoreLocation.CurrentUser) {
+				result = CheckCrls (subject, ski, UserRootStore.Store.Crls);
+				if (result != null)
+					return result;
 			}
 			return null;
 		}
diff --git a/mcs/class/corlib/Microsoft.Win32/ChangeLog b/mcs/class/corlib/Microsoft.Win32/ChangeLog
index 22a2726..085a3f8 100644
--- a/mcs/class/corlib/Microsoft.Win32/ChangeLog
+++ b/mcs/class/corlib/Microsoft.Win32/ChangeLog
@@ -1,3 +1,8 @@
+2010-11-11  Marek Habersack  <grendel at twistedcode.net>
+
+	[corlib] Fix for bug #652807. Handle RegistryValueKind.QWord in
+	Win32RegistryApi.{Get,Set}Value
+
 2010-08-07  Carlos Alberto Cortez  <calberto.cortez at gmail.com>
 
 	* Microsoft.Win32/Win32RegistryApi.cs: *
diff --git a/mcs/class/corlib/Microsoft.Win32/Win32RegistryApi.cs b/mcs/class/corlib/Microsoft.Win32/Win32RegistryApi.cs
index 4ad202c..63e507a 100644
--- a/mcs/class/corlib/Microsoft.Win32/Win32RegistryApi.cs
+++ b/mcs/class/corlib/Microsoft.Win32/Win32RegistryApi.cs
@@ -57,6 +57,7 @@ namespace Microsoft.Win32
 
 		// FIXME must be a way to determin this dynamically?
 		const int Int32ByteSize = 4;
+		const int Int64ByteSize = 8;
 
 		// FIXME this is hard coded on Mono, can it be determined dynamically? 
 		readonly int NativeBytesPerCharacter = Marshal.SystemDefaultCharSize;
@@ -119,6 +120,11 @@ namespace Microsoft.Win32
 				string valueName, IntPtr reserved, RegistryValueKind type,
 				ref int data, int rawDataLength);
 
+		[DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegSetValueEx")]
+		private static extern int RegSetValueEx (IntPtr keyBase, 
+				string valueName, IntPtr reserved, RegistryValueKind type,
+				ref long data, int rawDataLength);
+
 		[DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegQueryValueEx")]
 		private static extern int RegQueryValueEx (IntPtr keyBase,
 				string valueName, IntPtr reserved, ref RegistryValueKind type,
@@ -134,6 +140,11 @@ namespace Microsoft.Win32
 				string valueName, IntPtr reserved, ref RegistryValueKind type,
 				ref int data, ref int dataSize);
 
+		[DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegQueryValueEx")]
+		private static extern int RegQueryValueEx (IntPtr keyBase,
+				string valueName, IntPtr reserved, ref RegistryValueKind type,
+				ref long data, ref int dataSize);
+
 		// Returns our handle from the RegistryKey
 		public IntPtr GetHandle (RegistryKey key)
 		{
@@ -192,6 +203,10 @@ namespace Microsoft.Win32
 				int data = 0;
 				result = RegQueryValueEx (handle, name, IntPtr.Zero, ref type, ref data, ref size);
 				obj = data;
+			} else if (type == RegistryValueKind.QWord) {
+				long data = 0;
+				result = RegQueryValueEx (handle, name, IntPtr.Zero, ref type, ref data, ref size);
+				obj = data;
 			} else if (type == RegistryValueKind.Binary) {
 				byte[] data;
 				result = GetBinaryValue (rkey, name, type, out data, size);
@@ -228,7 +243,10 @@ namespace Microsoft.Win32
 			int result;
 			IntPtr handle = GetHandle (rkey);
 
-			if (valueKind == RegistryValueKind.DWord && type == typeof (int)) {
+			if (valueKind == RegistryValueKind.QWord && type == typeof (long)) {
+				long rawValue = (long)value;
+				result = RegSetValueEx (handle, name, IntPtr.Zero, RegistryValueKind.QWord, ref rawValue, Int64ByteSize); 
+			} else if (valueKind == RegistryValueKind.DWord && type == typeof (int)) {
 				int rawValue = (int)value;
 				result = RegSetValueEx (handle, name, IntPtr.Zero, RegistryValueKind.DWord, ref rawValue, Int32ByteSize); 
 			} else if (valueKind == RegistryValueKind.Binary && type == typeof (byte[])) {
diff --git a/mcs/class/corlib/System.IO/ChangeLog b/mcs/class/corlib/System.IO/ChangeLog
index 3778389..748d531 100644
--- a/mcs/class/corlib/System.IO/ChangeLog
+++ b/mcs/class/corlib/System.IO/ChangeLog
@@ -1,3 +1,17 @@
+2010-09-03  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Linux /proc/mounts might have escaped characters
+
+	Translate escaped characters in mount paths.
+
+	Fixes bug #637078.
+
+2010-09-03  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Use UTF8 instead of ASCII when reading mount info
+
+	This allows for mount points with UTF8 characters in them.
+
 2010-05-27  William Holmes  <billholmes54 at gmail.com>
 
 	* Directory.cs (ValidateDirectoryListing): Removing an unnecessary
diff --git a/mcs/class/corlib/System.IO/ChangeLog b/mcs/class/corlib/System.IO/ChangeLog.old
similarity index 100%
copy from mcs/class/corlib/System.IO/ChangeLog
copy to mcs/class/corlib/System.IO/ChangeLog.old
diff --git a/mcs/class/corlib/System.IO/DriveInfo.cs b/mcs/class/corlib/System.IO/DriveInfo.cs
index a37ad1f..5efe84a 100644
--- a/mcs/class/corlib/System.IO/DriveInfo.cs
+++ b/mcs/class/corlib/System.IO/DriveInfo.cs
@@ -155,10 +155,11 @@ namespace System.IO {
 		static StreamReader TryOpen (string name)
 		{
 			if (File.Exists (name))
-				return new StreamReader (name, Encoding.ASCII);
+				return new StreamReader (name);
 			return null;
 		}
 
+		static char [] space = { ' ' };
 		static DriveInfo [] LinuxGetDrives ()
 		{
 			using (StreamReader mounts = TryOpen ("/proc/mounts")){
@@ -168,27 +169,42 @@ namespace System.IO {
 				while ((line = mounts.ReadLine ()) != null){
 					if (line.StartsWith ("rootfs"))
 						continue;
-					int p;
-
-					p = line.IndexOf (' ');
-					if (p == -1)
-						continue;
-					string rest = line.Substring (p+1);
-					p = rest.IndexOf (' ');
-					if (p == -1)
+					string [] parts = line.Split (space, 4);
+					if (parts.Length < 3)
 						continue;
-					string path = rest.Substring (0, p);
-					rest = rest.Substring (p+1);
-					p = rest.IndexOf (' ');
-					if (p == -1)
-						continue;
-					string fstype = rest.Substring (0, p);
+					string path = Unescape (parts [1]);
+					string fstype = parts [2];
 					drives.Add (new DriveInfo (_DriveType.Linux, path, fstype));
 				}
 
 				return (DriveInfo []) drives.ToArray (typeof (DriveInfo));
 			}
 		}
+
+		static string Unescape (string path)
+		{
+			StringBuilder sb = null;
+			int start = 0;
+			do {
+				int slash = path.IndexOf ('\\', start);
+				if (slash >= 0) {
+					if (sb == null)
+						sb = new StringBuilder ();
+					string str = path.Substring (start, slash - start);
+					sb.Append (path.Substring (start, slash - start));
+					char c = (char) ((path [slash + 1] - '0') << 6);
+					c += (char) ((path [slash + 2] - '0') << 3);
+					c += (char) (path [slash + 3] - '0');
+					sb.Append (c);
+					start = slash + 4;
+					continue;
+				}
+				if (start == 0)
+					return path;
+				sb.Append (path.Substring (start));
+				return sb.ToString ();
+			} while (true);
+		}
 		
 		static DriveInfo [] UnixGetDrives ()
 		{
diff --git a/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ChangeLog b/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ChangeLog
index 90418f0..7df4687 100644
--- a/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ChangeLog
+++ b/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ChangeLog
@@ -1,3 +1,10 @@
+2010-10-20  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Able to read MS serialized nullable<primitive>
+
+	Handle boxed primitive types for nullable fields. Fixes bug
+	#646556.
+
 2010-08-30  Carlos Alberto Cortez  <calberto.cortez at gmail.com>
 
 	* ObjectWriter.cs: Actually take SerializationBinder.BindToName
diff --git a/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs b/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs
index 8dbe14d..ced76cc 100644
--- a/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs
+++ b/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs
@@ -709,6 +709,22 @@ namespace System.Runtime.Serialization.Formatters.Binary
 			return metadata;
 		}
 
+		// Called for primitive types
+		static bool IsGeneric (MemberInfo minfo)
+		{
+			if (minfo == null)
+				return false;
+
+			Type mtype = null;
+			switch (minfo.MemberType) {
+			case MemberTypes.Field:
+				mtype = ((FieldInfo) minfo).FieldType;
+				break;
+			default:
+				throw new NotSupportedException ("Not supported: " + minfo.MemberType);
+			}
+			return (mtype != null && mtype.IsGenericType);
+		}
 
 		private void ReadValue (BinaryReader reader, object parentObject, long parentObjectId, SerializationInfo info, Type valueType, string fieldName, MemberInfo memberInfo, int[] indices)
 		{
@@ -716,7 +732,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
 			object val;
 
-			if (BinaryCommon.IsPrimitive (valueType))
+			if (BinaryCommon.IsPrimitive (valueType) && !IsGeneric (memberInfo))
 			{
 				val = ReadPrimitiveTypeValue (reader, valueType);
 				SetObjectValue (parentObject, fieldName, memberInfo, info, val, valueType, indices);
diff --git a/mcs/class/corlib/System.Threading/ChangeLog b/mcs/class/corlib/System.Threading/ChangeLog
index ca80827..f8bf5d1 100644
--- a/mcs/class/corlib/System.Threading/ChangeLog
+++ b/mcs/class/corlib/System.Threading/ChangeLog
@@ -1,3 +1,12 @@
+2010-10-21  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Fix the collision handling code
+
+	After the fix for bug #605092, inserting timers with an equal due
+	time was failing because searching in the list was also using a
+	reference comparison. Now, when adding a new timer, we search
+	using just the due time. Fixes bug #648130.
+
 2010-08-31  Jérémie Laval  <jeremie.laval at gmail.com>
 
 	Fix non 4.0 build of ReaderWriterLockSlim.
diff --git a/mcs/class/corlib/System.Threading/Timer.cs b/mcs/class/corlib/System.Threading/Timer.cs
index ab2193b..a20bade 100644
--- a/mcs/class/corlib/System.Threading/Timer.cs
+++ b/mcs/class/corlib/System.Threading/Timer.cs
@@ -237,11 +237,46 @@ namespace System.Threading
 				}
 			}
 
+			// lock held by caller
+			int FindByDueTime (long nr)
+			{
+				int min = 0;
+				int max = list.Count - 1;
+				if (max < 0)
+					return -1;
+
+				if (max < 20) {
+					while (min <= max) {
+						Timer t = (Timer) list.GetByIndex (min);
+						if (t.next_run == nr)
+							return min;
+						if (t.next_run > nr)
+							return -1;
+						min++;
+					}
+					return -1;
+				}
+
+				while (min <= max) {
+					int half = min + ((max - min) >> 1);
+					Timer t = (Timer) list.GetByIndex (half);
+					if (nr == t.next_run)
+						return half;
+					if (nr > t.next_run)
+						min = half + 1;
+					else
+						max = half - 1;
+				}
+
+				return -1;
+			}
+
 			// This should be the only caller to list.Add!
 			void Add (Timer timer)
 			{
 				// Make sure there are no collisions (10000 ticks == 1ms, so we should be safe here)
-				int idx = list.IndexOfKey (timer);
+				// Do not use list.IndexOfKey here. See bug #648130
+				int idx = FindByDueTime (timer.next_run);
 				if (idx != -1) {
 					bool up = (Int64.MaxValue - timer.next_run) > 20000 ? true : false;
 					while (true) {
diff --git a/mcs/class/corlib/System/Array.cs b/mcs/class/corlib/System/Array.cs
index dbd2fce..3f44f8c 100644
--- a/mcs/class/corlib/System/Array.cs
+++ b/mcs/class/corlib/System/Array.cs
@@ -1316,7 +1316,7 @@ namespace System
 				throw new ArgumentOutOfRangeException ("length", Locale.GetText (
 					"Value has to be >= 0."));
 
-			if (keys.Length != items.Length || keys.Length - (index + keys.GetLowerBound (0)) < length)
+			if (items.Length - (index + items.GetLowerBound (0)) < length || keys.Length - (index + keys.GetLowerBound (0)) < length)
 				throw new ArgumentException ();
 
 			SortImpl (keys, items, index, length, comparer);
@@ -1565,7 +1565,7 @@ namespace System
 			if (length < 0)
 				throw new ArgumentOutOfRangeException ("length");
 
-			if (keys.Length != items.Length || keys.Length - index < length)
+			if (items.Length - index < length || keys.Length - index < length)
 				throw new ArgumentException ();
 
 			SortImpl<TKey, TValue> (keys, items, index, length, comparer);
diff --git a/mcs/class/corlib/System/ChangeLog b/mcs/class/corlib/System/ChangeLog
index cec943f..7546fcf 100644
--- a/mcs/class/corlib/System/ChangeLog
+++ b/mcs/class/corlib/System/ChangeLog
@@ -1,3 +1,29 @@
+2010-11-02  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Revert change in FromBinary
+
+2010-10-23  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix another regression in the Array.Sort () methods, allow keys
+	and items to be of different length. Fixes #648828.
+
+2010-10-21  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	FromBinary does not need ToLocalTime
+
+	When converting to DateTime from a long, we don't need
+	ToLocalTime(). Setting the kind to Local is enough. Patch from
+	Mig.
+
+	Fixes bug #648252.
+
+2010-10-20  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Able to read MS serialized nullable<primitive>
+
+	Handle boxed primitive types for nullable fields. Fixes bug
+	#646556.
+
 2010-09-15  Rodrigo Kumpera  <kumpera at gmail.com>
 
 	* Type.cs (GetTypeCodeImpl): If the type is a TypeBuilder call
diff --git a/mcs/class/corlib/System/DateTime.cs b/mcs/class/corlib/System/DateTime.cs
index 9aa38a1..39b863f 100644
--- a/mcs/class/corlib/System/DateTime.cs
+++ b/mcs/class/corlib/System/DateTime.cs
@@ -649,7 +649,7 @@ namespace System
 
 		public static DateTime FromBinary (long dateData)
 		{
-			switch ((ulong)dateData >> 62) {
+			switch ((ulong)dateData >> KindShift) {
 			case 1: // Utc
 				return new DateTime (dateData & TicksMask, DateTimeKind.Utc);
 			case 0: // Unspecified
diff --git a/mcs/class/corlib/Test/System/ArrayTest.cs b/mcs/class/corlib/Test/System/ArrayTest.cs
index 0ffcb6c..c047987 100644
--- a/mcs/class/corlib/Test/System/ArrayTest.cs
+++ b/mcs/class/corlib/Test/System/ArrayTest.cs
@@ -2311,6 +2311,13 @@ public class ArrayTest
 			Assert.AreEqual (3, i1[4], "#N91");
 			Assert.AreEqual (6, i1[5], "#N92");
 		}
+
+		{
+			// #648828
+			double[] a = new double[115];
+			int[] b = new int[256];
+			Array.Sort<double, int> (a, b, 0, 115);
+		}
 	}
 
 	[Test] // #616416
diff --git a/mcs/class/corlib/Test/System/ChangeLog b/mcs/class/corlib/Test/System/ChangeLog
index 6a1c70f..6b9a901 100644
--- a/mcs/class/corlib/Test/System/ChangeLog
+++ b/mcs/class/corlib/Test/System/ChangeLog
@@ -1,3 +1,8 @@
+2010-10-23  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix another regression in the Array.Sort () methods, allow keys
+	and items to be of different length. Fixes #648828.
+
 2010-08-07  Zoltan Varga  <vargaz at gmail.com>
 
 	Fix Math.Log (2, 1). Fixes #626944.
diff --git a/mcs/class/lib/monolite/Mono.Security.dll b/mcs/class/lib/monolite/Mono.Security.dll
index bbd1e5b..d0ed236 100755
Binary files a/mcs/class/lib/monolite/Mono.Security.dll and b/mcs/class/lib/monolite/Mono.Security.dll differ
diff --git a/mcs/class/lib/monolite/System.Core.dll b/mcs/class/lib/monolite/System.Core.dll
index 5023039..99a8269 100755
Binary files a/mcs/class/lib/monolite/System.Core.dll and b/mcs/class/lib/monolite/System.Core.dll differ
diff --git a/mcs/class/lib/monolite/System.Xml.dll b/mcs/class/lib/monolite/System.Xml.dll
index 80ab926..a3581f8 100755
Binary files a/mcs/class/lib/monolite/System.Xml.dll and b/mcs/class/lib/monolite/System.Xml.dll differ
diff --git a/mcs/class/lib/monolite/System.dll b/mcs/class/lib/monolite/System.dll
index 3c6bc82..c5953dc 100755
Binary files a/mcs/class/lib/monolite/System.dll and b/mcs/class/lib/monolite/System.dll differ
diff --git a/mcs/class/lib/monolite/gmcs.exe b/mcs/class/lib/monolite/gmcs.exe
index a7e349a..09c0eb1 100755
Binary files a/mcs/class/lib/monolite/gmcs.exe and b/mcs/class/lib/monolite/gmcs.exe differ
diff --git a/mcs/class/lib/monolite/mscorlib.dll b/mcs/class/lib/monolite/mscorlib.dll
index 48f65de..eb1efb8 100755
Binary files a/mcs/class/lib/monolite/mscorlib.dll and b/mcs/class/lib/monolite/mscorlib.dll differ
diff --git a/mcs/mcs/ChangeLog b/mcs/mcs/ChangeLog
index e5c600e..5a6ce06 100644
--- a/mcs/mcs/ChangeLog
+++ b/mcs/mcs/ChangeLog
@@ -1,3 +1,20 @@
+2010-11-01  Marek Safar  <marek.safar at gmail.com>
+
+	Set correct result type for chained folded enum subtraction
+
+2010-10-15  Marek Safar  <marek.safar at gmail.com>
+
+	[646997] Correctly emit platform ILOnly flag
+
+2010-10-14  Marek Safar  <marek.safar at gmail.com>
+
+	[646298] Compile multiple interface event declarators
+
+2010-10-08  Marek Safar  <marek.safar at gmail.com>
+
+	[642975] Fix initializer of partially static multidimensional
+	arrays
+
 2010-09-29  Marek Safar  <marek.safar at gmail.com>
 
 	[642437] Nested types have to check type arguments only and not
diff --git a/mcs/mcs/cfold.cs b/mcs/mcs/cfold.cs
index eb4ef94..e31a1ba 100644
--- a/mcs/mcs/cfold.cs
+++ b/mcs/mcs/cfold.cs
@@ -169,7 +169,7 @@ namespace Mono.CSharp {
 					case Binary.Operator.Subtraction:
 						result = BinaryFold (ec, oper, ((EnumConstant)left).Child, ((EnumConstant)right).Child, loc);
 						if (result != null)
-							result = result.Resolve (ec).TryReduce (ec, ((EnumConstant)left).Child.Type, loc);
+							result = result.Resolve (ec).TryReduce (ec, EnumSpec.GetUnderlyingType (lt), loc);
 						return result;
 
 					///
diff --git a/mcs/mcs/codegen.cs b/mcs/mcs/codegen.cs
index b425f99..8b0c5d8 100644
--- a/mcs/mcs/codegen.cs
+++ b/mcs/mcs/codegen.cs
@@ -184,15 +184,15 @@ namespace Mono.CSharp {
 
 			switch (RootContext.Platform) {
 			case Platform.X86:
-				pekind = PortableExecutableKinds.Required32Bit;
+				pekind = PortableExecutableKinds.Required32Bit | PortableExecutableKinds.ILOnly;
 				machine = ImageFileMachine.I386;
 				break;
 			case Platform.X64:
-				pekind = PortableExecutableKinds.PE32Plus;
+				pekind = PortableExecutableKinds.ILOnly;
 				machine = ImageFileMachine.AMD64;
 				break;
 			case Platform.IA64:
-				pekind = PortableExecutableKinds.PE32Plus;
+				pekind = PortableExecutableKinds.ILOnly;
 				machine = ImageFileMachine.IA64;
 				break;
 			case Platform.AnyCPU:
diff --git a/mcs/mcs/expression.cs b/mcs/mcs/expression.cs
index d4e2531..26b4540 100644
--- a/mcs/mcs/expression.cs
+++ b/mcs/mcs/expression.cs
@@ -5833,7 +5833,6 @@ namespace Mono.CSharp {
 			if (initializers == null)
 				return true;
 
-			only_constant_initializers = true;
 			for (int i = 0; i < probe.Count; ++i) {
 				var o = probe [i];
 				if (o is ArrayInitializer) {
@@ -5941,6 +5940,8 @@ namespace Mono.CSharp {
 
 		protected bool ResolveInitializers (ResolveContext ec)
 		{
+			only_constant_initializers = true;
+
 			if (arguments != null) {
 				bool res = true;
 				for (int i = 0; i < arguments.Count; ++i) {
diff --git a/mcs/mcs/property.cs b/mcs/mcs/property.cs
index 30b9ac5..13e5551 100644
--- a/mcs/mcs/property.cs
+++ b/mcs/mcs/property.cs
@@ -1001,14 +1001,19 @@ namespace Mono.CSharp
 
 		public override bool Define()
 		{
+			var mod_flags_src = ModFlags;
+
 			if (!base.Define ())
 				return false;
 
 			if (declarators != null) {
+				if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFER) != 0)
+					mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFER);
+
 				var t = new TypeExpression (MemberType, TypeExpression.Location);
 				int index = Parent.PartialContainer.Events.IndexOf (this);
 				foreach (var d in declarators) {
-					var ef = new EventField (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
+					var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
 
 					if (d.Initializer != null)
 						ef.initializer = d.Initializer;
diff --git a/mcs/tests/ChangeLog b/mcs/tests/ChangeLog
index 24742f7..de9531c 100644
--- a/mcs/tests/ChangeLog
+++ b/mcs/tests/ChangeLog
@@ -1,3 +1,16 @@
+2010-11-01  Marek Safar  <marek.safar at gmail.com>
+
+	Set correct result type for chained folded enum subtraction
+
+2010-10-15  Marek Safar  <marek.safar at gmail.com>
+
+	[646997] Correctly emit platform ILOnly flag
+
+2010-10-08  Marek Safar  <marek.safar at gmail.com>
+
+	[642975] Fix initializer of partially static multidimensional
+	arrays
+
 2010-08-31  Marek Safar  <marek.safar at gmail.com>
 
 	Add support for indirect pointer type constants.
diff --git a/mcs/tests/gtest-450.cs b/mcs/tests/gtest-450.cs
index 541f5e3..5f78ba0 100644
--- a/mcs/tests/gtest-450.cs
+++ b/mcs/tests/gtest-450.cs
@@ -12,7 +12,7 @@ class Program {
 
 		typeof (Program).Module.GetPEKind (out pekind, out machine);
 
-		if ((pekind & PortableExecutableKinds.ILOnly) != 0)
+		if ((pekind & PortableExecutableKinds.ILOnly) == 0)
 			return 1;
 
 		if ((pekind & PortableExecutableKinds.Required32Bit) == 0)
diff --git a/mcs/tests/test-539.cs b/mcs/tests/test-539.cs
new file mode 100644
index 0000000..2b93801
--- /dev/null
+++ b/mcs/tests/test-539.cs
@@ -0,0 +1,24 @@
+// Compiler options: -optimize
+using System;
+
+class Test
+{
+	static int Main ()
+	{
+		//switching to a constant fixes the problem
+		double thisIsCausingTheProblem = 5.0;
+
+		double[,] m1 = new double[4, 4] {
+			{ 1.0, 0.0, 0.0, thisIsCausingTheProblem },
+			{ 0.0, 1.0, 0.0, thisIsCausingTheProblem },
+			{ 0.0, 0.0, 1.0, thisIsCausingTheProblem },
+			{ 0.0, 0.0, 0.0, 1.0 }
+		};
+
+		var r = m1[0, 3];
+		if (r != 5)
+			return 1;
+
+		return 0;
+	}
+}
diff --git a/mcs/tests/test-99.cs b/mcs/tests/test-99.cs
index 79c5d7d..caf2f67 100644
--- a/mcs/tests/test-99.cs
+++ b/mcs/tests/test-99.cs
@@ -32,6 +32,8 @@ class X {
 		// Now try the implicit conversions for underlying types in enum operators
 		byte b = 1;
 		short s = (short) (Test.A + b);
+		
+		const int e = A.b + 1 - A.a;
 
 		//
 		// Make sure that other operators still work
diff --git a/mcs/tools/xbuild/ChangeLog b/mcs/tools/xbuild/ChangeLog
index 7e28e55..0bc3bef 100644
--- a/mcs/tools/xbuild/ChangeLog
+++ b/mcs/tools/xbuild/ChangeLog
@@ -1,3 +1,40 @@
+2010-10-15  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Fix bug #646941. Add explicit System.Core for >=3.5
+	projects.
+
+	For projects targeting TargetFrameworkVersion >= 3.5,
+	automatically add a reference to System.Core . This can be
+	controlled via two properties:
+
+	$(AddAdditionalExplicitAssemblyReferences) and
+	$(AdditionalExplicitAssemblyReferences) .
+
+	This is used only for projects built with ToolsVersion=4.0 .
+
+2010-10-15  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Set default TargetFrameworkVersion=4.0 for
+	ToolsVersion=4.0
+
+2010-10-14  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Add ResolveAssemblyReferencesDependsOn .
+
+	Add GetFrameworkPaths and PrepareForBuild as dependencies for the
+	ResolveAssemblyReferences target. This is required when it is
+	invoked directly from MD.
+
+	Patch from Michael Hutchinson (mhutchinson at novell.com).
+
+2010-10-05  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Update regex to not require EndProject in a sln file.
+
+	In a solution file, a Project might not have a corresponding
+	EndProject. This seems to be supported by VS, so updating xbuild
+	to support that too. Updated the regex.
+
 2010-09-15  Ankit Jain  <radical at corewars.org>
 
 	[xbuild] Fix references to Microsoft.Build.* assemblies for 3.5 .
diff --git a/mcs/tools/xbuild/SolutionParser.cs b/mcs/tools/xbuild/SolutionParser.cs
index 1d4dea8..30e7b38 100644
--- a/mcs/tools/xbuild/SolutionParser.cs
+++ b/mcs/tools/xbuild/SolutionParser.cs
@@ -93,7 +93,7 @@ namespace Mono.XBuild.CommandLine {
 		static string guidExpression = "{[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}}";
 
 		static Regex slnVersionRegex = new Regex (@"Microsoft Visual Studio Solution File, Format Version (\d?\d.\d\d)");
-		static Regex projectRegex = new Regex ("Project\\(\"(" + guidExpression + ")\"\\) = \"(.*?)\", \"(.*?)\", \"(" + guidExpression + ")\"(\\s*?)((\\s*?)ProjectSection\\((.*?)\\) = (.*?)EndProjectSection(\\s*?))*(\\s*?)EndProject?", RegexOptions.Singleline);
+		static Regex projectRegex = new Regex ("Project\\(\"(" + guidExpression + ")\"\\) = \"(.*?)\", \"(.*?)\", \"(" + guidExpression + ")\"(\\s*?)((\\s*?)ProjectSection\\((.*?)\\) = (.*?)EndProjectSection(\\s*?))*(\\s*?)(EndProject)?", RegexOptions.Singleline);
 		static Regex projectDependenciesRegex = new Regex ("ProjectSection\\((.*?)\\) = \\w*(.*?)EndProjectSection", RegexOptions.Singleline);
 		static Regex projectDependencyRegex = new Regex ("\\s*(" + guidExpression + ") = (" + guidExpression + ")");
 		static Regex projectSectionPropertiesRegex = new Regex ("\\s*(?<name>.*) = \"(?<value>.*)\"");
diff --git a/mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.targets b/mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.targets
index 7eeb83e..8b237ee 100644
--- a/mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.targets
+++ b/mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.targets
@@ -139,6 +139,11 @@
 			ResolveAssemblyReferences;
 			AfterResolveReferences
 		</ResolveReferencesDependsOn>
+
+		<ResolveAssemblyReferencesDependsOn>
+			GetFrameworkPaths;
+			PrepareForBuild
+		</ResolveAssemblyReferencesDependsOn>
 	</PropertyGroup>
 
 	<Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
@@ -146,7 +151,7 @@
 	<Target Name="BeforeResolveReferences" />
 	<Target Name="AfterResolveReferences" />
 
-	<Target Name="ResolveAssemblyReferences">
+	<Target Name="ResolveAssemblyReferences" DependsOnTargets="$(ResolveAssemblyReferencesDependsOn)">
 		<ResolveAssemblyReference
 			Assemblies="@(Reference)"
 			AssemblyFiles="@(ChildProjectReferences)"
diff --git a/mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.targets b/mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.targets
index 7eeb83e..8b237ee 100644
--- a/mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.targets
+++ b/mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.targets
@@ -139,6 +139,11 @@
 			ResolveAssemblyReferences;
 			AfterResolveReferences
 		</ResolveReferencesDependsOn>
+
+		<ResolveAssemblyReferencesDependsOn>
+			GetFrameworkPaths;
+			PrepareForBuild
+		</ResolveAssemblyReferencesDependsOn>
 	</PropertyGroup>
 
 	<Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
@@ -146,7 +151,7 @@
 	<Target Name="BeforeResolveReferences" />
 	<Target Name="AfterResolveReferences" />
 
-	<Target Name="ResolveAssemblyReferences">
+	<Target Name="ResolveAssemblyReferences" DependsOnTargets="$(ResolveAssemblyReferencesDependsOn)">
 		<ResolveAssemblyReference
 			Assemblies="@(Reference)"
 			AssemblyFiles="@(ChildProjectReferences)"
diff --git a/mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.targets b/mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.targets
index 6545fc8..b55f2de 100644
--- a/mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.targets
+++ b/mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.targets
@@ -16,7 +16,7 @@
 		<OutputPath Condition="'$(OutputPath)' != '' and !HasTrailingSlash('$(OutputPath)')">$(OutputPath)\</OutputPath> 
 		<OutputPath Condition=" '$(Platform)'=='' and '$(Configuration)'=='' and '$(OutputPath)'=='' ">bin\Debug\</OutputPath>
 		<WarningLevel Condition="'$(WarningLevel)' == ''" >2</WarningLevel>
-		<TargetFrameworkVersion Condition="'$(TargetFrameworkVersion)' == ''">v2.0</TargetFrameworkVersion>
+		<TargetFrameworkVersion Condition="'$(TargetFrameworkVersion)' == ''">v4.0</TargetFrameworkVersion>
 	</PropertyGroup>
 
 	<PropertyGroup>
@@ -30,6 +30,9 @@
 		<_OriginalPlatform>$(Platform)</_OriginalPlatform>
 		<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
 		<PlatformName Condition="'$(PlatformName)' == ''">$(Platform)</PlatformName>
+
+		<AddAdditionalExplicitAssemblyReferences Condition="'$(AddAdditionalExplicitAssemblyReferences)' == ''">true</AddAdditionalExplicitAssemblyReferences>
+		<AdditionalExplicitAssemblyReferences Condition="'$(AddAdditionalExplicitAssemblyReferences)' == 'true' and '$(TargetFrameworkVersion)' != 'v2.0' and '$(TargetFrameworkVersion)' != 'v3.0'">System.Core;$(AdditionalExplicitAssemblyReferences)</AdditionalExplicitAssemblyReferences>
 	</PropertyGroup>
 
 	<PropertyGroup>
@@ -142,6 +145,11 @@
 			ResolveAssemblyReferences;
 			AfterResolveReferences
 		</ResolveReferencesDependsOn>
+
+		<ResolveAssemblyReferencesDependsOn>
+			GetFrameworkPaths;
+			PrepareForBuild
+		</ResolveAssemblyReferencesDependsOn>
 	</PropertyGroup>
 
 	<Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
@@ -149,9 +157,17 @@
 	<Target Name="BeforeResolveReferences" />
 	<Target Name="AfterResolveReferences" />
 
-	<Target Name="ResolveAssemblyReferences">
+	<Target Name="ResolveAssemblyReferences" DependsOnTargets="$(ResolveAssemblyReferencesDependsOn)">
+		<CreateItem Include="@(Reference)" Exclude="$(AdditionalExplicitAssemblyReferences)">
+			<Output TaskParameter="Include" ItemName="_Reference"/>
+		</CreateItem>
+
+		<CreateItem Include="$(AdditionalExplicitAssemblyReferences)">
+			<Output TaskParameter="Include" ItemName="_Reference"/>
+		</CreateItem>
+
 		<ResolveAssemblyReference
-			Assemblies="@(Reference)"
+			Assemblies="@(_Reference)"
 			AssemblyFiles="@(ChildProjectReferences)"
 			SearchPaths="$(AssemblySearchPaths)"
 			CandidateAssemblyFiles="@(Content);@(None)"
diff --git a/mono/io-layer/ChangeLog b/mono/io-layer/ChangeLog
index 028ebda..b6c9944 100644
--- a/mono/io-layer/ChangeLog
+++ b/mono/io-layer/ChangeLog
@@ -1,3 +1,40 @@
+2010-11-02  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Renaming a dangling symlink works now
+
+	Ditto.
+
+	Fixes bug #650779.
+
+2010-10-21  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Replace EnumProcesses with OpenProcess
+
+	namedmutex_prewait was (partially) listing the running processes
+	and then searching through them. Now we use OpenProcess to verify
+	the owner of the mutex is still alive.
+
+	Fixes bug #648133 (note that you need MONO_ENABLE_SHM for this to
+	work)
+
+2010-09-04  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Fixed GetLogicalDriveString
+
+	When calling GetLogicalDriveString, icall.c was passing the length
+	in the wrong units.
+
+	GetLogicalDriveString now translates any octal sequence found into
+	its corresponding byte. Use the UTF16 length ('items_written')
+	instead of the UTF8 input string length ('items_read') when
+	computing the total size.
+
+2010-09-14  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	GetProcessById now works on the Mac too
+
+	Ditto. This should fix MD problems when SHM is disabled.
+
 2010-10-05  Michael Hutchinson  <mhutchinson at novell.com>
 
 	[io-layer] Cope with pids > 16 bits
diff --git a/mono/io-layer/io.c b/mono/io-layer/io.c
index 9896f53..64a15e6 100644
--- a/mono/io-layer/io.c
+++ b/mono/io-layer/io.c
@@ -1817,10 +1817,12 @@ gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
 	 * the same file as src.
 	 */
 	if (_wapi_stat (utf8_name, &stat_src) < 0) {
-		_wapi_set_last_path_error_from_errno (NULL, utf8_name);
-		g_free (utf8_name);
-		g_free (utf8_dest_name);
-		return FALSE;
+		if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
+			_wapi_set_last_path_error_from_errno (NULL, utf8_name);
+			g_free (utf8_name);
+			g_free (utf8_dest_name);
+			return FALSE;
+		}
 	}
 	
 	if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
@@ -3553,6 +3555,34 @@ guint32 GetTempPath (guint32 len, gunichar2 *buf)
 	return(ret);
 }
 
+/* In-place octal sequence replacement */
+static void
+unescape_octal (gchar *str)
+{
+	gchar *rptr;
+	gchar *wptr;
+
+	if (str == NULL)
+		return;
+
+	rptr = wptr = str;
+	while (*rptr != '\0') {
+		if (*rptr == '\\') {
+			char c;
+			rptr++;
+			c = (*(rptr++) - '0') << 6;
+			c += (*(rptr++) - '0') << 3;
+			c += *(rptr++) - '0';
+			*wptr++ = c;
+		} else if (wptr != rptr) {
+			*wptr++ = *rptr++;
+		} else {
+			rptr++; wptr++;
+		}
+	}
+	*wptr = '\0';
+}
+
 gint32
 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
 {
@@ -3588,10 +3618,12 @@ GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
 			continue;
 		}
 
-		dir = g_utf8_to_utf16 (*(splitted + 1), -1, &length, NULL, NULL);
+		unescape_octal (*(splitted + 1));
+		dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
 		g_strfreev (splitted);
 		if (total + length + 1 > len) {
 			fclose (fp);
+			g_free (dir);
 			return len * 2; /* guess */
 		}
 
diff --git a/mono/io-layer/mutexes.c b/mono/io-layer/mutexes.c
index e4f51eb..63fad05 100644
--- a/mono/io-layer/mutexes.c
+++ b/mono/io-layer/mutexes.c
@@ -282,74 +282,36 @@ static void namedmutex_prewait (gpointer handle)
 			   __func__, handle);
 #endif
 	} else {
-		guint32 *pids = g_new0 (guint32, 32);
-		guint32 count = 32, needed_bytes, i;
-		gboolean ret;
 		int thr_ret;
+		gpointer proc_handle;
 		
 #ifdef DEBUG
 		g_message ("%s: Named mutex handle %p owned by another process", __func__, handle);
 #endif
-		
-		ret = EnumProcesses (pids, count * sizeof(guint32),
-				     &needed_bytes);
-		if (ret == FALSE) {
-			do {
-				count = needed_bytes / sizeof(guint32);
-#ifdef DEBUG
-				g_message ("%s: Retrying pid lookup with %d slots", __func__, count);
-#endif
-				pids = g_renew (guint32, pids, count);
-				ret = EnumProcesses (pids, needed_bytes,
-						     &needed_bytes);
-			} while (ret == FALSE);
-		}
-
-		count = needed_bytes / sizeof(guint32);
-
-#ifdef DEBUG
-		g_message ("%s: Need to look at %d pids for named mutex handle %p", __func__, count, handle);
-#endif
-
-		thr_ret = _wapi_handle_lock_shared_handles ();
-		g_assert (thr_ret == 0);
-
-		for (i = 0; i < count; i++) {
-#ifdef DEBUG
-			g_message ("%s: Checking pid %d for named mutex handle %p", __func__, pids[i], handle);
-#endif
-
-			if (pids[i] == namedmutex_handle->pid) {
-				/* Must be still alive, because
-				 * EnumProcesses() checks for us
-				 */
-#ifdef DEBUG
-				g_message ("%s: Found active pid %d for named mutex handle %p", __func__, pids[i], handle);
-#endif
-
-				break;
-			}
-		}
-		
-		g_free (pids);
-
-		if (i == count) {
+		proc_handle = OpenProcess (0, 0, namedmutex_handle->pid);
+		if (proc_handle == NULL) {
 			/* Didn't find the process that this handle
 			 * was owned by, overriding it
 			 */
-
 #ifdef DEBUG
 			g_message ("%s: overriding old owner of named mutex handle %p", __func__, handle);
 #endif
+			thr_ret = _wapi_handle_lock_shared_handles ();
+			g_assert (thr_ret == 0);
 
 			namedmutex_handle->pid = 0;
 			namedmutex_handle->tid = 0;
 			namedmutex_handle->recursion = 0;
 
 			_wapi_shared_handle_set_signal_state (handle, TRUE);
+			_wapi_handle_unlock_shared_handles ();
+		} else {
+#ifdef DEBUG
+			g_message ("%s: Found active pid %d for named mutex handle %p", __func__, namedmutex_handle->pid, handle);
+#endif
 		}
-
-		_wapi_handle_unlock_shared_handles ();
+		if (proc_handle != NULL)
+			CloseProcess (proc_handle);
 	}
 }
 
diff --git a/mono/io-layer/processes.c b/mono/io-layer/processes.c
index 0274859..1ce52fa 100644
--- a/mono/io-layer/processes.c
+++ b/mono/io-layer/processes.c
@@ -1711,9 +1711,10 @@ gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_
 	g_message ("%s: looking for process %d", __func__, pid);
 #endif
 
-	handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
-				      process_open_compare,
-				      GUINT_TO_POINTER (pid), NULL, TRUE);
+	if (_wapi_shm_enabled ())
+		handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
+					      process_open_compare,
+					      GUINT_TO_POINTER (pid), NULL, TRUE);
 	if (handle == 0) {
 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
 		if ((kill(pid, 0) == 0) || (errno == EPERM)) {
diff --git a/mono/metadata/ChangeLog b/mono/metadata/ChangeLog
index 912c906..9aa08c8 100644
--- a/mono/metadata/ChangeLog
+++ b/mono/metadata/ChangeLog
@@ -1,3 +1,65 @@
+2010-11-05  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix DISABLE_REFLECTION_EMIT build.
+
+2010-10-12  Paolo Molaro  <lupus at oddwiz.org>
+
+	* loader.c: we don't search the current directory anymore for
+	shared libraries referenced in DllImport attributes, as it has a
+	slight security risk. We search in the same directory where the
+	referencing image was loaded from, instead. Fixes bug# 641915.
+
+2010-10-21  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	Disable cardtable unde 64bits as it is broken for 2.8.
+
+2010-09-03  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Allow ordinal entry points in windows.
+
+	Windows allows entry point names like "#10" which refer to the Nth
+	function (n > 1 and less than the highest ordinal value in the
+	.def file).
+
+	Fixes bug #636966.
+
+2010-09-04  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Fixed GetLogicalDriveString
+
+	When calling GetLogicalDriveString, icall.c was passing the length
+	in the wrong units.
+
+	GetLogicalDriveString now translates any octal sequence found into
+	its corresponding byte. Use the UTF16 length ('items_written')
+	instead of the UTF8 input string length ('items_read') when
+	computing the total size.
+
+2010-10-04  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Map SO_EXCLUSIVEADDRUSE to !SO_REUSEADDR
+
+	This will make windows app that use that property work on *nix.
+	Fixes bug #643475.
+
+2010-10-21  Zoltan Varga  <vargaz at gmail.com>
+
+	Avoid caching stuff in socket-io.c in static variables, since the
+	socket assembly can be unloaded, cache them in MonoDomain instead.
+
+2010-10-19  Tak  <levi at unity3d.com>
+
+	* metadata/object.c: * mini/mini.c: Ensure that exceptions get
+	propagated back to the caller when mono is being embedded.
+	License: MIT/X11
+
+2010-10-14  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	[ThreadPool] Clear the thread state
+
+	Clear the thread state after finishing a work item. We were only
+	resetting the background state.
+
 2010-10-05  Geoff Norton  <grompf at sublimeintervention.com>
 
 	Fix the build on windows
@@ -828,6 +890,12 @@
 
 	Fixes #560348
 
+2010-11-03  Martin Baulig  <martin at ximian.com>
+
+	* mono-debug.c (mono_register_symfile_for_assembly): New method.
+	This is used together with mono_register_bundled_assemblies() and
+	mono_register_config_for_assembly() to support bundles.
+
 2010-07-30  Mark Probst  <mark.probst at gmail.com>
 
 	* sgen-archdep.h (ARCH_COPY_SIGCTX_REGS): Add casts to fix
diff --git a/mono/metadata/ChangeLog.old b/mono/metadata/ChangeLog.old
index 5594580..71269ce 100644
--- a/mono/metadata/ChangeLog.old
+++ b/mono/metadata/ChangeLog.old
@@ -1,3 +1,9 @@
+2010-11-03  Martin Baulig  <martin at ximian.com>
+
+	* mono-debug.c (mono_register_symfile_for_assembly): New method.
+	This is used together with mono_register_bundled_assemblies() and
+	mono_register_config_for_assembly() to support bundles.
+
 2010-07-30  Mark Probst  <mark.probst at gmail.com>
 
 	* sgen-archdep.h (ARCH_COPY_SIGCTX_REGS): Add casts to fix
diff --git a/mono/metadata/assembly.h b/mono/metadata/assembly.h
index ff06e20..0b8fd8d 100644
--- a/mono/metadata/assembly.h
+++ b/mono/metadata/assembly.h
@@ -99,6 +99,7 @@ typedef struct {
 
 void          mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
 void          mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
+void          mono_register_symfile_for_assembly (const char* assembly_name, const mono_byte *raw_contents, int size);
 void	      mono_register_machine_config (const char *config_xml);
 
 void          mono_set_rootdir (void);
diff --git a/mono/metadata/domain-internals.h b/mono/metadata/domain-internals.h
index 415a29c..9380b07 100644
--- a/mono/metadata/domain-internals.h
+++ b/mono/metadata/domain-internals.h
@@ -318,6 +318,12 @@ struct _MonoDomain {
 	/* Assembly bindings, the per-domain part */
 	GSList *assembly_bindings;
 	gboolean assembly_bindings_parsed;
+
+	/* Used by socket-io.c */
+	/* These are domain specific, since the assembly can be unloaded */
+	MonoImage *socket_assembly;
+	MonoClass *sockaddr_class;
+	MonoClassField *sockaddr_data_field;
 };
 
 typedef struct  {
diff --git a/mono/metadata/icall.c b/mono/metadata/icall.c
index 0b2bad5..ab790a3 100644
--- a/mono/metadata/icall.c
+++ b/mono/metadata/icall.c
@@ -6522,7 +6522,7 @@ ves_icall_System_Environment_GetWindowsFolderPath (int folder)
 static MonoArray *
 ves_icall_System_Environment_GetLogicalDrives (void)
 {
-        gunichar2 buf [128], *ptr, *dname;
+        gunichar2 buf [256], *ptr, *dname;
 	gunichar2 *u16;
 	guint initial_size = 127, size = 128;
 	gint ndrives;
diff --git a/mono/metadata/loader.c b/mono/metadata/loader.c
index 7709583..db126b8 100644
--- a/mono/metadata/loader.c
+++ b/mono/metadata/loader.c
@@ -1340,32 +1340,34 @@ mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char
 
 		if (!module) {
 			void *iter = NULL;
-			while ((full_name = mono_dl_build_path (NULL, file_name, &iter))) {
+			char *mdirname = g_path_get_dirname (image->name);
+			while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
 				mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
-						"DllImport loading location: '%s'.", full_name);
+					"DllImport loading library: '%s'.", full_name);
 				module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
 				if (!module) {
 					mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
-							"DllImport error loading library: '%s'.",
-							error_msg);
+						"DllImport error loading library '%s'.",
+						error_msg);
 					g_free (error_msg);
 				}
 				g_free (full_name);
 				if (module)
 					break;
 			}
+			g_free (mdirname);
 		}
 
 		if (!module) {
 			void *iter = NULL;
-			while ((full_name = mono_dl_build_path (".", file_name, &iter))) {
+			while ((full_name = mono_dl_build_path (NULL, file_name, &iter))) {
 				mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
-					"DllImport loading library: '%s'.", full_name);
+						"DllImport loading location: '%s'.", full_name);
 				module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
 				if (!module) {
 					mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
-						"DllImport error loading library '%s'.",
-						error_msg);
+							"DllImport error loading library: '%s'.",
+							error_msg);
 					g_free (error_msg);
 				}
 				g_free (full_name);
@@ -1404,6 +1406,16 @@ mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char
 		return NULL;
 	}
 
+#ifdef TARGET_WIN32
+	if (import && import [0] == '#' && isdigit (import [1])) {
+		char *end;
+		long id;
+
+		id = strtol (import + 1, &end, 10);
+		if (id > 0 && *end == '\0')
+			import++;
+	}
+#endif
 	mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
 				"Searching for '%s'.", import);
 
diff --git a/mono/metadata/mono-debug.c b/mono/metadata/mono-debug.c
index 92c70c3..ac575a2 100644
--- a/mono/metadata/mono-debug.c
+++ b/mono/metadata/mono-debug.c
@@ -122,6 +122,8 @@ static void                 mono_debug_add_assembly    (MonoAssembly *assembly,
 							gpointer user_data);
 static void                 mono_debug_add_type        (MonoClass *klass);
 
+static MonoDebugHandle     *open_symfile_from_bundle   (MonoImage *image);
+
 void _mono_debug_init_corlib (MonoDomain *domain);
 
 extern void (*mono_debugger_class_init_func) (MonoClass *klass);
@@ -422,8 +424,14 @@ mono_debug_open_image (MonoImage *image, const guint8 *raw_contents, int size)
 static void
 mono_debug_add_assembly (MonoAssembly *assembly, gpointer user_data)
 {
+	MonoDebugHandle *handle;
+	MonoImage *image;
+
 	mono_debugger_lock ();
-	mono_debug_open_image (mono_assembly_get_image (assembly), NULL, 0);
+	image = mono_assembly_get_image (assembly);
+	handle = open_symfile_from_bundle (image);
+	if (!handle)
+		mono_debug_open_image (image, NULL, 0);
 	mono_debugger_unlock ();
 }
 
@@ -1181,3 +1189,45 @@ mono_is_debugger_attached (void)
 	return is_attached;
 }
 
+/*
+ * Bundles
+ */
+
+typedef struct _BundledSymfile BundledSymfile;
+
+struct _BundledSymfile {
+	BundledSymfile *next;
+	const char *aname;
+	const mono_byte *raw_contents;
+	int size;
+};
+
+static BundledSymfile *bundled_symfiles = NULL;
+
+void
+mono_register_symfile_for_assembly (const char *assembly_name, const mono_byte *raw_contents, int size)
+{
+	BundledSymfile *bsymfile;
+
+	bsymfile = g_new0 (BundledSymfile, 1);
+	bsymfile->aname = assembly_name;
+	bsymfile->raw_contents = raw_contents;
+	bsymfile->size = size;
+	bsymfile->next = bundled_symfiles;
+	bundled_symfiles = bsymfile;
+}
+
+static MonoDebugHandle *
+open_symfile_from_bundle (MonoImage *image)
+{
+	BundledSymfile *bsymfile;
+
+	for (bsymfile = bundled_symfiles; bsymfile; bsymfile = bsymfile->next) {
+		if (strcmp (bsymfile->aname, image->module_name))
+			continue;
+
+		return mono_debug_open_image (image, bsymfile->raw_contents, bsymfile->size);
+	}
+
+	return NULL;
+}
diff --git a/mono/metadata/object.c b/mono/metadata/object.c
index ac3b34f..9acb0a3 100644
--- a/mono/metadata/object.c
+++ b/mono/metadata/object.c
@@ -276,7 +276,9 @@ mono_runtime_class_init_full (MonoVTable *vtable, gboolean raise_exception)
 			MonoVTable *module_vtable = mono_class_vtable_full (vtable->domain, module_klass, raise_exception);
 			if (!module_vtable)
 				return NULL;
-			mono_runtime_class_init (module_vtable);
+			exc = mono_runtime_class_init_full (module_vtable, raise_exception);
+			if (exc)
+				return exc;
 		}
 	}
 	method = mono_class_get_cctor (klass);
diff --git a/mono/metadata/reflection.c b/mono/metadata/reflection.c
index 1338f2c..7a4e700 100644
--- a/mono/metadata/reflection.c
+++ b/mono/metadata/reflection.c
@@ -11574,6 +11574,19 @@ mono_reflection_is_valid_dynamic_token (MonoDynamicImage *image, guint32 token)
 	return mono_g_hash_table_lookup (image->tokens, GUINT_TO_POINTER (token)) != NULL;
 }
 
+MonoMethodSignature *
+mono_reflection_lookup_signature (MonoImage *image, MonoMethod *method, guint32 token)
+{
+	MonoMethodSignature *sig;
+	g_assert (image->dynamic);
+
+	sig = g_hash_table_lookup (((MonoDynamicImage*)image)->vararg_aux_hash, GUINT_TO_POINTER (token));
+	if (sig)
+		return sig;
+
+	return mono_method_signature (method);
+}
+
 #ifndef DISABLE_REFLECTION_EMIT
 
 /**
@@ -11608,19 +11621,6 @@ mono_reflection_lookup_dynamic_token (MonoImage *image, guint32 token, gboolean
 	return resolve_object (image, obj, handle_class, context);
 }
 
-MonoMethodSignature *
-mono_reflection_lookup_signature (MonoImage *image, MonoMethod *method, guint32 token)
-{
-	MonoMethodSignature *sig;
-	g_assert (image->dynamic);
-
-	sig = g_hash_table_lookup (((MonoDynamicImage*)image)->vararg_aux_hash, GUINT_TO_POINTER (token));
-	if (sig)
-		return sig;
-
-	return mono_method_signature (method);
-}
-
 /*
  * ensure_complete_type:
  *
diff --git a/mono/metadata/sgen-gc.h b/mono/metadata/sgen-gc.h
index 81e969e..4b45267 100644
--- a/mono/metadata/sgen-gc.h
+++ b/mono/metadata/sgen-gc.h
@@ -49,7 +49,10 @@
 
 //#define SGEN_BINARY_PROTOCOL
 
+#if SIZEOF_VOID_P == 4
 #define SGEN_HAVE_CARDTABLE	1
+#endif
+
 #if SIZEOF_VOID_P == 8
 #define SGEN_HAVE_OVERLAPPING_CARDS	1
 #endif
diff --git a/mono/metadata/socket-io.c b/mono/metadata/socket-io.c
index 07540a0..d38bb8b 100644
--- a/mono/metadata/socket-io.c
+++ b/mono/metadata/socket-io.c
@@ -659,14 +659,16 @@ static MonoImage *get_socket_assembly (void)
 {
 	static const char *version = NULL;
 	static gboolean moonlight;
-	static MonoImage *socket_assembly = NULL;
+	MonoDomain *domain = mono_domain_get ();
 	
 	if (version == NULL) {
 		version = mono_get_runtime_info ()->framework_version;
 		moonlight = !strcmp (version, "2.1");
 	}
 	
-	if (socket_assembly == NULL) {
+	if (domain->socket_assembly == NULL) {
+		MonoImage *socket_assembly;
+
 		if (moonlight) {
 			socket_assembly = mono_image_loaded ("System.Net");
 			if (!socket_assembly) {
@@ -690,9 +692,11 @@ static MonoImage *get_socket_assembly (void)
 				}
 			}
 		}
+
+		domain->socket_assembly = socket_assembly;
 	}
 	
-	return(socket_assembly);
+	return domain->socket_assembly;
 }
 
 #ifdef AF_INET6
@@ -902,17 +906,21 @@ static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
 {
 	MonoDomain *domain = mono_domain_get ();
 	MonoObject *sockaddr_obj;
-	MonoClass *sockaddr_class;
-	MonoClassField *field;
 	MonoArray *data;
 	MonoAddressFamily family;
 
 	/* Build a System.Net.SocketAddress object instance */
-	sockaddr_class=mono_class_from_name_cached (get_socket_assembly (), "System.Net", "SocketAddress");
-	sockaddr_obj=mono_object_new(domain, sockaddr_class);
+	if (!domain->sockaddr_class) {
+		domain->sockaddr_class=mono_class_from_name (get_socket_assembly (), "System.Net", "SocketAddress");
+		g_assert (domain->sockaddr_class);
+	}
+	sockaddr_obj=mono_object_new(domain, domain->sockaddr_class);
 	
 	/* Locate the SocketAddress data buffer in the object */
-	field=mono_class_get_field_from_name_cached (sockaddr_class, "data");
+	if (!domain->sockaddr_data_field) {
+		domain->sockaddr_data_field=mono_class_get_field_from_name (domain->sockaddr_class, "data");
+		g_assert (domain->sockaddr_data_field);
+	}
 
 	/* Make sure there is space for the family and size bytes */
 #ifdef HAVE_SYS_UN_H
@@ -960,7 +968,7 @@ static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
 		mono_array_set(data, guint8, 6, (address>>8) & 0xff);
 		mono_array_set(data, guint8, 7, (address) & 0xff);
 	
-		mono_field_set_value (sockaddr_obj, field, data);
+		mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
 
 		return(sockaddr_obj);
 #ifdef AF_INET6
@@ -990,7 +998,7 @@ static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
 		mono_array_set(data, guint8, 27,
 			       (sa_in->sin6_scope_id >> 24) & 0xff);
 
-		mono_field_set_value (sockaddr_obj, field, data);
+		mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
 
 		return(sockaddr_obj);
 #endif
@@ -1002,7 +1010,7 @@ static MonoObject *create_object_from_sockaddr(struct sockaddr *saddr,
 			mono_array_set (data, guint8, i+2, saddr->sa_data[i]);
 		}
 		
-		mono_field_set_value (sockaddr_obj, field, data);
+		mono_field_set_value (sockaddr_obj, domain->sockaddr_data_field, data);
 
 		return sockaddr_obj;
 #endif
@@ -1790,8 +1798,18 @@ void ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal(SOCKET soc
 
 	*error = 0;
 	
-	ret=convert_sockopt_level_and_name(level, name, &system_level,
-					   &system_name);
+#if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
+	if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse) {
+		system_level = SOL_SOCKET;
+		system_name = SO_REUSEADDR;
+		ret = 0;
+	} else
+#endif
+	{
+
+		ret = convert_sockopt_level_and_name (level, name, &system_level, &system_name);
+	}
+
 	if(ret==-1) {
 		*error = WSAENOPROTOOPT;
 		return;
@@ -1898,9 +1916,12 @@ void ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal(SOCKET soc
 #endif
 
 	default:
+#if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
+		if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse)
+			val = val ? 0 : 1;
+#endif
 		obj = int_to_object (domain, val);
 	}
-
 	*obj_val=obj;
 }
 
@@ -2015,6 +2036,15 @@ void ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal(SOCKET sock, g
 
 	ret=convert_sockopt_level_and_name(level, name, &system_level,
 					   &system_name);
+
+#if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
+	if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse) {
+		system_name = SO_REUSEADDR;
+		int_val = int_val ? 0 : 1;
+		ret = 0;
+	}
+#endif
+
 	if(ret==-1) {
 		*error = WSAENOPROTOOPT;
 		return;
diff --git a/mono/metadata/threadpool.c b/mono/metadata/threadpool.c
index 2420c3d..d5d9758 100644
--- a/mono/metadata/threadpool.c
+++ b/mono/metadata/threadpool.c
@@ -1879,6 +1879,7 @@ async_invoke_thread (gpointer data)
 				mono_thread_pop_appdomain_ref ();
 				InterlockedDecrement (&tp->busy_threads);
 				/* If the callee changes the background status, set it back to TRUE */
+				mono_thread_clr_state (thread , ~ThreadState_Background);
 				if (!mono_thread_test_state (thread , ThreadState_Background))
 					ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
 			}
diff --git a/mono/mini/ChangeLog b/mono/mini/ChangeLog
index d8f9da2..6f38780 100644
--- a/mono/mini/ChangeLog
+++ b/mono/mini/ChangeLog
@@ -1,3 +1,121 @@
+2010-11-10  Zoltan Varga  <vargaz at gmail.com>
+
+	When single stepping from a exception throw site, single step to
+	the catch site. Fixes #652590.
+
+2010-11-08  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix a typo in process_breakpoint_inner which doesn't break our
+	tests for some reason.
+
+2010-11-05  Zoltan Varga  <vargaz at gmail.com>
+
+	Enlarge try-finally blocks preceeded by a Monitor.Enter () call to
+	include the call itself, to avoid races inherent in such code.
+	Fixes #651546.
+
+2010-11-05  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix a bug introduced by the previous change to
+	mono_jit_walk_stack_from_ctx_in_thread ().
+
+2010-11-05  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix crashes in the debugger stack walk code if a gshared method
+	calls another using a managed-to-native translation.
+
+2010-11-05  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix more gshared problems in the soft debugger.
+
+2010-11-05  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix gshared support in the soft debugger. Fixes #651251.
+
+2010-11-02  Marek Habersack  <grendel at twistedcode.net>
+
+	[runtime] mono_cfg_set_exception is not present in 2.8. Fixes the
+	build.
+
+2010-11-01  Zoltan Varga  <vargaz at gmail.com>
+
+	Cache the array of classes in find_typespec_for_class ().
+
+2010-11-01  Zoltan Varga  <vargaz at gmail.com>
+
+	Avoid asserts if a forced inline fails. Fix typos. Fixes #650407.
+
+2010-10-30  Brian Luczkiewicz  <brian at sooloos.com>
+
+	Enable --aot (but not --aot=full) on osx/x86
+
+2010-10-31  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix the generation of GenericEqualityComparer () instances in AOT.
+
+2010-10-30  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Fix the build
+
+2010-10-28  Geoff Norton  <grompf at sublimeintervention.com>
+
+	[OSX] Fix debug=casts on OSX (Bug: 639172)
+
+	mono --debug=casts requires fast tls access and the jit tls
+	intrinsic. We already had support for OP_TLS_GET on darwin/x86,
+	but we did not expose the "tls offset (pthread_key_t)" from mini
+	to the intrinsic, instead falling back on the io-layer keys. We
+	now store mono_lmf_addr in a pthread_key for darwin/x86 so that we
+	can do fast-tls in the jit and fix this feature. X86 only for now.
+
+	r: kumpera
+
+2010-10-26  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	Fix some counters under 32bits.
+
+2010-10-25  Zoltan Varga  <vargaz at gmail.com>
+
+	Disable catchpoints when the DISABLE_BREAKPOINTS flag is used
+	during an invoke. Fixes #632224.
+
+2010-10-23  Zoltan Varga  <vargaz at gmail.com>
+
+	Implement memory barriers for amd64/x86. Fixes #648831.
+
+2010-10-22  Zoltan Varga  <vargaz at gmail.com>
+
+	Emit GenericEqualityComparer<T> instances for each
+	EqualityComparer<T> instance in AOT, the former is created
+	dynamically by the latter.
+
+2010-10-21  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix an assert in the LLVM backend if a long value was passed to
+	'localloc'.
+
+2010-10-20  Zoltan Varga  <vargaz at gmail.com>
+
+	Avoid trying to read the gc name in the AOT runtime from older AOT
+	images. Fixes #647918.
+
+2010-10-19  Tak  <levi at unity3d.com>
+
+	[Fix] Ensure that exceptions are propagated when embedding
+
+2010-10-14  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix crashes in the AOT compiler when the loaded LLVM module is
+	used. Fixes #646314.
+
+2010-10-14  Zoltan Varga  <vargaz at gmail.com>
+
+	Update the IMT thunk creation code on sparc to support net 4.0.
+
+2010-10-08  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix the sparc build.
+
 2010-10-01  Zoltan Varga  <vargaz at gmail.com>
 
 	Check the debugger_thread_exited condition in a loop to guard
diff --git a/mono/mini/aot-compiler.c b/mono/mini/aot-compiler.c
index dcc8da1..7a8e3b5 100644
--- a/mono/mini/aot-compiler.c
+++ b/mono/mini/aot-compiler.c
@@ -82,6 +82,8 @@
 #define SHARED_EXT ".dll"
 #elif defined(__ppc__) && defined(__MACH__)
 #define SHARED_EXT ".dylib"
+#elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
+#define SHARED_EXT ".dylib"
 #else
 #define SHARED_EXT ".so"
 #endif
@@ -178,6 +180,7 @@ typedef struct MonoAotCompile {
 	gboolean llvm;
 	MonoAotFileFlags flags;
 	MonoDynamicStream blob;
+	MonoClass **typespec_classes;
 } MonoAotCompile;
 
 typedef struct {
@@ -1564,16 +1567,21 @@ static guint32
 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
 {
 	int i;
-	MonoClass *k = NULL;
+	int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
 
 	/* FIXME: Search referenced images as well */
-	for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
-		k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
-		if (k == klass)
+	if (!acfg->typespec_classes) {
+		acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
+		for (i = 0; i < len; ++i) {
+			acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
+		}
+	}
+	for (i = 0; i < len; ++i) {
+		if (acfg->typespec_classes [i] == klass)
 			break;
 	}
 
-	if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
+	if (i < len)
 		return MONO_TOKEN_TYPE_SPEC | (i + 1);
 	else
 		return 0;
@@ -2681,6 +2689,27 @@ add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
 			add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx));
 		}
 	}
+
+	/* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
+	if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
+		MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
+		MonoClass *iface, *gcomparer;
+		MonoGenericContext ctx;
+		MonoType *args [16];
+
+		memset (&ctx, 0, sizeof (ctx));
+
+		iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
+		g_assert (iface);
+		args [0] = &tclass->byval_arg;
+		ctx.class_inst = mono_metadata_get_generic_inst (1, args);
+
+		if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
+			gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
+			g_assert (gcomparer);
+			add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx));
+		}
+	}
 }
 
 static void
@@ -6020,6 +6049,8 @@ compile_asm (MonoAotCompile *acfg)
 #define LD_OPTIONS "-m elf64ppc"
 #elif defined(sparc) && SIZEOF_VOID_P == 8
 #define AS_OPTIONS "-xarch=v9"
+#elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
+#define AS_OPTIONS "-arch i386 -W"
 #else
 #define AS_OPTIONS ""
 #endif
@@ -6085,6 +6116,8 @@ compile_asm (MonoAotCompile *acfg)
 	command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
 #elif defined(HOST_WIN32)
 	command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
+#elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
+	command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
 #else
 	command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
 #endif
@@ -6253,11 +6286,11 @@ mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
 		}
 	}
 
-#ifdef ENABLE_LLVM
-	acfg->llvm = TRUE;
- 	acfg->aot_opts.asm_writer = TRUE;
-	acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
-#endif
+	if (mono_use_llvm) {
+		acfg->llvm = TRUE;
+		acfg->aot_opts.asm_writer = TRUE;
+		acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
+	}
 
 	if (acfg->aot_opts.full_aot)
 		acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
@@ -6306,8 +6339,10 @@ mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
 	acfg->plt_offset = 1;
 
 #ifdef ENABLE_LLVM
-	llvm_acfg = acfg;
-	mono_llvm_create_aot_module (acfg->got_symbol_base);
+	if (acfg->llvm) {
+		llvm_acfg = acfg;
+		mono_llvm_create_aot_module (acfg->got_symbol_base);
+	}
 #endif
 
 	/* GOT offset 0 is reserved for the address of the current assembly */
@@ -6351,9 +6386,9 @@ mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
 		} else {
 			acfg->tmpfname = g_strdup ("temp.s");
 		}
-	}
 
-	emit_llvm_file (acfg);
+		emit_llvm_file (acfg);
+	}
 #endif
 
 	if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
diff --git a/mono/mini/aot-runtime.c b/mono/mini/aot-runtime.c
index 40587fa..d27d44c 100644
--- a/mono/mini/aot-runtime.c
+++ b/mono/mini/aot-runtime.c
@@ -65,6 +65,8 @@
 #define SHARED_EXT ".dll"
 #elif ((defined(__ppc__) || defined(__powerpc__) || defined(__ppc64__)) || defined(__MACH__)) && !defined(__linux__)
 #define SHARED_EXT ".dylib"
+#elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
+#define SHARED_EXT ".dylib"
 #else
 #define SHARED_EXT ".so"
 #endif
@@ -1067,7 +1069,7 @@ load_aot_module (MonoAssembly *assembly, gpointer user_data)
 
 	find_symbol (sofile, globals, "blob", (gpointer*)&blob);
 
-	if (((MonoAotFileInfo*)file_info)->gc_name_index != -1) {
+	if (usable && ((MonoAotFileInfo*)file_info)->gc_name_index != -1) {
 		char *gc_name = (char*)&blob [((MonoAotFileInfo*)file_info)->gc_name_index];
 		const char *current_gc_name = mono_gc_get_gc_name ();
 
diff --git a/mono/mini/debugger-agent.c b/mono/mini/debugger-agent.c
index f37e66f..ef9c7c9 100644
--- a/mono/mini/debugger-agent.c
+++ b/mono/mini/debugger-agent.c
@@ -112,6 +112,11 @@ typedef struct
 	guint32 il_offset;
 	MonoDomain *domain;
 	MonoMethod *method;
+	/*
+	 * If method is gshared, this is the actual instance, otherwise this is equal to
+	 * method.
+	 */
+	MonoMethod *actual_method;
 	MonoContext ctx;
 	MonoDebugMethodJitInfo *jit;
 	int flags;
@@ -224,6 +229,14 @@ typedef struct {
 	 * The current mono_runtime_invoke invocation.
 	 */
 	InvokeData *invoke;
+
+	/*
+	 * The context where single stepping should resume while the thread is suspended because
+	 * of an EXCEPTION event.
+	 */
+	MonoContext catch_ctx;
+
+	gboolean has_catch_ctx;
 } DebuggerTlsData;
 
 /* 
@@ -631,7 +644,7 @@ static void ids_cleanup (void);
 
 static void suspend_init (void);
 
-static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls);
+static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
 static void ss_destroy (SingleStepReq *req);
 
@@ -2374,6 +2387,32 @@ find_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32
 }
 
 /*
+ * find_next_seq_point_for_native_offset:
+ *
+ *   Find the first sequence point after NATIVE_OFFSET.
+ */
+static SeqPoint*
+find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
+{
+	MonoSeqPointInfo *seq_points;
+	int i;
+
+	mono_domain_lock (domain);
+	seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
+	mono_domain_unlock (domain);
+	g_assert (seq_points);
+
+	*info = seq_points;
+
+	for (i = 0; i < seq_points->len; ++i) {
+		if (seq_points->seq_points [i].native_offset >= native_offset)
+			return &seq_points->seq_points [i];
+	}
+
+	return NULL;
+}
+
+/*
  * find_seq_point:
  *
  *   Find the sequence point corresponding to the IL offset IL_OFFSET, which
@@ -2444,7 +2483,7 @@ process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
 {
 	ComputeFramesUserData *ud = user_data;
 	StackFrame *frame;
-	MonoMethod *method;
+	MonoMethod *method, *actual_method;
 
 	if (info->type != FRAME_TYPE_MANAGED) {
 		if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
@@ -2459,6 +2498,7 @@ process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
 		method = info->ji->method;
 	else
 		method = info->method;
+	actual_method = info->actual_method;
 
 	if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
 		return FALSE;
@@ -2482,6 +2522,7 @@ process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
 
 	frame = g_new0 (StackFrame, 1);
 	frame->method = method;
+	frame->actual_method = actual_method;
 	frame->il_offset = info->il_offset;
 	if (ctx) {
 		frame->ctx = *ctx;
@@ -3560,7 +3601,7 @@ process_breakpoint_inner (DebuggerTlsData *tls, MonoContext *ctx)
 	/* Process single step requests */
 	for (i = 0; i < ss_reqs_orig->len; ++i) {
 		EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
-		SingleStepReq *ss_req = bp->req->info;
+		SingleStepReq *ss_req = req->info;
 		gboolean hit = TRUE;
 		MonoSeqPointInfo *info;
 		SeqPoint *sp;
@@ -3593,7 +3634,7 @@ process_breakpoint_inner (DebuggerTlsData *tls, MonoContext *ctx)
 			g_ptr_array_add (ss_reqs, req);
 
 		/* Start single stepping again from the current sequence point */
-		ss_start (ss_req, ji->method, sp, info, ctx, NULL);
+		ss_start (ss_req, ji->method, sp, info, ctx, NULL, FALSE);
 	}
 	
 	if (ss_reqs->len > 0)
@@ -3955,7 +3996,7 @@ ss_stop (SingleStepReq *ss_req)
  *   Start the single stepping operation given by SS_REQ from the sequence point SP.
  */
 static void
-ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls)
+ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
 {
 	gboolean use_bp = FALSE;
 	int i, frame_index;
@@ -3968,7 +4009,10 @@ ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointI
 	/*
 	 * Implement single stepping using breakpoints if possible.
 	 */
-	if (ss_req->depth == STEP_DEPTH_OVER) {
+	if (step_to_catch) {
+		bp = set_breakpoint (method, sp->il_offset, ss_req->req);
+		ss_req->bps = g_slist_append (ss_req->bps, bp);
+	} else if (ss_req->depth == STEP_DEPTH_OVER) {
 		frame_index = 1;
 		/*
 		 * Find the first sequence point in the current or in a previous frame which
@@ -4016,6 +4060,8 @@ ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequ
 	MonoSeqPointInfo *info;
 	SeqPoint *sp = NULL;
 	MonoMethod *method = NULL;
+	MonoDebugMethodInfo *minfo;
+	gboolean step_to_catch = FALSE;
 
 	if (suspend_count == 0)
 		return ERR_NOT_SUSPENDED;
@@ -4042,9 +4088,37 @@ ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequ
 	g_assert (tls->has_context);
 	ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->ctx);
 
-	if (ss_req->size == STEP_SIZE_LINE) {
+	if (tls->has_catch_ctx) {
+		gboolean res;
+		StackFrameInfo frame;
+		MonoContext new_ctx;
+		MonoLMF *lmf = NULL;
+
+		/*
+		 * We are stopped at a throw site. Stepping should go to the catch site.
+		 */
+
+		/* Find the the jit info for the catch context */
+		res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, &frame);
+		g_assert (res);
+		g_assert (frame.type == FRAME_TYPE_MANAGED);
+
+		/*
+		 * Find the seq point corresponding to the landing site ip, which is the first seq
+		 * point after ip.
+		 */
+		sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
+		g_assert (sp);
+
+		method = frame.method;
+
+		step_to_catch = TRUE;
+		/* This make sure the seq point is not skipped by process_single_step () */
+		ss_req->last_sp = NULL;
+	}
+
+	if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
 		StackFrame *frame;
-		MonoDebugMethodInfo *minfo;
 
 		/* Compute the initial line info */
 		compute_frame_info (thread, tls);
@@ -4066,7 +4140,7 @@ ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequ
 		}
 	}
 
-	if (ss_req->depth == STEP_DEPTH_OVER) {
+	if (!step_to_catch && ss_req->depth == STEP_DEPTH_OVER) {
 		StackFrame *frame;
 
 		compute_frame_info (thread, tls);
@@ -4074,7 +4148,7 @@ ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequ
 		g_assert (tls->frame_count);
 		frame = tls->frames [0];
 
-		if (frame->il_offset != -1) {
+		if (!method && frame->il_offset != -1) {
 			/* FIXME: Sort the table and use a binary search */
 			sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
 			g_assert (sp);
@@ -4082,7 +4156,7 @@ ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequ
 		}
 	}
 
-	ss_start (ss_req, method, sp, info, NULL, tls);
+	ss_start (ss_req, method, sp, info, NULL, tls, step_to_catch);
 
 	return 0;
 }
@@ -4107,10 +4181,10 @@ mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx
 	GSList *events;
 	MonoJitInfo *ji;
 	EventInfo ei;
+	DebuggerTlsData *tls = NULL;
 
 	if (thread_to_tls != NULL) {
 		MonoInternalThread *thread = mono_thread_internal_current ();
-		DebuggerTlsData *tls;
 
 		mono_loader_lock ();
 		tls = mono_g_hash_table_lookup (thread_to_tls, thread);
@@ -4118,6 +4192,8 @@ mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx
 
 		if (tls && tls->abort_requested)
 			return;
+		if (tls && tls->disable_breakpoints)
+			return;
 	}
 
 	memset (&ei, 0, sizeof (EventInfo));
@@ -4174,7 +4250,15 @@ mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx
 	events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
 	mono_loader_unlock ();
 
+	if (tls && catch_ctx) {
+		tls->catch_ctx = *catch_ctx;
+		tls->has_catch_ctx = TRUE;
+	}
+
 	process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
+
+	if (tls)
+		tls->has_catch_ctx = FALSE;
 }
 
 /*
@@ -6256,7 +6340,7 @@ thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
 		buffer_add_int (buf, tls->frame_count);
 		for (i = 0; i < tls->frame_count; ++i) {
 			buffer_add_int (buf, tls->frames [i]->id);
-			buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->method);
+			buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
 			buffer_add_int (buf, tls->frames [i]->il_offset);
 			/*
 			 * Instead of passing the frame type directly to the client, we associate
@@ -6336,12 +6420,12 @@ frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
 	}
 	jit = frame->jit;
 
-	sig = mono_method_signature (frame->method);
+	sig = mono_method_signature (frame->actual_method);
 
 	switch (command) {
 	case CMD_STACK_FRAME_GET_VALUES: {
 		len = decode_int (p, &p, end);
-		header = mono_method_get_header (frame->method);
+		header = mono_method_get_header (frame->actual_method);
 
 		for (i = 0; i < len; ++i) {
 			pos = decode_int (p, &p, end);
@@ -6371,12 +6455,12 @@ frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
 				MonoObject *p = NULL;
 				buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
 			} else {
-				add_var (buf, &frame->method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
+				add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
 			}
 		} else {
 			if (!sig->hasthis) {
 				MonoObject *p = NULL;
-				buffer_add_value (buf, &frame->method->klass->byval_arg, &p, frame->domain);
+				buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
 			} else {
 				add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
 			}
@@ -6389,7 +6473,7 @@ frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
 		MonoDebugVarInfo *var;
 
 		len = decode_int (p, &p, end);
-		header = mono_method_get_header (frame->method);
+		header = mono_method_get_header (frame->actual_method);
 
 		for (i = 0; i < len; ++i) {
 			pos = decode_int (p, &p, end);
diff --git a/mono/mini/generics.cs b/mono/mini/generics.cs
index 5fce0b6..b7a3351 100644
--- a/mono/mini/generics.cs
+++ b/mono/mini/generics.cs
@@ -490,6 +490,11 @@ class Tests {
 		return l.Count;
 	}
 
+	public static int test_0_fullaot_comparer_t_2 () {
+		var l = new Dictionary <TimeSpan, int> ();
+		return l.Count;
+	}
+
 	static void enumerate<T> (IEnumerable<T> arr) {
 		foreach (var o in arr)
 			;
diff --git a/mono/mini/image-writer.c b/mono/mini/image-writer.c
index ff7e3d8..4a3cf02 100644
--- a/mono/mini/image-writer.c
+++ b/mono/mini/image-writer.c
@@ -113,7 +113,7 @@
 #define USE_ELF_RELA 1
 #endif
 
-#if defined(TARGET_X86) && !defined(TARGET_WIN32)
+#if defined(TARGET_X86) && !defined(TARGET_WIN32) && !defined(__APPLE__)
 #define USE_ELF_WRITER 1
 #endif
 
@@ -1576,7 +1576,7 @@ static void
 asm_writer_emit_global (MonoImageWriter *acfg, const char *name, gboolean func)
 {
 	asm_writer_emit_unset_mode (acfg);
-#if  (defined(__ppc__) && defined(TARGET_ASM_APPLE)) || (defined(HOST_WIN32) && !defined(MONO_CROSS_COMPILE))
+#if  ((defined(__ppc__) || defined(TARGET_X86)) && defined(TARGET_ASM_APPLE)) || (defined(HOST_WIN32) && !defined(MONO_CROSS_COMPILE))
     // mach-o always uses a '_' prefix.
 	fprintf (acfg->fp, "\t.globl _%s\n", name);
 #else
@@ -1612,7 +1612,13 @@ static void
 asm_writer_emit_label (MonoImageWriter *acfg, const char *name)
 {
 	asm_writer_emit_unset_mode (acfg);
-#if defined(HOST_WIN32) && (defined(TARGET_X86) || defined(TARGET_AMD64))
+#if (defined(TARGET_X86) && defined(TARGET_ASM_APPLE))
+        name = get_label(name);
+        fprintf (acfg->fp, "%s:\n", name);
+        if (name[0] != 'L')
+            fprintf (acfg->fp, "_%s:\n", name);
+
+#elif (defined(HOST_WIN32) && (defined(TARGET_X86) || defined(TARGET_AMD64))) || (defined(TARGET_X86) && defined(TARGET_ASM_APPLE))
 	fprintf (acfg->fp, "_%s:\n", name);
 #if defined(HOST_WIN32)
 	/* Emit a normal label too */
diff --git a/mono/mini/method-to-ir.c b/mono/mini/method-to-ir.c
index 0d871d6..3a123a4 100644
--- a/mono/mini/method-to-ir.c
+++ b/mono/mini/method-to-ir.c
@@ -4689,7 +4689,7 @@ check_inline_caller_method_name_limit (MonoMethod *caller_method)
 
 static int
 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
-		guchar *ip, guint real_offset, GList *dont_inline, gboolean inline_allways)
+		guchar *ip, guint real_offset, GList *dont_inline, gboolean inline_always)
 {
 	MonoInst *ins, *rvar = NULL;
 	MonoMethodHeader *cheader;
@@ -4711,11 +4711,11 @@ inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig,
 	g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
 
 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
-	if ((! inline_allways) && ! check_inline_called_method_name_limit (cmethod))
+	if ((! inline_always) && ! check_inline_called_method_name_limit (cmethod))
 		return 0;
 #endif
 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
-	if ((! inline_allways) && ! check_inline_caller_method_name_limit (cfg->method))
+	if ((! inline_always) && ! check_inline_caller_method_name_limit (cfg->method))
 		return 0;
 #endif
 
@@ -4731,8 +4731,13 @@ inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig,
 	cheader = mono_method_get_header (cmethod);
 
 	if (cheader == NULL || mono_loader_get_last_error ()) {
+		MonoLoaderError *error = mono_loader_get_last_error ();
+
 		if (cheader)
 			mono_metadata_free_mh (cheader);
+		if (inline_always && error)
+			cfg->exception_type = error->exception_type;
+
 		mono_loader_clear_error ();
 		return 0;
 	}
@@ -4791,7 +4796,7 @@ inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig,
 	cfg->ret_var_set = prev_ret_var_set;
 	cfg->inline_depth --;
 
-	if ((costs >= 0 && costs < 60) || inline_allways) {
+	if ((costs >= 0 && costs < 60) || inline_always) {
 		if (cfg->verbose_level > 2)
 			printf ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
 		
@@ -5512,6 +5517,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 			MonoExceptionClause *clause = &header->clauses [i];
 			GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
 			try_bb->real_offset = clause->try_offset;
+			try_bb->try_start = TRUE;
+			try_bb->region = ((i + 1) << 8) | clause->flags;
 			GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
 			tblock->real_offset = clause->handler_offset;
 			tblock->flags |= BB_EXCEPTION_HANDLER;
@@ -5524,6 +5531,10 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 			if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
 			    clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
 			    clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
+				if (seq_points) {
+					NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
+					MONO_ADD_INS (tblock, ins);
+				}
 				MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
 				MONO_ADD_INS (tblock, ins);
 
@@ -6631,6 +6642,33 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 				break;
 			}
 
+			/*
+			 * Implement a workaround for the inherent races involved in locking:
+			 * Monitor.Enter ()
+			 * try {
+			 * } finally {
+			 *    Monitor.Exit ()
+			 * }
+			 * If a thread abort happens between the call to Monitor.Enter () and the start of the
+			 * try block, the Exit () won't be executed, see:
+			 * http://www.bluebytesoftware.com/blog/2007/01/30/MonitorEnterThreadAbortsAndOrphanedLocks.aspx
+			 * To work around this, we extend such try blocks to include the last x bytes
+			 * of the Monitor.Enter () call.
+			 */
+			if (cmethod && cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
+				MonoBasicBlock *tbb;
+
+				GET_BBLOCK (cfg, tbb, ip + 5);
+				/* 
+				 * Only extend try blocks with a finally, to avoid catching exceptions thrown
+				 * from Monitor.Enter like ArgumentNullException.
+				 */
+				if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
+					/* Mark this bblock as needing to be extended */
+					tbb->extend_try_block = TRUE;
+				}
+			}
+
 			/* Conversion to a JIT intrinsic */
 			if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_method (cfg, cmethod, fsig, sp))) {
 				bblock = cfg->cbb;
@@ -6653,17 +6691,17 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 			    mono_method_check_inlining (cfg, cmethod) &&
 				 !g_list_find (dont_inline, cmethod)) {
 				int costs;
-				gboolean allways = FALSE;
+				gboolean always = FALSE;
 
 				if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
 					(cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
 					/* Prevent inlining of methods that call wrappers */
 					INLINE_FAILURE;
 					cmethod = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc, FALSE);
-					allways = TRUE;
+					always = TRUE;
 				}
 
- 				if ((costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, dont_inline, allways))) {
+ 				if ((costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, dont_inline, always))) {
 					ip += 5;
 					cfg->real_offset += 5;
 					bblock = cfg->cbb;
@@ -7850,7 +7888,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 				iargs [0] = sp [0];
 				
 				costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), 
-							   iargs, ip, cfg->real_offset, dont_inline, TRUE);			
+							   iargs, ip, cfg->real_offset, dont_inline, TRUE);
+				CHECK_CFG_EXCEPTION;
 				g_assert (costs > 0);
 				
 				ip += 5;
@@ -7904,7 +7943,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 				iargs [0] = sp [0];
 
 				costs = inline_method (cfg, mono_isinst, mono_method_signature (mono_isinst), 
-							   iargs, ip, cfg->real_offset, dont_inline, TRUE);			
+							   iargs, ip, cfg->real_offset, dont_inline, TRUE);
+				CHECK_CFG_EXCEPTION;
 				g_assert (costs > 0);
 				
 				ip += 5;
@@ -7949,7 +7989,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 
 					costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), 
 										   iargs, ip, cfg->real_offset, dont_inline, TRUE);
-			
+					CHECK_CFG_EXCEPTION;
 					g_assert (costs > 0);
 				
 					ip += 5;
@@ -8180,6 +8220,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 					if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
 						costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), 
 								       iargs, ip, cfg->real_offset, dont_inline, TRUE);
+						CHECK_CFG_EXCEPTION;
 						g_assert (costs > 0);
 						      
 						cfg->real_offset += 5;
@@ -8226,6 +8267,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 				if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
 					costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), 
 										   iargs, ip, cfg->real_offset, dont_inline, TRUE);
+					CHECK_CFG_EXCEPTION;
 					bblock = cfg->cbb;
 					g_assert (costs > 0);
 						      
@@ -9194,7 +9236,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 					NEW_BBLOCK (cfg, dont_throw);
 
 					/*
-					 * Currently, we allways rethrow the abort exception, despite the 
+					 * Currently, we always rethrow the abort exception, despite the 
 					 * fact that this is not correct. See thread6.cs for an example. 
 					 * But propagating the abort exception is more important than 
 					 * getting the sematics right.
diff --git a/mono/mini/mini-amd64.c b/mono/mini/mini-amd64.c
index 2dcd2d0..7bbcc34 100644
--- a/mono/mini/mini-amd64.c
+++ b/mono/mini/mini-amd64.c
@@ -973,8 +973,6 @@ mono_arch_cpu_optimizazions (guint32 *exclude_mask)
 	int eax, ebx, ecx, edx;
 	guint32 opts = 0;
 
-	/* FIXME: AMD64 */
-
 	*exclude_mask = 0;
 	/* Feature Flags function, flags returned in EDX. */
 	if (cpuid (1, &eax, &ebx, &ecx, &edx)) {
@@ -4848,7 +4846,9 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
 			break;
 		}
 		case OP_MEMORY_BARRIER: {
-			/* Not needed on amd64 */
+			/* http://blogs.sun.com/dave/resource/NHM-Pipeline-Blog-V2.txt */
+			x86_prefix (code, X86_LOCK_PREFIX);
+			amd64_alu_membase_imm (code, X86_ADD, AMD64_RSP, 0, 0);
 			break;
 		}
 		case OP_ATOMIC_ADD_I4:
diff --git a/mono/mini/mini-exceptions.c b/mono/mini/mini-exceptions.c
index a753c58..fd16f3a 100644
--- a/mono/mini/mini-exceptions.c
+++ b/mono/mini/mini-exceptions.c
@@ -767,6 +767,19 @@ mono_jit_walk_stack_from_ctx_in_thread (MonoJitStackWalk func, MonoDomain *domai
 
 		frame.il_offset = il_offset;
 
+		if (frame.ji) {
+			if (frame.ji->has_generic_jit_info && frame.type == FRAME_TYPE_MANAGED_TO_NATIVE) {
+				/*
+				 * FIXME: These frames show up twice, and ctx could refer to native code.
+				 */
+				ctx = new_ctx;
+				continue;
+			}
+			frame.actual_method = get_method_from_stack_frame (frame.ji, get_generic_info_from_stack_frame (frame.ji, &ctx));
+		} else {
+			frame.actual_method = frame.method;
+		}
+
 		if (func (&frame, &ctx, user_data))
 			return;
 		
@@ -1370,6 +1383,8 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
 								}
 								g_list_free (trace_ips);
 
+								/* mono_debugger_agent_handle_exception () needs this */
+								MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
 								return TRUE;
 							}
 							/*
diff --git a/mono/mini/mini-llvm.c b/mono/mini/mini-llvm.c
index cb068ea..5040275 100644
--- a/mono/mini/mini-llvm.c
+++ b/mono/mini/mini-llvm.c
@@ -2768,7 +2768,7 @@ process_bb (EmitContext *ctx, MonoBasicBlock *bb)
 		case OP_LOCALLOC: {
 			LLVMValueRef v, size;
 				
-			size = LLVMBuildAnd (builder, LLVMBuildAdd (builder, lhs, LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT - 1, FALSE), ""), LLVMConstInt (LLVMInt32Type (), ~ (MONO_ARCH_FRAME_ALIGNMENT - 1), FALSE), "");
+			size = LLVMBuildAnd (builder, LLVMBuildAdd (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT - 1, FALSE), ""), LLVMConstInt (LLVMInt32Type (), ~ (MONO_ARCH_FRAME_ALIGNMENT - 1), FALSE), "");
 
 			v = mono_llvm_build_alloca (builder, LLVMInt8Type (), size, MONO_ARCH_FRAME_ALIGNMENT, "");
 
diff --git a/mono/mini/mini-llvm.h b/mono/mini/mini-llvm.h
index 6b4f81d..ce97367 100644
--- a/mono/mini/mini-llvm.h
+++ b/mono/mini/mini-llvm.h
@@ -48,12 +48,14 @@ mono_llvm_emit_call (MonoCompile *cfg, MonoCallInst *call)
 void
 mono_llvm_create_aot_module (const char *got_symbol)
 {
+	g_assert (mono_llvm_create_aot_module_fptr);
 	mono_llvm_create_aot_module_fptr (got_symbol);
 }
 
 void
 mono_llvm_emit_aot_module (const char *filename, int got_size)
 {
+	g_assert (mono_llvm_emit_aot_module_fptr);
 	mono_llvm_emit_aot_module_fptr (filename, got_size);
 }
 
diff --git a/mono/mini/mini-sparc.c b/mono/mini/mini-sparc.c
index 8806120..e3c17ef 100644
--- a/mono/mini/mini-sparc.c
+++ b/mono/mini/mini-sparc.c
@@ -2316,8 +2316,12 @@ mono_arch_build_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckI
 				item->jmp_code = (guint8*)code;
 				sparc_branch (code, 0, sparc_bne, 0);
 				sparc_nop (code);
-				sparc_set (code, ((guint32)(&(vtable->vtable [item->value.vtable_slot]))), sparc_g5);
-				sparc_ld (code, sparc_g5, 0, sparc_g5);
+				if (item->has_target_code) {
+					sparc_set (code, item->value.target_code, sparc_f5);
+				} else {
+					sparc_set (code, ((guint32)(&(vtable->vtable [item->value.vtable_slot]))), sparc_g5);
+					sparc_ld (code, sparc_g5, 0, sparc_g5);
+				}
 				sparc_jmpl (code, sparc_g5, sparc_g0, sparc_g0);
 				sparc_nop (code);
 
diff --git a/mono/mini/mini-x86.c b/mono/mini/mini-x86.c
index a7abb88..5cba2a9 100644
--- a/mono/mini/mini-x86.c
+++ b/mono/mini/mini-x86.c
@@ -3887,7 +3887,9 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
 			break;
 		}
 		case OP_MEMORY_BARRIER: {
-			/* Not needed on x86 */
+			/* http://blogs.sun.com/dave/resource/NHM-Pipeline-Blog-V2.txt */
+			x86_prefix (code, X86_LOCK_PREFIX);
+			x86_alu_membase_imm (code, X86_ADD, X86_ESP, 0, 0);
 			break;
 		}
 		case OP_ATOMIC_ADD_I4: {
diff --git a/mono/mini/mini-x86.h b/mono/mini/mini-x86.h
index 5406278..d2e2fab 100644
--- a/mono/mini/mini-x86.h
+++ b/mono/mini/mini-x86.h
@@ -265,7 +265,9 @@ typedef struct {
 #define MONO_ARCH_HAVE_IS_INT_OVERFLOW 1
 #define MONO_ARCH_HAVE_INVALIDATE_METHOD 1
 #define MONO_ARCH_NEED_GOT_VAR 1
+#if !defined(__APPLE__)
 #define MONO_ARCH_ENABLE_MONO_LMF_VAR 1
+#endif
 #define MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE 1
 #define MONO_ARCH_HAVE_ATOMIC_ADD 1
 #define MONO_ARCH_HAVE_ATOMIC_EXCHANGE 1
@@ -283,7 +285,9 @@ typedef struct {
 #define MONO_ARCH_MONITOR_OBJECT_REG X86_EAX
 #endif
 #define MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE 1
+#if !defined (__APPLE__) || defined(__native_client_codegen__)
 #define MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES 1
+#endif
 #define MONO_ARCH_GOT_REG X86_EBX
 #define MONO_ARCH_HAVE_GET_TRAMPOLINES 1
 
@@ -295,9 +299,7 @@ typedef struct {
 
 #define MONO_ARCH_HAVE_DECOMPOSE_LONG_OPTS 1
 
-#if !defined(__APPLE__) || defined(__native_client_codegen__)
 #define MONO_ARCH_AOT_SUPPORTED 1
-#endif
 
 #if defined(__linux__) || defined(__sun)
 #define MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH 1
diff --git a/mono/mini/mini.c b/mono/mini/mini.c
index 0f3d634..4042684 100644
--- a/mono/mini/mini.c
+++ b/mono/mini/mini.c
@@ -69,6 +69,24 @@
 #include "mini-gc.h"
 #include "debugger-agent.h"
 
+#if defined(HAVE_KW_THREAD)
+#define MINI_FAST_TLS_SET(x,y) x = y
+#define MINI_FAST_TLS_GET(x) x
+#define MINI_FAST_TLS_INIT(x)
+#define MINI_FAST_TLS_DECLARE(x) static __thread gpointer x MONO_TLS_FAST;
+#define MINI_HAVE_FAST_TLS
+#define MINI_THREAD_VAR_OFFSET(x,y) MONO_THREAD_VAR_OFFSET(x,y)
+#elif (defined(__APPLE__) && defined(__i386__))
+#define MINI_FAST_TLS_SET(x,y) pthread_setspecific(x, y)
+#define MINI_FAST_TLS_GET(x) pthread_getspecific(x)
+#define MINI_FAST_TLS_INIT(x) pthread_key_create(&x, NULL)
+#define MINI_FAST_TLS_DECLARE(x) static pthread_key_t x;
+#define MINI_HAVE_FAST_TLS
+#define MINI_THREAD_VAR_OFFSET(x,y) y = (gint32) x
+#else
+#define MINI_THREAD_VAR_OFFSET(x,y) MONO_THREAD_VAR_OFFSET(x,y)
+#endif
+
 static gpointer mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt, MonoException **ex);
 
 /* helper methods signature */
@@ -91,8 +109,8 @@ static gboolean default_opt_set = FALSE;
 
 guint32 mono_jit_tls_id = -1;
 
-#ifdef HAVE_KW_THREAD
-static __thread gpointer mono_jit_tls MONO_TLS_FAST;
+#ifdef MINI_HAVE_FAST_TLS
+MINI_FAST_TLS_DECLARE(mono_jit_tls);
 #endif
 
 MonoTraceSpec *mono_jit_trace_calls = NULL;
@@ -2304,14 +2322,14 @@ mono_destroy_compile (MonoCompile *cfg)
 	g_free (cfg);
 }
 
-#ifdef HAVE_KW_THREAD
-static __thread gpointer mono_lmf_addr MONO_TLS_FAST;
+#ifdef MINI_HAVE_FAST_TLS
+MINI_FAST_TLS_DECLARE(mono_lmf_addr);
 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
 /* 
  * When this is defined, the current lmf is stored in this tls variable instead of in 
  * jit_tls->lmf.
  */
-static __thread gpointer mono_lmf MONO_TLS_FAST;
+MINI_FAST_TLS_DECLARE(mono_lmf);
 #endif
 #endif
 
@@ -2324,9 +2342,9 @@ mono_get_jit_tls_key (void)
 gint32
 mono_get_jit_tls_offset (void)
 {
-#ifdef HAVE_KW_THREAD
+#ifdef MINI_HAVE_FAST_TLS
 	int offset;
-	MONO_THREAD_VAR_OFFSET (mono_jit_tls, offset);
+	MINI_THREAD_VAR_OFFSET (mono_jit_tls, offset);
 	return offset;
 #else
 	return -1;
@@ -2336,9 +2354,9 @@ mono_get_jit_tls_offset (void)
 gint32
 mono_get_lmf_tls_offset (void)
 {
-#if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
+#if defined(MINI_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
 	int offset;
-	MONO_THREAD_VAR_OFFSET(mono_lmf,offset);
+	MINI_THREAD_VAR_OFFSET(mono_lmf,offset);
 	return offset;
 #else
 	return -1;
@@ -2349,15 +2367,15 @@ gint32
 mono_get_lmf_addr_tls_offset (void)
 {
 	int offset;
-	MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
+	MINI_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
 	return offset;
 }
 
 MonoLMF *
 mono_get_lmf (void)
 {
-#if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
-	return mono_lmf;
+#if defined(MINI_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
+	return MINI_FAST_TLS_GET (mono_lmf);
 #else
 	MonoJitTlsData *jit_tls;
 
@@ -2372,8 +2390,8 @@ mono_get_lmf (void)
 MonoLMF **
 mono_get_lmf_addr (void)
 {
-#ifdef HAVE_KW_THREAD
-	return mono_lmf_addr;
+#ifdef MINI_HAVE_FAST_TLS
+	return MINI_FAST_TLS_GET (mono_lmf_addr);
 #else
 	MonoJitTlsData *jit_tls;
 
@@ -2401,8 +2419,8 @@ mono_get_lmf_addr (void)
 void
 mono_set_lmf (MonoLMF *lmf)
 {
-#if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
-	mono_lmf = lmf;
+#if defined(MINI_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
+	MINI_FAST_TLS_SET (mono_lmf, lmf);
 #endif
 
 	(*mono_get_lmf_addr ()) = lmf;
@@ -2419,8 +2437,8 @@ mono_jit_thread_attach (MonoDomain *domain)
 		 */
 		domain = mono_get_root_domain ();
 
-#ifdef HAVE_KW_THREAD
-	if (!mono_lmf_addr) {
+#ifdef MINI_HAVE_FAST_TLS
+	if (!MINI_FAST_TLS_GET (mono_lmf_addr)) {
 		mono_thread_attach (domain);
 	}
 #else
@@ -2467,8 +2485,8 @@ setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
 
 	TlsSetValue (mono_jit_tls_id, jit_tls);
 
-#ifdef HAVE_KW_THREAD
-	mono_jit_tls = jit_tls;
+#ifdef MINI_HAVE_FAST_TLS
+	MINI_FAST_TLS_SET (mono_jit_tls, jit_tls);
 #endif
 
 	jit_tls->abort_func = abort_func;
@@ -2483,13 +2501,13 @@ setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
 
 	jit_tls->first_lmf = lmf;
 
-#if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
+#if defined(MINI_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
 	/* jit_tls->lmf is unused */
-	mono_lmf = lmf;
-	mono_lmf_addr = &mono_lmf;
+	MINI_FAST_TLS_SET (mono_lmf, lmf);
+	MINI_FAST_TLS_SET (mono_lmf_addr, &mono_lmf);
 #else
-#if defined(HAVE_KW_THREAD)
-	mono_lmf_addr = &jit_tls->lmf;	
+#if defined(MINI_HAVE_FAST_TLS)
+	MINI_FAST_TLS_SET (mono_lmf_addr, &jit_tls->lmf);
 #endif
 
 	jit_tls->lmf = lmf;
@@ -2560,11 +2578,11 @@ mini_thread_cleanup (MonoThread *thread)
 		if (internal == mono_thread_internal_current ()) {
 			TlsSetValue (mono_jit_tls_id, NULL);
 
-#ifdef HAVE_KW_THREAD
-			mono_jit_tls = NULL;
-			mono_lmf_addr = NULL;
+#ifdef MINI_HAVE_FAST_TLS
+			MINI_FAST_TLS_SET (mono_jit_tls, NULL);
+			MINI_FAST_TLS_SET (mono_lmf_addr, NULL);
 #if defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
-			mono_lmf = NULL;
+			MINI_FAST_TLS_SET (mono_lmf, NULL);
 #endif
 #endif		
 		}
@@ -3671,8 +3689,16 @@ create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
 
 			tblock = cfg->cil_offset_to_bb [ec->try_offset];
 			g_assert (tblock);
-			ei->try_start = cfg->native_code + tblock->native_offset;
 			g_assert (tblock->native_offset);
+			ei->try_start = cfg->native_code + tblock->native_offset;
+			if (tblock->extend_try_block) {
+				/*
+				 * Extend the try block backwards to include parts of the previous call
+				 * instruction.
+				 * FIXME: This is arch specific.
+				 */
+				ei->try_start = (guint8*)ei->try_start - 1;
+			}
 			tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
 			g_assert (tblock);
 			if (!tblock->native_offset) {
@@ -5017,11 +5043,16 @@ mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt, MonoException
 		/* We can't use a domain specific method in another domain */
 		if (! ((domain != target_domain) && !info->domain_neutral)) {
 			MonoVTable *vtable;
+			MonoException *tmpEx;
 
 			mono_jit_stats.methods_lookups++;
 			vtable = mono_class_vtable (domain, method->klass);
 			g_assert (vtable);
-			mono_runtime_class_init (vtable);
+			tmpEx = mono_runtime_class_init_full (vtable, ex == NULL);
+			if (tmpEx) {
+				*ex = tmpEx;
+				return NULL;
+			}
 			return mono_create_ftnptr (target_domain, info->code_start);
 		}
 	}
@@ -5689,8 +5720,8 @@ mini_get_addr_from_ftnptr (gpointer descr)
 static void
 register_jit_stats (void)
 {
-	mono_counters_register ("Compiled methods", MONO_COUNTER_JIT | MONO_COUNTER_LONG, &mono_jit_stats.methods_compiled);
-	mono_counters_register ("Methods from AOT", MONO_COUNTER_JIT | MONO_COUNTER_LONG, &mono_jit_stats.methods_aot);
+	mono_counters_register ("Compiled methods", MONO_COUNTER_JIT | MONO_COUNTER_WORD, &mono_jit_stats.methods_compiled);
+	mono_counters_register ("Methods from AOT", MONO_COUNTER_JIT | MONO_COUNTER_WORD, &mono_jit_stats.methods_aot);
 	mono_counters_register ("Methods JITted using LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_llvm);	
 	mono_counters_register ("Methods JITted using mono JIT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_without_llvm);
 }
@@ -5803,6 +5834,14 @@ mini_init (const char *filename, const char *runtime_version)
 		mini_debugger_init ();
 #endif
 
+#ifdef MINI_HAVE_FAST_TLS
+	MINI_FAST_TLS_INIT (mono_jit_tls);
+	MINI_FAST_TLS_INIT (mono_lmf_addr);
+#ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
+	MINI_FAST_TLS_INIT (mono_lmf);
+#endif
+#endif
+
 #ifdef MONO_ARCH_HAVE_TLS_GET
 	mono_runtime_set_has_tls_get (MONO_ARCH_HAVE_TLS_GET);
 #else
diff --git a/mono/mini/mini.h b/mono/mini/mini.h
index c9f86b4..c9e9d5c 100644
--- a/mono/mini/mini.h
+++ b/mono/mini/mini.h
@@ -230,6 +230,10 @@ typedef struct {
 	 * to native code, or the method which was JITted.
 	 */
 	MonoMethod *method;
+	/*
+	 * If ji->method is a gshared method, this is the actual method instance.
+	 */
+	MonoMethod *actual_method;
 	/* The domain containing the code executed by this frame */
 	MonoDomain *domain;
 	gboolean managed;
@@ -523,6 +527,14 @@ struct MonoBasicBlock {
 	guint has_jump_table : 1;
 	/* Whenever this bblock contains an OP_CALL_HANDLER instruction */
 	guint has_call_handler : 1;
+	/* Whenever this bblock starts a try block */
+	guint try_start : 1;
+	/*
+	 * If this is set, extend the try range started by this bblock by an arch specific
+	 * number of bytes to encompass the end of the previous bblock (e.g. a Monitor.Enter
+	 * call).
+	 */
+	guint extend_try_block : 1;
 	
 	/* use for liveness analysis */
 	MonoBitSet *gen_set;
@@ -554,7 +566,7 @@ struct MonoBasicBlock {
 	 *        | clause-flags |   MONO_REGION  | clause-index 
 	 *
 	 */
-        guint region;
+	guint region;
 
 	/* The current symbolic register number, used in local register allocation. */
 	guint32 max_vreg;
@@ -988,6 +1000,8 @@ enum {
 
 #define MONO_BBLOCK_IS_IN_REGION(bblock, regtype) (((bblock)->region & (0xf << 4)) == (regtype))
 
+#define MONO_REGION_FLAGS(region) ((region) & 0x7)
+
 #define get_vreg_to_inst(cfg, vreg) ((vreg) < (cfg)->vreg_to_inst_len ? (cfg)->vreg_to_inst [(vreg)] : NULL)
 
 #define vreg_is_volatile(cfg, vreg) (G_UNLIKELY (get_vreg_to_inst ((cfg), (vreg)) && (get_vreg_to_inst ((cfg), (vreg))->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))))
diff --git a/mono/mini/tramp-sparc.c b/mono/mini/tramp-sparc.c
index fa469c9..6fbee01 100644
--- a/mono/mini/tramp-sparc.c
+++ b/mono/mini/tramp-sparc.c
@@ -265,8 +265,6 @@ mono_arch_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_ty
 	if (code_len)
 		*code_len = (code - buf) * 4;
 
-	mono_jit_stats.method_trampolines++;
-
 	mono_arch_flush_icache ((guint8*)buf, (code - buf) * 4);
 
 	return buf;
diff --git a/mono/profiler/ChangeLog b/mono/profiler/ChangeLog
index 2a4e158..9b7b472 100644
--- a/mono/profiler/ChangeLog
+++ b/mono/profiler/ChangeLog
@@ -1,3 +1,7 @@
+2010-10-21  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix building the logging profiler.
+
 
 Tue Mar 16 11:20:14 CET 2010 Paolo Molaro <lupus at ximian.com>
 
diff --git a/mono/profiler/ChangeLog b/mono/profiler/ChangeLog.old
similarity index 100%
copy from mono/profiler/ChangeLog
copy to mono/profiler/ChangeLog.old
diff --git a/mono/profiler/Makefile.am b/mono/profiler/Makefile.am
index bf668bb..eca313b 100644
--- a/mono/profiler/Makefile.am
+++ b/mono/profiler/Makefile.am
@@ -23,6 +23,6 @@ libmono_profiler_cov_la_LIBADD = $(top_builddir)/mono/mini/libmono-$(API_VER).la
 libmono_profiler_aot_la_SOURCES = mono-profiler-aot.c
 libmono_profiler_aot_la_LIBADD = $(top_builddir)/mono/mini/libmono-$(API_VER).la
 libmono_profiler_logging_la_SOURCES = mono-profiler-logging.c
-libmono_profiler_logging_la_LIBADD = $(top_builddir)/mono/mini/libmono-$(API_VER).la
+libmono_profiler_logging_la_LIBADD = $(top_builddir)/mono/mini/libmono-$(API_VER).la $(GLIB_LIBS)
 libmono_profiler_iomap_la_SOURCES = mono-profiler-iomap.c
 libmono_profiler_iomap_la_LIBADD = $(top_builddir)/mono/mini/libmono-$(API_VER).la
diff --git a/mono/profiler/Makefile.in b/mono/profiler/Makefile.in
index 46de658..9297559 100644
--- a/mono/profiler/Makefile.in
+++ b/mono/profiler/Makefile.in
@@ -83,8 +83,10 @@ libmono_profiler_iomap_la_OBJECTS =  \
 @DISABLE_PROFILER_FALSE@@JIT_SUPPORTED_TRUE@@PLATFORM_LINUX_FALSE@	$(libdir)
 @DISABLE_PROFILER_FALSE@@JIT_SUPPORTED_TRUE@@PLATFORM_LINUX_TRUE at am_libmono_profiler_iomap_la_rpath = -rpath \
 @DISABLE_PROFILER_FALSE@@JIT_SUPPORTED_TRUE@@PLATFORM_LINUX_TRUE@	$(libdir)
+am__DEPENDENCIES_1 =
 libmono_profiler_logging_la_DEPENDENCIES =  \
-	$(top_builddir)/mono/mini/libmono-$(API_VER).la
+	$(top_builddir)/mono/mini/libmono-$(API_VER).la \
+	$(am__DEPENDENCIES_1)
 am_libmono_profiler_logging_la_OBJECTS = mono-profiler-logging.lo
 libmono_profiler_logging_la_OBJECTS =  \
 	$(am_libmono_profiler_logging_la_OBJECTS)
@@ -316,7 +318,7 @@ libmono_profiler_cov_la_LIBADD = $(top_builddir)/mono/mini/libmono-$(API_VER).la
 libmono_profiler_aot_la_SOURCES = mono-profiler-aot.c
 libmono_profiler_aot_la_LIBADD = $(top_builddir)/mono/mini/libmono-$(API_VER).la
 libmono_profiler_logging_la_SOURCES = mono-profiler-logging.c
-libmono_profiler_logging_la_LIBADD = $(top_builddir)/mono/mini/libmono-$(API_VER).la
+libmono_profiler_logging_la_LIBADD = $(top_builddir)/mono/mini/libmono-$(API_VER).la $(GLIB_LIBS)
 libmono_profiler_iomap_la_SOURCES = mono-profiler-iomap.c
 libmono_profiler_iomap_la_LIBADD = $(top_builddir)/mono/mini/libmono-$(API_VER).la
 all: all-am
diff --git a/mono/tests/ChangeLog b/mono/tests/ChangeLog
index 6be0ffa..dae7aa0 100644
--- a/mono/tests/ChangeLog
+++ b/mono/tests/ChangeLog
@@ -1,3 +1,9 @@
+2010-11-05  Zoltan Varga  <vargaz at gmail.com>
+
+	Enlarge try-finally blocks preceeded by a Monitor.Enter () call to
+	include the call itself, to avoid races inherent in such code.
+	Fixes #651546.
+
 2010-08-24  Rodrigo Kumpera  <kumpera at gmail.com>
 
 	Add regression test for 633291.
diff --git a/mono/tests/Makefile.am b/mono/tests/Makefile.am
index f98d4da..4ddc71d 100644
--- a/mono/tests/Makefile.am
+++ b/mono/tests/Makefile.am
@@ -369,7 +369,8 @@ BASE_TEST_CS_SRC=		\
 	bug-562150.cs	\
 	bug-575941.cs	\
 	bug-599469.cs	\
-	bug-389886-3.cs
+	bug-389886-3.cs \
+	monitor.cs
 
 TEST_CS_SRC_DIST=	\
 	$(BASE_TEST_CS_SRC)	\
diff --git a/mono/tests/Makefile.in b/mono/tests/Makefile.in
index d8d8eec..75f415c 100644
--- a/mono/tests/Makefile.in
+++ b/mono/tests/Makefile.in
@@ -631,7 +631,8 @@ BASE_TEST_CS_SRC = \
 	bug-562150.cs	\
 	bug-575941.cs	\
 	bug-599469.cs	\
-	bug-389886-3.cs
+	bug-389886-3.cs \
+	monitor.cs
 
 TEST_CS_SRC_DIST = \
 	$(BASE_TEST_CS_SRC)	\
diff --git a/mono/tests/monitor.cs b/mono/tests/monitor.cs
new file mode 100644
index 0000000..7b96860
--- /dev/null
+++ b/mono/tests/monitor.cs
@@ -0,0 +1,77 @@
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Threading;
+
+public class Tests  {
+	static void Main ()
+	{
+		TestDriver.RunTests (typeof (Tests));
+	}
+
+	// Check that try-catch clauses are not enlarged to encompass a Monitor.Enter
+	public static int test_0_enter_catch_clause () {
+		try {
+			Monitor.Enter (null);
+			try {
+				Console.WriteLine ();
+			} catch (Exception ex) {
+				return 1;
+			}
+		} catch (Exception ex) {
+			return 0;
+		}
+		return 1;
+	}
+
+	const int thread_count = 3;
+
+	// #651546
+	public static int test_0_enter_abort_race () {
+		AppDomain ad = AppDomain.CreateDomain ("foo");
+		Thread t = new Thread (StartAppDomain);
+		t.Start (ad);
+		Thread.Sleep (thread_count * 100 * 2);
+		// This will abort the threads created by StartAppDomain
+		AppDomain.Unload (ad);
+		return 0;
+	}
+	
+	static void StartAppDomain (object dummy)
+	{
+		((AppDomain) dummy).DoCallBack (Main2);
+	}
+
+	static void Main2 ()
+	{
+		Thread[] t = new Thread [thread_count];
+		for (int i = 0; i < t.Length; i++) {
+			t[i] = new Thread (LockMe);
+			t[i].Start (i);
+			Thread.Sleep (100); // this is just so that gdb's [New Thread ...] message are properly coupled with our "Thread # entered" messages
+		}
+		Thread.Sleep ((int) (thread_count * 100 * 1.5));
+	}
+
+	static object the_lock = new object ();
+
+	static void LockMe (object thread_id)
+	{
+		bool unlocked = false;
+		try {
+			Monitor.Enter (the_lock);
+			try {
+				Thread.Sleep (thread_count * 1000);
+			} finally {
+				unlocked = true;
+				Monitor.Exit (the_lock);
+			}
+		
+		} catch (Exception ex) {
+			if (!unlocked) {
+			}
+		} finally {
+		}
+	}
+}
diff --git a/mono/utils/ChangeLog b/mono/utils/ChangeLog
index 2b3d1cf..80f154c 100644
--- a/mono/utils/ChangeLog
+++ b/mono/utils/ChangeLog
@@ -1,3 +1,37 @@
+2010-10-01  Geoff Norton  <gnorton at novell.com>
+
+	Fix a crash when using the embedding api
+
+	error_msg is null when passed into this function from a few
+	places, so lets not do a null deref here.
+
+2010-09-13  Michael Hutchinson  <mhutchinson at novell.com>
+
+	[Embedding] Make mono-dl-fallback.h public-safe
+
+2010-09-11  Miguel de Icaza  <miguel at gnome.org>
+
+	Do not install sample header, add to EXTRA_DIST
+
+2010-09-10  Miguel de Icaza  <miguel at gnome.org>
+
+	[Embedded] Add new fallback API to allow hooking up to the
+	P/Invoke lookup system
+
+	This patch allows a developer to register a fallback for P/Invoke
+	when embedding Mono. Typically this is done when you statically
+	link all of your libraries in some embedded systems and you need
+	to dynamically resolve symbol names.
+
+	There is a *sample* API included (but not compiled into Mono
+	itself) called mono-embed.c that shows a layman use of the API. A
+	full implementation would mandate sorted tables, and would use a
+	bsearch or a hashtable instead of having linear searches.
+
+2010-10-13  Robert Nagy  <robert at bsd.hu>
+
+	merge from head
+
 2010-08-25  Robert Nagy  <robert at bsd.hu>
 
 	Make sgen compile on OpenBSD, by adding the missing stuff
diff --git a/mono/utils/Makefile.am b/mono/utils/Makefile.am
index 72e86e4..d9209c4 100644
--- a/mono/utils/Makefile.am
+++ b/mono/utils/Makefile.am
@@ -67,7 +67,6 @@ monoutils_sources = \
 	mono-codeman.h	\
 	mono-counters.h	\
 	mono-digest.h	\
-	mono-embed.h	\
 	mono-error.h	\
 	mono-math.h	\
 	mono-membar.h	\
@@ -97,9 +96,10 @@ endif
 libmonoutils_la_SOURCES = $(monoutils_sources) $(arch_sources)
 libmonoutilsincludedir = $(includedir)/mono-$(API_VER)/mono/utils
 
-libmonoutilsinclude_HEADERS = \
-	mono-logger.h	\
-	mono-error.h	\
-	mono-publib.h
+libmonoutilsinclude_HEADERS = 	\
+	mono-logger.h		\
+	mono-error.h		\
+	mono-publib.h		\
+	mono-dl-fallback.h
 
-EXTRA_DIST = ChangeLog
+EXTRA_DIST = ChangeLog mono-embed.h mono-embed.c
diff --git a/mono/utils/Makefile.in b/mono/utils/Makefile.in
index 1af34dd..9885c60 100644
--- a/mono/utils/Makefile.in
+++ b/mono/utils/Makefile.in
@@ -69,11 +69,11 @@ am__libmonoutils_la_SOURCES_DIST = mono-md5.c mono-sha1.c \
 	mono-value-hash.c freebsd-elf_common.h freebsd-elf32.h \
 	freebsd-elf64.h freebsd-dwarf.h dtrace.h gc_wrapper.h \
 	mono-error.c mono-error-internals.h monobitset.h \
-	mono-codeman.h mono-counters.h mono-digest.h mono-embed.h \
-	mono-error.h mono-math.h mono-membar.h mono-path.h mono-poll.h \
-	mono-uri.h mono-stdlib.h valgrind.h mach-support.c \
-	mach-support.h memcheck.h mach-support-x86.c \
-	mach-support-amd64.c mach-support-arm.c
+	mono-codeman.h mono-counters.h mono-digest.h mono-error.h \
+	mono-math.h mono-membar.h mono-path.h mono-poll.h mono-uri.h \
+	mono-stdlib.h valgrind.h mach-support.c mach-support.h \
+	memcheck.h mach-support-x86.c mach-support-amd64.c \
+	mach-support-arm.c
 am__objects_1 = mono-md5.lo mono-sha1.lo mono-logger.lo \
 	mono-codeman.lo dlmalloc.lo mono-counters.lo mono-dl.lo \
 	mono-internal-hash.lo mono-io-portability.lo monobitset.lo \
@@ -363,7 +363,6 @@ monoutils_sources = \
 	mono-codeman.h	\
 	mono-counters.h	\
 	mono-digest.h	\
-	mono-embed.h	\
 	mono-error.h	\
 	mono-math.h	\
 	mono-membar.h	\
@@ -380,11 +379,12 @@ arch_sources = $(am__append_1) $(am__append_2) $(am__append_3)
 libmonoutils_la_SOURCES = $(monoutils_sources) $(arch_sources)
 libmonoutilsincludedir = $(includedir)/mono-$(API_VER)/mono/utils
 libmonoutilsinclude_HEADERS = \
-	mono-logger.h	\
-	mono-error.h	\
-	mono-publib.h
+	mono-logger.h		\
+	mono-error.h		\
+	mono-publib.h		\
+	mono-dl-fallback.h
 
-EXTRA_DIST = ChangeLog
+EXTRA_DIST = ChangeLog mono-embed.h mono-embed.c
 all: $(BUILT_SOURCES)
 	$(MAKE) $(AM_MAKEFLAGS) all-am
 
diff --git a/mono/utils/mono-dl-fallback.h b/mono/utils/mono-dl-fallback.h
new file mode 100644
index 0000000..06945ae
--- /dev/null
+++ b/mono/utils/mono-dl-fallback.h
@@ -0,0 +1,34 @@
+#ifndef __MONO_UTILS_DL_FALLBACK_H__
+#define __MONO_UTILS_DL_FALLBACK_H__
+
+#include <mono/utils/mono-publib.h>
+
+MONO_BEGIN_DECLS
+
+enum {
+	MONO_DL_LAZY  = 1,
+	MONO_DL_LOCAL = 2,
+	MONO_DL_MASK  = 3
+};
+
+/*
+ * This is the dynamic loader fallback API
+ */
+typedef struct MonoDlFallbackHandler MonoDlFallbackHandler;
+
+/*
+ * The "err" variable contents must be allocated using g_malloc or g_strdup
+ */
+typedef void* (*MonoDlFallbackLoad) (const char *name, int flags, char **err, void *user_data);
+typedef void* (*MonoDlFallbackSymbol) (void *handle, const char *name, char **err, void *user_data);
+typedef void* (*MonoDlFallbackClose) (void *handle, void *user_data);
+
+MonoDlFallbackHandler *mono_dl_fallback_register (MonoDlFallbackLoad load_func, MonoDlFallbackSymbol symbol_func,
+						  MonoDlFallbackClose close_func, void *user_data);
+
+void                   mono_dl_fallback_unregister (MonoDlFallbackHandler *handler);
+
+MONO_END_DECLS
+
+#endif /* __MONO_UTILS_DL_FALLBACK_H__ */
+
diff --git a/mono/utils/mono-dl.c b/mono/utils/mono-dl.c
index 6a233c7..2b9d518 100644
--- a/mono/utils/mono-dl.c
+++ b/mono/utils/mono-dl.c
@@ -29,11 +29,6 @@ static const char suffixes [][8] = {
 	".so",
 	".bundle"
 };
-#elif EMBEDDED_PINVOKE
-#define SOPREFIX ""
-static const char suffixes [][1] = {
-	""
-};
 #else
 #define SOPREFIX "lib"
 static const char suffixes [][4] = {
@@ -80,15 +75,6 @@ convert_flags (int flags)
 	return lflags;
 }
 
-#elif EMBEDDED_PINVOKE
-#define SO_HANDLE_TYPE void*
-void *LL_SO_OPEN   (const char *file, int flags);
-int   LL_SO_CLOSE  (void *handle);
-#define LL_SO_SYMBOL(module,symbol) _LL_SO_SYMBOL((module)->handle, (symbol))
-void *_LL_SO_SYMBOL (void *handle, const char *symbol);
-char *LL_SO_ERROR();
-#define LL_SO_TRFLAGS(flags)      0
-
 #else
 /* no dynamic loader supported */
 #define SO_HANDLE_TYPE void*
@@ -100,9 +86,21 @@ char *LL_SO_ERROR();
 
 #endif
 
+static GSList *fallback_handlers;
+
+struct MonoDlFallbackHandler {
+	MonoDlFallbackLoad load_func;
+	MonoDlFallbackSymbol symbol_func;
+	MonoDlFallbackClose close_func;
+	void *user_data;
+};
+	
 struct _MonoDl {
 	SO_HANDLE_TYPE handle;
 	int main_module;
+
+	/* If not NULL, use the methods in MonoDlFallbackHandler instead of the LL_* methods */
+	MonoDlFallbackHandler *dl_fallback;
 };
 
 #ifdef TARGET_WIN32
@@ -314,6 +312,7 @@ mono_dl_open (const char *name, int flags, char **error_msg)
 {
 	MonoDl *module;
 	void *lib;
+	MonoDlFallbackHandler *dl_fallback = NULL;
 	int lflags = LL_SO_TRFLAGS (flags);
 
 	if (error_msg)
@@ -328,6 +327,23 @@ mono_dl_open (const char *name, int flags, char **error_msg)
 	module->main_module = name == NULL? TRUE: FALSE;
 	lib = LL_SO_OPEN (name, lflags);
 	if (!lib) {
+		GSList *node;
+		for (node = fallback_handlers; node != NULL; node = node->next){
+			MonoDlFallbackHandler *handler = (MonoDlFallbackHandler *) node->data;
+			if (error_msg)
+				*error_msg = NULL;
+			
+			lib = handler->load_func (name, lflags, error_msg, handler->user_data);
+			if (error_msg && *error_msg != NULL)
+				g_free (*error_msg);
+			
+			if (lib != NULL){
+				dl_fallback = handler;
+				break;
+			}
+		}
+	}
+	if (!lib && !dl_fallback) {
 		char *lname;
 		char *llname;
 		const char *suff;
@@ -358,6 +374,7 @@ mono_dl_open (const char *name, int flags, char **error_msg)
 		}
 	}
 	module->handle = lib;
+	module->dl_fallback = dl_fallback;
 	return module;
 }
 
@@ -376,18 +393,24 @@ char*
 mono_dl_symbol (MonoDl *module, const char *name, void **symbol)
 {
 	void *sym;
+	char *err = NULL;
 
+	if (module->dl_fallback) {
+		sym = module->dl_fallback->symbol_func (module->handle, name, &err, module->dl_fallback->user_data);
+	} else {
 #if MONO_DL_NEED_USCORE
-	{
-		char *usname = malloc (strlen (name) + 2);
-		*usname = '_';
-		strcpy (usname + 1, name);
-		sym = LL_SO_SYMBOL (module, usname);
-		free (usname);
-	}
+		{
+			char *usname = malloc (strlen (name) + 2);
+			*usname = '_';
+			strcpy (usname + 1, name);
+			sym = LL_SO_SYMBOL (module, usname);
+			free (usname);
+		}
 #else
-	sym = LL_SO_SYMBOL (module, name);
+		sym = LL_SO_SYMBOL (module, name);
 #endif
+	}
+
 	if (sym) {
 		if (symbol)
 			*symbol = sym;
@@ -395,7 +418,7 @@ mono_dl_symbol (MonoDl *module, const char *name, void **symbol)
 	}
 	if (symbol)
 		*symbol = NULL;
-	return LL_SO_ERROR ();
+	return (module->dl_fallback != NULL) ? err :  LL_SO_ERROR ();
 }
 
 /**
@@ -409,7 +432,14 @@ mono_dl_symbol (MonoDl *module, const char *name, void **symbol)
 void
 mono_dl_close (MonoDl *module)
 {
-	LL_SO_CLOSE (module);
+	MonoDlFallbackHandler *dl_fallback = module->dl_fallback;
+	
+	if (dl_fallback){
+		if (dl_fallback->close_func != NULL)
+			dl_fallback->close_func (module->handle, dl_fallback->user_data);
+	} else
+		LL_SO_CLOSE (module);
+	
 	free (module);
 }
 
@@ -485,92 +515,34 @@ mono_dl_build_path (const char *directory, const char *name, void **iter)
 	return res;
 }
 
-#if EMBEDDED_PINVOKE
-static GHashTable *mono_dls;
-static char *ll_last_error = "";
-
-/**
- * mono_dl_register_library:
- * @name: Library name, this is the name used by the DllImport as the external library name
- * @mappings: the mappings to register for P/Invoke.
- *
- * This function is only available on builds that define
- * EMBEDDED_PINVOKE, this is available for systems that do not provide
- * a dynamic linker but still want to use DllImport to easily invoke
- * code from the managed side into the unmanaged world.
- *
- * Mappings is a pointer to the first element of an array of
- * MonoDlMapping values.  The list must be terminated with both 
- * the name and addr fields set to NULL.
- *
- * This is typically used like this:
- * MonoDlMapping sample_library_mappings [] = {
- *   { "CallMe", CallMe },
- *   { NULL, NULL }
- * };
- *
- * ...
- * main ()
- * {
- *    ...
- *    mono_dl_register_library ("sample", sample_library_mappings);
- *    ...
- * }
- *
- * Then the C# code can use this P/Invoke signature:
- *
- * 	[DllImport ("sample")]
- *	extern static int CallMe (int f);
- */
-void
-mono_dl_register_library (const char *name, MonoDlMapping *mappings)
+MonoDlFallbackHandler *
+mono_dl_fallback_register (MonoDlFallbackLoad load_func, MonoDlFallbackSymbol symbol_func, MonoDlFallbackClose close_func, void *user_data)
 {
-	if (mono_dls == NULL)
-		mono_dls = g_hash_table_new (g_str_hash, g_str_equal);
+	MonoDlFallbackHandler *handler;
 	
-	printf ("Inserting: 0x%p\n", mappings);
-	g_hash_table_insert (mono_dls, g_strdup (name), mappings);
-}
+	g_return_val_if_fail (load_func != NULL, NULL);
+	g_return_val_if_fail (symbol_func != NULL, NULL);
 
-void *
-LL_SO_OPEN (const char *file, int flag)
-{
-	void *mappings;
+	handler = g_new (MonoDlFallbackHandler, 1);
+	handler->load_func = load_func;
+	handler->symbol_func = symbol_func;
+	handler->close_func = close_func;
+	handler->user_data = user_data;
+
+	fallback_handlers = g_slist_prepend (fallback_handlers, handler);
 	
-	if (mono_dls == NULL){
-		ll_last_error = "Library not registered";
-		return NULL;
-	}
-		
-	mappings = g_hash_table_lookup (mono_dls, file);
-	ll_last_error = mappings == NULL ? "File not registered" : "";
-	return mappings;
+	return handler;
 }
 
-int LL_SO_CLOSE (void *handle)
+void
+mono_dl_fallback_unregister (MonoDlFallbackHandler *handler)
 {
-	// No-op
-	return 0;
-}
+	GSList *found;
 
-void *
-_LL_SO_SYMBOL (void *handle, const char *symbol)
-{
-	MonoDlMapping *mappings = (MonoDlMapping *) handle;
-	
-	for (;mappings->name; mappings++){
-		if (strcmp (symbol, mappings->name) == 0){
-			ll_last_error = "";
-			return mappings->addr;
-		}
-	}
-	ll_last_error = "Symbol not found";
-	return NULL;
-}
+	found = g_slist_find (fallback_handlers, handler);
+	if (found == NULL)
+		return;
 
-char *
-LL_SO_ERROR (void)
-{
-	return g_strdup (ll_last_error);
+	g_slist_remove (fallback_handlers, handler);
+	g_free (handler);
 }
-#endif
diff --git a/mono/utils/mono-dl.h b/mono/utils/mono-dl.h
index 87db045..819fcf6 100644
--- a/mono/utils/mono-dl.h
+++ b/mono/utils/mono-dl.h
@@ -2,12 +2,7 @@
 #define __MONO_UTILS_DL_H__
 
 #include "mono/utils/mono-compiler.h"
-
-enum {
-	MONO_DL_LAZY  = 1,
-	MONO_DL_LOCAL = 2,
-	MONO_DL_MASK  = 3
-};
+#include "mono/utils/mono-dl-fallback.h"
 
 typedef struct _MonoDl MonoDl;
 
@@ -17,6 +12,5 @@ void        mono_dl_close      (MonoDl *module) MONO_INTERNAL;
 
 char*       mono_dl_build_path (const char *directory, const char *name, void **iter) MONO_INTERNAL;
 
-
 #endif /* __MONO_UTILS_DL_H__ */
 
diff --git a/mono/utils/mono-embed.c b/mono/utils/mono-embed.c
new file mode 100644
index 0000000..3bb1ac6
--- /dev/null
+++ b/mono/utils/mono-embed.c
@@ -0,0 +1,97 @@
+/*
+ * mono-embed.c: Example code APIs to register a libraries using
+ * mono_dl_fallback_register.  Real implementations should instead
+ * use a binary search for implementing the dl_mapping_open and
+ * dl_mapping_symbol methods here.
+ *
+ * Author:
+ *    Mono Team (http://www.mono-project.com)
+ *
+ * Copyright 2001-2004 Ximian, Inc.
+ * Copyright 2004-2010 Novell, Inc.
+ *
+ */
+#include "config.h"
+#include "mono/utils/mono-dl.h"
+#include "mono/utils/mono-embed.h"
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <ctype.h>
+#include <string.h>
+#include <glib.h>
+
+static GHashTable *mono_dls;
+
+static void *
+dl_mapping_open (const char *file, int flags, char **err, void *user_data)
+{
+	MonoDlMapping *mappings;
+	
+	if (mono_dls == NULL){
+		*err = g_strdup ("Library not registered");
+		return NULL;
+	}
+		
+	mappings = (MonoDlMapping *) g_hash_table_lookup (mono_dls, file);
+	*err = g_strdup (mappings == NULL ? "File not registered" : "");
+	return mappings;
+}
+
+static void *
+dl_mapping_symbol (void *handle, const char *symbol, char **err, void *user_data)
+{
+	MonoDlMapping *mappings = (MonoDlMapping *) handle;
+	
+	for (;mappings->name; mappings++){
+		if (strcmp (symbol, mappings->name) == 0){
+			*err = g_strdup ("");
+			return mappings->addr;
+		}
+	}
+	*err = g_strdup ("Symbol not found");
+	return NULL;
+}
+
+/**
+ * mono_dl_register_library:
+u * @name: Library name, this is the name used by the DllImport as the external library name
+ * @mappings: the mappings to register for P/Invoke.
+ *
+ * The mappings registered using this function are used as fallbacks if the dynamic linker 
+ * fails, or if the platform doesn't have a dynamic linker.
+ *
+ * Mappings is a pointer to the first element of an array of
+ * MonoDlMapping values.  The list must be terminated with both 
+ * the name and addr fields set to NULL.
+ *
+ * This is typically used like this:
+ * MonoDlMapping sample_library_mappings [] = {
+ *   { "CallMe", CallMe },
+ *   { NULL, NULL }
+ * };
+ *
+ * ...
+ * main ()
+ * {
+ *    ...
+ *    mono_dl_register_library ("sample", sample_library_mappings);
+ *    ...
+ * }
+ *
+ * Then the C# code can use this P/Invoke signature:
+ *
+ * 	[DllImport ("sample")]
+ *	extern static int CallMe (int f);
+ */
+void
+mono_dl_register_library (const char *name, MonoDlMapping *mappings)
+{
+	if (mono_dls == NULL){
+		mono_dls = g_hash_table_new (g_str_hash, g_str_equal);
+		mono_dl_fallback_register (dl_mapping_open, dl_mapping_symbol, NULL, NULL);
+	}
+	
+	g_hash_table_insert (mono_dls, g_strdup (name), mappings);
+}
+
diff --git a/mono/utils/mono-embed.h b/mono/utils/mono-embed.h
index 826d471..2a8a697 100755
--- a/mono/utils/mono-embed.h
+++ b/mono/utils/mono-embed.h
@@ -1,10 +1,12 @@
 #ifndef __MONO_EMBED_H__
 #define __MONO_EMBED_H__
 
+#include <mono/utils/mono-publib.h>
+
+MONO_BEGIN_DECLS
+
 /* 
- * These are only used and available on embedded systems, the
- * EMBEDDED_PINVOKE configuration option must be set, and it
- * overrides any platform symbol loading functionality 
+ * This is a fallback for platform symbol loading functionality.
  */
 typedef struct {
 	const char *name;	
@@ -13,4 +15,6 @@ typedef struct {
 
 void mono_dl_register_library (const char *name, MonoDlMapping *mappings);
 
+MONO_END_DECLS
+
 #endif /* __MONO_EMBED_H__ */
diff --git a/mono/utils/mono-sigcontext.h b/mono/utils/mono-sigcontext.h
index 5c8a57a..a794a28 100644
--- a/mono/utils/mono-sigcontext.h
+++ b/mono/utils/mono-sigcontext.h
@@ -58,15 +58,15 @@
 	#define UCONTEXT_REG_EDI(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_EDI])
 	#define UCONTEXT_REG_EIP(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_EIP])
 #elif defined(__OpenBSD__)
-	#define UCONTEXT_REG_EAX(ctx) ((ctx)->sc_eax)
-	#define UCONTEXT_REG_EBX(ctx) ((ctx)->sc_ebx)
-	#define UCONTEXT_REG_ECX(ctx) ((ctx)->sc_ecx)
-	#define UCONTEXT_REG_EDX(ctx) ((ctx)->sc_edx)
-	#define UCONTEXT_REG_EBP(ctx) ((ctx)->sc_ebp)
-	#define UCONTEXT_REG_ESP(ctx) ((ctx)->sc_esp)
-	#define UCONTEXT_REG_ESI(ctx) ((ctx)->sc_esi)
-	#define UCONTEXT_REG_EDI(ctx) ((ctx)->sc_edi)
-	#define UCONTEXT_REG_EIP(ctx) ((ctx)->sc_eip)
+    #define UCONTEXT_REG_EAX(ctx) (((ucontext_t*)(ctx))->sc_eax)
+	#define UCONTEXT_REG_EBX(ctx) (((ucontext_t*)(ctx))->sc_ebx)
+	#define UCONTEXT_REG_ECX(ctx) (((ucontext_t*)(ctx))->sc_ecx)
+	#define UCONTEXT_REG_EDX(ctx) (((ucontext_t*)(ctx))->sc_edx)
+	#define UCONTEXT_REG_EBP(ctx) (((ucontext_t*)(ctx))->sc_ebp)
+	#define UCONTEXT_REG_ESP(ctx) (((ucontext_t*)(ctx))->sc_esp)
+	#define UCONTEXT_REG_ESI(ctx) (((ucontext_t*)(ctx))->sc_esi)
+	#define UCONTEXT_REG_EDI(ctx) (((ucontext_t*)(ctx))->sc_edi)
+	#define UCONTEXT_REG_EIP(ctx) (((ucontext_t*)(ctx))->sc_eip)
 #else
 	#define UCONTEXT_REG_EAX(ctx) (((ucontext_t*)(ctx))->uc_mcontext.gregs [REG_EAX])
 	#define UCONTEXT_REG_EBX(ctx) (((ucontext_t*)(ctx))->uc_mcontext.gregs [REG_EBX])
@@ -103,23 +103,23 @@
 #define UCONTEXT_GREGS(ctx)	((guint64*)&(((ucontext_t*)(ctx))->uc_mcontext))
 #elif defined(__OpenBSD__)
     /* OpenBSD/amd64 has no gregs array, ucontext_t == sigcontext */
-	#define UCONTEXT_REG_RAX(ctx) ((ctx)->sc_rax)
-	#define UCONTEXT_REG_RBX(ctx) ((ctx)->sc_rbx)
-	#define UCONTEXT_REG_RCX(ctx) ((ctx)->sc_rcx)
-	#define UCONTEXT_REG_RDX(ctx) ((ctx)->sc_rdx)
-	#define UCONTEXT_REG_RBP(ctx) ((ctx)->sc_rbp)
-	#define UCONTEXT_REG_RSP(ctx) ((ctx)->sc_rsp)
-	#define UCONTEXT_REG_RSI(ctx) ((ctx)->sc_rsi)
-	#define UCONTEXT_REG_RDI(ctx) ((ctx)->sc_rdi)
-	#define UCONTEXT_REG_RIP(ctx) ((ctx)->sc_rip)
-	#define UCONTEXT_REG_R8(ctx) ((ctx)->sc_r8)
-	#define UCONTEXT_REG_R9(ctx) ((ctx)->sc_r9)
-	#define UCONTEXT_REG_R10(ctx) ((ctx)->sc_r10)
-	#define UCONTEXT_REG_R11(ctx) ((ctx)->sc_r11)
-	#define UCONTEXT_REG_R12(ctx) ((ctx)->sc_r12)
-	#define UCONTEXT_REG_R13(ctx) ((ctx)->sc_r13)
-	#define UCONTEXT_REG_R14(ctx) ((ctx)->sc_r14)
-	#define UCONTEXT_REG_R15(ctx) ((ctx)->sc_r15)
+	#define UCONTEXT_REG_RAX(ctx) (((ucontext_t*)(ctx))->sc_rax)
+	#define UCONTEXT_REG_RBX(ctx) (((ucontext_t*)(ctx))->sc_rbx)
+	#define UCONTEXT_REG_RCX(ctx) (((ucontext_t*)(ctx))->sc_rcx)
+	#define UCONTEXT_REG_RDX(ctx) (((ucontext_t*)(ctx))->sc_rdx)
+	#define UCONTEXT_REG_RBP(ctx) (((ucontext_t*)(ctx))->sc_rbp)
+	#define UCONTEXT_REG_RSP(ctx) (((ucontext_t*)(ctx))->sc_rsp)
+	#define UCONTEXT_REG_RSI(ctx) (((ucontext_t*)(ctx))->sc_rsi)
+	#define UCONTEXT_REG_RDI(ctx) (((ucontext_t*)(ctx))->sc_rdi)
+	#define UCONTEXT_REG_RIP(ctx) (((ucontext_t*)(ctx))->sc_rip)
+	#define UCONTEXT_REG_R8(ctx) (((ucontext_t*)(ctx))->sc_r8)
+	#define UCONTEXT_REG_R9(ctx) (((ucontext_t*)(ctx))->sc_r9)
+	#define UCONTEXT_REG_R10(ctx) (((ucontext_t*)(ctx))->sc_r10)
+	#define UCONTEXT_REG_R11(ctx) (((ucontext_t*)(ctx))->sc_r11)
+	#define UCONTEXT_REG_R12(ctx) (((ucontext_t*)(ctx))->sc_r12)
+	#define UCONTEXT_REG_R13(ctx) (((ucontext_t*)(ctx))->sc_r13)
+	#define UCONTEXT_REG_R14(ctx) (((ucontext_t*)(ctx))->sc_r14)
+	#define UCONTEXT_REG_R15(ctx) (((ucontext_t*)(ctx))->sc_r15)
 #else
 #define UCONTEXT_GREGS(ctx)	((guint64*)&(((ucontext_t*)(ctx))->uc_mcontext.gregs))
 #endif
diff --git a/po/mcs/de.gmo b/po/mcs/de.gmo
index e3ab1bf..7b9efc9 100644
Binary files a/po/mcs/de.gmo and b/po/mcs/de.gmo differ
diff --git a/po/mcs/de.po b/po/mcs/de.po
index 42a2c90..9ae6fcf 100644
--- a/po/mcs/de.po
+++ b/po/mcs/de.po
@@ -2,7 +2,7 @@ msgid ""
 msgstr ""
 "Project-Id-Version: \n"
 "Report-Msgid-Bugs-To: http://www.mono-project.com/Bugs\n"
-"POT-Creation-Date: 2010-10-05 14:01-0600\n"
+"POT-Creation-Date: 2010-11-12 03:29-0700\n"
 "PO-Revision-Date: 2008-09-26 15:14+0100\n"
 "Last-Translator: Daniel Nauck <dna at mono-project.de>\n"
 "Language-Team: http://www.mono-project.de\n"
@@ -1837,95 +1837,95 @@ msgstr ""
 msgid "An array initializer of length `{0}' was expected"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5842
+#: mcs/mcs/expression.cs:5841
 msgid ""
 "Array initializers can only be used in a variable or field initializer. Try "
 "using a new expression instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5850
+#: mcs/mcs/expression.cs:5849
 msgid "A nested array initializer was expected"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5887
+#: mcs/mcs/expression.cs:5886
 msgid "An expression tree cannot contain a multidimensional array initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5971
+#: mcs/mcs/expression.cs:5972
 msgid ""
 "An implicitly typed local variable declarator cannot use an array initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5992
+#: mcs/mcs/expression.cs:5993
 msgid ""
 "Can only use array initializer expressions to assign to array types. Try "
 "using a new expression instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6393
+#: mcs/mcs/expression.cs:6394
 msgid ""
 "The type of an implicitly typed array cannot be inferred from the "
 "initializer. Try specifying array type explicitly"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6521
+#: mcs/mcs/expression.cs:6522
 msgid ""
 "Keyword `this' is not valid in a static property, static method, or static "
 "field initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6524
+#: mcs/mcs/expression.cs:6525
 msgid ""
 "Anonymous methods inside structs cannot access instance members of `this'. "
 "Consider copying `this' to a local variable outside the anonymous method and "
 "using the local instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6527
+#: mcs/mcs/expression.cs:6528
 msgid "Keyword `this' is not available in the current context"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6591
+#: mcs/mcs/expression.cs:6592
 msgid ""
 "The `this' object cannot be used before all of its fields are assigned to"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6621
+#: mcs/mcs/expression.cs:6622
 msgid "Cannot take the address of `this' because it is read-only"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6623
+#: mcs/mcs/expression.cs:6624
 msgid "Cannot pass `this' as a ref or out argument because it is read-only"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6625
+#: mcs/mcs/expression.cs:6626
 msgid "Cannot assign to `this' because it is read-only"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6678
+#: mcs/mcs/expression.cs:6679
 msgid "The __arglist construct is valid only within a variable argument method"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6728
+#: mcs/mcs/expression.cs:6729
 msgid "An expression tree cannot contain a method with variable arguments"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6804
+#: mcs/mcs/expression.cs:6805
 msgid ""
 "System.Void cannot be used from C#. Use typeof (void) to get the void type "
 "object"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6809
+#: mcs/mcs/expression.cs:6810
 msgid "The typeof operator cannot be used on the dynamic type"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6878
+#: mcs/mcs/expression.cs:6879
 #, csharp-format
 msgid "`{0}': an attribute argument cannot use type parameters"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7129
+#: mcs/mcs/expression.cs:7130
 #, csharp-format
 msgid ""
 "`{0}' does not have a predefined size, therefore sizeof can only be used in "
@@ -1933,12 +1933,12 @@ msgid ""
 "SizeOf)"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7185
+#: mcs/mcs/expression.cs:7186
 #, csharp-format
 msgid "Alias `{0}' not found"
 msgstr "Alias `{0}' wurde nicht gefunden"
 
-#: mcs/mcs/expression.cs:7196
+#: mcs/mcs/expression.cs:7197
 #, csharp-format
 msgid ""
 "Alias `{0}' cannot be used with '::' since it denotes a type. Consider "
@@ -1947,32 +1947,32 @@ msgstr ""
 "Der Alias `{0}' kann nicht mit '::' verwendet werden, da der Alias auf einen "
 "Typ verweist. Verwenden Sie '.' stattdessen."
 
-#: mcs/mcs/expression.cs:7212
+#: mcs/mcs/expression.cs:7213
 #, csharp-format
 msgid ""
 "A namespace alias qualifier `{0}' did not resolve to a namespace or a type"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7369
+#: mcs/mcs/expression.cs:7370
 msgid "Cannot perform member binding on `null' value"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7436
+#: mcs/mcs/expression.cs:7437
 #, csharp-format
 msgid "`{0}': cannot reference a type through an expression; try `{1}' instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7512
+#: mcs/mcs/expression.cs:7513
 #, csharp-format
 msgid "A nested type cannot be specified through a type parameter `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7559
+#: mcs/mcs/expression.cs:7560
 #, csharp-format
 msgid "The nested type `{0}' does not exist in the type `{1}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7567
+#: mcs/mcs/expression.cs:7568
 #, csharp-format
 msgid ""
 "Type `{0}' does not contain a definition for `{1}' and no extension method `"
@@ -1980,107 +1980,107 @@ msgid ""
 "assembly reference?)"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7747
+#: mcs/mcs/expression.cs:7748
 #, csharp-format
 msgid "Cannot apply indexing with [] to an expression of type `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7763
+#: mcs/mcs/expression.cs:7764
 msgid "A pointer must be indexed by only one value"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7812
+#: mcs/mcs/expression.cs:7813
 msgid "An element access expression cannot use named argument"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7868
+#: mcs/mcs/expression.cs:7869
 #, csharp-format
 msgid "Wrong number of indexes `{0}' inside [], expected `{1}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8176
+#: mcs/mcs/expression.cs:8177
 msgid ""
 "The indexer base access cannot be dynamically dispatched. Consider casting "
 "the dynamic arguments or eliminating the base access"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8248
+#: mcs/mcs/expression.cs:8249
 msgid "An expression tree may not contain a base access"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8265
+#: mcs/mcs/expression.cs:8266
 msgid "Keyword `base' is not available in a static method"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8267
+#: mcs/mcs/expression.cs:8268
 msgid "Keyword `base' is not available in the current context"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8298
+#: mcs/mcs/expression.cs:8299
 msgid ""
 "A property, indexer or dynamic member access may not be passed as `ref' or "
 "`out' parameter"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8571
+#: mcs/mcs/expression.cs:8572
 #, csharp-format
 msgid "Array elements cannot be of type `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8574
+#: mcs/mcs/expression.cs:8575
 #, csharp-format
 msgid "Array elements cannot be of static type `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8724
+#: mcs/mcs/expression.cs:8725
 msgid "Cannot use a negative size with stackalloc"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8728
+#: mcs/mcs/expression.cs:8729
 msgid "Cannot use stackalloc in finally or catch"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8833
+#: mcs/mcs/expression.cs:8834
 #, csharp-format
 msgid ""
 "Member `{0}' cannot be initialized. An object initializer may only be used "
 "for fields, or properties"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8842
+#: mcs/mcs/expression.cs:8843
 #, csharp-format
 msgid ""
 "Static field or property `{0}' cannot be assigned in an object initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9015
+#: mcs/mcs/expression.cs:9016
 #, csharp-format
 msgid ""
 "A field or property `{0}' cannot be initialized with a collection object "
 "initializer because type `{1}' does not implement `{2}' interface"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9026
+#: mcs/mcs/expression.cs:9027
 #, csharp-format
 msgid "Inconsistent `{0}' member declaration"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9034
+#: mcs/mcs/expression.cs:9035
 #, csharp-format
 msgid ""
 "An object initializer includes more than one member `{0}' initialization"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9052
+#: mcs/mcs/expression.cs:9053
 #, csharp-format
 msgid "Cannot initialize object of type `{0}' with a collection initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9295
+#: mcs/mcs/expression.cs:9296
 msgid "Anonymous types cannot be used in this expression"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9383
+#: mcs/mcs/expression.cs:9384
 #, csharp-format
 msgid "An anonymous type property `{0}' cannot be initialized with `{1}'"
 msgstr ""
diff --git a/po/mcs/es.gmo b/po/mcs/es.gmo
index 0ef1d7a..93ea06e 100644
Binary files a/po/mcs/es.gmo and b/po/mcs/es.gmo differ
diff --git a/po/mcs/es.po b/po/mcs/es.po
index 1142cbf..6b2998d 100644
--- a/po/mcs/es.po
+++ b/po/mcs/es.po
@@ -6,7 +6,7 @@ msgid ""
 msgstr ""
 "Project-Id-Version: mono 2.1\n"
 "Report-Msgid-Bugs-To: http://www.mono-project.com/Bugs\n"
-"POT-Creation-Date: 2010-10-05 14:01-0600\n"
+"POT-Creation-Date: 2010-11-12 03:29-0700\n"
 "PO-Revision-Date: 2008-09-19 13:28-0400\n"
 "Last-Translator: Miguel de Icaza <miguel at novell.com>\n"
 "Language-Team: es <mono-list at lists.ximian.com>\n"
@@ -1937,95 +1937,95 @@ msgstr ""
 msgid "An array initializer of length `{0}' was expected"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5842
+#: mcs/mcs/expression.cs:5841
 msgid ""
 "Array initializers can only be used in a variable or field initializer. Try "
 "using a new expression instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5850
+#: mcs/mcs/expression.cs:5849
 msgid "A nested array initializer was expected"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5887
+#: mcs/mcs/expression.cs:5886
 msgid "An expression tree cannot contain a multidimensional array initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5971
+#: mcs/mcs/expression.cs:5972
 msgid ""
 "An implicitly typed local variable declarator cannot use an array initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5992
+#: mcs/mcs/expression.cs:5993
 msgid ""
 "Can only use array initializer expressions to assign to array types. Try "
 "using a new expression instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6393
+#: mcs/mcs/expression.cs:6394
 msgid ""
 "The type of an implicitly typed array cannot be inferred from the "
 "initializer. Try specifying array type explicitly"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6521
+#: mcs/mcs/expression.cs:6522
 msgid ""
 "Keyword `this' is not valid in a static property, static method, or static "
 "field initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6524
+#: mcs/mcs/expression.cs:6525
 msgid ""
 "Anonymous methods inside structs cannot access instance members of `this'. "
 "Consider copying `this' to a local variable outside the anonymous method and "
 "using the local instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6527
+#: mcs/mcs/expression.cs:6528
 msgid "Keyword `this' is not available in the current context"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6591
+#: mcs/mcs/expression.cs:6592
 msgid ""
 "The `this' object cannot be used before all of its fields are assigned to"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6621
+#: mcs/mcs/expression.cs:6622
 msgid "Cannot take the address of `this' because it is read-only"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6623
+#: mcs/mcs/expression.cs:6624
 msgid "Cannot pass `this' as a ref or out argument because it is read-only"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6625
+#: mcs/mcs/expression.cs:6626
 msgid "Cannot assign to `this' because it is read-only"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6678
+#: mcs/mcs/expression.cs:6679
 msgid "The __arglist construct is valid only within a variable argument method"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6728
+#: mcs/mcs/expression.cs:6729
 msgid "An expression tree cannot contain a method with variable arguments"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6804
+#: mcs/mcs/expression.cs:6805
 msgid ""
 "System.Void cannot be used from C#. Use typeof (void) to get the void type "
 "object"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6809
+#: mcs/mcs/expression.cs:6810
 msgid "The typeof operator cannot be used on the dynamic type"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6878
+#: mcs/mcs/expression.cs:6879
 #, csharp-format
 msgid "`{0}': an attribute argument cannot use type parameters"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7129
+#: mcs/mcs/expression.cs:7130
 #, csharp-format
 msgid ""
 "`{0}' does not have a predefined size, therefore sizeof can only be used in "
@@ -2033,44 +2033,44 @@ msgid ""
 "SizeOf)"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7185
+#: mcs/mcs/expression.cs:7186
 #, csharp-format
 msgid "Alias `{0}' not found"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7196
+#: mcs/mcs/expression.cs:7197
 #, csharp-format
 msgid ""
 "Alias `{0}' cannot be used with '::' since it denotes a type. Consider "
 "replacing '::' with '.'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7212
+#: mcs/mcs/expression.cs:7213
 #, csharp-format
 msgid ""
 "A namespace alias qualifier `{0}' did not resolve to a namespace or a type"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7369
+#: mcs/mcs/expression.cs:7370
 msgid "Cannot perform member binding on `null' value"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7436
+#: mcs/mcs/expression.cs:7437
 #, csharp-format
 msgid "`{0}': cannot reference a type through an expression; try `{1}' instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7512
+#: mcs/mcs/expression.cs:7513
 #, csharp-format
 msgid "A nested type cannot be specified through a type parameter `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7559
+#: mcs/mcs/expression.cs:7560
 #, csharp-format
 msgid "The nested type `{0}' does not exist in the type `{1}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7567
+#: mcs/mcs/expression.cs:7568
 #, csharp-format
 msgid ""
 "Type `{0}' does not contain a definition for `{1}' and no extension method `"
@@ -2078,115 +2078,115 @@ msgid ""
 "assembly reference?)"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7747
+#: mcs/mcs/expression.cs:7748
 #, csharp-format
 msgid "Cannot apply indexing with [] to an expression of type `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7763
+#: mcs/mcs/expression.cs:7764
 msgid "A pointer must be indexed by only one value"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7812
+#: mcs/mcs/expression.cs:7813
 msgid "An element access expression cannot use named argument"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7868
+#: mcs/mcs/expression.cs:7869
 #, csharp-format
 msgid "Wrong number of indexes `{0}' inside [], expected `{1}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8176
+#: mcs/mcs/expression.cs:8177
 msgid ""
 "The indexer base access cannot be dynamically dispatched. Consider casting "
 "the dynamic arguments or eliminating the base access"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8248
+#: mcs/mcs/expression.cs:8249
 msgid "An expression tree may not contain a base access"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8265
+#: mcs/mcs/expression.cs:8266
 #, fuzzy
 msgid "Keyword `base' is not available in a static method"
 msgstr ""
 "La palabra reservada `new' no está permitida en los elementos de un espacio "
 "de nombres"
 
-#: mcs/mcs/expression.cs:8267
+#: mcs/mcs/expression.cs:8268
 #, fuzzy
 msgid "Keyword `base' is not available in the current context"
 msgstr ""
 "La palabra reservada `new' no está permitida en los elementos de un espacio "
 "de nombres"
 
-#: mcs/mcs/expression.cs:8298
+#: mcs/mcs/expression.cs:8299
 msgid ""
 "A property, indexer or dynamic member access may not be passed as `ref' or "
 "`out' parameter"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8571
+#: mcs/mcs/expression.cs:8572
 #, csharp-format
 msgid "Array elements cannot be of type `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8574
+#: mcs/mcs/expression.cs:8575
 #, csharp-format
 msgid "Array elements cannot be of static type `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8724
+#: mcs/mcs/expression.cs:8725
 msgid "Cannot use a negative size with stackalloc"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8728
+#: mcs/mcs/expression.cs:8729
 msgid "Cannot use stackalloc in finally or catch"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8833
+#: mcs/mcs/expression.cs:8834
 #, csharp-format
 msgid ""
 "Member `{0}' cannot be initialized. An object initializer may only be used "
 "for fields, or properties"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8842
+#: mcs/mcs/expression.cs:8843
 #, csharp-format
 msgid ""
 "Static field or property `{0}' cannot be assigned in an object initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9015
+#: mcs/mcs/expression.cs:9016
 #, csharp-format
 msgid ""
 "A field or property `{0}' cannot be initialized with a collection object "
 "initializer because type `{1}' does not implement `{2}' interface"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9026
+#: mcs/mcs/expression.cs:9027
 #, csharp-format
 msgid "Inconsistent `{0}' member declaration"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9034
+#: mcs/mcs/expression.cs:9035
 #, csharp-format
 msgid ""
 "An object initializer includes more than one member `{0}' initialization"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9052
+#: mcs/mcs/expression.cs:9053
 #, csharp-format
 msgid "Cannot initialize object of type `{0}' with a collection initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9295
+#: mcs/mcs/expression.cs:9296
 #, fuzzy
 msgid "Anonymous types cannot be used in this expression"
 msgstr ""
 "Los métodos anónimos no pueden ser convertidos a árboles de expresiones"
 
-#: mcs/mcs/expression.cs:9383
+#: mcs/mcs/expression.cs:9384
 #, csharp-format
 msgid "An anonymous type property `{0}' cannot be initialized with `{1}'"
 msgstr ""
diff --git a/po/mcs/ja.gmo b/po/mcs/ja.gmo
index ca1a0fc..a53ef90 100644
Binary files a/po/mcs/ja.gmo and b/po/mcs/ja.gmo differ
diff --git a/po/mcs/ja.po b/po/mcs/ja.po
index a33306b..467f05b 100644
--- a/po/mcs/ja.po
+++ b/po/mcs/ja.po
@@ -2,7 +2,7 @@ msgid ""
 msgstr ""
 "Project-Id-Version: \n"
 "Report-Msgid-Bugs-To: http://www.mono-project.com/Bugs\n"
-"POT-Creation-Date: 2010-10-05 14:01-0600\n"
+"POT-Creation-Date: 2010-11-12 03:29-0700\n"
 "PO-Revision-Date: \n"
 "Last-Translator: Atsushi Eno <atsushi at ximian.com>\n"
 "Language-Team: \n"
@@ -1911,95 +1911,95 @@ msgstr ""
 msgid "An array initializer of length `{0}' was expected"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5842
+#: mcs/mcs/expression.cs:5841
 msgid ""
 "Array initializers can only be used in a variable or field initializer. Try "
 "using a new expression instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5850
+#: mcs/mcs/expression.cs:5849
 msgid "A nested array initializer was expected"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5887
+#: mcs/mcs/expression.cs:5886
 msgid "An expression tree cannot contain a multidimensional array initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5971
+#: mcs/mcs/expression.cs:5972
 msgid ""
 "An implicitly typed local variable declarator cannot use an array initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5992
+#: mcs/mcs/expression.cs:5993
 msgid ""
 "Can only use array initializer expressions to assign to array types. Try "
 "using a new expression instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6393
+#: mcs/mcs/expression.cs:6394
 msgid ""
 "The type of an implicitly typed array cannot be inferred from the "
 "initializer. Try specifying array type explicitly"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6521
+#: mcs/mcs/expression.cs:6522
 msgid ""
 "Keyword `this' is not valid in a static property, static method, or static "
 "field initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6524
+#: mcs/mcs/expression.cs:6525
 msgid ""
 "Anonymous methods inside structs cannot access instance members of `this'. "
 "Consider copying `this' to a local variable outside the anonymous method and "
 "using the local instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6527
+#: mcs/mcs/expression.cs:6528
 msgid "Keyword `this' is not available in the current context"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6591
+#: mcs/mcs/expression.cs:6592
 msgid ""
 "The `this' object cannot be used before all of its fields are assigned to"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6621
+#: mcs/mcs/expression.cs:6622
 msgid "Cannot take the address of `this' because it is read-only"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6623
+#: mcs/mcs/expression.cs:6624
 msgid "Cannot pass `this' as a ref or out argument because it is read-only"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6625
+#: mcs/mcs/expression.cs:6626
 msgid "Cannot assign to `this' because it is read-only"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6678
+#: mcs/mcs/expression.cs:6679
 msgid "The __arglist construct is valid only within a variable argument method"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6728
+#: mcs/mcs/expression.cs:6729
 msgid "An expression tree cannot contain a method with variable arguments"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6804
+#: mcs/mcs/expression.cs:6805
 msgid ""
 "System.Void cannot be used from C#. Use typeof (void) to get the void type "
 "object"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6809
+#: mcs/mcs/expression.cs:6810
 msgid "The typeof operator cannot be used on the dynamic type"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6878
+#: mcs/mcs/expression.cs:6879
 #, csharp-format
 msgid "`{0}': an attribute argument cannot use type parameters"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7129
+#: mcs/mcs/expression.cs:7130
 #, csharp-format
 msgid ""
 "`{0}' does not have a predefined size, therefore sizeof can only be used in "
@@ -2007,44 +2007,44 @@ msgid ""
 "SizeOf)"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7185
+#: mcs/mcs/expression.cs:7186
 #, csharp-format
 msgid "Alias `{0}' not found"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7196
+#: mcs/mcs/expression.cs:7197
 #, csharp-format
 msgid ""
 "Alias `{0}' cannot be used with '::' since it denotes a type. Consider "
 "replacing '::' with '.'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7212
+#: mcs/mcs/expression.cs:7213
 #, csharp-format
 msgid ""
 "A namespace alias qualifier `{0}' did not resolve to a namespace or a type"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7369
+#: mcs/mcs/expression.cs:7370
 msgid "Cannot perform member binding on `null' value"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7436
+#: mcs/mcs/expression.cs:7437
 #, csharp-format
 msgid "`{0}': cannot reference a type through an expression; try `{1}' instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7512
+#: mcs/mcs/expression.cs:7513
 #, csharp-format
 msgid "A nested type cannot be specified through a type parameter `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7559
+#: mcs/mcs/expression.cs:7560
 #, csharp-format
 msgid "The nested type `{0}' does not exist in the type `{1}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7567
+#: mcs/mcs/expression.cs:7568
 #, csharp-format
 msgid ""
 "Type `{0}' does not contain a definition for `{1}' and no extension method `"
@@ -2052,110 +2052,110 @@ msgid ""
 "assembly reference?)"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7747
+#: mcs/mcs/expression.cs:7748
 #, csharp-format
 msgid "Cannot apply indexing with [] to an expression of type `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7763
+#: mcs/mcs/expression.cs:7764
 msgid "A pointer must be indexed by only one value"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7812
+#: mcs/mcs/expression.cs:7813
 msgid "An element access expression cannot use named argument"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7868
+#: mcs/mcs/expression.cs:7869
 #, csharp-format
 msgid "Wrong number of indexes `{0}' inside [], expected `{1}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8176
+#: mcs/mcs/expression.cs:8177
 msgid ""
 "The indexer base access cannot be dynamically dispatched. Consider casting "
 "the dynamic arguments or eliminating the base access"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8248
+#: mcs/mcs/expression.cs:8249
 msgid "An expression tree may not contain a base access"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8265
+#: mcs/mcs/expression.cs:8266
 #, fuzzy
 msgid "Keyword `base' is not available in a static method"
 msgstr "キーワード `new' は名前空間要素で認められていません"
 
-#: mcs/mcs/expression.cs:8267
+#: mcs/mcs/expression.cs:8268
 #, fuzzy
 msgid "Keyword `base' is not available in the current context"
 msgstr "キーワード `new' は名前空間要素で認められていません"
 
-#: mcs/mcs/expression.cs:8298
+#: mcs/mcs/expression.cs:8299
 msgid ""
 "A property, indexer or dynamic member access may not be passed as `ref' or "
 "`out' parameter"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8571
+#: mcs/mcs/expression.cs:8572
 #, csharp-format
 msgid "Array elements cannot be of type `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8574
+#: mcs/mcs/expression.cs:8575
 #, csharp-format
 msgid "Array elements cannot be of static type `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8724
+#: mcs/mcs/expression.cs:8725
 msgid "Cannot use a negative size with stackalloc"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8728
+#: mcs/mcs/expression.cs:8729
 msgid "Cannot use stackalloc in finally or catch"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8833
+#: mcs/mcs/expression.cs:8834
 #, csharp-format
 msgid ""
 "Member `{0}' cannot be initialized. An object initializer may only be used "
 "for fields, or properties"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8842
+#: mcs/mcs/expression.cs:8843
 #, csharp-format
 msgid ""
 "Static field or property `{0}' cannot be assigned in an object initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9015
+#: mcs/mcs/expression.cs:9016
 #, csharp-format
 msgid ""
 "A field or property `{0}' cannot be initialized with a collection object "
 "initializer because type `{1}' does not implement `{2}' interface"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9026
+#: mcs/mcs/expression.cs:9027
 #, csharp-format
 msgid "Inconsistent `{0}' member declaration"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9034
+#: mcs/mcs/expression.cs:9035
 #, csharp-format
 msgid ""
 "An object initializer includes more than one member `{0}' initialization"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9052
+#: mcs/mcs/expression.cs:9053
 #, csharp-format
 msgid "Cannot initialize object of type `{0}' with a collection initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9295
+#: mcs/mcs/expression.cs:9296
 #, fuzzy
 msgid "Anonymous types cannot be used in this expression"
 msgstr "匿名メソッドを式ツリーに変換することはできません"
 
-#: mcs/mcs/expression.cs:9383
+#: mcs/mcs/expression.cs:9384
 #, csharp-format
 msgid "An anonymous type property `{0}' cannot be initialized with `{1}'"
 msgstr ""
diff --git a/po/mcs/mcs.pot b/po/mcs/mcs.pot
index d6c18ec..3d9e81e 100644
--- a/po/mcs/mcs.pot
+++ b/po/mcs/mcs.pot
@@ -6,9 +6,9 @@
 #, fuzzy
 msgid ""
 msgstr ""
-"Project-Id-Version: mono 2.8\n"
+"Project-Id-Version: mono 2.8.1\n"
 "Report-Msgid-Bugs-To: http://www.mono-project.com/Bugs\n"
-"POT-Creation-Date: 2010-10-05 14:01-0600\n"
+"POT-Creation-Date: 2010-11-12 03:29-0700\n"
 "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
 "Last-Translator: FULL NAME <EMAIL at ADDRESS>\n"
 "Language-Team: LANGUAGE <LL at li.org>\n"
@@ -1829,95 +1829,95 @@ msgstr ""
 msgid "An array initializer of length `{0}' was expected"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5842
+#: mcs/mcs/expression.cs:5841
 msgid ""
 "Array initializers can only be used in a variable or field initializer. Try "
 "using a new expression instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5850
+#: mcs/mcs/expression.cs:5849
 msgid "A nested array initializer was expected"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5887
+#: mcs/mcs/expression.cs:5886
 msgid "An expression tree cannot contain a multidimensional array initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5971
+#: mcs/mcs/expression.cs:5972
 msgid ""
 "An implicitly typed local variable declarator cannot use an array initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:5992
+#: mcs/mcs/expression.cs:5993
 msgid ""
 "Can only use array initializer expressions to assign to array types. Try "
 "using a new expression instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6393
+#: mcs/mcs/expression.cs:6394
 msgid ""
 "The type of an implicitly typed array cannot be inferred from the "
 "initializer. Try specifying array type explicitly"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6521
+#: mcs/mcs/expression.cs:6522
 msgid ""
 "Keyword `this' is not valid in a static property, static method, or static "
 "field initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6524
+#: mcs/mcs/expression.cs:6525
 msgid ""
 "Anonymous methods inside structs cannot access instance members of `this'. "
 "Consider copying `this' to a local variable outside the anonymous method and "
 "using the local instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6527
+#: mcs/mcs/expression.cs:6528
 msgid "Keyword `this' is not available in the current context"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6591
+#: mcs/mcs/expression.cs:6592
 msgid ""
 "The `this' object cannot be used before all of its fields are assigned to"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6621
+#: mcs/mcs/expression.cs:6622
 msgid "Cannot take the address of `this' because it is read-only"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6623
+#: mcs/mcs/expression.cs:6624
 msgid "Cannot pass `this' as a ref or out argument because it is read-only"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6625
+#: mcs/mcs/expression.cs:6626
 msgid "Cannot assign to `this' because it is read-only"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6678
+#: mcs/mcs/expression.cs:6679
 msgid "The __arglist construct is valid only within a variable argument method"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6728
+#: mcs/mcs/expression.cs:6729
 msgid "An expression tree cannot contain a method with variable arguments"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6804
+#: mcs/mcs/expression.cs:6805
 msgid ""
 "System.Void cannot be used from C#. Use typeof (void) to get the void type "
 "object"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6809
+#: mcs/mcs/expression.cs:6810
 msgid "The typeof operator cannot be used on the dynamic type"
 msgstr ""
 
-#: mcs/mcs/expression.cs:6878
+#: mcs/mcs/expression.cs:6879
 #, csharp-format
 msgid "`{0}': an attribute argument cannot use type parameters"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7129
+#: mcs/mcs/expression.cs:7130
 #, csharp-format
 msgid ""
 "`{0}' does not have a predefined size, therefore sizeof can only be used in "
@@ -1925,44 +1925,44 @@ msgid ""
 "SizeOf)"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7185
+#: mcs/mcs/expression.cs:7186
 #, csharp-format
 msgid "Alias `{0}' not found"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7196
+#: mcs/mcs/expression.cs:7197
 #, csharp-format
 msgid ""
 "Alias `{0}' cannot be used with '::' since it denotes a type. Consider "
 "replacing '::' with '.'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7212
+#: mcs/mcs/expression.cs:7213
 #, csharp-format
 msgid ""
 "A namespace alias qualifier `{0}' did not resolve to a namespace or a type"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7369
+#: mcs/mcs/expression.cs:7370
 msgid "Cannot perform member binding on `null' value"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7436
+#: mcs/mcs/expression.cs:7437
 #, csharp-format
 msgid "`{0}': cannot reference a type through an expression; try `{1}' instead"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7512
+#: mcs/mcs/expression.cs:7513
 #, csharp-format
 msgid "A nested type cannot be specified through a type parameter `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7559
+#: mcs/mcs/expression.cs:7560
 #, csharp-format
 msgid "The nested type `{0}' does not exist in the type `{1}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7567
+#: mcs/mcs/expression.cs:7568
 #, csharp-format
 msgid ""
 "Type `{0}' does not contain a definition for `{1}' and no extension method `"
@@ -1970,107 +1970,107 @@ msgid ""
 "assembly reference?)"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7747
+#: mcs/mcs/expression.cs:7748
 #, csharp-format
 msgid "Cannot apply indexing with [] to an expression of type `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7763
+#: mcs/mcs/expression.cs:7764
 msgid "A pointer must be indexed by only one value"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7812
+#: mcs/mcs/expression.cs:7813
 msgid "An element access expression cannot use named argument"
 msgstr ""
 
-#: mcs/mcs/expression.cs:7868
+#: mcs/mcs/expression.cs:7869
 #, csharp-format
 msgid "Wrong number of indexes `{0}' inside [], expected `{1}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8176
+#: mcs/mcs/expression.cs:8177
 msgid ""
 "The indexer base access cannot be dynamically dispatched. Consider casting "
 "the dynamic arguments or eliminating the base access"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8248
+#: mcs/mcs/expression.cs:8249
 msgid "An expression tree may not contain a base access"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8265
+#: mcs/mcs/expression.cs:8266
 msgid "Keyword `base' is not available in a static method"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8267
+#: mcs/mcs/expression.cs:8268
 msgid "Keyword `base' is not available in the current context"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8298
+#: mcs/mcs/expression.cs:8299
 msgid ""
 "A property, indexer or dynamic member access may not be passed as `ref' or "
 "`out' parameter"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8571
+#: mcs/mcs/expression.cs:8572
 #, csharp-format
 msgid "Array elements cannot be of type `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8574
+#: mcs/mcs/expression.cs:8575
 #, csharp-format
 msgid "Array elements cannot be of static type `{0}'"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8724
+#: mcs/mcs/expression.cs:8725
 msgid "Cannot use a negative size with stackalloc"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8728
+#: mcs/mcs/expression.cs:8729
 msgid "Cannot use stackalloc in finally or catch"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8833
+#: mcs/mcs/expression.cs:8834
 #, csharp-format
 msgid ""
 "Member `{0}' cannot be initialized. An object initializer may only be used "
 "for fields, or properties"
 msgstr ""
 
-#: mcs/mcs/expression.cs:8842
+#: mcs/mcs/expression.cs:8843
 #, csharp-format
 msgid ""
 "Static field or property `{0}' cannot be assigned in an object initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9015
+#: mcs/mcs/expression.cs:9016
 #, csharp-format
 msgid ""
 "A field or property `{0}' cannot be initialized with a collection object "
 "initializer because type `{1}' does not implement `{2}' interface"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9026
+#: mcs/mcs/expression.cs:9027
 #, csharp-format
 msgid "Inconsistent `{0}' member declaration"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9034
+#: mcs/mcs/expression.cs:9035
 #, csharp-format
 msgid ""
 "An object initializer includes more than one member `{0}' initialization"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9052
+#: mcs/mcs/expression.cs:9053
 #, csharp-format
 msgid "Cannot initialize object of type `{0}' with a collection initializer"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9295
+#: mcs/mcs/expression.cs:9296
 msgid "Anonymous types cannot be used in this expression"
 msgstr ""
 
-#: mcs/mcs/expression.cs:9383
+#: mcs/mcs/expression.cs:9384
 #, csharp-format
 msgid "An anonymous type property `{0}' cannot be initialized with `{1}'"
 msgstr ""

-- 
mono



More information about the Pkg-mono-svn-commits mailing list