[Pkg-mono-svn-commits] [SCM] mono branch, upstream-experimental, updated. upstream/2.10

Jo Shields directhex at apebox.org
Thu Feb 17 00:26:49 UTC 2011


The following commit has been merged in the upstream-experimental branch:
commit 24a880a3d798d10c6f40c91fcf8343e030e4c43d
Author: Jo Shields <directhex at apebox.org>
Date:   Wed Feb 16 22:45:03 2011 +0000

    Imported Upstream version 2.10

diff --git a/ChangeLog b/ChangeLog
index 698db2a..02f20e5 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,71 @@
+2011-02-10  Andrew Jorgensen  <ajorgensen at novell.com>
+
+	Mono.Debugger.Soft.dll is installed for 4.0 also.
+
+2011-02-08  Marek Habersack  <grendel at twistedcode.net>
+
+	[cross-compilation] Added some flexibility regarding the location
+	of development packages
+
+	The script now supports an extra cross-compilation directory in
+	which you can unpack the library and development packages
+	necessary for the build to succeed (glib, zlib etc). Also
+	supported now is specifying the location at which Mono will be
+	installed on Windows. Replaced SVN and GIT-SVN version checks with
+	git checks.
+
+2010-06-14  Hib Eris  <hib at hiberis.nl>
+
+	Fix build-mingw32.sh for CROSS_PKG_CONFIG_DIR without *.pc files
+
+2010-06-14  Hib Eris  <hib at hiberis.nl>
+
+	No longer include glib binaries in build-mingw32.sh builds.
+
+	By default, Mono now uses an embedded glib implementation, so
+	there is no need to ship external glib libraries anymore.
+
+2010-06-14  Hib Eris  <hib at hiberis.nl>
+
+	Let build-mingw32.sh script also work on dist tarballs
+
+2011-02-07  Hib Eris  <hib at hiberis.nl>
+
+	Use winternl.h instead of ddk (when available)
+
+	These changes are nescessary for compiling with a mingw-w64
+	compiler.
+
+2011-01-27  Zoltan Varga  <vargaz at gmail.com>
+
+	Applied patch from Burkhard Linke
+	<blinke at cebitec.uni-bielefeld.de>. Add support for newer boehm-gc
+	versions.
+
+2011-01-26  Andrew Jorgensen  <ajorgensen at novell.com>
+
+	Add 2.0 and 4.0 S.D.S.C
+
+2011-01-24  Andrew Jorgensen  <ajorgensen at novell.com>
+
+	Add WebMatrix.Data to spec
+
+2011-01-19  Mark Probst  <mark.probst at gmail.com>
+
+	[build] pkg-config support for libmonosgen.
+
+2011-01-21  Andrew Jorgensen  <ajorgensen at novell.com>
+
+	Oops, Microsoft.Web.Infrastructure, not System.
+
+2011-01-21  Andrew Jorgensen  <ajorgensen at novell.com>
+
+	add Microsoft.Web.Infrastructure
+
+2011-01-19  Andrew Jorgensen  <ajorgensen at novell.com>
+
+	Dist more files needed by MSVC build
+
 2011-01-13  Andrew Jorgensen  <ajorgensen at novell.com>
 
 	2.10
diff --git a/Makefile.am b/Makefile.am
index 339d38c..b507915 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -19,7 +19,16 @@ DIST_SUBDIRS = po libgc eglib mono ikvm-native support data runtime scripts man
 endif
 endif
 
-EXTRA_DIST= nls.m4 po.m4 progtest.m4 mono-uninstalled.pc.in build-mingw32.sh LICENSE mkinstalldirs autogen.sh 
+EXTRA_DIST= \
+	    LICENSE \
+	    autogen.sh \
+	    build-mingw32.sh \
+	    mkinstalldirs \
+	    mono-uninstalled.pc.in \
+	    nls.m4 \
+	    po.m4 \
+	    progtest.m4 \
+	    winconfig.h
 
 DISTCHECK_CONFIGURE_FLAGS = EXTERNAL_MCS=false EXTERNAL_RUNTIME=false
 
diff --git a/Makefile.in b/Makefile.in
index 35c6c83..2fd3f95 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -282,7 +282,17 @@ MOONLIGHT_SUBDIRS = $(libgc_dir) eglib/src mono
 @CROSS_COMPILING_FALSE@@ONLY_MOONLIGHT_FALSE at DIST_SUBDIRS = po libgc eglib mono ikvm-native support data runtime scripts man samples tools msvc docs
 # Keep in sync with SUBDIRS
 @CROSS_COMPILING_TRUE at DIST_SUBDIRS = po libgc eglib mono ikvm-native         data runtime scripts man samples tools msvc docs
-EXTRA_DIST = nls.m4 po.m4 progtest.m4 mono-uninstalled.pc.in build-mingw32.sh LICENSE mkinstalldirs autogen.sh 
+EXTRA_DIST = \
+	    LICENSE \
+	    autogen.sh \
+	    build-mingw32.sh \
+	    mkinstalldirs \
+	    mono-uninstalled.pc.in \
+	    nls.m4 \
+	    po.m4 \
+	    progtest.m4 \
+	    winconfig.h
+
 DISTCHECK_CONFIGURE_FLAGS = EXTERNAL_MCS=false EXTERNAL_RUNTIME=false
 pkgconfigdir = $(libdir)/pkgconfig
 noinst_DATA = mono-uninstalled.pc
diff --git a/build-mingw32.sh b/build-mingw32.sh
index 16b91ce..d751b2e 100755
--- a/build-mingw32.sh
+++ b/build-mingw32.sh
@@ -2,7 +2,7 @@
 CURDIR="`pwd`"
 MINGW=i386-mingw32msvc
 CROSS_DIR=/opt/cross/$MINGW
-COPY_DLLS="libgio*.dll libglib*.dll libgmodule*.dll libgthread*.dll libgobject*.dll"
+EXTRA_CROSS_DIR=
 INSTALL_DESTDIR="$CURDIR/mono-win32"
 PROFILES="default net_2_0 net_3_5 net_4_0 moonlight"
 TEMPORARY_PKG_CONFIG_DIR=/tmp/$RANDOM-pkg-config-$RANDOM
@@ -17,62 +17,119 @@ function cleanup ()
     fi
 }
 
+function check_pkg_config_dir ()
+{
+    local DIR="$1"
+    local DIR_PREFIX="$2"
+
+    if [ ! -d "$DIR" ]; then
+	return
+    fi
+
+    install -d -m 755 "$TEMPORARY_PKG_CONFIG_DIR"
+    for pc in "$DIR"/*.pc; do
+	if [ -f $pc ]; then
+	    pcname="`basename $pc`"
+	    sed -e "s;^prefix=.*;prefix=$DIR_PREFIX;g" < $pc > "$TEMPORARY_PKG_CONFIG_DIR"/$pcname
+	fi;
+    done
+
+    if [ -z "$CROSS_PKG_CONFIG_DIR" ]; then
+	CROSS_PKG_CONFIG_DIR="$TEMPORARY_PKG_CONFIG_DIR"
+    fi
+}
+
+function show_build_info ()
+{
+    cat <<EOF
+Installation prefix: $MONO_PREFIX
+           CPPFLAGS: ${CPPFLAGS:=not set}
+            LDFLAGS: ${LDFLAGS:=not set}
+          MONO_PATH: ${MONO_PATH:=not set}
+EOF
+}
+
 function setup ()
 {
     local pcname
 
     CROSS_BIN_DIR="$CROSS_DIR/bin"
     CROSS_DLL_DIR="$CROSS_DIR/bin"
-    CROSS_PKG_CONFIG_DIR=$CROSS_DIR/lib/pkgconfig
     PATH=$CROSS_BIN_DIR:$PATH
 
-    export PATH
-    if [ -d ./.git/svn ]; then
-	SVN_INFO='git svn info'
-    elif [ -d ./.svn ]; then
-	SVN_INFO='svn info'
-    else
-	SVN_INFO=""
-    fi
-
-    if [ -n "$SVN_INFO" ]; then
-	MONO_SVN_REVISION=`$SVN_INFO | grep Revision | sed 's/.*: //'`
-	MONO_BRANCH=`$SVN_INFO | grep URL | sed -e 's;.*source/;;g' -e 's;/mono;;g'`
+    MONO_VERSION=`grep AM_INIT_AUTOMAKE configure.in | cut -d ',' -f 2|tr -d '\)'`
+    
+    if [ -d ./.git ]; then
+	MONO_GIT_COMMIT="`git log -1 --format=format:%t`"
+	MONO_GIT_BRANCH="`git branch|grep '\*'|cut -d ' ' -f 2`"
+	MONO_RELEASE="$MONO_VERSION-$MONO_GIT_BRANCH-$MONO_GIT_COMMIT"
     else
-	MONO_SVN_REVISION="rUNKNOWN"
-	MONO_BRANCH="tarball"
+	MONO_RELEASE="$MONO_VERSION"
     fi
 
-    MONO_VERSION=`grep AM_INIT_AUTOMAKE configure.in | cut -d ',' -f 2|tr -d '\)'`
-    MONO_RELEASE="$MONO_VERSION-$MONO_BRANCH-r$MONO_SVN_REVISION"
-    MONO_PREFIX="/mono-$MONO_RELEASE"
+    MONO_PREFIX="$MONO_PREFIX/mono-$MONO_RELEASE"
 
     NOCONFIGURE=yes
     export NOCONFIGURE
 
-    if [ -d "$CROSS_PKG_CONFIG_DIR" ]; then
-	install -d -m 755 "$TEMPORARY_PKG_CONFIG_DIR"
-	for pc in "$CROSS_PKG_CONFIG_DIR"/*.pc; do
-	    pcname="`basename $pc`"
-	    sed -e "s;^prefix=.*;prefix=$CROSS_DIR;g" < $pc > "$TEMPORARY_PKG_CONFIG_DIR"/$pcname
-	done
-	CROSS_PKG_CONFIG_DIR="$TEMPORARY_PKG_CONFIG_DIR"
+    check_pkg_config_dir "$CROSS_DIR/lib/pkgconfig" "$CROSS_DIR"
+
+    if [ -n "$EXTRA_CROSS_DIR" -a -d "$EXTRA_CROSS_DIR" ]; then
+	if [ -d "$EXTRA_CROSS_DIR/bin" ]; then
+		PATH="$EXTRA_CROSS_DIR/bin":$PATH
+	fi
+	
+	check_pkg_config_dir "$EXTRA_CROSS_DIR/lib/pkgconfig" "$EXTRA_CROSS_DIR"
+
+	if [ -d "$EXTRA_CROSS_DIR/include" ]; then
+	    if [ -z "$CPPFLAGS" ]; then
+		CPPFLAGS="-I \"$EXTRA_CROSS_DIR/include\""
+	    else
+		CPPFLAGS="-I \"$EXTRA_CROSS_DIR/include\" $CFLAGS"
+	    fi
+	fi
+
+	if [ -d "$EXTRA_CROSS_DIR/lib" ]; then
+	    if [ -z "$LDFLAGS" ]; then
+		LDFLAGS="-I \"$EXTRA_CROSS_DIR/lib\""
+	    else
+		LDFLAGS="-I \"$EXTRA_CROSS_DIR/lib\" $LDFLAGS"
+	    fi
+	fi
+
+	if [ -d "$EXTRA_CROSS_DIR/share/aclocal" ]; then
+	    if [ -z "$MONO_PATH" ]; then
+		MONO_PATH="\"$EXTRA_CROSS_DIR\""
+	    else
+		MONO_PATH="\"$EXTRA_CROSS_DIR\":$MONO_PATH"
+	    fi
+	fi
     fi
-
-    echo Mono Win32 installation prefix: $MONO_PREFIX
+    
+    export PATH MONO_PATH CPPFLAGS
+    show_build_info
 }
 
 function build ()
 {
-    ./autogen.sh 
-
-    BUILD="`./config.guess`"
-
     if [ -f ./Makefile ]; then
 	make distclean
-	rm -rf autom4te.cache
     fi
 
+    if [ -d ./autom4te.cache ]; then
+	rm -rf ./autom4te.cache
+    fi
+
+    if [ -f ./config.status ]; then
+	for f in `find -name config.status -type f`; do
+	    rm $f
+	done
+    fi
+
+    ./autogen.sh 
+
+    BUILD="`./config.guess`"
+
     if [ ! -d "$CURDIR/build-cross-windows" ]; then
 	mkdir "$CURDIR/build-cross-windows"
     fi
@@ -105,27 +162,28 @@ function doinstall ()
     cd "$CURDIR/build-cross-windows"
     make DESTDIR="$INSTALL_DESTDIR" USE_BATCH_FILES=yes install
 
-    cd "$CURDIR/../mcs/mcs"
+    if test -d $CURDIR/mcs; then
+      mcsdir=$CURDIR/mcs
+    else
+      mcsdir=$CURDIR/../mcs
+    fi
 
+    cd "$mcsdir/mcs"
     for p in $PROFILES; do
 	make DESTDIR="$INSTALL_DESTDIR" PROFILE=$p install || echo "mcs profile $p installation failed"
     done
 
-    cd "$CURDIR/../mcs/class"
+    cd "$mcsdir/class"
     for p in $PROFILES; do
 	make DESTDIR="$INSTALL_DESTDIR" PROFILE=$p install || echo "class library profile $p installation failed"
     done
 
-    cd "$CURDIR/../mcs/tools"
+    cd "$mcsdir/tools"
     for p in $PROFILES; do
 	make DESTDIR="$INSTALL_DESTDIR" PROFILE=$p install || echo "tools profile $p installation failed"
     done
 
     cd "$CURDIR/mono-win32"
-    for dll in $COPY_DLLS; do
-	cp -ap "$CROSS_DLL_DIR"/$dll "$INSTALL_DESTDIR/$MONO_PREFIX/bin"
-    done
-
     rm -f "$CURDIR/mono-win32-$MONO_RELEASE".zip
     zip -9r "$CURDIR/mono-win32-$MONO_RELEASE".zip .
 
@@ -139,7 +197,9 @@ Usage: build-mingw32.sh [OPTIONS]
 where OPTIONS are:
 
  -d DIR     Sets the location of directory where MINGW is installed [$CROSS_DIR]
+ -e DIR     Sets the location of directory where additional cross develoment packages are installed [${EXTRA_CROSS_DIR:=none}]
  -m MINGW   Sets the MINGW target name to be passed to configure [$MINGW]
+ -p PREFIX  Prefix at which Mono is to be installed. Build will append the 'mono-X.Y' string to that path
 EOF
 
     exit 1
@@ -149,10 +209,12 @@ trap cleanup 0
 
 pushd . > /dev/null
 
-while getopts "d:m:h" opt; do
+while getopts "d:m:e:p:" opt; do
     case "$opt" in
 	d) CROSS_DIR="$OPTARG" ;;
 	m) MINGW="$OPTARG" ;;
+	e) EXTRA_CROSS_DIR="$OPTARG" ;;
+	p) MONO_PREFIX="$OPTARG" ;;
 	*) usage ;;
     esac
 done
@@ -160,5 +222,6 @@ done
 setup
 build
 doinstall
+show_build_info
 
 popd > /dev/null
diff --git a/config.h.in b/config.h.in
index c011dc9..d21f0b3 100644
--- a/config.h.in
+++ b/config.h.in
@@ -189,6 +189,9 @@
 /* Define to 1 if you have the `futimes' function. */
 #undef HAVE_FUTIMES
 
+/* GC requires thread registration */
+#undef HAVE_GC_ALLOW_REGISTER_THREADS
+
 /* Define to 1 if you have the <gc/gc.h> header file. */
 #undef HAVE_GC_GC_H
 
@@ -687,6 +690,9 @@
 /* Define to 1 if you have the <wchar.h> header file. */
 #undef HAVE_WCHAR_H
 
+/* Define to 1 if you have the <winternl.h> header file. */
+#undef HAVE_WINTERNL_H
+
 /* Have a working sigaltstack */
 #undef HAVE_WORKING_SIGALTSTACK
 
diff --git a/configure b/configure
index 7203023..900c178 100755
--- a/configure
+++ b/configure
@@ -21688,6 +21688,86 @@ fi
 		if test "x$found_gc_enable" = "xyes"; then
 			BOEHM_DEFINES="-DHAVE_GC_ENABLE $BOEHM_DEFINES"
 		fi
+
+		# check whether we need to explicitly allow
+               	# thread registering
+               	{ $as_echo "$as_me:$LINENO: checking for GC_allow_register_threads in -lgc" >&5
+$as_echo_n "checking for GC_allow_register_threads in -lgc... " >&6; }
+if test "${ac_cv_lib_gc_GC_allow_register_threads+set}" = set; then
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgc $libdl $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char GC_allow_register_threads ();
+int
+main ()
+{
+return GC_allow_register_threads ();
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\""
+$as_echo "$ac_try_echo") >&5
+  (eval "$ac_link") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest$ac_exeext && {
+	 test "$cross_compiling" = yes ||
+	 $as_test_x conftest$ac_exeext
+       }; then
+  ac_cv_lib_gc_GC_allow_register_threads=yes
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_cv_lib_gc_GC_allow_register_threads=no
+fi
+
+rm -rf conftest.dSYM
+rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+      conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_gc_GC_allow_register_threads" >&5
+$as_echo "$ac_cv_lib_gc_GC_allow_register_threads" >&6; }
+if test "x$ac_cv_lib_gc_GC_allow_register_threads" = x""yes; then
+  found_allow_register_threads="yes"
+fi
+
+               	if test "x$found_allow_register_threads" = "xyes"; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_GC_ALLOW_REGISTER_THREADS 1
+_ACEOF
+
+               	fi
+
 		;;
 
 	xincluded)
@@ -36814,6 +36894,153 @@ cat >>confdefs.h <<\_ACEOF
 _ACEOF
 
 else
+
+for ac_header in winternl.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
+  { $as_echo "$as_me:$LINENO: checking for $ac_header" >&5
+$as_echo_n "checking for $ac_header... " >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+  $as_echo_n "(cached) " >&6
+fi
+ac_res=`eval 'as_val=${'$as_ac_Header'}
+		 $as_echo "$as_val"'`
+	       { $as_echo "$as_me:$LINENO: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+else
+  # Is the header compilable?
+{ $as_echo "$as_me:$LINENO: checking $ac_header usability" >&5
+$as_echo_n "checking $ac_header usability... " >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\""
+$as_echo "$ac_try_echo") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_header_compiler=yes
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+$as_echo "$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ $as_echo "$as_me:$LINENO: checking $ac_header presence" >&5
+$as_echo_n "checking $ac_header presence... " >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\""
+$as_echo "$ac_try_echo") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       }; then
+  ac_header_preproc=yes
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+$as_echo "$ac_header_preproc" >&6; }
+
+# So?  What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+  yes:no: )
+    { $as_echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+$as_echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+    { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+$as_echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+    ac_header_preproc=yes
+    ;;
+  no:yes:* )
+    { $as_echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+$as_echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+    { $as_echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing prerequisite headers?" >&5
+$as_echo "$as_me: WARNING: $ac_header:     check for missing prerequisite headers?" >&2;}
+    { $as_echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+$as_echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+    { $as_echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But Cannot Be Compiled\"" >&5
+$as_echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Compiled\"" >&2;}
+    { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+$as_echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+    { $as_echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+$as_echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+
+    ;;
+esac
+{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5
+$as_echo_n "checking for $ac_header... " >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+  $as_echo_n "(cached) " >&6
+else
+  eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval 'as_val=${'$as_ac_Header'}
+		 $as_echo "$as_val"'`
+	       { $as_echo "$as_me:$LINENO: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+
+fi
+as_val=`eval 'as_val=${'$as_ac_Header'}
+		 $as_echo "$as_val"'`
+   if test "x$as_val" = x""yes; then
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
 	jdk_headers_found=no
 	{ $as_echo "$as_me:$LINENO: checking for main in -lws2_32" >&5
 $as_echo_n "checking for main in -lws2_32... " >&6; }
@@ -40478,7 +40705,7 @@ if test x$enable_quiet_build = xyes; then
 
 fi
 
-ac_config_files="$ac_config_files Makefile mono-core.spec mono-uninstalled.pc scripts/mono-find-provides scripts/mono-find-requires mono/Makefile mono/utils/Makefile mono/metadata/Makefile mono/dis/Makefile mono/cil/Makefile mono/arch/Makefile mono/arch/x86/Makefile mono/arch/amd64/Makefile mono/arch/hppa/Makefile mono/arch/ppc/Makefile mono/arch/sparc/Makefile mono/arch/s390/Makefile mono/arch/s390x/Makefile mono/arch/arm/Makefile mono/arch/alpha/Makefile mono/arch/ia64/Makefile mono/arch/mips/Makefile mono/interpreter/Makefile mono/tests/Makefile mono/tests/tests-config mono/tests/assemblyresolve/Makefile mono/tests/cas/Makefile mono/tests/cas/assembly/Makefile mono/tests/cas/demand/Makefile mono/tests/cas/inheritance/Makefile mono/tests/cas/linkdemand/Makefile mono/tests/cas/threads/Makefile mono/benchmark/Makefile mono/monograph/Makefile mono/io-layer/Makefile mono/mini/Makefile mono/profiler/Makefile ikvm-native/Makefile scripts/Makefile man/Makefile docs/Makefile data/Makefile data/net_2_0/Makefile data/net_4_0/Makefile data/net_2_0/Browsers/Makefile data/mint.pc data/mono-2.pc data/mono.pc data/mono-cairo.pc data/mono-nunit.pc data/mono-options.pc data/mono-lineeditor.pc data/monodoc.pc data/mono.web.pc data/dotnet.pc data/dotnet35.pc data/wcf.pc data/cecil.pc data/system.web.extensions_1.0.pc data/system.web.extensions.design_1.0.pc data/system.web.mvc.pc data/system.web.mvc2.pc samples/Makefile support/Makefile data/config tools/Makefile tools/locale-builder/Makefile tools/sgen/Makefile runtime/Makefile msvc/Makefile po/Makefile"
+ac_config_files="$ac_config_files Makefile mono-core.spec mono-uninstalled.pc scripts/mono-find-provides scripts/mono-find-requires mono/Makefile mono/utils/Makefile mono/metadata/Makefile mono/dis/Makefile mono/cil/Makefile mono/arch/Makefile mono/arch/x86/Makefile mono/arch/amd64/Makefile mono/arch/hppa/Makefile mono/arch/ppc/Makefile mono/arch/sparc/Makefile mono/arch/s390/Makefile mono/arch/s390x/Makefile mono/arch/arm/Makefile mono/arch/alpha/Makefile mono/arch/ia64/Makefile mono/arch/mips/Makefile mono/interpreter/Makefile mono/tests/Makefile mono/tests/tests-config mono/tests/assemblyresolve/Makefile mono/tests/cas/Makefile mono/tests/cas/assembly/Makefile mono/tests/cas/demand/Makefile mono/tests/cas/inheritance/Makefile mono/tests/cas/linkdemand/Makefile mono/tests/cas/threads/Makefile mono/benchmark/Makefile mono/monograph/Makefile mono/io-layer/Makefile mono/mini/Makefile mono/profiler/Makefile ikvm-native/Makefile scripts/Makefile man/Makefile docs/Makefile data/Makefile data/net_2_0/Makefile data/net_4_0/Makefile data/net_2_0/Browsers/Makefile data/mint.pc data/mono-2.pc data/monosgen-2.pc data/mono.pc data/mono-cairo.pc data/mono-nunit.pc data/mono-options.pc data/mono-lineeditor.pc data/monodoc.pc data/mono.web.pc data/dotnet.pc data/dotnet35.pc data/wcf.pc data/cecil.pc data/system.web.extensions_1.0.pc data/system.web.extensions.design_1.0.pc data/system.web.mvc.pc data/system.web.mvc2.pc samples/Makefile support/Makefile data/config tools/Makefile tools/locale-builder/Makefile tools/sgen/Makefile runtime/Makefile msvc/Makefile po/Makefile"
 
 cat >confcache <<\_ACEOF
 # This file is a shell script that caches the results of configure
@@ -41921,6 +42148,7 @@ do
     "data/net_2_0/Browsers/Makefile") CONFIG_FILES="$CONFIG_FILES data/net_2_0/Browsers/Makefile" ;;
     "data/mint.pc") CONFIG_FILES="$CONFIG_FILES data/mint.pc" ;;
     "data/mono-2.pc") CONFIG_FILES="$CONFIG_FILES data/mono-2.pc" ;;
+    "data/monosgen-2.pc") CONFIG_FILES="$CONFIG_FILES data/monosgen-2.pc" ;;
     "data/mono.pc") CONFIG_FILES="$CONFIG_FILES data/mono.pc" ;;
     "data/mono-cairo.pc") CONFIG_FILES="$CONFIG_FILES data/mono-cairo.pc" ;;
     "data/mono-nunit.pc") CONFIG_FILES="$CONFIG_FILES data/mono-nunit.pc" ;;
diff --git a/configure.in b/configure.in
index 11b47dc..0729f41 100644
--- a/configure.in
+++ b/configure.in
@@ -851,6 +851,14 @@ case "x$gc" in
 		if test "x$found_gc_enable" = "xyes"; then
 			BOEHM_DEFINES="-DHAVE_GC_ENABLE $BOEHM_DEFINES"
 		fi
+
+		# check whether we need to explicitly allow
+               	# thread registering
+               	AC_CHECK_LIB(gc, GC_allow_register_threads, found_allow_register_threads="yes",,$libdl)
+               	if test "x$found_allow_register_threads" = "xyes"; then
+                        AC_DEFINE(HAVE_GC_ALLOW_REGISTER_THREADS, 1, [GC requires thread registration])
+               	fi
+
 		;;
 
 	xincluded)
@@ -1746,6 +1754,11 @@ if test x$target_win32 = xno; then
 	dnl * on xp+
 	AC_DEFINE(HAVE_GETPROCESSID, 1, [Define if GetProcessId is available])
 else
+	dnl *********************************
+	dnl *** Checks for Windows compilation ***
+	dnl *********************************
+	AC_CHECK_HEADERS(winternl.h)
+
 	jdk_headers_found=no
 	AC_CHECK_LIB(ws2_32, main, LIBS="$LIBS -lws2_32", AC_ERROR(bad mingw install?))
 	AC_CHECK_LIB(psapi, main, LIBS="$LIBS -lpsapi", AC_ERROR(bad mingw install?))
@@ -2876,6 +2889,7 @@ data/net_4_0/Makefile
 data/net_2_0/Browsers/Makefile
 data/mint.pc
 data/mono-2.pc
+data/monosgen-2.pc
 data/mono.pc
 data/mono-cairo.pc
 data/mono-nunit.pc
diff --git a/data/ChangeLog b/data/ChangeLog
index a991ea8..ca7a866 100644
--- a/data/ChangeLog
+++ b/data/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-19  Mark Probst  <mark.probst at gmail.com>
+
+	[build] pkg-config support for libmonosgen.
+
 2010-12-01  Jonathan Pryor  <jonpryor at vt.edu>
 
 	Add response file suport to Mono.Options.
diff --git a/data/Makefile.am b/data/Makefile.am
index 14ef47b..97e713f 100644
--- a/data/Makefile.am
+++ b/data/Makefile.am
@@ -9,7 +9,7 @@ monodir = $(sysconfdir)/mono
 EXTRA_DIST =  	\
 	config.in \
 	browscap.ini mono.supp mono.d README ChangeLog \
-	mono.pc.in mono-2.pc.in mint.pc.in dotnet.pc.in dotnet35.pc.in wcf.pc.in monodoc.pc.in \
+	mono.pc.in mono-2.pc.in monosgen-2.pc.in mint.pc.in dotnet.pc.in dotnet35.pc.in wcf.pc.in monodoc.pc.in \
 	mono-nunit.pc.in mono-cairo.pc.in mono-options.pc.in cecil.pc.in \
 	mono-lineeditor.pc.in system.web.extensions_1.0.pc.in system.web.extensions.design_1.0.pc.in\
 	dtrace-prelink.sh mono.web.pc.in system.web.mvc.pc.in system.web.mvc2.pc.in \
@@ -19,20 +19,26 @@ EXTRA_DIST =  	\
 
 pkgconfigdir = $(libdir)/pkgconfig
 
+if SUPPORT_SGEN
+SGENPCFILE=monosgen-2.pc
+else
+SGENPCFILE=
+endif
+
 if JIT_SUPPORTED
 if INTERP_SUPPORTED
 pkgconfig_DATA= mono.pc mono-2.pc mint.pc dotnet.pc dotnet35.pc wcf.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc system.web.extensions_1.0.pc \
-		system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc
+		system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc $(SGENPCFILE)
 else
 pkgconfig_DATA= mono.pc mono-2.pc dotnet.pc dotnet35.pc wcf.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc system.web.extensions_1.0.pc \
-		system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc
+		system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc $(SGENPCFILE)
 endif
 else
 pkgconfig_DATA= mint.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc
 endif
 
 DISTCLEANFILES= mono-2.pc mono.pc mint.pc dotnet.pc dotnet35.pc wcf.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc system.web.extensions_1.0.pc \
-		system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc
+		system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc $(SGENPCFILE)
 
 mono_DATA =  config \
 	     browscap.ini
diff --git a/data/Makefile.in b/data/Makefile.in
index fd59878..0655585 100644
--- a/data/Makefile.in
+++ b/data/Makefile.in
@@ -42,7 +42,7 @@ DIST_COMMON = README $(srcdir)/Makefile.am $(srcdir)/Makefile.in \
 	$(srcdir)/mono-cairo.pc.in $(srcdir)/mono-lineeditor.pc.in \
 	$(srcdir)/mono-nunit.pc.in $(srcdir)/mono-options.pc.in \
 	$(srcdir)/mono.pc.in $(srcdir)/mono.web.pc.in \
-	$(srcdir)/monodoc.pc.in \
+	$(srcdir)/monodoc.pc.in $(srcdir)/monosgen-2.pc.in \
 	$(srcdir)/system.web.extensions.design_1.0.pc.in \
 	$(srcdir)/system.web.extensions_1.0.pc.in \
 	$(srcdir)/system.web.mvc.pc.in $(srcdir)/system.web.mvc2.pc.in \
@@ -58,9 +58,9 @@ am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs
 CONFIG_HEADER = $(top_builddir)/config.h
-CONFIG_CLEAN_FILES = mint.pc mono-2.pc mono.pc mono-cairo.pc \
-	mono-nunit.pc mono-options.pc mono-lineeditor.pc monodoc.pc \
-	mono.web.pc dotnet.pc dotnet35.pc wcf.pc cecil.pc \
+CONFIG_CLEAN_FILES = mint.pc mono-2.pc monosgen-2.pc mono.pc \
+	mono-cairo.pc mono-nunit.pc mono-options.pc mono-lineeditor.pc \
+	monodoc.pc mono.web.pc dotnet.pc dotnet35.pc wcf.pc cecil.pc \
 	system.web.extensions_1.0.pc \
 	system.web.extensions.design_1.0.pc system.web.mvc.pc \
 	system.web.mvc2.pc config
@@ -289,7 +289,7 @@ monodir = $(sysconfdir)/mono
 EXTRA_DIST = \
 	config.in \
 	browscap.ini mono.supp mono.d README ChangeLog \
-	mono.pc.in mono-2.pc.in mint.pc.in dotnet.pc.in dotnet35.pc.in wcf.pc.in monodoc.pc.in \
+	mono.pc.in mono-2.pc.in monosgen-2.pc.in mint.pc.in dotnet.pc.in dotnet35.pc.in wcf.pc.in monodoc.pc.in \
 	mono-nunit.pc.in mono-cairo.pc.in mono-options.pc.in cecil.pc.in \
 	mono-lineeditor.pc.in system.web.extensions_1.0.pc.in system.web.extensions.design_1.0.pc.in\
 	dtrace-prelink.sh mono.web.pc.in system.web.mvc.pc.in system.web.mvc2.pc.in \
@@ -298,15 +298,17 @@ EXTRA_DIST = \
 	gdb/gdb-python.diff
 
 pkgconfigdir = $(libdir)/pkgconfig
+ at SUPPORT_SGEN_FALSE@SGENPCFILE = 
+ at SUPPORT_SGEN_TRUE@SGENPCFILE = monosgen-2.pc
 @INTERP_SUPPORTED_FALSE@@JIT_SUPPORTED_TRUE at pkgconfig_DATA = mono.pc mono-2.pc dotnet.pc dotnet35.pc wcf.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc system.web.extensions_1.0.pc \
- at INTERP_SUPPORTED_FALSE@@JIT_SUPPORTED_TRUE@		system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc
+ at INTERP_SUPPORTED_FALSE@@JIT_SUPPORTED_TRUE@		system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc $(SGENPCFILE)
 
 @INTERP_SUPPORTED_TRUE@@JIT_SUPPORTED_TRUE at pkgconfig_DATA = mono.pc mono-2.pc mint.pc dotnet.pc dotnet35.pc wcf.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc system.web.extensions_1.0.pc \
- at INTERP_SUPPORTED_TRUE@@JIT_SUPPORTED_TRUE@		system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc
+ at INTERP_SUPPORTED_TRUE@@JIT_SUPPORTED_TRUE@		system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc $(SGENPCFILE)
 
 @JIT_SUPPORTED_FALSE at pkgconfig_DATA = mint.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc
 DISTCLEANFILES = mono-2.pc mono.pc mint.pc dotnet.pc dotnet35.pc wcf.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc system.web.extensions_1.0.pc \
-		system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc
+		system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc $(SGENPCFILE)
 
 mono_DATA = config \
 	     browscap.ini
@@ -349,6 +351,8 @@ mint.pc: $(top_builddir)/config.status $(srcdir)/mint.pc.in
 	cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@
 mono-2.pc: $(top_builddir)/config.status $(srcdir)/mono-2.pc.in
 	cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@
+monosgen-2.pc: $(top_builddir)/config.status $(srcdir)/monosgen-2.pc.in
+	cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@
 mono.pc: $(top_builddir)/config.status $(srcdir)/mono.pc.in
 	cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@
 mono-cairo.pc: $(top_builddir)/config.status $(srcdir)/mono-cairo.pc.in
diff --git a/data/gdb/mono-gdb.py b/data/gdb/mono-gdb.py
index 1ce7e6e..b53f197 100644
--- a/data/gdb/mono-gdb.py
+++ b/data/gdb/mono-gdb.py
@@ -288,6 +288,8 @@ def lookup_pretty_printer(val):
         return ObjectPrinter (val)    
     if t == "string":
         return StringPrinter (val)
+    if t == "MonoString *":
+        return StringPrinter (val)
     if t == "MonoMethod *":
         return MonoMethodPrinter (val)
     if t == "MonoClass *":
diff --git a/data/monosgen-2.pc.in b/data/monosgen-2.pc.in
new file mode 100644
index 0000000..a6ba571
--- /dev/null
+++ b/data/monosgen-2.pc.in
@@ -0,0 +1,11 @@
+prefix=${pcfiledir}/../..
+exec_prefix=${pcfiledir}/../..
+libdir=${prefix}/@reloc_libdir@
+includedir=${prefix}/include/mono- at API_VER@
+sysconfdir=@sysconfdir@
+
+Name: Mono
+Description: Mono Runtime
+Version: @VERSION@
+Libs: -L${libdir} @export_ldflags@ -lmonosgen- at API_VER@ @libmono_ldflags@
+Cflags: -I${includedir} @libmono_cflags@
diff --git a/data/net_2_0/ChangeLog b/data/net_2_0/ChangeLog
index 18e0ca0..ba417db 100644
--- a/data/net_2_0/ChangeLog
+++ b/data/net_2_0/ChangeLog
@@ -1,3 +1,8 @@
+2011-01-25  Marek Habersack  <grendel at twistedcode.net>
+
+	[machine.config] Added the <system.transactions> section
+	definition
+
 2010-11-19  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
 
 	Web service help fix
diff --git a/data/net_2_0/machine.config b/data/net_2_0/machine.config
index 5d6e736..73ddbb8 100644
--- a/data/net_2_0/machine.config
+++ b/data/net_2_0/machine.config
@@ -84,6 +84,10 @@
 			<section name="serviceHostingEnvironment" type="System.ServiceModel.Configuration.ServiceHostingEnvironmentSection, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
 			<section name="services" type="System.ServiceModel.Configuration.ServicesSection, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
 		</sectionGroup>
+		<sectionGroup name="system.transactions" type="System.Transactions.Configuration.TransactionsSectionGroup, System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null">
+			<section name="defaultSettings" type="System.Transactions.Configuration.DefaultSettingsSection, System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null"/>
+			<section name="machineSettings" type="System.Transactions.Configuration.MachineSettingsSection, System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null" allowDefinition="MachineOnly" allowExeDefinition="MachineOnly"/>
+		</sectionGroup>
 		<section name="system.webServer" type="System.Configuration.IgnoreSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
 		<section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
 	</configSections>
diff --git a/data/net_4_0/ChangeLog b/data/net_4_0/ChangeLog
index e431d5e..9e1baf3 100644
--- a/data/net_4_0/ChangeLog
+++ b/data/net_4_0/ChangeLog
@@ -1,3 +1,8 @@
+2011-01-25  Marek Habersack  <grendel at twistedcode.net>
+
+	[machine.config] Added the <system.transactions> section
+	definition
+
 2010-12-13  Marek Habersack  <grendel at twistedcode.net>
 
 	[asp.net] .NET 4.0 declares the <system.web.extensions> section in
diff --git a/data/net_4_0/machine.config b/data/net_4_0/machine.config
index 6e6db73..2957a3c 100644
--- a/data/net_4_0/machine.config
+++ b/data/net_4_0/machine.config
@@ -98,6 +98,10 @@
 			<section name="routing" type="System.ServiceModel.Routing.Configuration.RoutingSection, System.ServiceModel.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
 			<section name="protocolMapping" type="System.ServiceModel.Configuration.ProtocolMappingSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
 		</sectionGroup>
+		<sectionGroup name="system.transactions" type="System.Transactions.Configuration.TransactionsSectionGroup, System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null">
+			<section name="defaultSettings" type="System.Transactions.Configuration.DefaultSettingsSection, System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null"/>
+			<section name="machineSettings" type="System.Transactions.Configuration.MachineSettingsSection, System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null" allowDefinition="MachineOnly" allowExeDefinition="MachineOnly"/>
+		</sectionGroup>
 		<section name="system.webServer" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
 		<section name="uri" type="System.Configuration.UriSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
 		<sectionGroup name="system.runtime.caching" type="System.Runtime.Caching.Configuration.CachingSectionGroup, System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
diff --git a/eglib/ChangeLog b/eglib/ChangeLog
index f66a9e2..f31ea41 100644
--- a/eglib/ChangeLog
+++ b/eglib/ChangeLog
@@ -1,3 +1,22 @@
+2011-02-07  Hib Eris  <hib at hiberis.nl>
+
+	Do not distribute eglib-config.h
+
+	The file eglib-config.h is generated when running configure.
+	Distributing eglib-config.h in tarballs causes errors when
+	building out of the source tree.
+
+2011-02-07  Hib Eris  <hib at hiberis.nl>
+
+	Use _vscprintf() for mingw-w64 compilers
+
+	The mingw-w64 compilers implement a vsnprintf() function that do
+	not conform to the C99 standard (just like MSVC).
+
+2011-02-07  Zoltan Varga  <vargaz at gmail.com>
+
+	Include sys/types.h for pid_t on mingw. Fixes #670076.
+
 2011-01-11  Christian Hergert  <chris at dronelabs.com>
 
 	Fix broken g_int_hash/g_int_equal semantics
diff --git a/eglib/configure b/eglib/configure
index b16b2de..5e43570 100755
--- a/eglib/configure
+++ b/eglib/configure
@@ -13306,7 +13306,8 @@ fi
 
 
 
-for ac_header in getopt.h sys/time.h sys/wait.h pwd.h langinfo.h iconv.h localcharset.h
+
+for ac_header in getopt.h sys/time.h sys/wait.h pwd.h langinfo.h iconv.h localcharset.h sys/types.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 7d52c70..659a4f6 100644
--- a/eglib/configure.ac
+++ b/eglib/configure.ac
@@ -126,7 +126,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 localcharset.h)
+AC_CHECK_HEADERS(getopt.h sys/time.h sys/wait.h pwd.h langinfo.h iconv.h localcharset.h sys/types.h)
 AC_CHECK_HEADER(alloca.h, [HAVE_ALLOCA_H=1], [HAVE_ALLOCA_H=0])
 AC_SUBST(HAVE_ALLOCA_H)
 
diff --git a/eglib/src/Makefile.am b/eglib/src/Makefile.am
index 189d698..6ef2c53 100644
--- a/eglib/src/Makefile.am
+++ b/eglib/src/Makefile.am
@@ -24,7 +24,6 @@ os_files = $(unix_files)
 endif
 
 libeglib_la_SOURCES = \
-	eglib-config.h	\
 	eglib-remap.h	\
 	sort.frag.h	\
 	glib.h	     	\
diff --git a/eglib/src/Makefile.in b/eglib/src/Makefile.in
index 8d283e6..c8e8696 100644
--- a/eglib/src/Makefile.in
+++ b/eglib/src/Makefile.in
@@ -48,15 +48,15 @@ LTLIBRARIES = $(noinst_LTLIBRARIES)
 am__DEPENDENCIES_1 =
 @HOST_WIN32_TRUE at am__DEPENDENCIES_2 = $(am__DEPENDENCIES_1)
 libeglib_static_la_DEPENDENCIES = $(am__DEPENDENCIES_2)
-am__libeglib_static_la_SOURCES_DIST = eglib-config.h eglib-remap.h \
-	sort.frag.h glib.h garray.c gbytearray.c gerror.c ghashtable.c \
-	gmem.c gmodule.h goutput.c gstr.c gslist.c gstring.c \
-	gptrarray.c glist.c gqueue.c gpath.c gshell.c gspawn.c gfile.c \
-	gfile-posix.c gpattern.c gmarkup.c gutf8.c gunicode.c \
-	unicode-data.h gdate-unix.c gdir-unix.c gfile-unix.c \
-	gmisc-unix.c gmodule-unix.c gtimer-unix.c eglib-config.hw \
-	gdate-win32.c gdir-win32.c gfile-win32.c gmisc-win32.c \
-	gmodule-win32.c gtimer-win32.c vasprintf.c
+am__libeglib_static_la_SOURCES_DIST = eglib-remap.h sort.frag.h glib.h \
+	garray.c gbytearray.c gerror.c ghashtable.c gmem.c gmodule.h \
+	goutput.c gstr.c gslist.c gstring.c gptrarray.c glist.c \
+	gqueue.c gpath.c gshell.c gspawn.c gfile.c gfile-posix.c \
+	gpattern.c gmarkup.c gutf8.c gunicode.c unicode-data.h \
+	gdate-unix.c gdir-unix.c gfile-unix.c gmisc-unix.c \
+	gmodule-unix.c gtimer-unix.c eglib-config.hw gdate-win32.c \
+	gdir-win32.c gfile-win32.c gmisc-win32.c gmodule-win32.c \
+	gtimer-win32.c vasprintf.c
 am__objects_1 = libeglib_static_la-gdate-unix.lo \
 	libeglib_static_la-gdir-unix.lo \
 	libeglib_static_la-gfile-unix.lo \
@@ -91,15 +91,15 @@ libeglib_static_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \
 	$(libeglib_static_la_CFLAGS) $(CFLAGS) \
 	$(libeglib_static_la_LDFLAGS) $(LDFLAGS) -o $@
 @HOST_WIN32_TRUE at libeglib_la_DEPENDENCIES = $(am__DEPENDENCIES_1)
-am__libeglib_la_SOURCES_DIST = eglib-config.h eglib-remap.h \
-	sort.frag.h glib.h garray.c gbytearray.c gerror.c ghashtable.c \
-	gmem.c gmodule.h goutput.c gstr.c gslist.c gstring.c \
-	gptrarray.c glist.c gqueue.c gpath.c gshell.c gspawn.c gfile.c \
-	gfile-posix.c gpattern.c gmarkup.c gutf8.c gunicode.c \
-	unicode-data.h gdate-unix.c gdir-unix.c gfile-unix.c \
-	gmisc-unix.c gmodule-unix.c gtimer-unix.c eglib-config.hw \
-	gdate-win32.c gdir-win32.c gfile-win32.c gmisc-win32.c \
-	gmodule-win32.c gtimer-win32.c vasprintf.c
+am__libeglib_la_SOURCES_DIST = eglib-remap.h sort.frag.h glib.h \
+	garray.c gbytearray.c gerror.c ghashtable.c gmem.c gmodule.h \
+	goutput.c gstr.c gslist.c gstring.c gptrarray.c glist.c \
+	gqueue.c gpath.c gshell.c gspawn.c gfile.c gfile-posix.c \
+	gpattern.c gmarkup.c gutf8.c gunicode.c unicode-data.h \
+	gdate-unix.c gdir-unix.c gfile-unix.c gmisc-unix.c \
+	gmodule-unix.c gtimer-unix.c eglib-config.hw gdate-win32.c \
+	gdir-win32.c gfile-win32.c gmisc-win32.c gmodule-win32.c \
+	gtimer-win32.c vasprintf.c
 am__objects_6 = libeglib_la-gdate-unix.lo libeglib_la-gdir-unix.lo \
 	libeglib_la-gfile-unix.lo libeglib_la-gmisc-unix.lo \
 	libeglib_la-gmodule-unix.lo libeglib_la-gtimer-unix.lo
@@ -296,7 +296,6 @@ unix_files = \
 @HOST_WIN32_FALSE at os_files = $(unix_files)
 @HOST_WIN32_TRUE at os_files = $(win_files)
 libeglib_la_SOURCES = \
-	eglib-config.h	\
 	eglib-remap.h	\
 	sort.frag.h	\
 	glib.h	     	\
diff --git a/eglib/src/eglib-config.h b/eglib/src/eglib-config.h
deleted file mode 100644
index e3ff6ed..0000000
--- a/eglib/src/eglib-config.h
+++ /dev/null
@@ -1,45 +0,0 @@
-#ifndef __EGLIB_CONFIG_H
-#define __EGLIB_CONFIG_H
-
-/*
- * System-dependent settings
- */
-#define G_GNUC_PRETTY_FUNCTION   
-#define G_GNUC_UNUSED            __attribute__((__unused__))
-#define G_BYTE_ORDER             G_LITTLE_ENDIAN
-#define G_GNUC_NORETURN          __attribute__((__noreturn__))
-#define G_SEARCHPATH_SEPARATOR_S ":"
-#define G_SEARCHPATH_SEPARATOR   ':'
-#define G_DIR_SEPARATOR          '/'
-#define G_DIR_SEPARATOR_S        "/"
-#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))
-#define GINT_TO_POINTER(v)     ((gpointer)(glong) (v))
-#define GUINT_TO_POINTER(v)    ((gpointer)(gulong) (v))
-
-#if 1 == 1
-#define G_HAVE_ALLOCA_H
-#endif
-
-typedef unsigned long gsize;
-typedef signed   long gssize;
-
-#define G_GSIZE_FORMAT   "lu"
-#define G_GUINT64_FORMAT "lu"
-#define G_GINT64_FORMAT "ld"
-
-#if 1 == 1
-#define G_HAVE_ISO_VARARGS
-#endif
-
-#if defined (__native_client__)
-#define sem_trywait(x) sem_wait(x)
-#define sem_timedwait(x,y) sem_wait(x)
-#define getdtablesize() (32768)
-#undef G_BREAKPOINT
-#define G_BREAKPOINT()
-#endif
-
-#endif
diff --git a/eglib/src/glib.h b/eglib/src/glib.h
index 8b6082e..3485015 100644
--- a/eglib/src/glib.h
+++ b/eglib/src/glib.h
@@ -16,6 +16,10 @@
 /* For pid_t */
 #ifndef WIN32
 #include <unistd.h>
+#else
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
 #endif
 #endif
 
diff --git a/eglib/src/vasprintf.c b/eglib/src/vasprintf.c
index 8699df2..56e1971 100644
--- a/eglib/src/vasprintf.c
+++ b/eglib/src/vasprintf.c
@@ -9,7 +9,7 @@ int vasprintf(char **ret, const char *fmt, va_list ap)
 	size_t buflen;
 	va_list ap2;
 	
-#ifdef _MSC_VER
+#if defined(_MSC_VER) || defined(__MINGW64_VERSION_MAJOR)
 	ap2 = ap;
 	len = _vscprintf(fmt, ap2); // NOTE MS specific extension ( :-( )
 #else
diff --git a/man/ChangeLog b/man/ChangeLog
index c58a084..11ca174 100644
--- a/man/ChangeLog
+++ b/man/ChangeLog
@@ -1,3 +1,15 @@
+2011-01-30  Miguel de Icaza  <miguel at gnome.org>
+
+	[repl] Add support for -e EXPRESSION to the csharp command
+
+2011-01-30  Miguel de Icaza  <miguel at gnome.org>
+
+	Document csharp #! support
+
+2011-01-19  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	Document precise marking
+
 2011-01-17  Marek Safar  <marek.safar at gmail.com>
 
 	Add new mcs -sdk option
diff --git a/man/csharp.1 b/man/csharp.1
index 2f6497d..50cbdc8 100644
--- a/man/csharp.1
+++ b/man/csharp.1
@@ -6,7 +6,7 @@
 .SH NAME 
 csharp, gsharp \- Interactive C# Shell 
 .SH SYNOPSIS
-.B csharp [--attach PID] [file1 [file2]]
+.B csharp [--attach PID] [-e EXPRESSION] [file1 [file2]]
 [options] 
 .P
 .B gsharp [file1 [file2]]
@@ -29,7 +29,22 @@ target process.
 .PP
 Files specified in the command line will be loaded and executed as
 scripts.
+.PP
+Starting with Mono 2.10, the 
+.I csharp
+command can be used as an interpreter executed by executables flagged
+with the Unix execute attribute.   To do this, make the first line of
+your C# source code look like this:
+.nf
+"#!/usr/bin/csharp" 
+Console.WriteLine ("Hello, World");
+.fi
 .SH OPTIONS
+The commands accept all of the commands that are available to the 
+.I mcs
+command, so you can reference assemblies, specify paths, language
+level and so on from the command line.   In addition, the following
+command line options are supported:
 .TP 
 .I "\-\-attach"
 This is an advanced option and should only be used if you have a deep
@@ -42,6 +57,9 @@ special measures to avoid crashing the target application while using
 it.  For example, you might have to take the proper locks before
 issuing any commands that might affect the target process state, or
 sending commands through a method dispatcher.     
+.TP 
+.I "\-e" EXPRESSION
+This will evaluate the specified C# EXPRESSION and exit
 .SH OPERATION
 Once you launch the csharp command, you will be greeted with the
 interactive prompt:
diff --git a/man/mono.1 b/man/mono.1
index 08b3012..88bd2ed 100644
--- a/man/mono.1
+++ b/man/mono.1
@@ -1021,6 +1021,16 @@ Enables or disables concurrent sweep for the Mark&Sweep collector.  If
 enabled, the sweep phase of the garbage collection is done in a thread
 concurrently with the application.  Concurrent sweep is disabled by
 default.
+.TP
+\fBstack-mark=\fImark-mode\fR
+Specifies how application threads should be scanned. Options are
+`precise` and `conservative`. Precise marking allow the collector
+to know what values on stack are references and what are not.
+Conservative marking threats all values as potentially references
+and leave them untouched. Precise marking reduces floating garbage
+and can speed up nursery collection and allocation rate, it has
+the downside of requiring a significant extra memory per compiled
+method. The right option, unfortunately, requires experimentation.
 .ne
 .RE
 .TP
diff --git a/mcs/class/ChangeLog b/mcs/class/ChangeLog
index afe9ab0..1fc3f80 100644
--- a/mcs/class/ChangeLog
+++ b/mcs/class/ChangeLog
@@ -1,3 +1,112 @@
+2011-02-01  Atsushi Eno  <atsushi at ximian.com>
+
+	quick build workaround.
+
+2011-02-01  Atsushi Eno  <atsushi at ximian.com>
+
+	in NET_4_0, remove types that went into System.Xaml.dll. Change
+	build order.
+
+2011-01-27  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Leave db connection opened until requested to close it and add
+	more unit tests
+
+2011-01-25  Miguel de Icaza  <miguel at gnome.org>
+
+	Restoring some of the formal beauty of this text document as we
+	carefully restore the missing tabs that helped carefully align the
+	continuation characters in a list of assemblies.
+
+	As we align these newline separators, suddenly, a new form emerges
+	from the chaos, something that gives us the illusion that this
+	stream of bytes is indeed almost like a dawn of a new day as we
+	breathe the air in a valley overlooking a beautiful mountain at
+	the beginning of the spring.
+
+2011-01-25  Marek Habersack  <grendel at twistedcode.net>
+
+	[wcf] Install the System.Data.Services.Client properly.
+
+2011-01-22  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Add unit test for Database
+
+2011-01-22  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Add unit tests for DynamicRecord
+
+2011-01-22  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Just fixup comment
+
+2011-01-21  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Add GetLastInsertId
+
+2011-01-21  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Foobar trigger connection
+
+2011-01-21  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Add Close method
+
+2011-01-21  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Add ConnectionOpened event to Database
+
+2011-01-21  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Fix up compilation of Database and DynamicRecord
+
+2011-01-21  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Add Dispose calls to Database
+
+2011-01-21  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Add Database type
+
+2011-01-21  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Complete base DynamicRecord API
+
+2011-01-21  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Stub DynamicRecord
+
+2011-01-21  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Add WebMatrix.Data assembly skeleton
+
+2011-01-20  Andrew Jorgensen  <ajorgensen at novell.com>
+
+	remove conflict marker
+
+2011-01-19  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net,mvc] Make unobtrustive request validation in MVC v3
+	possible
+
+	Validation is enabled early in the pipeline during request.
+	ValidationUtility makes sure that validation is indeed enabled and
+	replaces the default form and query string collections with a lazy
+	version which will validate values only when an existing key is
+	found and requested.
+
+2011-01-17  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] ValidationUtility implementation
+
+2011-01-17  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Implemented dynamic HTTP module registration
+
+2011-01-13  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Added the Microsoft.Web.Infrastructure assembly
+
 2011-01-17  Marek Safar  <marek.safar at gmail.com>
 
 	Update IKVM.Reflection
diff --git a/mcs/class/Makefile b/mcs/class/Makefile
index 63bc061..fe5faa7 100644
--- a/mcs/class/Makefile
+++ b/mcs/class/Makefile
@@ -102,15 +102,15 @@ net_2_0_dirs := \
 	Mono.Tasklets       		\
 	Mono.CSharp			\
 	Moonlight.Build.Tasks		\
-	WindowsBase			\
-	System.Data.Services	\
-	System.Data.Services.Client \
+	System.Data.Services		\
 	System.Net
 
 net_2_0_only_dirs := \
 	System.Web.Extensions_1.0	\
 	System.Web.Extensions.Design_1.0	\
-	Compat.ICSharpCode.SharpZipLib
+	Compat.ICSharpCode.SharpZipLib	\
+	WindowsBase			\
+	System.Data.Services.Client
 
 moonlight_dirs := \
 	corlib			\
@@ -159,11 +159,15 @@ net_4_0_dirs := \
 	System.Windows.Forms.DataVisualization	\
 	System.ComponentModel.Composition \
 	System.Xaml \
+	WindowsBase \
+	System.Data.Services.Client \
 	System.ServiceModel.Routing \
 	System.ServiceModel.Discovery \
 	System.Runtime.Caching \
 	System.Runtime.DurableInstancing \
-	Mono.CodeContracts
+	Mono.CodeContracts \
+	Microsoft.Web.Infrastructure \
+	WebMatrix.Data
 
 net_2_0_SUBDIRS := $(common_dirs) $(net_2_0_dirs) $(net_2_0_only_dirs)
 moonlight_raw_SUBDIRS := $(moonlight_dirs)
diff --git a/mcs/class/Managed.Windows.Forms/System.Windows.Forms.CarbonInternal/ChangeLog b/mcs/class/Managed.Windows.Forms/System.Windows.Forms.CarbonInternal/ChangeLog
index 89dca72..674dfe9 100644
--- a/mcs/class/Managed.Windows.Forms/System.Windows.Forms.CarbonInternal/ChangeLog
+++ b/mcs/class/Managed.Windows.Forms/System.Windows.Forms.CarbonInternal/ChangeLog
@@ -1,3 +1,7 @@
+2011-02-01  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Avoid a stack overflow when deactivating a window
+
 2010-09-07  Atsushi Eno  <atsushi at ximian.com>
 
 	Avoid crash for use of deprecated InstallTrackingHandler in Snow
diff --git a/mcs/class/Managed.Windows.Forms/System.Windows.Forms.CarbonInternal/WindowHandler.cs b/mcs/class/Managed.Windows.Forms/System.Windows.Forms.CarbonInternal/WindowHandler.cs
index bfac5dd..0bd4320 100644
--- a/mcs/class/Managed.Windows.Forms/System.Windows.Forms.CarbonInternal/WindowHandler.cs
+++ b/mcs/class/Managed.Windows.Forms/System.Windows.Forms.CarbonInternal/WindowHandler.cs
@@ -148,7 +148,7 @@ namespace System.Windows.Forms.CarbonInternal {
 						Control c = Control.FromHandle (hwnd.client_window);
 						if (c != null) {
 							Form form = c.FindForm ();
-							if (form != null) {
+							if (form != null && XplatUICarbon.UnactiveWindow != form.Handle) {
 								Driver.SendMessage (form.Handle, Msg.WM_ACTIVATE, (IntPtr) WindowActiveFlags.WA_INACTIVE, IntPtr.Zero);
 								XplatUICarbon.ActiveWindow = IntPtr.Zero;
 							}
diff --git a/mcs/class/Managed.Windows.Forms/System.Windows.Forms/ChangeLog b/mcs/class/Managed.Windows.Forms/System.Windows.Forms/ChangeLog
index e7e312a..d8fdd98 100644
--- a/mcs/class/Managed.Windows.Forms/System.Windows.Forms/ChangeLog
+++ b/mcs/class/Managed.Windows.Forms/System.Windows.Forms/ChangeLog
@@ -1,3 +1,12 @@
+2011-02-11  Miguel de Icaza  <miguel at gnome.org>
+
+	[fix] changing Form.Enabled sometimes can change the list of
+	OpenForms, fixes 671098
+
+2011-02-01  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Avoid a stack overflow when deactivating a window
+
 2011-01-06  Thomas Goldstein  <stifu at free.fr>
 
 	Replace decimal to hex string conversion code with a much more
diff --git a/mcs/class/Managed.Windows.Forms/System.Windows.Forms/Form.cs b/mcs/class/Managed.Windows.Forms/System.Windows.Forms/Form.cs
index 2ef8c7f..9fc4c25 100644
--- a/mcs/class/Managed.Windows.Forms/System.Windows.Forms/Form.cs
+++ b/mcs/class/Managed.Windows.Forms/System.Windows.Forms/Form.cs
@@ -33,6 +33,7 @@ using System.ComponentModel.Design.Serialization;
 using System.Collections;
 using System.Runtime.InteropServices;
 using System.Threading;
+using System.Collections.Generic;
 
 namespace System.Windows.Forms {
 	[DesignerCategory("Form")]
@@ -1792,13 +1793,13 @@ namespace System.Windows.Forms {
 				XplatUI.UngrabWindow(capture_window);
 			}
 
+			var disable = new List<Form> ();
 			foreach (Form form in Application.OpenForms)
-			{
-				if (form.Enabled == true)
-				{
-					disabled_by_showdialog.Add(form);
-					form.Enabled = false;
-				}
+				if (form.Enabled)
+					disable.Add (form);
+			foreach (Form form in disable){
+				disabled_by_showdialog.Add (form);
+				form.Enabled = false;
 			}
 			modal_dialogs.Add(this);
 
diff --git a/mcs/class/Managed.Windows.Forms/System.Windows.Forms/XplatUICarbon.cs b/mcs/class/Managed.Windows.Forms/System.Windows.Forms/XplatUICarbon.cs
index 0241dc6..47e0c9f 100644
--- a/mcs/class/Managed.Windows.Forms/System.Windows.Forms/XplatUICarbon.cs
+++ b/mcs/class/Managed.Windows.Forms/System.Windows.Forms/XplatUICarbon.cs
@@ -48,6 +48,7 @@ namespace System.Windows.Forms {
 		// Internal members available to the event handler sub-system
 		internal static IntPtr FocusWindow;
 		internal static IntPtr ActiveWindow;
+		internal static IntPtr UnactiveWindow;
 		internal static IntPtr ReverseWindow;
 		internal static IntPtr CaretWindow;
 
@@ -785,6 +786,7 @@ namespace System.Windows.Forms {
 
 		internal override void Activate(IntPtr handle) {
 			if (ActiveWindow != IntPtr.Zero) {
+				UnactiveWindow = ActiveWindow;
 				ActivateWindow (HIViewGetWindow (ActiveWindow), false);
 			}
 			ActivateWindow (HIViewGetWindow (handle), true);
diff --git a/mcs/class/Microsoft.Build.Engine/ChangeLog b/mcs/class/Microsoft.Build.Engine/ChangeLog
index e0b67ba..e7c2333 100644
--- a/mcs/class/Microsoft.Build.Engine/ChangeLog
+++ b/mcs/class/Microsoft.Build.Engine/ChangeLog
@@ -1,3 +1,17 @@
+2011-02-11  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Update Utilities.FromMSBuildPath from monodevelop.
+
+	Updating FromMSBuildPath also fixes a bug on windows.
+
+2011-01-26  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Improve error messages for condition evaluation.
+
+	Also, add new ExpressionEvaluationException class. Wrap
+	Expression*Exceptions in InvalidProjectFileException with info
+	about the full condition being evaluated.
+
 2011-01-11  Ankit Jain  <radical at corewars.org>
 
 	[xbuild] Fix bug #663180, second part.
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildItem.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildItem.cs
index a4a0ac6..a706ad3 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildItem.cs
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildItem.cs
@@ -64,7 +64,7 @@ namespace Microsoft.Build.BuildEngine {
 
 			this.name = itemName;
 			this.finalItemSpec = taskItem.ItemSpec;
-			this.itemInclude = Utilities.Escape (taskItem.ItemSpec);
+			this.itemInclude = MSBuildUtils.Escape (taskItem.ItemSpec);
 			this.evaluatedMetadata = (Hashtable) taskItem.CloneCustomMetadata ();
 			this.unevaluatedMetadata = (Hashtable) taskItem.CloneCustomMetadata ();
 		}
@@ -127,7 +127,7 @@ namespace Microsoft.Build.BuildEngine {
 		{
 			if (ReservedNameUtils.IsReservedMetadataName (metadataName)) {
 				string metadata = ReservedNameUtils.GetReservedMetadata (FinalItemSpec, metadataName, evaluatedMetadata);
-				return (metadataName.ToLower () == "fullpath") ? Utilities.Escape (metadata) : metadata;
+				return (metadataName.ToLower () == "fullpath") ? MSBuildUtils.Escape (metadata) : metadata;
 			}
 
 			if (evaluatedMetadata.Contains (metadataName))
@@ -140,7 +140,7 @@ namespace Microsoft.Build.BuildEngine {
 		{
 			if (ReservedNameUtils.IsReservedMetadataName (metadataName)) {
 				string metadata = ReservedNameUtils.GetReservedMetadata (FinalItemSpec, metadataName, unevaluatedMetadata);
-				return (metadataName.ToLower () == "fullpath") ? Utilities.Escape (metadata) : metadata;
+				return (metadataName.ToLower () == "fullpath") ? MSBuildUtils.Escape (metadata) : metadata;
 			} else if (unevaluatedMetadata.Contains (metadataName))
 				return (string) unevaluatedMetadata [metadataName];
 			else
@@ -199,7 +199,7 @@ namespace Microsoft.Build.BuildEngine {
 					metadataName));
 
 			if (treatMetadataValueAsLiteral && !HasParentItem)
-				metadataValue = Utilities.Escape (metadataValue);
+				metadataValue = MSBuildUtils.Escape (metadataValue);
 
 			if (FromXml) {
 				XmlElement element = itemElement [metadataName];
@@ -231,7 +231,7 @@ namespace Microsoft.Build.BuildEngine {
 				evaluatedMetadata [name] = (string) e.ConvertTo (parent_item_group.ParentProject,
 						typeof (string), ExpressionOptions.ExpandItemRefs);
 			} else
-				evaluatedMetadata [name] = Utilities.Unescape (value);
+				evaluatedMetadata [name] = MSBuildUtils.Unescape (value);
 				
 			unevaluatedMetadata [name] = value;
 		}
@@ -247,9 +247,9 @@ namespace Microsoft.Build.BuildEngine {
 
 		internal void Evaluate (Project project, bool evaluatedTo)
 		{
-			// FIXME: maybe make Expression.ConvertTo (null, ...) work as Utilities.Unescape ()?
+			// FIXME: maybe make Expression.ConvertTo (null, ...) work as MSBuildUtils.Unescape ()?
 			if (project == null) {
-				this.finalItemSpec = Utilities.Unescape (Include);
+				this.finalItemSpec = MSBuildUtils.Unescape (Include);
 				return;
 			}
 			
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildProperty.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildProperty.cs
index 3256311..62caeda 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildProperty.cs
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildProperty.cs
@@ -35,6 +35,7 @@ using System.Xml;
 
 using Microsoft.Build.Framework;
 using Microsoft.Build.Utilities;
+using Mono.XBuild.Utilities;
 
 namespace Microsoft.Build.BuildEngine {
 	public class BuildProperty {
@@ -80,7 +81,7 @@ namespace Microsoft.Build.BuildEngine {
 			this.propertyType = PropertyType.Normal;
 			this.parentProject = parentProject;
 			this.name = propertyElement.Name;
-			this.value = Utilities.UnescapeFromXml (propertyElement.InnerXml);
+			this.value = MSBuildUtils.UnescapeFromXml (propertyElement.InnerXml);
 			this.isImported = false;
 		}
 
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ChangeLog b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ChangeLog
index 55cd142..aaf93bc 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ChangeLog
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ChangeLog
@@ -1,3 +1,35 @@
+2011-02-11  Ankit Jain  <radical at corewars.org>
+
+	* Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Utilities.cs:
+	Move to.. *
+	Microsoft.Build.Utilities/Mono.XBuild.Utilities/MSBuildUtils.cs:
+	.. this. Also, update FromMSBuildPath from monodevelop. * Update
+	Engine/* and Tasks/* to track the new api.
+
+2011-02-02  Ankit Jain  <radical at corewars.org>
+
+	*
+	class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Project.cs
+	(GetToolsVersionToUse): Add a 'emitWarning' bool param. (Build):
+	Call GetToolsVersionToUse () to ensure that a warning is emitted
+	in case of a unknown tools version.
+
+2011-01-26  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Improve error messages for condition evaluation.
+
+	Also, add new ExpressionEvaluationException class. Wrap
+	Expression*Exceptions in InvalidProjectFileException with info
+	about the full condition being evaluated.
+
+2011-01-26  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Support short-circuiting in conditions.
+
+2011-01-14  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Error out, if no target is found in a project.
+
 2011-01-14  Ankit Jain  <radical at corewars.org>
 
 	[xbuild] Use the backing field directly to avoid evaluating again.
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConditionAndExpression.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConditionAndExpression.cs
index 326e055..55c40d8 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConditionAndExpression.cs
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConditionAndExpression.cs
@@ -72,7 +72,9 @@ namespace Microsoft.Build.BuildEngine {
 		
 		public override bool CanEvaluateToBool (Project context)
 		{
-			return left.CanEvaluateToBool (context) && right.CanEvaluateToBool (context);
+			// Short-circuiting, check only left expr, right
+			// would be required only if left == true
+			return left.CanEvaluateToBool (context);
 		}
 		
 		public override bool CanEvaluateToNumber (Project context)
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConditionFactorExpresion.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConditionFactorExpresion.cs
index 07c8378..9f8f6c6 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConditionFactorExpresion.cs
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConditionFactorExpresion.cs
@@ -77,7 +77,9 @@ namespace Microsoft.Build.BuildEngine {
 			else if (falseValues [evaluatedToken.Value] != null)
 				return false;
 			else
-				throw new InvalidProjectFileException ();
+				throw new ExpressionEvaluationException (
+						String.Format ("Expression \"{0}\" evaluated to \"{1}\" instead of a boolean value",
+								token.Value, evaluatedToken.Value));
 		}
 		
 		public override float NumberEvaluate (Project context)
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConditionParser.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConditionParser.cs
index a0cce01..f1a2ae6 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConditionParser.cs
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConditionParser.cs
@@ -53,12 +53,22 @@ namespace Microsoft.Build.BuildEngine {
 			if (String.IsNullOrEmpty (condition))
 				return true;
 
-			ConditionExpression ce = ParseCondition (condition);
+			try {
+				ConditionExpression ce = ParseCondition (condition);
 
-			if (!ce.CanEvaluateToBool (context))
-				throw new InvalidProjectFileException (String.Format ("Can not evaluate \"{0}\" to bool.", condition));
+				if (!ce.CanEvaluateToBool (context))
+					throw new InvalidProjectFileException (String.Format ("Can not evaluate \"{0}\" to bool.", condition));
 
-			return ce.BoolEvaluate (context);
+				return ce.BoolEvaluate (context);
+			} catch (ExpressionParseException epe) {
+				throw new InvalidProjectFileException (
+						String.Format ("Unable to parse condition \"{0}\" : {1}", condition, epe.Message),
+						epe);
+			} catch (ExpressionEvaluationException epe) {
+				throw new InvalidProjectFileException (
+						String.Format ("Unable to evaluate condition \"{0}\" : {1}", condition, epe.Message),
+						epe);
+			}
 		}
 
 		public static ConditionExpression ParseCondition (string condition)
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Expression.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Expression.cs
index 7d4efa5..bbda1ac 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Expression.cs
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Expression.cs
@@ -33,6 +33,7 @@ using System.Collections;
 using System.Collections.Generic;
 using System.Text;
 using System.Text.RegularExpressions;
+using Mono.XBuild.Utilities;
 
 namespace Microsoft.Build.BuildEngine {
 
@@ -131,7 +132,7 @@ namespace Microsoft.Build.BuildEngine {
 			for (int i = 0; i < lists.Count; i++) {
 				foreach (object o in lists [i]) {
 					if (o is string)
-						expressionCollection.Add (Utilities.Unescape ((string) o));
+						expressionCollection.Add (MSBuildUtils.Unescape ((string) o));
 					else if (!allowItems && o is ItemReference)
 						expressionCollection.Add (((ItemReference) o).OriginalString);
 					else if (!allowMd && o is MetadataReference) {
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ExpressionEvaluationException.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ExpressionEvaluationException.cs
new file mode 100644
index 0000000..e08c148
--- /dev/null
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ExpressionEvaluationException.cs
@@ -0,0 +1,61 @@
+//
+// ExpressionEvaluationException.cs
+//
+// Author:
+//   Ankit Jain (jankit at novell.com)
+//
+// Copyright 2011 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.
+
+#if NET_2_0
+
+using System;
+using System.Runtime.Serialization;
+
+namespace Microsoft.Build.BuildEngine {
+	[Serializable]
+	internal class ExpressionEvaluationException : Exception {
+
+		public ExpressionEvaluationException ()
+			: base ("Exception occured when evaluating the expression.")
+		{
+		}
+
+		public ExpressionEvaluationException (string message)
+			: base (message)
+		{
+		}
+
+		public ExpressionEvaluationException (string message,
+					Exception innerException)
+			: base (message, innerException)
+		{
+		}
+
+		protected ExpressionEvaluationException (SerializationInfo info,
+					   StreamingContext context)
+			: base (info, context)
+		{
+		}
+	}
+}
+
+#endif
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Import.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Import.cs
index 9c595a0..e77209c 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Import.cs
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Import.cs
@@ -32,6 +32,7 @@ using System.IO;
 using System.Xml;
 
 using Microsoft.Build.Framework;
+using Mono.XBuild.Utilities;
 
 namespace Microsoft.Build.BuildEngine {
 	public class Import {
@@ -121,7 +122,7 @@ namespace Microsoft.Build.BuildEngine {
 			envvar = String.Join (":", new string [] {
 						// For mac osx, look in the 'External' dir on macosx,
 						// see bug #663180
-						Microsoft.Build.Tasks.Utilities.RunningOnMac ? MacOSXExternalXBuildDir : String.Empty,
+						MSBuildUtils.RunningOnMac ? MacOSXExternalXBuildDir : String.Empty,
 						(envvar ?? String.Empty),
 						DotConfigExtensionsPath});
 
@@ -173,7 +174,7 @@ namespace Microsoft.Build.BuildEngine {
 					file = Path.Combine (dir, EvaluatedProjectPath);
 			}
 			
-			return Utilities.FromMSBuildPath (file);
+			return MSBuildUtils.FromMSBuildPath (file);
 		}
 		
 		public string Condition {
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Project.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Project.cs
index 0b46834..d8f0a92 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Project.cs
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Project.cs
@@ -277,6 +277,11 @@ namespace Microsoft.Build.BuildEngine {
 		{
 			bool result = false;
 			ParentEngine.StartProjectBuild (this, targetNames);
+
+			// Invoking this to emit a warning in case of unsupported
+			// ToolsVersion
+			GetToolsVersionToUse (true);
+
 			string current_directory = Environment.CurrentDirectory;
 			try {
 				current_settings = buildFlags;
@@ -305,12 +310,18 @@ namespace Microsoft.Build.BuildEngine {
 			}
 			
 			if (targetNames == null || targetNames.Length == 0) {
-				if (defaultTargets != null && defaultTargets.Length != 0)
+				if (defaultTargets != null && defaultTargets.Length != 0) {
 					targetNames = defaultTargets;
-				else if (firstTargetName != null)
+				} else if (firstTargetName != null) {
 					targetNames = new string [1] { firstTargetName};
-				else
+				} else {
+					if (targets == null || targets.Count == 0) {
+						LogError (fullFileName, "No target found in the project");
+						return false;
+					}
+
 					return false;
+				}
 			}
 
 			if (!initialTargetsBuilt) {
@@ -805,7 +816,7 @@ namespace Microsoft.Build.BuildEngine {
 			targets = new TargetCollection (this);
 			last_item_group_containing = new Dictionary <string, BuildItemGroup> ();
 			
-			string effective_tools_version = GetToolsVersionToUse ();
+			string effective_tools_version = GetToolsVersionToUse (false);
 			taskDatabase = new TaskDatabase ();
 			taskDatabase.CopyTasks (ParentEngine.GetDefaultTasks (effective_tools_version));
 
@@ -970,7 +981,7 @@ namespace Microsoft.Build.BuildEngine {
 		// ToolsVersion property
 		// ToolsVersion attribute on the project
 		// parentEngine's DefaultToolsVersion
-		string GetToolsVersionToUse ()
+		string GetToolsVersionToUse (bool emitWarning)
 		{
 			if (!String.IsNullOrEmpty (ToolsVersion))
 				return ToolsVersion;
@@ -979,7 +990,8 @@ namespace Microsoft.Build.BuildEngine {
 				return parentEngine.DefaultToolsVersion;
 
 			if (parentEngine.Toolsets [DefaultToolsVersion] == null) {
-				LogWarning (FullFileName, "Project has unknown ToolsVersion '{0}'. Using the default tools version '{1}' instead.",
+				if (emitWarning)
+					LogWarning (FullFileName, "Project has unknown ToolsVersion '{0}'. Using the default tools version '{1}' instead.",
 						DefaultToolsVersion, parentEngine.DefaultToolsVersion);
 				return parentEngine.DefaultToolsVersion;
 			}
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Utilities.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Utilities.cs
index 7fa30bc..235dd2e 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Utilities.cs
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Utilities.cs
@@ -30,154 +30,19 @@
 
 #if NET_2_0
 
-using System;
-using System.Collections;
-using System.IO;
-using System.Text;
+using Mono.XBuild.Utilities;
 
 namespace Microsoft.Build.BuildEngine {
 	public static class Utilities {
-	
-		static Hashtable charsToEscape;
-	
-		static Utilities ()
-		{
-			charsToEscape = new Hashtable ();
-			
-			charsToEscape.Add ('$', null);
-			charsToEscape.Add ('%', null);
-			charsToEscape.Add ('\'', null);
-			charsToEscape.Add ('(', null);
-			charsToEscape.Add (')', null);
-			charsToEscape.Add ('*', null);
-			charsToEscape.Add (';', null);
-			charsToEscape.Add ('?', null);
-			charsToEscape.Add ('@', null);
-		}
-	
-		public static string Escape (string unescapedExpression)
-		{
-			StringBuilder sb = new StringBuilder ();
-			
-			foreach (char c in unescapedExpression) {
-				if (charsToEscape.Contains (c))
-					sb.AppendFormat ("%{0:x2}", (int) c);
-				else
-					sb.Append (c);
-			}
-			
-			return sb.ToString ();
-		}
-		
-		// FIXME: add tests for this
-		internal static string Unescape (string escapedExpression)
-		{
-			StringBuilder sb = new StringBuilder ();
-			
-			int i = 0;
-			while (i < escapedExpression.Length) {
-				sb.Append (Uri.HexUnescape (escapedExpression, ref i));
-			}
-			
-			return sb.ToString ();
-		}
 
-		internal static string UnescapeFromXml (string text)
+		public static string Escape (string unescapedExpression)
 		{
-			StringBuilder sb = new StringBuilder ();
-			for (int i = 0; i < text.Length; i++) {
-				char c1 = text[i];
-				if (c1 == '&') {
-					int end = text.IndexOf (';', i);
-					if (end == -1)
-						throw new FormatException ("Unterminated XML entity.");
-					string entity = text.Substring (i+1, end - i - 1);
-					switch (entity) {
-					case "lt":
-						sb.Append ('<');
-						break;
-					case "gt":
-						sb.Append ('>');
-						break;
-					case "amp":
-						sb.Append ('&');
-						break;
-					case "apos":
-						sb.Append ('\'');
-						break;
-					case "quot":
-						sb.Append ('"');
-						break;
-					default:
-						throw new FormatException ("Unrecogised XML entity '&" + entity + ";'.");
-					}
-					i = end;
-				} else
-					sb.Append (c1);
-			}
-			return sb.ToString ();
+			return MSBuildUtils.Escape (unescapedExpression);
 		}
 
-
 		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);
-			}
+			return MSBuildUtils.FromMSBuildPath (relPath);
 		}
 	}
 
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.Engine.dll.sources b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.Engine.dll.sources
index a7bb42b..41ed073 100644
--- a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.Engine.dll.sources
+++ b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.Engine.dll.sources
@@ -2,7 +2,7 @@
 ../../build/common/MonoTODOAttribute.cs
 Assembly/AssemblyInfo.cs
 ../Microsoft.Build.Framework/Mono.XBuild.Framework/AssemblyLoadInfo.cs
-../Microsoft.Build.Tasks/Microsoft.Build.Tasks/Utilities.cs
+../Microsoft.Build.Utilities/Mono.XBuild.Utilities/MSBuildUtils.cs
 ../Microsoft.Build.Utilities/Mono.XBuild.Utilities/ReservedNameUtils.cs
 ../../tools/xbuild/SolutionParser.cs
 Microsoft.Build.BuildEngine/BatchingImplBase.cs
@@ -37,6 +37,7 @@ Microsoft.Build.BuildEngine/Engine.cs
 Microsoft.Build.BuildEngine/EventSource.cs
 Microsoft.Build.BuildEngine/Expression.cs
 Microsoft.Build.BuildEngine/ExpressionCollection.cs
+Microsoft.Build.BuildEngine/ExpressionEvaluationException.cs
 Microsoft.Build.BuildEngine/ExpressionParseException.cs
 Microsoft.Build.BuildEngine/FileLogger.cs
 Microsoft.Build.BuildEngine/GroupingCollection.cs
diff --git a/mcs/class/Microsoft.Build.Engine/Test/various/ChangeLog b/mcs/class/Microsoft.Build.Engine/Test/various/ChangeLog
index 02476d6..c6d17fb 100644
--- a/mcs/class/Microsoft.Build.Engine/Test/various/ChangeLog
+++ b/mcs/class/Microsoft.Build.Engine/Test/various/ChangeLog
@@ -1,3 +1,15 @@
+2011-01-26  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Improve error messages for condition evaluation.
+
+	Also, add new ExpressionEvaluationException class. Wrap
+	Expression*Exceptions in InvalidProjectFileException with info
+	about the full condition being evaluated.
+
+2011-01-26  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Support short-circuiting in conditions.
+
 2010-03-04  Ankit Jain  <jankit at novell.com>
 
 	* Build.cs (TestBuildContinueOnError*): New.
diff --git a/mcs/class/Microsoft.Build.Engine/Test/various/ChangeLog b/mcs/class/Microsoft.Build.Engine/Test/various/ChangeLog.old
similarity index 100%
copy from mcs/class/Microsoft.Build.Engine/Test/various/ChangeLog
copy to mcs/class/Microsoft.Build.Engine/Test/various/ChangeLog.old
diff --git a/mcs/class/Microsoft.Build.Engine/Test/various/Conditions.cs b/mcs/class/Microsoft.Build.Engine/Test/various/Conditions.cs
index 47ef21d..d3954a2 100644
--- a/mcs/class/Microsoft.Build.Engine/Test/various/Conditions.cs
+++ b/mcs/class/Microsoft.Build.Engine/Test/various/Conditions.cs
@@ -336,6 +336,27 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various {
 			Assert.AreEqual ("fr_c.txt", bgp [2].FinalItemSpec, "A4");
 		}
 
+		// Test shortcircuiting
+		[Test]
+		public void TestCondition12 ()
+		{
+			Engine engine = new Engine (Consts.BinPath);
+			Project proj = engine.CreateNewProject ();
+
+			string documentString = @"
+				<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
+					<PropertyGroup>
+						<A Condition=""'$(NonExistant)' != '' and $(NonExistant)""></A>
+					</PropertyGroup>
+				</Project>
+			";
+
+			proj.LoadXml (documentString);
+
+			Assert.IsNull (proj.EvaluatedProperties ["A"], "A1");
+		}
+
+
 		[Test]
 		public void TestHasTrailingSlash1 ()
 		{
@@ -481,5 +502,24 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various {
 
 			proj.LoadXml (documentString);
 		}
+
+		[Test]
+		[ExpectedException (typeof (InvalidProjectFileException))]
+		public void TestIncorrectCondition6 ()
+		{
+			Engine engine = new Engine (Consts.BinPath);
+			Project proj = engine.CreateNewProject ();
+
+			string documentString = @"
+				<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
+					<ItemGroup>
+						<A Include='a' Condition=""'$(NonExistant)' != '' or $(NonExistant)""/>
+					</ItemGroup>
+				</Project>
+			";
+
+			proj.LoadXml (documentString);
+		}
+
 	}
 }
diff --git a/mcs/class/Microsoft.Build.Tasks/ChangeLog b/mcs/class/Microsoft.Build.Tasks/ChangeLog
index ef3cbdb..541474e 100644
--- a/mcs/class/Microsoft.Build.Tasks/ChangeLog
+++ b/mcs/class/Microsoft.Build.Tasks/ChangeLog
@@ -1,3 +1,9 @@
+2011-02-11  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Update Utilities.FromMSBuildPath from monodevelop.
+
+	Updating FromMSBuildPath also fixes a bug on windows.
+
 2010-09-15  Marek Safar  <marek.safar at gmail.com>
 
 	[637935] Fixed 3.5 version of msbuild dlls to reference 3.5
diff --git a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks.dll.sources b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks.dll.sources
index 9d53168..0430fcf 100644
--- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks.dll.sources
+++ b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks.dll.sources
@@ -104,7 +104,6 @@ Microsoft.Build.Tasks/ToolTaskExtension.cs
 Microsoft.Build.Tasks/Touch.cs
 Microsoft.Build.Tasks/UnregisterAssembly.cs
 Microsoft.Build.Tasks/UpdateManifest.cs
-Microsoft.Build.Tasks/Utilities.cs
 Microsoft.Build.Tasks/Vbc.cs
 Microsoft.Build.Tasks/VCBuild.cs
 Microsoft.Build.Tasks/Warning.cs
@@ -113,5 +112,6 @@ Mono.XBuild.Tasks.GenerateResourceInternal/PoResourceReader.cs
 Mono.XBuild.Tasks.GenerateResourceInternal/PoResourceWriter.cs
 Mono.XBuild.Tasks.GenerateResourceInternal/TxtResourceReader.cs
 Mono.XBuild.Tasks.GenerateResourceInternal/TxtResourceWriter.cs
+../Microsoft.Build.Utilities/Mono.XBuild.Utilities/MSBuildUtils.cs
 ../Microsoft.Build.Engine/Microsoft.Build.BuildEngine/DirectoryScanner.cs
 ../Microsoft.Build.Engine/Microsoft.Build.BuildEngine/UnknownToolsVersionException.cs
diff --git a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/AL.cs b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/AL.cs
index 9e3426d..f0195f0 100644
--- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/AL.cs
+++ b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/AL.cs
@@ -237,7 +237,7 @@ namespace Microsoft.Build.Tasks {
 
 		protected override string ToolName {
 			get {
-				return Utilities.RunningOnWindows ? "al.bat" : "al";
+				return MSBuildUtils.RunningOnWindows ? "al.bat" : "al";
 			}
 		}
 
diff --git a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/AspNetCompiler.cs b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/AspNetCompiler.cs
index 9f4da84..ac4930c 100644
--- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/AspNetCompiler.cs
+++ b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/AspNetCompiler.cs
@@ -30,6 +30,7 @@
 using System;
 using System.IO;
 using Microsoft.Build.Framework;
+using Mono.XBuild.Utilities;
 
 namespace Microsoft.Build.Tasks {
 	public class AspNetCompiler : ToolTaskExtension {
@@ -142,7 +143,7 @@ namespace Microsoft.Build.Tasks {
 		}
 		
 		protected override string ToolName {
-			get { return Utilities.RunningOnWindows ? "aspnet_compiler.bat" : "aspnet_compiler"; }
+			get { return MSBuildUtils.RunningOnWindows ? "aspnet_compiler.bat" : "aspnet_compiler"; }
 		}
 	}
 }
diff --git a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/ChangeLog b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/ChangeLog
index b61593f..a3a51c0 100644
--- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/ChangeLog
+++ b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/ChangeLog
@@ -1,3 +1,9 @@
+2011-02-11  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Update Utilities.FromMSBuildPath from monodevelop.
+
+	Updating FromMSBuildPath also fixes a bug on windows.
+
 2011-01-11  Ankit Jain  <radical at corewars.org>
 
 	[xbuild] Copy metadata from Project items to target outputs.
diff --git a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Csc.cs b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Csc.cs
index 9dc504d..711fe5f 100644
--- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Csc.cs
+++ b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Csc.cs
@@ -32,6 +32,7 @@ using System.IO;
 using Microsoft.Build.Framework;
 using Microsoft.Build.Tasks.Hosting;
 using Microsoft.Build.Utilities;
+using Mono.XBuild.Utilities;
 
 namespace Microsoft.Build.Tasks {
 	public class Csc : ManagedCompiler {
@@ -195,9 +196,9 @@ namespace Microsoft.Build.Tasks {
 		protected override string ToolName {
 			get {
 #if NET_4_0
-				return Utilities.RunningOnWindows ? "dmcs.bat" : "dmcs";
+				return MSBuildUtils.RunningOnWindows ? "dmcs.bat" : "dmcs";
 #else
-				return Utilities.RunningOnWindows ? "gmcs.bat" : "gmcs";
+				return MSBuildUtils.RunningOnWindows ? "gmcs.bat" : "gmcs";
 #endif
 			}
 		}
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 31676af..5610a8c 100644
--- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/GenerateResource.cs
+++ b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/GenerateResource.cs
@@ -43,6 +43,7 @@ using System.Xml;
 using Microsoft.Build.Framework;
 using Microsoft.Build.Utilities;
 using Mono.XBuild.Tasks.GenerateResourceInternal;
+using Mono.XBuild.Utilities;
 
 namespace Microsoft.Build.Tasks {
 	public sealed class GenerateResource : TaskExtension {
@@ -155,7 +156,7 @@ namespace Microsoft.Build.Tasks {
 
 					string [] parts = value.Split (';');
 					if (parts.Length > 0) {
-						string referenced_filename = Utilities.FromMSBuildPath (
+						string referenced_filename = MSBuildUtils.FromMSBuildPath (
 								Path.Combine (basepath, parts [0]).Trim ());
 						if (File.Exists (referenced_filename) &&
 							IsFileNewerThan (referenced_filename, resources_filename))
@@ -383,7 +384,7 @@ namespace Microsoft.Build.Tasks {
 		}
 
 		protected override string ToolName {
-			get { return Utilities.RunningOnWindows ? "resgen2.bat" : "resgen2"; }
+			get { return MSBuildUtils.RunningOnWindows ? "resgen2.bat" : "resgen2"; }
 		}
 
 		public string SourceFile { get; set; }
diff --git a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/LC.cs b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/LC.cs
index 6943818..3d91d82 100644
--- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/LC.cs
+++ b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/LC.cs
@@ -115,7 +115,7 @@ namespace Microsoft.Build.Tasks {
 
 		protected override string ToolName {
 			get {
-				return Utilities.RunningOnWindows ? "lc.bat" : "lc";
+				return MSBuildUtils.RunningOnWindows ? "lc.bat" : "lc";
 			}
 		}
 	}
diff --git a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/PcFileCache.cs b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/PcFileCache.cs
index 8069d65..aa96a31 100644
--- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/PcFileCache.cs
+++ b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/PcFileCache.cs
@@ -355,7 +355,7 @@ namespace Mono.PkgConfig
 				// For mac osx, look in the 'External' dir on macosx,
 				// see bug #663180
 				string pkgConfigPath = String.Format ("{0}:{1}",
-						Microsoft.Build.Tasks.Utilities.RunningOnMac ? MacOSXExternalPkgConfigDir : String.Empty,
+						Mono.XBuild.Utilities.MSBuildUtils.RunningOnMac ? MacOSXExternalPkgConfigDir : String.Empty,
 						Environment.GetEnvironmentVariable ("PKG_CONFIG_PATH") ?? String.Empty);
 
 				string pkgConfigDir = Environment.GetEnvironmentVariable ("PKG_CONFIG_LIBDIR");
diff --git a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/SGen.cs b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/SGen.cs
index 394e897..ab5f75e 100644
--- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/SGen.cs
+++ b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/SGen.cs
@@ -30,6 +30,7 @@
 using System;
 using Microsoft.Build.Framework; 
 using Microsoft.Build.Tasks;
+using Mono.XBuild.Utilities;
 
 namespace Microsoft.Build.Tasks {
 	public class SGen : ToolTaskExtension {
@@ -115,7 +116,7 @@ namespace Microsoft.Build.Tasks {
 
 		[MonoTODO]
 		protected override string ToolName {
-			get { return Utilities.RunningOnWindows ? "sgen.bat" : "sgen"; }
+			get { return MSBuildUtils.RunningOnWindows ? "sgen.bat" : "sgen"; }
 		}
 
 		[MonoTODO]
diff --git a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Utilities.cs b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Utilities.cs
deleted file mode 100644
index 1738d9e..0000000
--- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Utilities.cs
+++ /dev/null
@@ -1,134 +0,0 @@
-//
-// Utilities.cs:
-//
-// Author:
-//	Ankit Jain (jankit at novell.com)
-//
-// Copyright (c) 2009 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.
-
-#if NET_2_0
-
-using System;
-using System.IO;
-using System.Runtime.InteropServices;
-
-namespace Microsoft.Build.Tasks {
-	internal static class Utilities {
-
-		public readonly static bool RunningOnMac;
-		public readonly static bool RunningOnWindows;
-
-		static Utilities ()
-		{
-			RunningOnWindows = Path.DirectorySeparatorChar == '\\';
-			RunningOnMac = !RunningOnWindows && IsRunningOnMac ();
-		}
-
-		[DllImport ("libc")]
-		static extern int uname (IntPtr buf);
-
-		//From Managed.Windows.Forms/XplatUI
-		static bool IsRunningOnMac ()
-		{
-			IntPtr buf = IntPtr.Zero;
-			try {
-				buf = System.Runtime.InteropServices.Marshal.AllocHGlobal (8192);
-				// This is a hacktastic way of getting sysname from uname ()
-				if (uname (buf) == 0) {
-					string os = System.Runtime.InteropServices.Marshal.PtrToStringAnsi (buf);
-					if (os == "Darwin")
-						return true;
-				}
-			} catch {
-			} finally {
-				if (buf != IntPtr.Zero)
-					System.Runtime.InteropServices.Marshal.FreeHGlobal (buf);
-			}
-			return false;
-		}
-
-		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);
-			}
-		}
-
-	}
-
-}
-
-#endif
diff --git a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Vbc.cs b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Vbc.cs
index 52a8da8..e6867ab 100644
--- a/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Vbc.cs
+++ b/mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Vbc.cs
@@ -35,6 +35,7 @@ using System.Text.RegularExpressions;
 
 using Microsoft.Build.Framework;
 using Microsoft.Build.Utilities;
+using Mono.XBuild.Utilities;
 
 namespace Microsoft.Build.Tasks {
 
@@ -303,7 +304,7 @@ namespace Microsoft.Build.Tasks {
 
 		[MonoTODO]
 		protected override string ToolName {
-			get { return Utilities.RunningOnWindows ? "vbnc.bat" : "vbnc"; }
+			get { return MSBuildUtils.RunningOnWindows ? "vbnc.bat" : "vbnc"; }
 		}
 
 		[MonoTODO]
diff --git a/mcs/class/Microsoft.Build.Utilities/ChangeLog b/mcs/class/Microsoft.Build.Utilities/ChangeLog
index 25b1654..856ed84 100644
--- a/mcs/class/Microsoft.Build.Utilities/ChangeLog
+++ b/mcs/class/Microsoft.Build.Utilities/ChangeLog
@@ -1,3 +1,7 @@
+2011-02-11  Zoltan Varga  <vargaz at gmail.com>
+
+	Add Mono.XBuild.Utilities/MSBuildUtils.cs to the build.
+
 2010-09-15  Marek Safar  <marek.safar at gmail.com>
 
 	[637935] Fixed 3.5 version of msbuild dlls to reference 3.5
diff --git a/mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities.dll.sources b/mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities.dll.sources
index 3ea52dc..c377282 100644
--- a/mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities.dll.sources
+++ b/mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities.dll.sources
@@ -17,4 +17,5 @@ Microsoft.Build.Utilities/ToolLocationHelper.cs
 Microsoft.Build.Utilities/ToolTask.cs
 Mono.XBuild.Utilities/MonoLocationHelper.cs
 Mono.XBuild.Utilities/ReservedNameUtils.cs
+Mono.XBuild.Utilities/MSBuildUtils.cs
 ../System/System.Collections.Specialized/ProcessStringDictionary.cs
diff --git a/mcs/class/Microsoft.Build.Utilities/Mono.XBuild.Utilities/ChangeLog b/mcs/class/Microsoft.Build.Utilities/Mono.XBuild.Utilities/ChangeLog
index eb6e691..231735e 100644
--- a/mcs/class/Microsoft.Build.Utilities/Mono.XBuild.Utilities/ChangeLog
+++ b/mcs/class/Microsoft.Build.Utilities/Mono.XBuild.Utilities/ChangeLog
@@ -1,3 +1,9 @@
+2011-02-11  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Update Utilities.FromMSBuildPath from monodevelop.
+
+	Updating FromMSBuildPath also fixes a bug on windows.
+
 2010-07-16  Ankit Jain  <jankit at novell.com>
 
 	* AbsoluteToRelativePath: New.
diff --git a/mcs/class/Microsoft.Build.Utilities/Mono.XBuild.Utilities/ChangeLog b/mcs/class/Microsoft.Build.Utilities/Mono.XBuild.Utilities/ChangeLog.old
similarity index 100%
copy from mcs/class/Microsoft.Build.Utilities/Mono.XBuild.Utilities/ChangeLog
copy to mcs/class/Microsoft.Build.Utilities/Mono.XBuild.Utilities/ChangeLog.old
diff --git a/mcs/class/Microsoft.Build.Utilities/Mono.XBuild.Utilities/MSBuildUtils.cs b/mcs/class/Microsoft.Build.Utilities/Mono.XBuild.Utilities/MSBuildUtils.cs
new file mode 100644
index 0000000..5cd2ea0
--- /dev/null
+++ b/mcs/class/Microsoft.Build.Utilities/Mono.XBuild.Utilities/MSBuildUtils.cs
@@ -0,0 +1,231 @@
+//
+// Utilities.cs:
+//
+// Author:
+//	Ankit Jain (jankit at novell.com)
+//
+// Copyright (c) 2009 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.
+
+#if NET_2_0
+
+using System;
+using System.Collections;
+using System.Text;
+using System.IO;
+using System.Runtime.InteropServices;
+
+namespace Mono.XBuild.Utilities {
+	internal static class MSBuildUtils {
+
+		public readonly static bool RunningOnMac;
+		public readonly static bool RunningOnWindows;
+		static Hashtable charsToEscape;
+
+		static MSBuildUtils ()
+		{
+			RunningOnWindows = Path.DirectorySeparatorChar == '\\';
+			RunningOnMac = !RunningOnWindows && IsRunningOnMac ();
+
+			charsToEscape = new Hashtable ();
+			
+			charsToEscape.Add ('$', null);
+			charsToEscape.Add ('%', null);
+			charsToEscape.Add ('\'', null);
+			charsToEscape.Add ('(', null);
+			charsToEscape.Add (')', null);
+			charsToEscape.Add ('*', null);
+			charsToEscape.Add (';', null);
+			charsToEscape.Add ('?', null);
+			charsToEscape.Add ('@', null);
+		}
+	
+		public static string Escape (string unescapedExpression)
+		{
+			StringBuilder sb = new StringBuilder ();
+			
+			foreach (char c in unescapedExpression) {
+				if (charsToEscape.Contains (c))
+					sb.AppendFormat ("%{0:x2}", (int) c);
+				else
+					sb.Append (c);
+			}
+			
+			return sb.ToString ();
+		}
+		
+		// FIXME: add tests for this
+		internal static string Unescape (string escapedExpression)
+		{
+			StringBuilder sb = new StringBuilder ();
+			
+			int i = 0;
+			while (i < escapedExpression.Length) {
+				sb.Append (Uri.HexUnescape (escapedExpression, ref i));
+			}
+			
+			return sb.ToString ();
+		}
+
+		internal static string UnescapeFromXml (string text)
+		{
+			StringBuilder sb = new StringBuilder ();
+			for (int i = 0; i < text.Length; i++) {
+				char c1 = text[i];
+				if (c1 == '&') {
+					int end = text.IndexOf (';', i);
+					if (end == -1)
+						throw new FormatException ("Unterminated XML entity.");
+					string entity = text.Substring (i+1, end - i - 1);
+					switch (entity) {
+					case "lt":
+						sb.Append ('<');
+						break;
+					case "gt":
+						sb.Append ('>');
+						break;
+					case "amp":
+						sb.Append ('&');
+						break;
+					case "apos":
+						sb.Append ('\'');
+						break;
+					case "quot":
+						sb.Append ('"');
+						break;
+					default:
+						throw new FormatException ("Unrecogised XML entity '&" + entity + ";'.");
+					}
+					i = end;
+				} else
+					sb.Append (c1);
+			}
+			return sb.ToString ();
+		}
+
+		[DllImport ("libc")]
+		static extern int uname (IntPtr buf);
+
+		//From Managed.Windows.Forms/XplatUI
+		static bool IsRunningOnMac ()
+		{
+			IntPtr buf = IntPtr.Zero;
+			try {
+				buf = System.Runtime.InteropServices.Marshal.AllocHGlobal (8192);
+				// This is a hacktastic way of getting sysname from uname ()
+				if (uname (buf) == 0) {
+					string os = System.Runtime.InteropServices.Marshal.PtrToStringAnsi (buf);
+					if (os == "Darwin")
+						return true;
+				}
+			} catch {
+			} finally {
+				if (buf != IntPtr.Zero)
+					System.Runtime.InteropServices.Marshal.FreeHGlobal (buf);
+			}
+			return false;
+		}
+
+		internal static string FromMSBuildPath (string relPath)
+		{
+			string result = null;
+			FromMSBuildPath (String.Empty, relPath, out result);
+			return result;
+		}
+
+		internal static bool FromMSBuildPath (string basePath, string relPath, out string resultPath)
+		{
+			resultPath = relPath;
+			
+			if (string.IsNullOrEmpty (relPath))
+				return false;
+			
+			string path = relPath;
+			if (!RunningOnWindows)
+				path = path.Replace ("\\", "/");
+			
+			path = Unescape (path);
+
+			if (char.IsLetter (path [0]) && path.Length > 1 && path[1] == ':') {
+				if (RunningOnWindows) {
+					resultPath = path; // Return the escaped value
+					return true;
+				} else
+					return false;
+			}
+			
+			if (basePath != null)
+				path = Path.Combine (basePath, path);
+			
+			if (System.IO.File.Exists (path) || System.IO.Directory.Exists (path)){
+				resultPath = Path.GetFullPath (path);
+				return true;
+			}
+				
+			if (Path.IsPathRooted (path) && !RunningOnWindows) {
+					
+				// 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 false; // 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];
+						resultPath = part;
+						return true;
+					}
+
+					part = fpath;
+				}
+				resultPath = Path.GetFullPath (part);
+			} else {
+				resultPath = Path.GetFullPath (path);
+			}
+			return true;
+		}
+	}
+
+}
+
+#endif
diff --git a/mcs/class/Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/CSharpBinder.cs b/mcs/class/Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/CSharpBinder.cs
index 1dd5584..608d928 100644
--- a/mcs/class/Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/CSharpBinder.cs
+++ b/mcs/class/Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/CSharpBinder.cs
@@ -69,7 +69,7 @@ namespace Microsoft.CSharp.RuntimeBinder
 		{
 			Expression res;
 			try {
-				var rc = new Compiler.ResolveContext (new RuntimeBinderContext (ctx, ctx.ImportType (callingType)), ResolveOptions);
+				var rc = new Compiler.ResolveContext (new RuntimeBinderContext (ctx, callingType), ResolveOptions);
 
 				// Static typemanager and internal caches are not thread-safe
 				lock (resolver) {
diff --git a/mcs/class/Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/ChangeLog b/mcs/class/Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/ChangeLog
index fd77b26..023999b 100644
--- a/mcs/class/Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/ChangeLog
+++ b/mcs/class/Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/ChangeLog
@@ -1,3 +1,11 @@
+2011-02-03  Marek Safar  <marek.safar at gmail.com>
+
+	Don't even try to import type when its context is wrong
+
+2011-02-02  Marek Safar  <marek.safar at gmail.com>
+
+	Add handling of broken Convert callsite from Orchard Project
+
 2010-12-07  Marek Safar  <marek.safar at gmail.com>
 
 	Add IKVM.Reflection support
diff --git a/mcs/class/Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/RuntimeBinderContext.cs b/mcs/class/Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/RuntimeBinderContext.cs
index 1dddbb4..e9053fc 100644
--- a/mcs/class/Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/RuntimeBinderContext.cs
+++ b/mcs/class/Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/RuntimeBinderContext.cs
@@ -1,4 +1,4 @@
-//
+//
 // RuntimeBinderContext.cs
 //
 // Authors:
@@ -35,18 +35,39 @@ namespace Microsoft.CSharp.RuntimeBinder
 	class RuntimeBinderContext : Compiler.IMemberContext
 	{
 		readonly Compiler.ModuleContainer module;
-		readonly Compiler.TypeSpec currentType;
+		readonly Type callingType;
+		readonly DynamicContext ctx;
+		Compiler.TypeSpec callingTypeImported;
 
-		public RuntimeBinderContext (DynamicContext ctx, Compiler.TypeSpec currentType)
+		public RuntimeBinderContext (DynamicContext ctx, Compiler.TypeSpec callingType)
 		{
+			this.ctx = ctx;
 			this.module = ctx.Module;
-			this.currentType = currentType;
+			this.callingTypeImported = callingType;
+		}
+
+		public RuntimeBinderContext (DynamicContext ctx, Type callingType)
+		{
+			this.ctx = ctx;
+			this.module = ctx.Module;
+			this.callingType = callingType;
 		}
 
 		#region IMemberContext Members
 
 		public Compiler.TypeSpec CurrentType {
-			get { return currentType; }
+			get {
+				//
+				// Delay importing of calling type to be compatible with .net
+				// Some libraries are setting it to null which is invalid
+				// but the NullReferenceException is thrown only when the context
+				// is used and not during initialization
+				//
+				if (callingTypeImported == null && callingType != null)
+					callingTypeImported = ctx.ImportType (callingType);
+
+				return callingTypeImported;
+			}
 		}
 
 		public Compiler.TypeParameter[] CurrentTypeParameters {
diff --git a/mcs/class/Microsoft.Web.Infrastructure/Assembly/AssemblyInfo.cs b/mcs/class/Microsoft.Web.Infrastructure/Assembly/AssemblyInfo.cs
new file mode 100644
index 0000000..792e465
--- /dev/null
+++ b/mcs/class/Microsoft.Web.Infrastructure/Assembly/AssemblyInfo.cs
@@ -0,0 +1,54 @@
+// 
+// AssemblyInfo.cs
+//  
+// Author:
+//       Marek Habersack <grendel at twistedcode.net>
+// 
+// Copyright (c) 2011 Novell, Inc (http://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.Diagnostics;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using System.Security;
+
+[assembly: AssemblyProduct ("ASP.Net WebPages")]
+[assembly: AssemblyCompany ("Novell, Inc")]
+[assembly: AssemblyCopyright ("© Novell, Inc. All rights reserved.")]
+[assembly: AssemblyConfiguration ("")]
+[assembly: RuntimeCompatibility (WrapNonExceptionThrows=true)]
+[assembly: AssemblyTrademark ("")]
+[assembly: NeutralResourcesLanguage ("en-US")]
+[assembly: Debuggable (DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
+[assembly: CLSCompliant (true)]
+[assembly: ComVisible (false)]
+[assembly: AssemblyFileVersion ("1.0.20105.407")]
+[assembly: AssemblyVersion ("1.0.0.0")]
+[assembly: TargetFramework (".NETFramework,Version=v4.0", FrameworkDisplayName=".NET Framework 4")]
+[assembly: AllowPartiallyTrustedCallers]
+[assembly: CompilationRelaxations (8)]
+[assembly: AssemblyTitle ("Microsoft.Web.Infrastructure")]
+[assembly: AssemblyDescription ("")]
+[assembly: AssemblyDelaySign (true)]
+[assembly: AssemblyKeyFile("../winfx.pub")]
diff --git a/mcs/class/Microsoft.Web.Infrastructure/Makefile b/mcs/class/Microsoft.Web.Infrastructure/Makefile
new file mode 100644
index 0000000..5fdef63
--- /dev/null
+++ b/mcs/class/Microsoft.Web.Infrastructure/Makefile
@@ -0,0 +1,20 @@
+thisdir = class/Microsoft.Web.Infrastructure
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = Microsoft.Web.Infrastructure.dll
+LIB_MCS_FLAGS = -r:System.dll \
+		-r:System.Configuration.dll \
+		-r:System.Web.dll
+
+EXTRA_DISTFILES = $(RESOURCE_FILES)
+
+VALID_PROFILE := $(filter 4.0, $(FRAMEWORK_VERSION))
+ifndef VALID_PROFILE
+LIBRARY_NAME = dummy-Microsoft.Web.Infrastructure.dll
+NO_INSTALL = yes
+NO_SIGN_ASSEMBLY = yes
+NO_TEST = yes
+endif
+
+include ../../build/library.make
diff --git a/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure.DynamicModuleHelper/DynamicModuleUtility.cs b/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure.DynamicModuleHelper/DynamicModuleUtility.cs
new file mode 100644
index 0000000..5a498db
--- /dev/null
+++ b/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure.DynamicModuleHelper/DynamicModuleUtility.cs
@@ -0,0 +1,50 @@
+// 
+// DynamicModuleUtility.cs
+//  
+// Author:
+//       Marek Habersack <grendel at twistedcode.net>
+// 
+// Copyright (c) 2011 Novell, Inc (http://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 Microsoft.Web.Infrastructure.DynamicModuleHelper;
+using System;
+using System.ComponentModel;
+using System.Security;
+using System.Web;
+using System.Web.Configuration;
+
+namespace Microsoft.Web.Infrastructure.DynamicModuleHelper
+{
+	[EditorBrowsable (EditorBrowsableState.Never)]
+	public static class DynamicModuleUtility
+	{
+		[SecuritySafeCritical]
+		public static void RegisterModule (Type moduleType)
+		{
+			if (moduleType == null)
+				return;
+
+			string typeName = moduleType.AssemblyQualifiedName;
+			var cfg = WebConfigurationManager.GetWebApplicationSection ("system.web/httpModules") as HttpModulesSection;
+			cfg.Modules.Add (new HttpModuleAction ("__Dynamic_Module_" + typeName, typeName));
+		}
+	}
+}
diff --git a/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure.DynamicValidationHelper/LazyWebROCollection.cs b/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure.DynamicValidationHelper/LazyWebROCollection.cs
new file mode 100644
index 0000000..f2a1b61
--- /dev/null
+++ b/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure.DynamicValidationHelper/LazyWebROCollection.cs
@@ -0,0 +1,65 @@
+//  
+// Author:
+//       Marek Habersack <grendel at twistedcode.net>
+// 
+// Copyright (c) 2011 Novell, Inc (http://novell.com/)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Specialized;
+using System.Web;
+using System.Web.Util;
+
+namespace Microsoft.Web.Infrastructure.DynamicValidationHelper
+{
+	sealed class LazyWebROCollection : WebROCollection
+	{
+		WebROCollection wrapped;
+		RequestValidationSource validationSource;
+		
+		public LazyWebROCollection (RequestValidationSource validationSource, WebROCollection wrapped)
+		{
+			if (wrapped == null)
+				throw new ArgumentNullException ("wrapped");
+			
+			this.validationSource = validationSource;
+			this.wrapped = wrapped;
+		}
+		
+		public override string Get (string name)
+		{
+			return Validate (name, wrapped.Get (name));
+		}
+
+		public override string Get (int index)
+		{
+			return Validate (wrapped.GetKey (index), wrapped.Get (index));
+		}
+
+		string Validate (string key, string value)
+		{
+			if (String.IsNullOrEmpty (value))
+				return value;
+
+			HttpRequest.ValidateString (key, value, validationSource);
+			return value;
+		}
+	}
+}
diff --git a/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure.DynamicValidationHelper/ValidationUtility.cs b/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure.DynamicValidationHelper/ValidationUtility.cs
new file mode 100644
index 0000000..85d6ed2
--- /dev/null
+++ b/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure.DynamicValidationHelper/ValidationUtility.cs
@@ -0,0 +1,85 @@
+// 
+// ValidationUtility.cs
+//  
+// Author:
+//       Marek Habersack <grendel at twistedcode.net>
+// 
+// Copyright (c) 2011 Novell, Inc (http://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.Collections.Specialized;
+using System.Security;
+using System.Web;
+using System.Web.Util;
+
+namespace Microsoft.Web.Infrastructure.DynamicValidationHelper
+{
+	[EditorBrowsable (EditorBrowsableState.Never)]
+	public static class ValidationUtility
+	{
+		[SecuritySafeCritical]
+		public static void EnableDynamicValidation (HttpContext context)
+		{
+			HttpRequest req = context != null ? context.Request : null;
+			if (req == null)
+				return;
+
+			// Just to be safe, make sure it's on
+			req.ValidateInput ();
+			req.SetFormCollection (new LazyWebROCollection (RequestValidationSource.Form, req.FormUnvalidated), true);
+			req.SetQueryStringCollection (new LazyWebROCollection (RequestValidationSource.QueryString, req.QueryStringUnvalidated), true);
+		}
+
+		[SecuritySafeCritical]
+		public static bool? IsValidationEnabled (HttpContext context)
+		{
+			HttpRequest req = context != null ? context.Request : null;
+			if (req == null)
+				return true;
+
+			return req.InputValidationEnabled;
+		}
+
+		[SecuritySafeCritical]
+		public static void GetUnvalidatedCollections (HttpContext context, out Func <NameValueCollection> formGetter, out Func <NameValueCollection> queryStringGetter)
+		{
+			if (context == null)
+				throw new ArgumentNullException ("context");
+			formGetter = null;
+			queryStringGetter = null;
+			
+			formGetter = () => {
+				HttpRequest req = context != null ? context.Request : null;
+				if (req == null)
+					return null;
+				return req.FormUnvalidated;
+			};
+
+			queryStringGetter = () => {
+				HttpRequest req = context != null ? context.Request : null;
+				if (req == null)
+					return null;
+				return req.QueryStringUnvalidated;
+			};
+		}
+	}
+}
diff --git a/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure.dll.sources b/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure.dll.sources
new file mode 100644
index 0000000..389240e
--- /dev/null
+++ b/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure.dll.sources
@@ -0,0 +1,10 @@
+../../build/common/Consts.cs
+../../build/common/Locale.cs
+../../build/common/MonoTODOAttribute.cs
+
+./Assembly/AssemblyInfo.cs
+./Microsoft.Web.Infrastructure.DynamicModuleHelper/DynamicModuleUtility.cs
+./Microsoft.Web.Infrastructure.DynamicValidationHelper/ValidationUtility.cs
+./Microsoft.Web.Infrastructure.DynamicValidationHelper/LazyWebROCollection.cs
+./Microsoft.Web.Infrastructure/HttpContextHelper.cs
+./Microsoft.Web.Infrastructure/InfrastructureHelper.cs
diff --git a/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure/HttpContextHelper.cs b/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure/HttpContextHelper.cs
new file mode 100644
index 0000000..4e0212e
--- /dev/null
+++ b/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure/HttpContextHelper.cs
@@ -0,0 +1,44 @@
+// 
+// HttpContextHelper.cs
+//  
+// Author:
+//       Marek Habersack <grendel at twistedcode.net>
+// 
+// Copyright (c) 2011 Novell, Inc (http://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 Microsoft.Web.Infrastructure;
+using System;
+using System.ComponentModel;
+using System.Security;
+using System.Web;
+
+namespace Microsoft.Web.Infrastructure
+{
+	[EditorBrowsable (EditorBrowsableState.Never)]
+	public static class HttpContextHelper
+	{
+		[SecuritySafeCritical]
+		public static void ExecuteInNullContext (Action action)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}
diff --git a/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure/InfrastructureHelper.cs b/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure/InfrastructureHelper.cs
new file mode 100644
index 0000000..f5c1acc
--- /dev/null
+++ b/mcs/class/Microsoft.Web.Infrastructure/Microsoft.Web.Infrastructure/InfrastructureHelper.cs
@@ -0,0 +1,49 @@
+// 
+// InfrastructureHelper.cs
+//  
+// Author:
+//       Marek Habersack <grendel at twistedcode.net>
+// 
+// Copyright (c) 2011 Novell, Inc (http://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 Microsoft.Web.Infrastructure;
+using System;
+using System.ComponentModel;
+using System.Security;
+
+namespace Microsoft.Web.Infrastructure
+{
+	[EditorBrowsable (EditorBrowsableState.Never)]
+	public static class InfrastructureHelper
+	{
+		[SecuritySafeCritical]
+		public static void UnloadAppDomain ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		[SecuritySafeCritical]
+		public static bool IsCodeDomDefinedExtension (string extension)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}
diff --git a/mcs/class/Mono.Debugger.Soft/Assembly/AssemblyInfo.cs b/mcs/class/Mono.Debugger.Soft/Assembly/AssemblyInfo.cs
new file mode 100644
index 0000000..619d9fb
--- /dev/null
+++ b/mcs/class/Mono.Debugger.Soft/Assembly/AssemblyInfo.cs
@@ -0,0 +1,39 @@
+//
+// AssemblyInfo.cs
+//
+// Author:
+//   Zoltan Varga (vargaz at gmail.com)
+//
+// (C) 2011 Novell (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.Reflection;
+using System.Runtime.InteropServices;
+using System.Security.Permissions;
+
+[assembly: AssemblyVersion (Consts.FxVersion)]
+
+[assembly: AssemblyTitle("Mono.Debugger.Soft.dll")]
+[assembly: AssemblyDescription("Mono Soft Debugger API library")]
diff --git a/mcs/class/Mono.Debugger.Soft/ChangeLog b/mcs/class/Mono.Debugger.Soft/ChangeLog
index b9ba549..9d25574 100644
--- a/mcs/class/Mono.Debugger.Soft/ChangeLog
+++ b/mcs/class/Mono.Debugger.Soft/ChangeLog
@@ -1,3 +1,15 @@
+2011-02-13  Zoltan Varga  <vargaz at gmail.com>
+
+	Add an assembly version to Mono.Debugger.Soft. Fixes #671536.
+
+2011-02-09  Zoltan Varga  <vargaz at gmail.com>
+
+	Install Mono.Debugger.Soft in the 4.0 profile as well.
+
+2011-01-27  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix dist issues in Mono.Debugger.Soft.
+
 2011-01-04  Zoltan Varga  <vargaz at gmail.com>
 
 	Add AssemblyLoadEventRequest () type to the sdb api, and use it to
diff --git a/mcs/class/Mono.Debugger.Soft/Makefile b/mcs/class/Mono.Debugger.Soft/Makefile
index 607d352..f4d0f73 100644
--- a/mcs/class/Mono.Debugger.Soft/Makefile
+++ b/mcs/class/Mono.Debugger.Soft/Makefile
@@ -15,14 +15,15 @@ dtest-app.exe: Test/dtest-app.cs
 	$(CSCOMPILE) -out:$@ -unsafe -debug Test/dtest-app.cs
 
 dtest-excfilter.exe: Test/dtest-excfilter.il
-	$(INTERNAL_ILASM) -out:$@ /exe /debug Test/dtest-excfilter.il
+	MONO_PATH=$(topdir)/class/lib/$(PROFILE) $(INTERNAL_ILASM) -out:$@ /exe /debug Test/dtest-excfilter.il
 
-CLEAN_FILES = dtest-app.exe dtest-app.exe.mdb
+CLEAN_FILES = dtest-app.exe dtest-app.exe.mdb dtest-excfilter.exe dtest-excfilter.exe.mdb
 
-#NO_TEST = yes
+EXTRA_DISTFILES = \
+	Test/dtest-app.cs \
+	Test/dtest.cs \
+	Test/dtest-excfilter.il
 
-ifneq (net_2_0, $(PROFILE))
-NO_INSTALL = yes
-endif
+#NO_TEST = yes
 
 include ../../build/library.make
diff --git a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft.dll.sources b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft.dll.sources
index 2cbc642..5fde5dd 100644
--- a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft.dll.sources
+++ b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft.dll.sources
@@ -1,3 +1,6 @@
+./Assembly/AssemblyInfo.cs
+../../build/common/Consts.cs
+../../build/common/Locale.cs
 Mono.Debugger.Soft/CustomAttributeTypedArgumentMirror.cs
 Mono.Debugger.Soft/ExceptionEvent.cs
 Mono.Debugger.Soft/ModuleMirror.cs
diff --git a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/ChangeLog b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/ChangeLog
index d876510..5914244 100644
--- a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/ChangeLog
+++ b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/ChangeLog
@@ -1,3 +1,27 @@
+2011-01-28  Zoltan Varga  <vargaz at gmail.com>
+
+	Add an AtLeast version to sdb's VersionInfo class.
+
+2011-01-28  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Bump SDB protocol so MonoDevelop can guard IL inspection of
+	dynamic methods
+
+2011-01-26  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Include operands when emitting the IL stream to sdb clients
+
+2011-01-21  Zoltan Varga  <vargaz at gmail.com>
+
+	Obsolete VirtualMachine.GetNextEvent () as it is impossible to
+	determine when to resume after an event, since the debuggee
+	suspends only once per event-set.
+
+2011-01-20  Zoltan Varga  <vargaz at gmail.com>
+
+	Add a TID field to ThreadMirror which returns the system thread
+	id.
+
 2011-01-04  Zoltan Varga  <vargaz at gmail.com>
 
 	Add AssemblyLoadEventRequest () type to the sdb api, and use it to
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 8bd711f..e364773 100644
--- a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs
+++ b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs
@@ -21,6 +21,16 @@ namespace Mono.Debugger.Soft
 		public int MinorVersion {
 			get; set;
 		}
+
+		/*
+		 * Check that this version is at least major:minor
+		 */
+		public bool AtLeast (int major, int minor) {
+			if ((MajorVersion > major) || ((MajorVersion == major && MinorVersion >= minor)))
+				return true;
+			else
+				return false;
+		}
 	}
 
 	class DebugInfo {
@@ -308,7 +318,7 @@ namespace Mono.Debugger.Soft
 		 * with newer runtimes, and vice versa.
 		 */
 		public const int MAJOR_VERSION = 2;
-		public const int MINOR_VERSION = 2;
+		public const int MINOR_VERSION = 3;
 
 		enum WPSuspendPolicy {
 			NONE = 0,
@@ -380,7 +390,9 @@ namespace Mono.Debugger.Soft
 			GET_STATE = 3,
 			GET_INFO = 4,
 			/* FIXME: Merge into GET_INFO when the major protocol version is increased */
-			GET_ID = 5
+			GET_ID = 5,
+			/* Ditto */
+			GET_TID = 6
 		}
 
 		enum CmdEventRequest {
@@ -1555,6 +1567,10 @@ namespace Mono.Debugger.Soft
 			return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_ID, new PacketWriter ().WriteId (id)).ReadLong ();
 		}
 
+		public long Thread_GetTID (long id) {
+			return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_TID, new PacketWriter ().WriteId (id)).ReadLong ();
+		}
+
 		/*
 		 * MODULE
 		 */
diff --git a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/MethodBodyMirror.cs b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/MethodBodyMirror.cs
index 20ec9aa..c03f4cd 100644
--- a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/MethodBodyMirror.cs
+++ b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/MethodBodyMirror.cs
@@ -105,28 +105,23 @@ namespace Mono.Debugger.Soft
 						instr.Operand = br.ReadByte ();
 					break;
 				case OperandType.ShortInlineVar :
-					br.ReadByte ();
-					//instr.Operand = GetVariable (body, br.ReadByte ());
+					instr.Operand = br.ReadByte ();
 					break;
 				case OperandType.ShortInlineArg :
-					br.ReadByte ();
-					//instr.Operand = GetParameter (body, br.ReadByte ());
+					instr.Operand = br.ReadByte ();
 					break;
 				case OperandType.InlineSig :
 					br.ReadInt32 ();
 					//instr.Operand = GetCallSiteAt (br.ReadInt32 (), context);
 					break;
 				case OperandType.InlineI :
-					br.ReadInt32 ();
-					//instr.Operand = br.ReadInt32 ();
+					instr.Operand = br.ReadInt32 ();
 					break;
 				case OperandType.InlineVar :
-					br.ReadInt16 ();
-					//instr.Operand = GetVariable (body, br.ReadInt16 ());
+					instr.Operand = br.ReadInt16 ();
 					break;
 				case OperandType.InlineArg :
-					br.ReadInt16 ();
-					//instr.Operand = GetParameter (body, br.ReadInt16 ());
+					instr.Operand = br.ReadInt16 ();
 					break;
 				case OperandType.InlineI8 :
 					instr.Operand = br.ReadInt64 ();
diff --git a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/ThreadMirror.cs b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/ThreadMirror.cs
index d18804b..617613d 100644
--- a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/ThreadMirror.cs
+++ b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/ThreadMirror.cs
@@ -61,5 +61,15 @@ namespace Mono.Debugger.Soft
 				return vm.conn.Thread_GetId (id);
 			}
 		}
+
+		/*
+		 * Return the system thread id (TID) for this thread, this id is not unique since
+		 * a newly started thread might reuse a dead thread's id.
+		 */
+		public long TID {
+			get {
+				return vm.conn.Thread_GetTID (id);
+			}
+		}
     }
 }
diff --git a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/VirtualMachine.cs b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/VirtualMachine.cs
index 2e0e622..28d7121 100644
--- a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/VirtualMachine.cs
+++ b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/VirtualMachine.cs
@@ -74,6 +74,11 @@ namespace Mono.Debugger.Soft
 		EventSet current_es;
 		int current_es_index;
 
+		/*
+		 * It is impossible to determine when to resume when using this method, since
+		 * the debuggee is suspended only once per event-set, not event.
+		 */
+		[Obsolete ("Use GetNextEventSet () instead")]
 		public Event GetNextEvent () {
 			lock (queue_monitor) {
 				if (current_es == null || current_es_index == current_es.Events.Length) {
@@ -102,6 +107,7 @@ namespace Mono.Debugger.Soft
 			}
 		}
 
+		[Obsolete ("Use GetNextEventSet () instead")]
 		public T GetNextEvent<T> () where T : Event {
 			return GetNextEvent () as T;
 		}
diff --git a/mcs/class/Mono.Debugger.Soft/Test/ChangeLog b/mcs/class/Mono.Debugger.Soft/Test/ChangeLog
index 3b52a4a..8730276 100644
--- a/mcs/class/Mono.Debugger.Soft/Test/ChangeLog
+++ b/mcs/class/Mono.Debugger.Soft/Test/ChangeLog
@@ -1,3 +1,14 @@
+2011-01-21  Zoltan Varga  <vargaz at gmail.com>
+
+	Obsolete VirtualMachine.GetNextEvent () as it is impossible to
+	determine when to resume after an event, since the debuggee
+	suspends only once per event-set.
+
+2011-01-20  Zoltan Varga  <vargaz at gmail.com>
+
+	Add a TID field to ThreadMirror which returns the system thread
+	id.
+
 2011-01-04  Zoltan Varga  <vargaz at gmail.com>
 
 	Add AssemblyLoadEventRequest () type to the sdb api, and use it to
diff --git a/mcs/class/Mono.Debugger.Soft/Test/dtest-app.cs b/mcs/class/Mono.Debugger.Soft/Test/dtest-app.cs
new file mode 100644
index 0000000..3e445c3
--- /dev/null
+++ b/mcs/class/Mono.Debugger.Soft/Test/dtest-app.cs
@@ -0,0 +1,864 @@
+/*
+ * dtest-app.cs:
+ *
+ *   Application program used by the debugger tests.
+ */
+using System;
+using System.Runtime.CompilerServices;
+using System.Reflection;
+using System.Reflection.Emit;
+using System.Diagnostics;
+using System.Threading;
+using System.Collections.Generic;
+using System.Linq;
+
+public class TestsBase
+{
+#pragma warning disable 0414
+#pragma warning disable 0169
+	public int base_field_i;
+	public string base_field_s;
+	static int base_static_i = 57;
+	static string base_static_s = "C";
+#pragma warning restore 0414
+#pragma warning restore 0169
+}
+
+public enum AnEnum {
+	A = 0,
+	B= 1
+}
+
+[DebuggerDisplay ("Tests", Name="FOO", Target=typeof (int))]
+[DebuggerTypeProxy (typeof (Tests))]
+public class Tests2 {
+	[DebuggerBrowsableAttribute (DebuggerBrowsableState.Collapsed)]
+	public int field_j;
+	public static int static_field_j;
+
+	[DebuggerBrowsableAttribute (DebuggerBrowsableState.Collapsed)]
+	public int AProperty {
+		get {
+			return 0;
+		}
+	}
+
+	public void invoke () {
+	}
+}
+
+public struct AStruct {
+	public int i;
+	public string s;
+	public byte k;
+	public IntPtr j;
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public int foo (int val) {
+		return val;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static int static_foo (int val) {
+		return val;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public int invoke_return_int () {
+		return i;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static int invoke_static () {
+		return 5;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public IntPtr invoke_return_intptr () {
+		return j;
+	}
+}
+
+public class GClass<T> {
+	public T field;
+	public static T static_field;
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public GClass () {
+	}
+}
+
+public struct GStruct<T> {
+	public T i;
+
+	public int j;
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public int invoke_return_int () {
+		return j;
+	}
+}
+
+public class Tests : TestsBase
+{
+#pragma warning disable 0414
+	int field_i;
+	string field_s;
+	AnEnum field_enum;
+	bool field_bool1, field_bool2;
+	char field_char;
+	byte field_byte;
+	sbyte field_sbyte;
+	short field_short;
+	ushort field_ushort;
+	long field_long;
+	ulong field_ulong;
+	float field_float;
+	double field_double;
+	Thread field_class;
+	IntPtr field_intptr;
+	static int static_i = 55;
+	static string static_s = "A";
+	public const int literal_i = 56;
+	public const string literal_s = "B";
+	public object child;
+	public AStruct field_struct;
+	public object field_boxed_struct;
+	public GStruct<int> generic_field_struct;
+	[ThreadStatic]
+	public static int tls_i;
+	public static bool is_attached = Debugger.IsAttached;
+
+#pragma warning restore 0414
+
+	public class NestedClass {
+	}
+
+	public int IntProperty {
+		get {
+			return field_i;
+		}
+		set {
+			field_i = value;
+		}
+	}
+
+	public int ReadOnlyProperty {
+		get {
+			return field_i;
+		}
+	}
+
+	public int this [int index] {
+		get {
+			return field_i;
+		}
+	}
+
+	public static int Main (String[] args) {
+		tls_i = 42;
+
+		if (args.Length > 0 && args [0] == "suspend-test")
+			/* This contains an infinite loop, so execute it conditionally */
+			suspend ();
+		breakpoints ();
+		single_stepping ();
+		arguments ();
+		objects ();
+		objrefs ();
+		vtypes ();
+		locals ();
+		line_numbers ();
+		type_info ();
+		assembly_load ();
+		invoke ();
+		exceptions ();
+		exception_filter ();
+		threads ();
+		dynamic_methods ();
+		if (args.Length > 0 && args [0] == "domain-test")
+			/* This takes a lot of time, so execute it conditionally */
+			domains ();
+		if (args.Length > 0 && args [0] == "ref-emit-test")
+			ref_emit ();
+		if (args.Length > 0 && args [0] == "frames-in-native")
+			frames_in_native ();
+		if (args.Length >0 && args [0] == "invoke-single-threaded")
+			new Tests ().invoke_single_threaded ();
+		return 3;
+	}
+
+	public static void breakpoints () {
+		/* Call these early so it is JITted by the time a breakpoint is placed on it */
+		bp3 ();
+		bp7<int> ();
+		bp7<string> ();
+
+		bp1 ();
+		bp2 ();
+		bp3 ();
+		bp4 ();
+		bp4 ();
+		bp4 ();
+		bp5 ();
+		bp6<string> ();
+		bp7<int> ();
+		bp7<string> ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void bp1 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void bp2 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void bp3 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void bp4 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void bp5 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void bp6<T> () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void bp7<T> () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void single_stepping () {
+		ss1 ();
+		ss2 ();
+		ss3 ();
+		ss3_2 ();
+		ss4 ();
+		ss5 (new int [] { 1, 2, 3 }, new Func<int, bool> (is_even));
+		try {
+			ss6 (true);
+		} catch {
+		}
+		ss_regress_654694 ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void ss1 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void ss2 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static int ss3 () {
+		int sum = 0;
+
+		for (int i = 0; i < 10; ++i)
+			sum += i;
+
+		return sum;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void ss3_2 () {
+		ss3_2_2 ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void ss3_2_2 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static int ss4 () {
+		ss1 (); ss1 ();
+		ss2 ();
+		return 0;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void ss5 (int[] arr, Func<int, bool> selector) {
+		// Call into linq which calls back into this assembly
+		arr.Count (selector);
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void ss6 (bool b) {
+		if (b) {
+			ss7 ();
+			throw new Exception ();
+		}
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void ss7 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static bool is_even (int i) {
+		return i % 2 == 0;
+	}
+
+	/*
+		lock (static_s) {
+			Console.WriteLine ("HIT!");
+		}
+		return 0;
+	}
+	*/
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void arguments () {
+		arg1 (SByte.MaxValue - 5, Byte.MaxValue - 5, true, Int16.MaxValue - 5, UInt16.MaxValue - 5, 'F', Int32.MaxValue - 5, UInt32.MaxValue - 5, Int64.MaxValue - 5, UInt64.MaxValue - 5, 1.2345f, 6.78910, new IntPtr (Int32.MaxValue - 5), new UIntPtr (UInt32.MaxValue - 5));
+		int i = 42;
+		arg2 ("FOO", null, "BLA", ref i, new GClass <int> { field = 42 }, new object ());
+		Tests t = new Tests () { field_i = 42, field_s = "S" };
+		t.arg3 ("BLA");
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static int arg1 (sbyte sb, byte b, bool bl, short s, ushort us, char c, int i, uint ui, long l, ulong ul, float f, double d, IntPtr ip, UIntPtr uip) {
+		return (int)(sb + b + (bl ? 0 : 1) + s + us + (int)c + i + ui + l + (long)ul + f + d + (int)ip + (int)uip);
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static string arg2 (string s, string s3, object o, ref int i, GClass <int> gc, object o2) {
+		return s + (s3 != null ? "" : "") + o + i + gc.field + o2;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public object arg3 (string s) {
+		return s + s + s + s + this;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void objects () {
+		Tests t = new Tests () { field_i = 42, field_bool1 = true, field_bool2 = false, field_char = 'A', field_byte = 129, field_sbyte = -33, field_short = Int16.MaxValue - 5, field_ushort = UInt16.MaxValue - 5, field_long = Int64.MaxValue - 5, field_ulong = UInt64.MaxValue - 5, field_float = 3.14f, field_double = 3.14f, field_s = "S", base_field_i = 43, base_field_s = "T", field_enum = AnEnum.B, field_class = null, field_intptr = new IntPtr (Int32.MaxValue - 5) };
+		t.o1 (new Tests2 () { field_j = 43 }, new GClass <int> { field = 42 }, new GClass <string> { field = "FOO" });
+		o2 (new string [] { "BAR", "BAZ" }, new int[] { 42, 43 }, new int [,] { { 1, 2 }, { 3, 4 }}, (int[,])Array.CreateInstance (typeof (int), new int [] { 2, 2}, new int [] { 1, 3}), new int[] { 0 });
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public object o1 (Tests2 t, GClass <int> gc1, GClass <string> gc2) {
+		if (t == null || gc1 == null || gc2 == null)
+			return null;
+		else
+			return this;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static string o2 (string[] s2, int[] s3, int[,] s4, int[,] s5, IList<int> s6) {
+		return s2 [0] + s3 [0] + s4 [0, 0] + s6 [0];
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void objrefs () {
+		Tests t = new Tests () {};
+		set_child (t);
+		t.objrefs1 ();
+		t.child = null;
+		GC.Collect ();
+		objrefs2 ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void set_child (Tests t) {
+		t.child = new Tests ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public void objrefs1 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void objrefs2 () {
+	}
+
+	public static void vtypes () {
+		Tests t = new Tests () { field_struct = new AStruct () { i = 42, s = "S", k = 43 }, generic_field_struct = new GStruct<int> () { i = 42 }, field_boxed_struct = new AStruct () { i = 42 }};
+		AStruct s = new AStruct { i = 44, s = "T", k = 45 };
+		AStruct[] arr = new AStruct[] { 
+			new AStruct () { i = 1, s = "S1" },
+			new AStruct () { i = 2, s = "S2" } };
+		t.vtypes1 (s, arr);
+		vtypes2 (s);
+		vtypes3 (s);
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public object vtypes1 (AStruct s, AStruct[] arr) {
+		if (arr != null)
+			return this;
+		else
+			return null;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void vtypes2 (AStruct s) {
+		s.foo (5);
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void vtypes3 (AStruct s) {
+		AStruct.static_foo (5);
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void locals () {
+		locals1 (null);
+		locals2<string> (null, 5, "ABC");
+		locals3 ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void locals1 (string[] args) {
+		long foo = 42;
+
+		for (int j = 0; j < 10; ++j) {
+			foo ++;
+		}
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void locals2<T> (string[] args, int arg, T t) {
+		long i = 42;
+		string s = "AB";
+
+		for (int j = 0; j < 10; ++j) {
+			if (s != null)
+				i ++;
+			if (t != null)
+				i ++;
+		}
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void locals3 () {
+		string s = "B";
+		s.ToString ();
+
+		{
+			long i = 42;
+			i ++;
+			locals4 ();
+		}
+		{
+			string i = "A";
+			i.ToString ();
+			locals5 ();
+		}
+		{
+			long j = 42;
+			j ++;
+		}
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void locals4 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void locals5 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void line_numbers () {
+		LineNumbers.ln1 ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void suspend () {
+		long i = 5;
+
+		while (true) {
+			i ++;
+		}
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void type_info () {
+		Tests t = new Tests () { field_i = 42, field_s = "S", base_field_i = 43, base_field_s = "T", field_enum = AnEnum.B };
+		t.ti1 (new Tests2 () { field_j = 43 }, new GClass <int> { field = 42 }, new GClass <string> { field = "FOO" });
+		int val = 0;
+		unsafe {
+			AStruct s = new AStruct () { i = 42, s = "S", k = 43 };
+
+			ti2 (new string [] { "BAR", "BAZ" }, new int[] { 42, 43 }, new int [,] { { 1, 2 }, { 3, 4 }}, ref val, (int*)IntPtr.Zero, 5, s, new Tests (), new Tests2 (), new GClass <int> (), AnEnum.B);
+		}
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public object ti1 (Tests2 t, GClass <int> gc1, GClass <string> gc2) {
+		if (t == null || gc1 == null || gc2 == null)
+			return null;
+		else
+			return this;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static unsafe string ti2 (string[] s2, int[] s3, int[,] s4, ref int ri, int* ptr, int i, AStruct s, Tests t, Tests2 t2, GClass<int> g, AnEnum ae) {
+		return s2 [0] + s3 [0] + s4 [0, 0];
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void assembly_load () {
+		assembly_load_2 ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void assembly_load_2 () {
+		// This will load System.dll while holding the loader lock
+		new Foo ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void invoke () {
+		new Tests ().invoke1 (new Tests2 (), new AStruct () { i = 42, j = (IntPtr)43 }, new GStruct<int> { j = 42 });
+		new Tests ().invoke_ex ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public void invoke1 (Tests2 t, AStruct s, GStruct<int> g) {
+		invoke2 ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public void invoke2 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public void invoke_ex () {
+		invoke_ex_inner ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public void invoke_ex_inner () {
+		try {
+			throw new Exception ();
+		} catch {
+		}
+	}
+
+	int counter;
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public void invoke_single_threaded () {
+		// Spawn a thread incrementing a counter
+		bool finished = false;
+
+		new Thread (delegate () {
+				while (!finished)
+					counter ++;
+		}).Start ();
+
+		Thread.Sleep (100);
+
+		invoke_single_threaded_2 ();
+
+		finished = true;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public void invoke_single_threaded_2 () {
+	}
+
+	public void invoke_return_void () {
+	}
+
+	public string invoke_return_ref () {
+		return "ABC";
+	}
+
+	public object invoke_return_null () {
+		return null;
+	}
+
+	public int invoke_return_primitive () {
+		return 42;
+	}
+
+	public void invoke_type_load () {
+		new Class3 ();
+	}
+
+	class Class3 {
+	}
+
+	public long invoke_pass_primitive (byte ub, sbyte sb, short ss, ushort us, int i, uint ui, long l, ulong ul, char c, bool b, float f, double d) {
+		return ub + sb + ss + us + i + ui + l + (long)ul + (int)c + (b ? 1 : 0) + (int)f + (int)d;
+	}
+
+	public int invoke_pass_primitive2 (bool b) {
+		return b ? 1 : 0;
+	}
+
+	public string invoke_pass_ref (string s) {
+		return s;
+	}
+
+	public static string invoke_static_pass_ref (string s) {
+		return s;
+	}
+
+	public static void invoke_static_return_void () {
+	}
+
+	public static void invoke_throws () {
+		throw new Exception ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void exceptions () {
+		try {
+			throw new OverflowException ();
+		} catch (Exception) {
+		}
+		try {
+			throw new OverflowException ();
+		} catch (Exception) {
+		}
+		try {
+			throw new ArgumentException ();
+		} catch (Exception) {
+		}
+		try {
+			throw new OverflowException ();
+		} catch (Exception) {
+		}
+
+		object o = null;
+		try {
+			o.GetType ();
+		} catch (Exception) {
+		}
+
+		try {
+			exceptions2 ();
+		} catch (Exception) {
+		}
+	}
+
+	internal static Delegate create_filter_delegate (Delegate dlg, MethodInfo filter_method)
+	{
+		if (dlg == null)
+			throw new ArgumentNullException ();
+		if (dlg.Target != null)
+			throw new ArgumentException ();
+		if (dlg.Method == null)
+			throw new ArgumentException ();
+
+		var ret_type = dlg.Method.ReturnType;
+		var param_types = dlg.Method.GetParameters ().Select (x => x.ParameterType).ToArray ();
+
+		var dynamic = new DynamicMethod (Guid.NewGuid ().ToString (), ret_type, param_types, typeof (object), true);
+		var ig = dynamic.GetILGenerator ();
+
+		LocalBuilder retval = null;
+		if (ret_type != typeof (void))
+			retval = ig.DeclareLocal (ret_type);
+
+		var label = ig.BeginExceptionBlock ();
+
+		for (int i = 0; i < param_types.Length; i++)
+			ig.Emit (OpCodes.Ldarg, i);
+		ig.Emit (OpCodes.Call, dlg.Method);
+
+		if (retval != null)
+			ig.Emit (OpCodes.Stloc, retval);
+
+		ig.Emit (OpCodes.Leave, label);
+
+		ig.BeginExceptFilterBlock ();
+
+		ig.Emit (OpCodes.Call, filter_method);
+
+		ig.BeginCatchBlock (null);
+
+		ig.Emit (OpCodes.Pop);
+
+		ig.EndExceptionBlock ();
+
+		if (retval != null)
+			ig.Emit (OpCodes.Ldloc, retval);
+
+		ig.Emit (OpCodes.Ret);
+
+		return dynamic.CreateDelegate (dlg.GetType ());
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	static void exception_filter_method () {
+		throw new InvalidOperationException ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	static int exception_filter_filter (Exception exc) {
+		return 1;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void exception_filter () {
+		var method = typeof (Tests).GetMethod (
+			"exception_filter_method", BindingFlags.NonPublic | BindingFlags.Static);
+		var filter_method = typeof (Tests).GetMethod (
+			"exception_filter_filter", BindingFlags.NonPublic | BindingFlags.Static);
+
+		var dlg = Delegate.CreateDelegate (typeof (Action), method);
+
+		var wrapper = (Action) create_filter_delegate (dlg, filter_method);
+
+		wrapper ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static bool return_true () {
+		return true;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void exceptions2 () {
+		if (return_true ())
+			throw new Exception ();
+		Console.WriteLine ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void threads () {
+		Thread t = new Thread (delegate () {});
+
+		t.Start ();
+		t.Join ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void domains () {
+		AppDomain domain = AppDomain.CreateDomain ("domain");
+
+		CrossDomain o = (CrossDomain)domain.CreateInstanceAndUnwrap (
+				   typeof (CrossDomain).Assembly.FullName, "CrossDomain");
+
+		o.invoke_2 ();
+
+		o.invoke ();
+
+		o.invoke_2 ();
+
+		AppDomain.Unload (domain);
+
+		domains_2 ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void domains_2 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void invoke_in_domain () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void invoke_in_domain_2 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void dynamic_methods () {
+		var m = new DynamicMethod ("dyn_method", typeof (void), new Type []  { typeof (int) }, typeof (object).Module);
+		var ig = m.GetILGenerator ();
+
+		ig.Emit (OpCodes.Ldstr, "FOO");
+		ig.Emit (OpCodes.Call, typeof (Tests).GetMethod ("dyn_call"));
+		ig.Emit (OpCodes.Ret);
+
+		var del = (Action<int>)m.CreateDelegate (typeof (Action<int>));
+
+		del (0);
+	}
+
+	public static void dyn_call (string s) {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void ref_emit () {
+		AssemblyName assemblyName = new AssemblyName ();
+		assemblyName.Name = "foo";
+
+		AssemblyBuilder assembly =
+			Thread.GetDomain ().DefineDynamicAssembly (
+													   assemblyName, AssemblyBuilderAccess.RunAndSave);
+
+		ModuleBuilder module = assembly.DefineDynamicModule ("foo.dll");
+
+		TypeBuilder tb = module.DefineType ("foo", TypeAttributes.Public, typeof (object));
+		MethodBuilder mb = tb.DefineMethod ("ref_emit_method", MethodAttributes.Public|MethodAttributes.Static, CallingConventions.Standard, typeof (void), new Type [] { });
+		ILGenerator ig = mb.GetILGenerator ();
+		ig.Emit (OpCodes.Ldstr, "FOO");
+		ig.Emit (OpCodes.Call, typeof (Tests).GetMethod ("ref_emit_call"));
+		ig.Emit (OpCodes.Ret);
+
+		Type t = tb.CreateType ();
+
+		t.GetMethod ("ref_emit_method").Invoke (null, null);
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void ref_emit_call (string s) {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void frames_in_native () {
+		Thread.Sleep (500);
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void string_call (string s) {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void ss_regress_654694 () {
+		if (true) {
+			string h = "hi";
+			string_call (h);
+		}
+	}
+}
+
+public class CrossDomain : MarshalByRefObject
+{
+	public void invoke () {
+		Tests.invoke_in_domain ();
+	}
+
+	public void invoke_2 () {
+		Tests.invoke_in_domain_2 ();
+	}
+}	
+
+public class Foo
+{
+	public ProcessStartInfo info;
+}
+
+// Class used for line number info testing, don't change its layout
+public class LineNumbers
+{
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void ln1 () {
+		ln2 ();
+		ln3 ();
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void ln2 () {
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void ln3 () {
+	}
+}
diff --git a/mcs/class/Mono.Debugger.Soft/Test/dtest-excfilter.il b/mcs/class/Mono.Debugger.Soft/Test/dtest-excfilter.il
new file mode 100644
index 0000000..3d435fd
--- /dev/null
+++ b/mcs/class/Mono.Debugger.Soft/Test/dtest-excfilter.il
@@ -0,0 +1,47 @@
+.assembly extern mscorlib
+{
+  .ver 2:0:0:0
+  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
+}
+.assembly 'dtest-lib' { }
+
+.class public auto ansi ExceptionFilterTest
+       extends [mscorlib]System.Object
+{
+	.method public static void Main () cil managed
+	{
+		.entrypoint
+		call void class ExceptionFilterTest::Test ()
+		ret
+	}
+
+	.method public static int32 Filter ([mscorlib]System.Exception exc) cil managed noinlining
+	{
+		ldc.i4.1
+		ret
+	}
+
+	.method public static void Handler ([mscorlib]System.Exception exc) cil managed noinlining
+	{
+		ret
+	}
+
+	.method public static void Test () cil managed noinlining
+	{
+		.try {
+			newobj instance void class [mscorlib]System.InvalidOperationException::.ctor ()
+			throw
+
+			leave end
+		} filter {
+			call int32 class ExceptionFilterTest::Filter([mscorlib]System.Exception)
+			endfilter
+		} {
+			call void class ExceptionFilterTest::Handler([mscorlib]System.Exception)
+			leave end
+		}
+
+	end:
+		ret
+	}
+}
diff --git a/mcs/class/Mono.Debugger.Soft/Test/dtest.cs b/mcs/class/Mono.Debugger.Soft/Test/dtest.cs
index 8734297..46fa1bd 100644
--- a/mcs/class/Mono.Debugger.Soft/Test/dtest.cs
+++ b/mcs/class/Mono.Debugger.Soft/Test/dtest.cs
@@ -36,6 +36,12 @@ public class DebuggerTests
 	public static string runtime = Environment.GetEnvironmentVariable ("DBG_RUNTIME");
 	public static string agent_args = Environment.GetEnvironmentVariable ("DBG_AGENT_ARGS");
 
+	Event GetNextEvent () {
+		var es = vm.GetNextEventSet ();
+		Assert.AreEqual (1, es.Events.Length);
+		return es [0];
+	}
+
 	void Start (string[] args) {
 		if (!listening) {
 			var pi = new Diag.ProcessStartInfo ();
@@ -54,7 +60,7 @@ public class DebuggerTests
 		var load_req = vm.CreateAssemblyLoadRequest ();
 		load_req.Enable ();
 
-		Event vmstart = vm.GetNextEvent ();
+		Event vmstart = GetNextEvent ();
 		Assert.AreEqual (EventType.VMStart, vmstart.EventType);
 
 		vm.Resume ();
@@ -66,7 +72,7 @@ public class DebuggerTests
 
 		/* Find out the entry point */
 		while (true) {
-			e = vm.GetNextEvent ();
+			e = GetNextEvent ();
 
 			if (e is AssemblyLoadEvent) {
 				AssemblyLoadEvent ae = (AssemblyLoadEvent)e;
@@ -91,7 +97,7 @@ public class DebuggerTests
 
 		while (true) {
 			vm.Resume ();
-			e = vm.GetNextEvent ();
+			e = GetNextEvent ();
 			if (e is BreakpointEvent)
 				break;
 		}
@@ -107,7 +113,7 @@ public class DebuggerTests
 		req.Enable ();
 
 		vm.Resume ();
-		Event e = vm.GetNextEvent ();
+		Event e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 
 		req.Disable ();
@@ -155,7 +161,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 		while (true) {
-			Event e = vm.GetNextEvent ();
+			Event e = GetNextEvent ();
 
 			if (e is VMDeathEvent)
 				break;
@@ -175,7 +181,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.AreEqual (EventType.Breakpoint, e.EventType);
 		Assert.IsTrue (e is BreakpointEvent);
 		Assert.AreEqual (m.Name, (e as BreakpointEvent).Method.Name);
@@ -189,8 +195,6 @@ public class DebuggerTests
 
 	[Test]
 	public void BreakpointsSameLocation () {
-		Event e;
-
 		MethodMirror m = entry_point.DeclaringType.GetMethod ("bp2");
 		Assert.IsNotNull (m);
 
@@ -199,13 +203,13 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
-		Assert.IsTrue (e is BreakpointEvent);
-		Assert.AreEqual (m, (e as BreakpointEvent).Method);
+		var es = vm.GetNextEventSet ();
+		Assert.AreEqual (2, es.Events.Length);
+		Assert.IsTrue (es [0] is BreakpointEvent);
+		Assert.AreEqual (m, (es [0] as BreakpointEvent).Method);
 
-		e = vm.GetNextEvent ();
-		Assert.IsTrue (e is BreakpointEvent);
-		Assert.AreEqual (m.Name, (e as BreakpointEvent).Method.Name);
+		Assert.IsTrue (es [1] is BreakpointEvent);
+		Assert.AreEqual (m.Name, (es [1] as BreakpointEvent).Method.Name);
 	}
 
 	[Test]
@@ -224,21 +228,21 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.AreEqual (EventType.Breakpoint, e.EventType);
 		Assert.AreEqual (m.Name, (e as BreakpointEvent).Method.Name);
 
 		vm.Resume ();
 
 		/* Non-shared instance */
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.AreEqual (EventType.Breakpoint, e.EventType);
 		Assert.AreEqual (m2.Name, (e as BreakpointEvent).Method.Name);
 
 		vm.Resume ();
 
 		/* Shared instance */
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.AreEqual (EventType.Breakpoint, e.EventType);
 		Assert.AreEqual (m2.Name, (e as BreakpointEvent).Method.Name);
 	}
@@ -259,19 +263,19 @@ public class DebuggerTests
 		/* Run until bp4 */
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
-		Assert.AreEqual (EventType.Breakpoint, e.EventType);
-		Assert.AreEqual (m.Name, (e as BreakpointEvent).Method.Name);
-		e = vm.GetNextEvent ();
-		Assert.AreEqual (EventType.Breakpoint, e.EventType);
-		Assert.AreEqual (m.Name, (e as BreakpointEvent).Method.Name);
+		var es = vm.GetNextEventSet ();
+		Assert.AreEqual (2, es.Events.Length);
+		Assert.AreEqual (EventType.Breakpoint, es [0].EventType);
+		Assert.AreEqual (m.Name, (es [0] as BreakpointEvent).Method.Name);
+		Assert.AreEqual (EventType.Breakpoint, es [1].EventType);
+		Assert.AreEqual (m.Name, (es [1] as BreakpointEvent).Method.Name);
 
 		/* Clear one of them */
 		req1.Disable ();
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.AreEqual (EventType.Breakpoint, e.EventType);
 		Assert.AreEqual (m.Name, (e as BreakpointEvent).Method.Name);
 
@@ -280,7 +284,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.AreEqual (EventType.Breakpoint, e.EventType);
 		Assert.AreEqual (m2.Name, (e as BreakpointEvent).Method.Name);
 	}
@@ -301,7 +305,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (!(e is BreakpointEvent));
 		if (e is VMDeathEvent)
 			vm = null;
@@ -318,7 +322,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.AreEqual (EventType.Breakpoint, e.EventType);
 		Assert.IsTrue (e is BreakpointEvent);
 		Assert.AreEqual (m.Name, (e as BreakpointEvent).Method.Name);
@@ -335,13 +339,13 @@ public class DebuggerTests
 
 		// Step into ss1
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("ss1", (e as StepEvent).Method.Name);
 
 		// Step out of ss1
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("single_stepping", (e as StepEvent).Method.Name);
 
@@ -352,7 +356,7 @@ public class DebuggerTests
 
 		// Step over ss2
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("single_stepping", (e as StepEvent).Method.Name);
 
@@ -363,7 +367,7 @@ public class DebuggerTests
 
 		// Step into ss3
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("ss3", (e as StepEvent).Method.Name);
 
@@ -374,7 +378,7 @@ public class DebuggerTests
 
 		// Step back into single_stepping
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("single_stepping", (e as StepEvent).Method.Name);
 
@@ -385,7 +389,7 @@ public class DebuggerTests
 
 		// Step into ss3_2 ()
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("ss3_2", (e as StepEvent).Method.Name);
 
@@ -396,7 +400,7 @@ public class DebuggerTests
 
 		// Step over ss3_2_2 ()
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("ss3_2", (e as StepEvent).Method.Name);
 
@@ -406,7 +410,7 @@ public class DebuggerTests
 
 		// Step back into single_stepping () with the new request
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("single_stepping", (e as StepEvent).Method.Name);
 
@@ -417,7 +421,7 @@ public class DebuggerTests
 
 		// Step into ss4 ()
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("ss4", (e as StepEvent).Method.Name);
 
@@ -429,7 +433,7 @@ public class DebuggerTests
 
 		// Step over ss1 (); ss1 ();
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 
 		// Step into ss2 ()
@@ -438,7 +442,7 @@ public class DebuggerTests
 		req.Enable ();
 
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("ss2", (e as StepEvent).Method.Name);
 
@@ -453,7 +457,7 @@ public class DebuggerTests
 
 		// Step into is_even, skipping the linq stuff
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("is_even", (e as StepEvent).Method.Name);
 
@@ -470,10 +474,10 @@ public class DebuggerTests
 
 		// Check that single stepping works in out-of-line bblocks
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("ss6", (e as StepEvent).Method.Name);
 
@@ -491,12 +495,12 @@ public class DebuggerTests
 		req2.Enable ();
 
 		vm.Resume ();
-		Event e = vm.GetNextEvent ();
+		Event e = GetNextEvent ();
 		Assert.IsTrue (e is MethodEntryEvent);
 		Assert.AreEqual ("ss1", (e as MethodEntryEvent).Method.Name);
 
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is MethodExitEvent);
 		Assert.AreEqual ("ss1", (e as MethodExitEvent).Method.Name);
 
@@ -518,13 +522,13 @@ public class DebuggerTests
 
 		// Enter ss2, ss1 is skipped
 		vm.Resume ();
-		Event e = vm.GetNextEvent ();
+		Event e = GetNextEvent ();
 		Assert.IsTrue (e is MethodEntryEvent);
 		Assert.AreEqual ("ss2", (e as MethodEntryEvent).Method.Name);
 
 		// Breakpoint on ss3, the entry event is no longer reported
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is BreakpointEvent);
 
 		req1.Disable ();
@@ -1375,13 +1379,13 @@ public class DebuggerTests
 		req.Enable ();
 
 		vm.Resume ();
-		var e = vm.GetNextEvent ();
+		var e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("locals2", (e as StepEvent).Method.Name);
 
 		// Execute s = "AB";
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("locals2", (e as StepEvent).Method.Name);
 
@@ -1441,7 +1445,7 @@ public class DebuggerTests
 
 		// invalid stack frames
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("locals2", (e as StepEvent).Method.Name);
 
@@ -1493,7 +1497,7 @@ public class DebuggerTests
 
 		vm.Exit (5);
 
-		var e = vm.GetNextEvent ();
+		var e = GetNextEvent ();
 		Assert.IsInstanceOfType (typeof (VMDeathEvent), e);
 
 		var p = vm.Process;
@@ -1517,7 +1521,7 @@ public class DebuggerTests
 
 		vm.Dispose ();
 
-		var e = vm.GetNextEvent ();
+		var e = GetNextEvent ();
 		Assert.IsInstanceOfType (typeof (VMDisconnectEvent), e);
 
 		var p = vm.Process;
@@ -1547,7 +1551,7 @@ public class DebuggerTests
 		
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 
 		l = e.Thread.GetFrames ()[0].Location;
@@ -1558,28 +1562,28 @@ public class DebuggerTests
 		int line_base = l.LineNumber;
 
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		l = e.Thread.GetFrames ()[0].Location;
 		Assert.AreEqual ("ln2", l.Method.Name);
 		Assert.AreEqual (line_base + 6, l.LineNumber);
 
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		l = e.Thread.GetFrames ()[0].Location;
 		Assert.AreEqual ("ln1", l.Method.Name);
 		Assert.AreEqual (line_base + 1, l.LineNumber);
 
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		l = e.Thread.GetFrames ()[0].Location;
 		Assert.AreEqual ("ln3", l.Method.Name);
 		Assert.AreEqual (line_base + 10, l.LineNumber);
 
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		l = e.Thread.GetFrames ()[0].Location;
 		Assert.AreEqual ("ln1", l.Method.Name);
@@ -1637,7 +1641,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsInstanceOfType (typeof (AssemblyLoadEvent), e);
 		Assert.IsTrue ((e as AssemblyLoadEvent).Assembly.Location.EndsWith ("System.dll"));
 
@@ -1904,7 +1908,7 @@ public class DebuggerTests
 		StackFrame invoke_frame = null;
 
 		try {
-			e = vm.GetNextEvent ();
+			e = GetNextEvent ();
 			Assert.IsInstanceOfType (typeof (BreakpointEvent), e);
 			// Check stack trace support and invokes
 			var frames = e.Thread.GetFrames ();
@@ -1982,7 +1986,7 @@ public class DebuggerTests
 				vm.Resume ();
 			}, null);
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.AreEqual (EventType.TypeLoad, e.EventType);
 	}
 
@@ -1999,18 +2003,20 @@ public class DebuggerTests
 
 		Assert.IsTrue (e.Thread.ThreadId > 0);
 
+		Assert.AreEqual (e.Thread.TID, e.Thread.TID);
+
 		vm.EnableEvents (EventType.ThreadStart, EventType.ThreadDeath);
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsInstanceOfType (typeof (ThreadStartEvent), e);
 		var state = e.Thread.ThreadState;
 		Assert.IsTrue (state == ThreadState.Running || state == ThreadState.Unstarted);
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsInstanceOfType (typeof (ThreadDeathEvent), e);
 		Assert.AreEqual (ThreadState.Stopped, e.Thread.ThreadState);
 	}
@@ -2104,7 +2110,7 @@ public class DebuggerTests
 
 		// Step into invoke2
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 		Assert.AreEqual ("invoke2", (e as StepEvent).Method.Name);
 
@@ -2121,7 +2127,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsInstanceOfType (typeof (ExceptionEvent), e);
 		Assert.AreEqual ("OverflowException", (e as ExceptionEvent).Exception.Type.Name);
 
@@ -2137,7 +2143,7 @@ public class DebuggerTests
 		// Skip the throwing of the second OverflowException	   
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsInstanceOfType (typeof (ExceptionEvent), e);
 		Assert.AreEqual ("ArgumentException", (e as ExceptionEvent).Exception.Type.Name);
 		req.Disable ();
@@ -2148,7 +2154,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsInstanceOfType (typeof (ExceptionEvent), e);
 		Assert.AreEqual ("OverflowException", (e as ExceptionEvent).Exception.Type.Name);
 		req.Disable ();
@@ -2159,7 +2165,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsInstanceOfType (typeof (ExceptionEvent), e);
 		Assert.AreEqual ("NullReferenceException", (e as ExceptionEvent).Exception.Type.Name);
 		req.Disable ();
@@ -2170,7 +2176,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsInstanceOfType (typeof (ExceptionEvent), e);
 		Assert.AreEqual ("Exception", (e as ExceptionEvent).Exception.Type.Name);
 		frames = e.Thread.GetFrames ();
@@ -2183,7 +2189,7 @@ public class DebuggerTests
 		sreq.Enable ();
 
 		vm.Resume ();
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsInstanceOfType (typeof (StepEvent), e);
 		frames = e.Thread.GetFrames ();
 		Assert.AreEqual ("exceptions", frames [0].Method.Name);
@@ -2206,7 +2212,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.AreEqual (EventType.Breakpoint, e.EventType);
 		Assert.IsTrue (e is BreakpointEvent);
 		Assert.AreEqual (m.Name, (e as BreakpointEvent).Method.Name);
@@ -2244,7 +2250,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		var e = vm.GetNextEvent ();
+		var e = GetNextEvent ();
 		Assert.AreEqual (EventType.Breakpoint, e.EventType);
 		Assert.IsTrue (e is BreakpointEvent);
 		Assert.AreEqual (filter_method.Name, (e as BreakpointEvent).Method.Name);
@@ -2319,7 +2325,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsInstanceOfType (typeof (ExceptionEvent), e);
 		Assert.AreEqual ("NullReferenceException", (e as ExceptionEvent).Exception.Type.Name);
 
@@ -2340,7 +2346,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 		
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsInstanceOfType (typeof (AppDomainCreateEvent), e);
 
 		var domain = (e as AppDomainCreateEvent).Domain;
@@ -2352,7 +2358,7 @@ public class DebuggerTests
 
 		while (true) {
 			vm.Resume ();
-			e = vm.GetNextEvent ();
+			e = GetNextEvent ();
 			if (e is BreakpointEvent)
 				break;
 		}
@@ -2375,7 +2381,7 @@ public class DebuggerTests
 
 		while (true) {
 			vm.Resume ();
-			e = vm.GetNextEvent ();
+			e = GetNextEvent ();
 			if (e is BreakpointEvent)
 				break;
 		}
@@ -2388,7 +2394,7 @@ public class DebuggerTests
 		// Run until the unload
 		while (true) {
 			vm.Resume ();
-			e = vm.GetNextEvent ();
+			e = GetNextEvent ();
 			if (e is AssemblyUnloadEvent) {
 				continue;
 			} else {
@@ -2561,7 +2567,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is BreakpointEvent);
 
 		var req = vm.CreateStepRequest (e.Thread);
@@ -2571,7 +2577,7 @@ public class DebuggerTests
 
 		vm.Resume ();
 
-		e = vm.GetNextEvent ();
+		e = GetNextEvent ();
 		Assert.IsTrue (e is StepEvent);
 	}
 
diff --git a/mcs/class/Mono.Posix/Mono.Remoting.Channels.Unix/ChangeLog b/mcs/class/Mono.Posix/Mono.Remoting.Channels.Unix/ChangeLog
index 554be02..3e72847 100644
--- a/mcs/class/Mono.Posix/Mono.Remoting.Channels.Unix/ChangeLog
+++ b/mcs/class/Mono.Posix/Mono.Remoting.Channels.Unix/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-31  Lluis Sanchez  <lluis at novell.com>
+
+	Handle possible exceptions thrown by Socket.Close
+
 2010-08-11  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
 
 	Adapt to new exception in threadpool behavior.
diff --git a/mcs/class/Mono.Posix/Mono.Remoting.Channels.Unix/UnixServerChannel.cs b/mcs/class/Mono.Posix/Mono.Remoting.Channels.Unix/UnixServerChannel.cs
index 3162d86..0cbb928 100644
--- a/mcs/class/Mono.Posix/Mono.Remoting.Channels.Unix/UnixServerChannel.cs
+++ b/mcs/class/Mono.Posix/Mono.Remoting.Channels.Unix/UnixServerChannel.cs
@@ -310,9 +310,12 @@ namespace Mono.Remoting.Channels.Unix
             }
             finally
             {
-                _stream.Close();
-				_client.Close ();
-                _serverChannel.ReleaseConnection (Thread.CurrentThread);
+				try {
+	                _serverChannel.ReleaseConnection (Thread.CurrentThread);
+	                _stream.Close();
+					_client.Close ();
+				} catch {
+				}
             }
         }
         
diff --git a/mcs/class/Mono.Security/Mono.Security.X509/ChangeLog b/mcs/class/Mono.Security/Mono.Security.X509/ChangeLog
index 7a8082b..b07ed23 100644
--- a/mcs/class/Mono.Security/Mono.Security.X509/ChangeLog
+++ b/mcs/class/Mono.Security/Mono.Security.X509/ChangeLog
@@ -1,3 +1,8 @@
+2011-02-11  Sebastien Pouliot  <sebastien at ximian.com>
+
+	Continue X509Chain processing even if the local machine directory
+	does not exists
+
 2010-11-03  Sebastien Pouliot  <sebastien at ximian.com>
 
 	Fix condition so the new feature is available outside NET_2_1
diff --git a/mcs/class/Mono.Security/Mono.Security.X509/X509Store.cs b/mcs/class/Mono.Security/Mono.Security.X509/X509Store.cs
index df9c8cb..c4bb4b9 100644
--- a/mcs/class/Mono.Security/Mono.Security.X509/X509Store.cs
+++ b/mcs/class/Mono.Security/Mono.Security.X509/X509Store.cs
@@ -232,7 +232,8 @@ namespace Mono.Security.X509 {
 			// If privateKey it's available, load it too..
 			CspParameters cspParams = new CspParameters ();
 			cspParams.KeyContainerName = CryptoConvert.ToHex (cert.Hash);
-			cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
+			if (_storePath.StartsWith (X509StoreManager.LocalMachinePath))
+				cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
 			KeyPairPersistence kpp = new KeyPairPersistence (cspParams);
 
 			if (!kpp.Load ())
@@ -314,7 +315,7 @@ namespace Mono.Security.X509 {
 			}
 			return list;
 		}
-#if !INSIDE_CORLIB
+#if !NET_2_1
 		private void ImportPrivateKey (X509Certificate certificate, CspParameters cspParams)
 		{
 			RSACryptoServiceProvider rsaCsp = certificate.RSA as RSACryptoServiceProvider;
diff --git a/mcs/class/System.ComponentModel.DataAnnotations/ChangeLog b/mcs/class/System.ComponentModel.DataAnnotations/ChangeLog
index 4a75b0d..6446dd7 100644
--- a/mcs/class/System.ComponentModel.DataAnnotations/ChangeLog
+++ b/mcs/class/System.ComponentModel.DataAnnotations/ChangeLog
@@ -1,3 +1,8 @@
+2011-01-26  Antoine Cailliau  <antoine.cailliau at uclouvain.be>
+
+	Implements
+	System.ComponentModel.DataAnnotations.RegularExpressionAttribute
+
 2010-08-21  Marek Habersack  <grendel at twistedcode.net>
 
 	Implemented the StringLengthAttribute
diff --git a/mcs/class/System.ComponentModel.DataAnnotations/System.ComponentModel.DataAnnotations/ChangeLog b/mcs/class/System.ComponentModel.DataAnnotations/System.ComponentModel.DataAnnotations/ChangeLog
index 6bf2343..4406805 100644
--- a/mcs/class/System.ComponentModel.DataAnnotations/System.ComponentModel.DataAnnotations/ChangeLog
+++ b/mcs/class/System.ComponentModel.DataAnnotations/System.ComponentModel.DataAnnotations/ChangeLog
@@ -1,3 +1,8 @@
+2011-01-26  Antoine Cailliau  <antoine.cailliau at uclouvain.be>
+
+	Implements
+	System.ComponentModel.DataAnnotations.RegularExpressionAttribute
+
 2011-01-13  Marek Habersack  <grendel at twistedcode.net>
 
 	[data-annotations] Added some missing 4.0 members
diff --git a/mcs/class/System.ComponentModel.DataAnnotations/System.ComponentModel.DataAnnotations/RegularExpressionAttribute.cs b/mcs/class/System.ComponentModel.DataAnnotations/System.ComponentModel.DataAnnotations/RegularExpressionAttribute.cs
index 15f6f61..342076c 100644
--- a/mcs/class/System.ComponentModel.DataAnnotations/System.ComponentModel.DataAnnotations/RegularExpressionAttribute.cs
+++ b/mcs/class/System.ComponentModel.DataAnnotations/System.ComponentModel.DataAnnotations/RegularExpressionAttribute.cs
@@ -3,8 +3,10 @@
 //
 // Author:
 //	Atsushi Enomoto <atsushi at ximian.com>
+//  Antoine Cailliau <a.cailliau at maximux.net>
 //
 // Copyright (C) 2008 Novell Inc. http://novell.com
+// Copyright (C) 20011 Maximux Scris. http://maximux.net
 //
 
 //
@@ -29,29 +31,47 @@
 //
 using System;
 using System.ComponentModel;
+using System.Text.RegularExpressions;
 
 namespace System.ComponentModel.DataAnnotations
 {
-	[AttributeUsage (AttributeTargets.Property|AttributeTargets.Field, AllowMultiple = false)]
+
+#if NET_4_0
+	[AttributeUsage (AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter, AllowMultiple = false)]
+#else
+	[AttributeUsage (AttributeTargets.Property|AttributeTargets.Field, AllowMultiple = false)]	
+#endif
 	public class RegularExpressionAttribute : ValidationAttribute
 	{
 		public RegularExpressionAttribute (string pattern)
+			: base(GetDefaultErrorMessage)
 		{
+			if (pattern == null)
+				throw new ArgumentNullException("pattern");
 			Pattern = pattern;
 		}
 
 		public string Pattern { get; private set; }
 
-		[MonoTODO]
+		static string GetDefaultErrorMessage ()
+		{
+			return "The field {0} must match the regular expression {1}.";
+		}
+		
 		public override string FormatErrorMessage (string name)
 		{
-			throw new NotImplementedException ();
+			return string.Format(ErrorMessageString, name, Pattern);
 		}
 
-		[MonoTODO]
+		// LAMESPEC: does not throw ValidationException when value does not match the regular expression
 		public override bool IsValid (object value)
 		{
-			throw new NotImplementedException ();
+			if (value == null) 
+				return true;
+			
+			string str = (string) value;
+			Regex regex = new Regex(Pattern);
+			return regex.IsMatch(str);
 		}
 	}
 }
diff --git a/mcs/class/System.ComponentModel.DataAnnotations/System.ComponentModel.DataAnnotations_test.dll.sources b/mcs/class/System.ComponentModel.DataAnnotations/System.ComponentModel.DataAnnotations_test.dll.sources
index dd44918..4db3c78 100644
--- a/mcs/class/System.ComponentModel.DataAnnotations/System.ComponentModel.DataAnnotations_test.dll.sources
+++ b/mcs/class/System.ComponentModel.DataAnnotations/System.ComponentModel.DataAnnotations_test.dll.sources
@@ -9,3 +9,4 @@ System.ComponentModel.DataAnnotations/StringLengthAttributeTest.cs
 System.ComponentModel.DataAnnotations/ValidationAttributeTest.cs
 System.ComponentModel.DataAnnotations/ValidationContextTest.cs
 System.ComponentModel.DataAnnotations/ValidationResultTest.cs
+System.ComponentModel.DataAnnotations/RegularExpressionAttributeTest.cs
diff --git a/mcs/class/System.ComponentModel.DataAnnotations/Test/System.ComponentModel.DataAnnotations/RegularExpressionAttributeTest.cs b/mcs/class/System.ComponentModel.DataAnnotations/Test/System.ComponentModel.DataAnnotations/RegularExpressionAttributeTest.cs
new file mode 100644
index 0000000..6577839
--- /dev/null
+++ b/mcs/class/System.ComponentModel.DataAnnotations/Test/System.ComponentModel.DataAnnotations/RegularExpressionAttributeTest.cs
@@ -0,0 +1,115 @@
+//
+// StringLengthAttributeTest.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack at novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Text;
+
+using NUnit.Framework;
+using MonoTests.Common;
+
+namespace MonoTests.System.ComponentModel.DataAnnotations
+{
+	[TestFixture]
+	public class RegularExpressionAttributeTest
+	{
+		class RegularExpressionAttributePoker : RegularExpressionAttribute
+		{
+			public RegularExpressionAttributePoker (string pattern)
+				: base(pattern)
+			{ }
+
+			public string GetErrorMessageString ()
+			{
+				return ErrorMessageString;
+			}
+		}
+
+		[Test]
+		public void Constructor ()
+		{
+			var rea = new RegularExpressionAttributePoker (@"[A-Za-z]");
+			Assert.AreEqual (@"[A-Za-z]", rea.Pattern, "Patterns not saved correctly.");
+			Assert.AreEqual (null, rea.ErrorMessage, "Error message not null when not yet matched.");
+			Assert.AreEqual ("The field {0} must match the regular expression {1}.", rea.GetErrorMessageString (), "Error message not valid.");
+		}
+
+		[Test]
+		public void FormatMessageString ()
+		{
+			var rea = new RegularExpressionAttributePoker (@"[A-Za-z]");
+
+			Assert.AreEqual ("The field MyField must match the regular expression [A-Za-z].", 
+				rea.FormatErrorMessage ("MyField"), 
+				"Error message not correctly formatted.");
+
+#if !NET_4_0
+			rea = new RegularExpressionAttributePoker (@"[A-Za-z]");
+#endif
+			rea.ErrorMessage = "Param 0: {0}";
+			Assert.AreEqual ("Param 0: MyField", rea.FormatErrorMessage ("MyField"), "Error message not correctly updated.");
+
+#if !NET_4_0
+			rea = new RegularExpressionAttributePoker (@"[A-Za-z]");
+#endif
+			rea.ErrorMessage = "Param 0: {0}; Param 1: {1}";
+			Assert.AreEqual ("Param 0: MyField; Param 1: [A-Za-z]", rea.FormatErrorMessage ("MyField"), "Error message not correctly updated.");
+			Assert.AreEqual ("Param 0: ; Param 1: [A-Za-z]", rea.FormatErrorMessage (null), "Error message fails on null value.");
+		}
+
+		[Test]
+		public void IsValid ()
+		{
+			var rea = new RegularExpressionAttributePoker (@"[A-Za-z]");
+
+			Assert.IsTrue (rea.IsValid (null), "Null does not match [A-Za-z].");
+			Assert.IsTrue (rea.IsValid ("A"), "'A' does not match [A-Za-z].");
+			Assert.IsTrue (rea.IsValid ("a"), "'a' does not match [A-Za-z].");
+			Assert.IsTrue (rea.IsValid ("Bz"), "'Bz' does not match [A-Za-z].");
+			Assert.IsTrue (rea.IsValid ("string"), "'string' does not match [A-Za-z].");
+			Assert.IsFalse (rea.IsValid (String.Empty), "Empty string matches [A-Za-z].");
+			Assert.IsFalse (rea.IsValid ("0123456789"), "'0123456789' matches [A-Za-z].");
+			Assert.IsFalse (rea.IsValid ("0123456789"), "'0123456789A' matches [A-Za-z].");
+			AssertExtensions.Throws<InvalidCastException> (() => {
+				rea.IsValid (123);
+			}, "Casting does not fails");
+			AssertExtensions.Throws<InvalidCastException> (() => {
+				rea.IsValid (DateTime.Now);
+			}, "Casting does not fails");
+
+			rea = new RegularExpressionAttributePoker ("");
+			Assert.IsTrue (rea.IsValid (null), "null does not match empty pattern");
+			Assert.IsTrue (rea.IsValid (String.Empty), "empty string does not match empty pattern");
+			Assert.IsTrue (rea.IsValid ("string"), "'string' does not match empty pattern");
+			
+			AssertExtensions.Throws<ArgumentNullException> (() => {
+				rea = new RegularExpressionAttributePoker (null);
+			}, "Null pattern allowed");
+		}
+	}
+}
diff --git a/mcs/class/System.Core/Assembly/AssemblyInfo.cs b/mcs/class/System.Core/Assembly/AssemblyInfo.cs
index 79c719c..dbbfcb0 100644
--- a/mcs/class/System.Core/Assembly/AssemblyInfo.cs
+++ b/mcs/class/System.Core/Assembly/AssemblyInfo.cs
@@ -74,7 +74,7 @@ using System.Runtime.InteropServices;
 
 [assembly: SecurityPermission (SecurityAction.RequestMinimum, SkipVerification = true)]
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 [assembly: TypeForwardedTo (typeof (System.Security.Cryptography.Aes))]
 #endif
 
diff --git a/mcs/class/System.Core/Assembly/ChangeLog b/mcs/class/System.Core/Assembly/ChangeLog
index 1ca0ed1..7a58f17 100644
--- a/mcs/class/System.Core/Assembly/ChangeLog
+++ b/mcs/class/System.Core/Assembly/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
 2010-12-14  Jeffrey Stedfast  <fejj at gnome.org>
 
 	Add TypeForwardedTo for Aes on MOONLIGHT and BOOTSTRAP_NET_4_0
diff --git a/mcs/class/System.Core/System.Collections.Generic/ChangeLog b/mcs/class/System.Core/System.Collections.Generic/ChangeLog
index e675eb2..1d7dca9 100644
--- a/mcs/class/System.Core/System.Collections.Generic/ChangeLog
+++ b/mcs/class/System.Core/System.Collections.Generic/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
 2010-12-15  Marek Safar  <marek.safar at gmail.com>
 
 	Some .net 4.0 api compatibility fixes
diff --git a/mcs/class/System.Core/System.Collections.Generic/HashSet.cs b/mcs/class/System.Core/System.Collections.Generic/HashSet.cs
index 579a154..7f8bac2 100644
--- a/mcs/class/System.Core/System.Collections.Generic/HashSet.cs
+++ b/mcs/class/System.Core/System.Collections.Generic/HashSet.cs
@@ -44,7 +44,7 @@ namespace System.Collections.Generic {
 	[DebuggerDisplay ("Count={Count}")]
 	[DebuggerTypeProxy (typeof (CollectionDebuggerView<,>))]
 	public class HashSet<T> : ICollection<T>, ISerializable, IDeserializationCallback
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 							, ISet<T>
 #endif
 	{
diff --git a/mcs/class/System.Core/System.Linq/ChangeLog b/mcs/class/System.Core/System.Linq/ChangeLog
index 0768dcc..4f19145 100644
--- a/mcs/class/System.Core/System.Linq/ChangeLog
+++ b/mcs/class/System.Core/System.Linq/ChangeLog
@@ -1,3 +1,19 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
+2011-01-26  Jb Evain  <jbevain at gmail.com>
+
+	[linq] Fix Reverse for IList implementors
+
+2011-01-25  Jb Evain  <jbevain at gmail.com>
+
+	[linq] Fix overflow check for Count
+
+2011-01-25  Jb Evain  <jbevain at gmail.com>
+
+	[linq] fix Range extreme boundaries
+
 2010-12-30  Jb Evain  <jbevain at gmail.com>
 
 	[LINQ] Fix non generic AsQueryable issue #661462
diff --git a/mcs/class/System.Core/System.Linq/Enumerable.cs b/mcs/class/System.Core/System.Linq/Enumerable.cs
index d0a4c77..74a6123 100644
--- a/mcs/class/System.Core/System.Linq/Enumerable.cs
+++ b/mcs/class/System.Core/System.Linq/Enumerable.cs
@@ -637,7 +637,7 @@ namespace System.Linq
 			int counter = 0;
 			using (var enumerator = source.GetEnumerator ())
 				while (enumerator.MoveNext ())
-					counter++;
+					checked { counter++; }
 
 			return counter;
 		}
@@ -649,7 +649,7 @@ namespace System.Linq
 			int counter = 0;
 			foreach (var element in source)
 				if (predicate (element))
-					counter++;
+					checked { counter++; }
 
 			return counter;
 		}
@@ -2163,18 +2163,16 @@ namespace System.Linq
 			if (count < 0)
 				throw new ArgumentOutOfRangeException ("count");
 
-			long upto = ((long) start + count) - 1;
-
-			if (upto > int.MaxValue)
+			if (((long) start + count) - 1L > int.MaxValue)
 				throw new ArgumentOutOfRangeException ();
 
-			return CreateRangeIterator (start, (int) upto);
+			return CreateRangeIterator (start, count);
 		}
 
-		static IEnumerable<int> CreateRangeIterator (int start, int upto)
+		static IEnumerable<int> CreateRangeIterator (int start, int count)
 		{
-			for (int i = start; i <= upto; i++)
-				yield return i;
+			for (int i = 0; i < count; i++)
+				yield return start + i;
 		}
 
 		#endregion
@@ -2208,12 +2206,10 @@ namespace System.Linq
 
 		static IEnumerable<TSource> CreateReverseIterator<TSource> (IEnumerable<TSource> source)
 		{
-			var list = source as IList<TSource>;
-			if (list == null)
-				list = new List<TSource> (source);
+			var array = source.ToArray ();
 
-			for (int i = list.Count - 1; i >= 0; i--)
-				yield return list [i];
+			for (int i = array.Length - 1; i >= 0; i--)
+				yield return array [i];
 		}
 
 		#endregion
@@ -2972,7 +2968,7 @@ namespace System.Linq
 
 		#endregion
 		
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		#region Zip
 		
 		public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult> (this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
diff --git a/mcs/class/System.Core/System.Linq/EnumerableExecutor.cs b/mcs/class/System.Core/System.Linq/EnumerableExecutor.cs
index 3e14e0f..e0b7db3 100644
--- a/mcs/class/System.Core/System.Linq/EnumerableExecutor.cs
+++ b/mcs/class/System.Core/System.Linq/EnumerableExecutor.cs
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 namespace System.Linq
 {
diff --git a/mcs/class/System.Core/System.Linq/EnumerableExecutor_T.cs b/mcs/class/System.Core/System.Linq/EnumerableExecutor_T.cs
index 59c7751..2ee2837 100644
--- a/mcs/class/System.Core/System.Linq/EnumerableExecutor_T.cs
+++ b/mcs/class/System.Core/System.Linq/EnumerableExecutor_T.cs
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 using System.Linq.Expressions;
 
diff --git a/mcs/class/System.Core/System.Linq/EnumerableQuery.cs b/mcs/class/System.Core/System.Linq/EnumerableQuery.cs
index cc72a16..d81e346 100644
--- a/mcs/class/System.Core/System.Linq/EnumerableQuery.cs
+++ b/mcs/class/System.Core/System.Linq/EnumerableQuery.cs
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 namespace System.Linq
 {
diff --git a/mcs/class/System.Core/System.Linq/EnumerableQuery_T.cs b/mcs/class/System.Core/System.Linq/EnumerableQuery_T.cs
index 77562b4..a35aebf 100644
--- a/mcs/class/System.Core/System.Linq/EnumerableQuery_T.cs
+++ b/mcs/class/System.Core/System.Linq/EnumerableQuery_T.cs
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 using System.Collections;
 using System.Collections.Generic;
diff --git a/mcs/class/System.Core/System.Runtime.CompilerServices/ChangeLog b/mcs/class/System.Core/System.Runtime.CompilerServices/ChangeLog
index c9853d7..8229070 100644
--- a/mcs/class/System.Core/System.Runtime.CompilerServices/ChangeLog
+++ b/mcs/class/System.Core/System.Runtime.CompilerServices/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
 2010-06-18  Rolf Bjarne Kvinge  <RKvinge at novell.com>
 
 	* ExecutionScope.cs: This class exists in Moonlight, but isn't supported.
diff --git a/mcs/class/System.Core/System.Runtime.CompilerServices/ChangeLog b/mcs/class/System.Core/System.Runtime.CompilerServices/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Core/System.Runtime.CompilerServices/ChangeLog
copy to mcs/class/System.Core/System.Runtime.CompilerServices/ChangeLog.old
diff --git a/mcs/class/System.Core/System.Runtime.CompilerServices/DynamicAttribute.cs b/mcs/class/System.Core/System.Runtime.CompilerServices/DynamicAttribute.cs
index dfe8283..53151f8 100644
--- a/mcs/class/System.Core/System.Runtime.CompilerServices/DynamicAttribute.cs
+++ b/mcs/class/System.Core/System.Runtime.CompilerServices/DynamicAttribute.cs
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 using System;
 using System.Collections.Generic;
diff --git a/mcs/class/System.Core/System.Runtime.CompilerServices/StrongBox_T.cs b/mcs/class/System.Core/System.Runtime.CompilerServices/StrongBox_T.cs
index dd75189..21f63e7 100644
--- a/mcs/class/System.Core/System.Runtime.CompilerServices/StrongBox_T.cs
+++ b/mcs/class/System.Core/System.Runtime.CompilerServices/StrongBox_T.cs
@@ -32,7 +32,7 @@ namespace System.Runtime.CompilerServices {
 
 		public T Value;
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public StrongBox ()
 		{
 		}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/Aes.cs b/mcs/class/System.Core/System.Security.Cryptography/Aes.cs
index e21627b..28c2446 100644
--- a/mcs/class/System.Core/System.Security.Cryptography/Aes.cs
+++ b/mcs/class/System.Core/System.Security.Cryptography/Aes.cs
@@ -31,7 +31,7 @@
 //
 
 // Since 4.0 (both FX and SL) this type is defined in mscorlib - before 4.0 it was in System.Core.dll
-#if (INSIDE_CORLIB && (NET_4_0 || MOONLIGHT)) || (!INSIDE_CORLIB && !NET_4_0 && !MOONLIGHT)
+#if (INSIDE_CORLIB && (NET_4_0 || MOONLIGHT || MOBILE)) || (!INSIDE_CORLIB && !NET_4_0 && !MOONLIGHT && !MOBILE)
 
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
@@ -44,7 +44,7 @@ namespace System.Security.Cryptography {
 
 #if INSIDE_CORLIB
 	// since 4.0 (both FX and SL) this type now resides inside mscorlib.dll and link back to System.Core.dll
-	#if MOONLIGHT
+	#if MOONLIGHT || MOBILE
 	// version has not changed between SL3 (System.Core) and SL4
 	[TypeForwardedFrom (Consts.AssemblySystem_Core)]
 	#elif NET_4_0
diff --git a/mcs/class/System.Core/System.Security.Cryptography/ChangeLog b/mcs/class/System.Core/System.Security.Cryptography/ChangeLog
index 6468676..2806879 100644
--- a/mcs/class/System.Core/System.Security.Cryptography/ChangeLog
+++ b/mcs/class/System.Core/System.Security.Cryptography/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
 2010-12-14  Jeffrey Stedfast  <fejj at gnome.org>
 
 	Fixed AesManaged parameter names to make gui-compare happy
diff --git a/mcs/class/System.Core/System/Actions.cs b/mcs/class/System.Core/System/Actions.cs
index 0d09183..534ef8b 100644
--- a/mcs/class/System.Core/System/Actions.cs
+++ b/mcs/class/System.Core/System/Actions.cs
@@ -29,7 +29,7 @@
 using System;
 using System.Runtime.CompilerServices;
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 [assembly:TypeForwardedTo (typeof(Action<>))]
 [assembly:TypeForwardedTo (typeof(Action<,>))]
 [assembly:TypeForwardedTo (typeof(Action<,,>))]
@@ -41,7 +41,7 @@ using System.Runtime.CompilerServices;
 
 namespace System
 {
-#if NET_4_0
+#if NET_4_0 || MOBILE
 	public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9> (
 		T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9);
 
diff --git a/mcs/class/System.Core/System/ChangeLog b/mcs/class/System.Core/System/ChangeLog
index 1a97f56..5b69781 100644
--- a/mcs/class/System.Core/System/ChangeLog
+++ b/mcs/class/System.Core/System/ChangeLog
@@ -1,3 +1,21 @@
+2011-01-31  Jonathan Pryor  <jonpryor at vt.edu>
+
+	Fix the basic-profile build.
+
+2011-01-31  Jonathan Pryor  <jonpryor at vt.edu>
+
+	Fix the MonoDroid build.
+
+	Most System.TimeZoneInfo members weren't being included.
+
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Fix the mobile build
+
 2010-12-16  Jonathan Pryor  <jonpryor at vt.edu>
 
 	[monodroid] Add support for the Android TimeZone file format.
diff --git a/mcs/class/System.Core/System/Funcs.cs b/mcs/class/System.Core/System/Funcs.cs
index 621bd63..e68c6e0 100644
--- a/mcs/class/System.Core/System/Funcs.cs
+++ b/mcs/class/System.Core/System/Funcs.cs
@@ -25,7 +25,7 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Runtime.CompilerServices;
 
@@ -38,7 +38,7 @@ using System.Runtime.CompilerServices;
 
 namespace System
 {
-#if NET_4_0
+#if NET_4_0 || MOBILE
 	public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, out TResult> (
 		T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9);
 
diff --git a/mcs/class/System.Core/System/InvalidTimeZoneException.cs b/mcs/class/System.Core/System/InvalidTimeZoneException.cs
index cb9e438..b625c13 100644
--- a/mcs/class/System.Core/System/InvalidTimeZoneException.cs
+++ b/mcs/class/System.Core/System/InvalidTimeZoneException.cs
@@ -24,7 +24,7 @@
  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 using System;
 using System.Runtime.CompilerServices;
diff --git a/mcs/class/System.Core/System/TimeZoneInfo.AdjustmentRule.cs b/mcs/class/System.Core/System/TimeZoneInfo.AdjustmentRule.cs
index c597a18..1bd4bb5 100644
--- a/mcs/class/System.Core/System/TimeZoneInfo.AdjustmentRule.cs
+++ b/mcs/class/System.Core/System/TimeZoneInfo.AdjustmentRule.cs
@@ -24,8 +24,7 @@
  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
 
-#if (INSIDE_CORLIB && (NET_4_0 || MOONLIGHT)) || (MOBILE && !INSIDE_CORLIB) || (NET_3_5 && !NET_4_0)
-
+#if (INSIDE_CORLIB && (NET_4_0 || MOONLIGHT || MOBILE)) || (!INSIDE_CORLIB && (NET_3_5 && !NET_4_0 && !MOBILE))
 using System.Runtime.CompilerServices;
 using System.Runtime.Serialization;
 
@@ -35,7 +34,7 @@ namespace System
 		[SerializableAttribute]
 #if NET_4_0
 		[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
-#elif MOONLIGHT
+#elif MOONLIGHT || MOBILE
 		[TypeForwardedFrom (Consts.AssemblySystem_Core)]
 #endif
 		public sealed class AdjustmentRule : IEquatable<TimeZoneInfo.AdjustmentRule>, ISerializable, IDeserializationCallback
diff --git a/mcs/class/System.Core/System/TimeZoneInfo.Android.cs b/mcs/class/System.Core/System/TimeZoneInfo.Android.cs
index c95bb1e..9518191 100644
--- a/mcs/class/System.Core/System/TimeZoneInfo.Android.cs
+++ b/mcs/class/System.Core/System/TimeZoneInfo.Android.cs
@@ -18,7 +18,7 @@
  * limitations under the License.
  */
 
-#if MONODROID
+#if (INSIDE_CORLIB && MONODROID)
 
 using System;
 using System.Collections.Generic;
diff --git a/mcs/class/System.Core/System/TimeZoneInfo.TransitionTime.cs b/mcs/class/System.Core/System/TimeZoneInfo.TransitionTime.cs
index 615bf2e..73d7435 100644
--- a/mcs/class/System.Core/System/TimeZoneInfo.TransitionTime.cs
+++ b/mcs/class/System.Core/System/TimeZoneInfo.TransitionTime.cs
@@ -24,7 +24,7 @@
  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
 
-#if (INSIDE_CORLIB && (NET_4_0 || MOONLIGHT)) || (MOBILE && !INSIDE_CORLIB) || (NET_3_5 && !NET_4_0)
+#if (INSIDE_CORLIB && (NET_4_0 || MOONLIGHT || MOBILE)) || (!INSIDE_CORLIB && (NET_3_5 && !NET_4_0 && !MOBILE))
 
 using System.Runtime.CompilerServices;
 using System.Runtime.Serialization;
@@ -36,7 +36,7 @@ namespace System
 		[SerializableAttribute]
 #if NET_4_0
 		[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
-#elif MOONLIGHT
+#elif MOONLIGHT || MOBILE
 		[TypeForwardedFrom (Consts.AssemblySystem_Core)]
 #endif
 		public struct TransitionTime : IEquatable<TimeZoneInfo.TransitionTime>, ISerializable, IDeserializationCallback
diff --git a/mcs/class/System.Core/System/TimeZoneInfo.cs b/mcs/class/System.Core/System/TimeZoneInfo.cs
index 8742194..56577a3 100644
--- a/mcs/class/System.Core/System/TimeZoneInfo.cs
+++ b/mcs/class/System.Core/System/TimeZoneInfo.cs
@@ -27,11 +27,11 @@
 using System;
 using System.Runtime.CompilerServices;
 
-#if !INSIDE_CORLIB && (NET_4_0 || MOONLIGHT)
+#if !INSIDE_CORLIB && (NET_4_0 || MOONLIGHT || MOBILE)
 
 [assembly:TypeForwardedTo (typeof(TimeZoneInfo))]
 
-#elif NET_3_5 || (MOBILE && !INSIDE_CORLIB) || (MOONLIGHT && INSIDE_CORLIB)
+#elif (INSIDE_CORLIB && (NET_4_0 || MOONLIGHT || MOBILE)) || (!INSIDE_CORLIB && (NET_3_5 && !NET_4_0 && !MOBILE))
 
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
@@ -50,7 +50,7 @@ namespace System
 {
 #if NET_4_0
 	[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
-#elif MOONLIGHT
+#elif MOONLIGHT || MOBILE
 	[TypeForwardedFrom (Consts.AssemblySystem_Core)]
 #endif
 	[SerializableAttribute]
@@ -528,8 +528,9 @@ namespace System
 				}
 #endif
 #if MONODROID
-			systemTimeZones.AddRange (ZoneInfoDB.GetAvailableIds ()
-					.Select (id => ZoneInfoDB.GetTimeZone (id)));
+			foreach (string id in ZoneInfoDB.GetAvailableIds ()) {
+				systemTimeZones.Add (ZoneInfoDB.GetTimeZone (id));
+			}
 #elif LIBC
 				string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
 				foreach (string continent in continents) {
diff --git a/mcs/class/System.Core/System/TimeZoneNotFoundException.cs b/mcs/class/System.Core/System/TimeZoneNotFoundException.cs
index 4903ff1..2c1cbf7 100644
--- a/mcs/class/System.Core/System/TimeZoneNotFoundException.cs
+++ b/mcs/class/System.Core/System/TimeZoneNotFoundException.cs
@@ -24,7 +24,7 @@
  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 using System;
 using System.Runtime.CompilerServices;
diff --git a/mcs/class/System.Data.OracleClient/System.Data.OracleClient/ChangeLog b/mcs/class/System.Data.OracleClient/System.Data.OracleClient/ChangeLog
index eea0a29..4d1b276 100644
--- a/mcs/class/System.Data.OracleClient/System.Data.OracleClient/ChangeLog
+++ b/mcs/class/System.Data.OracleClient/System.Data.OracleClient/ChangeLog
@@ -1,3 +1,9 @@
+2010-01-30  Veerapuram Varadhan  <vvaradhan at novell.com>
+
+	** Fixes #667236 - Based on patch by Kalyanov.Dmitry at gmail.com
+	* OracleParameter.cs (GetOutValue): Handle OciDataType.Integer 
+	appropriately using the underlying dbType.
+	
 2009-10-29  Veerapuram Varadhan  <vvaradhan at novell.com>
 
 	** Fixes #322695
diff --git a/mcs/class/System.Data.OracleClient/System.Data.OracleClient/OracleParameter.cs b/mcs/class/System.Data.OracleClient/System.Data.OracleClient/OracleParameter.cs
index 9cfcd96..8979761 100644
--- a/mcs/class/System.Data.OracleClient/System.Data.OracleClient/OracleParameter.cs
+++ b/mcs/class/System.Data.OracleClient/System.Data.OracleClient/OracleParameter.cs
@@ -1,4 +1,4 @@
-//
+//
 // OracleParameter.cs
 //
 // Part of the Mono class libraries at
@@ -1305,8 +1305,25 @@ namespace System.Data.OracleClient
 				OciCalls.OCICharSetToUnicode (env, ret, bytes, out rsize);
 
 				// if not empty, parse string as a decimal using session format
-				if (ret.Length > 0)
-					value = Decimal.Parse (ret.ToString (), cmd.Connection.SessionFormatProvider);
+				if (ret.Length > 0) {
+					switch (dbType) {
+					case DbType.UInt16: 
+						value = UInt16.Parse (ret.ToString (), cmd.Connection.SessionFormatProvider);
+						break;
+					case DbType.UInt32: 
+						value = UInt32.Parse (ret.ToString (), cmd.Connection.SessionFormatProvider);
+						break;
+					case DbType.Int16:
+						value = Int16.Parse (ret.ToString (), cmd.Connection.SessionFormatProvider);
+						break;							
+					case DbType.Int32:
+						value = Int32.Parse (ret.ToString (), cmd.Connection.SessionFormatProvider);
+						break;
+					default:
+						value = Decimal.Parse (ret.ToString (), cmd.Connection.SessionFormatProvider);
+						break;
+					}
+				}
 				break;
 			case OciDataType.TimeStamp:
 				value = dateTimeDesc.GetDateTime (connection.Environment, dateTimeDesc.ErrorHandle);
diff --git a/mcs/class/System.Data.Services.Client/Makefile b/mcs/class/System.Data.Services.Client/Makefile
index ec6e7dc..30bcc19 100644
--- a/mcs/class/System.Data.Services.Client/Makefile
+++ b/mcs/class/System.Data.Services.Client/Makefile
@@ -5,7 +5,6 @@ include ../../build/rules.make
 LIBRARY = System.Data.Services.Client.dll
 
 LIBRARY_SNK = ../mono.snk
-LIBRARY_PACKAGE = none
 
 LIB_MCS_FLAGS = \
 	-d:NET_3_5	\
diff --git a/mcs/class/System.Runtime.Serialization/ChangeLog b/mcs/class/System.Runtime.Serialization/ChangeLog
index 009f31a..51721e6 100644
--- a/mcs/class/System.Runtime.Serialization/ChangeLog
+++ b/mcs/class/System.Runtime.Serialization/ChangeLog
@@ -1,3 +1,10 @@
+2011-02-08  Atsushi Eno  <atsushi at ximian.com>
+
+	There's a tricky namespace-mismatching deserialization in .NET
+	implementation.
+
+	Fixed bug #666333.
+
 2010-10-05  Atsushi Eno  <atsushi at ximian.com>
 
 	Implement DataContractResolver support. At least TryResolveType in
diff --git a/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/ChangeLog b/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/ChangeLog
index 7e783bf..f57364a 100644
--- a/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/ChangeLog
+++ b/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/ChangeLog
@@ -1,3 +1,32 @@
+2011-02-08  Atsushi Eno  <atsushi at ximian.com>
+
+	There's a tricky namespace-mismatching deserialization in .NET
+	implementation.
+
+	Fixed bug #666333.
+
+2011-02-08  Atsushi Eno  <atsushi at ximian.com>
+
+	Contract-based type must ensure that the base type is also
+	contract-based.
+
+	Fixed bug #661987 on WCF side.
+
+	Conflicts:
+
+	mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XmlObjectSerializerTest.cs
+
+2011-02-01  Atsushi Eno  <atsushi at ximian.com>
+
+	Members in the base type in different namespace are serialized in
+	base ns.
+
+	When the serializer serializes a Type B which is derived from A,
+	it used to serialize member M in A as in namespace_of_B, not in
+	namespace_of_A.
+
+	This should fix bug #652331.
+
 2010-12-14  Atsushi Eno  <atsushi at ximian.com>
 
 	Fix enum serialization too.
diff --git a/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/DataContractSerializer.cs b/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/DataContractSerializer.cs
index d44a416..3cfe9d5 100755
--- a/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/DataContractSerializer.cs
+++ b/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/DataContractSerializer.cs
@@ -386,7 +386,7 @@ namespace System.Runtime.Serialization
 		}
 #endif
 
-		[MonoTODO ("support arrays; support Serializable; support SharedType; use DataContractSurrogate")]
+		[MonoTODO ("use DataContractSurrogate")]
 		/*
 			when writeContentOnly is true, then the input XmlWriter
 			must be at element state. This is to write possible
diff --git a/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/KnownTypeCollection.cs b/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/KnownTypeCollection.cs
index 0b742de..66fb3c5 100755
--- a/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/KnownTypeCollection.cs
+++ b/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/KnownTypeCollection.cs
@@ -792,6 +792,12 @@ namespace System.Runtime.Serialization
 			contracts.Add (ret);
 			ret.Initialize ();
 
+			if (type.BaseType != typeof (object)) {
+				TryRegister (type.BaseType);
+				if (!FindUserMap (type.BaseType).IsContractAllowedType)
+					throw new InvalidDataContractException (String.Format ("To be serializable by data contract, type '{0}' cannot inherit from non-contract and non-Serializable type '{1}'", type, type.BaseType));
+			}
+
 			object [] attrs = type.GetCustomAttributes (typeof (KnownTypeAttribute), true);
 			for (int i = 0; i < attrs.Length; i++) {
 				KnownTypeAttribute kt = (KnownTypeAttribute) attrs [i];
diff --git a/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/SerializationMap.cs b/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/SerializationMap.cs
index 5f1f2ac..2542424 100644
--- a/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/SerializationMap.cs
+++ b/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/SerializationMap.cs
@@ -124,6 +124,8 @@ namespace System.Runtime.Serialization
 
 		public QName XmlName { get; set; }
 
+		public abstract bool IsContractAllowedType { get; }
+
 		protected void HandleId (XmlReader reader, XmlFormatterDeserializer deserializer, object instance)
 		{
 			HandleId (reader.GetAttribute ("Id", KnownTypeCollection.MSSimpleNamespace), deserializer, instance);
@@ -264,7 +266,7 @@ namespace System.Runtime.Serialization
 			reader.MoveToContent ();
 			if (!isEmpty && reader.NodeType == XmlNodeType.EndElement)
 				reader.ReadEndElement ();
-			else if (!isEmpty && reader.NodeType != XmlNodeType.None) {
+			else if (!isEmpty && !reader.EOF && reader.NodeType != XmlNodeType.EndElement) {
 				var li = reader as IXmlLineInfo;
 				throw new SerializationException (String.Format ("Deserializing type '{3}'. Expecting state 'EndElement'. Encountered state '{0}' with name '{1}' with namespace '{2}'.{4}",
 					reader.NodeType,
@@ -300,36 +302,48 @@ namespace System.Runtime.Serialization
 
 			int depth = reader.NodeType == XmlNodeType.None ? reader.Depth : reader.Depth - 1;
 			bool [] filled = new bool [Members.Count];
+			bool [] nsmatched = new bool [Members.Count];
 			int memberInd = -1, ordered = -1;
 			while (!empty && reader.NodeType == XmlNodeType.Element && reader.Depth > depth) {
 				DataMemberInfo dmi = null;
 				int i = 0;
+				bool nsmatchedOne = false;
 				for (; i < Members.Count; i++) { // unordered
 					if (Members [i].Order >= 0)
 						break;
-					if (reader.LocalName == Members [i].XmlName &&
-						(Members [i].XmlRootNamespace == null || reader.NamespaceURI == Members [i].XmlRootNamespace)) {
+					if (reader.LocalName == Members [i].XmlName) {
 						memberInd = i;
 						dmi = Members [i];
-						break;
+						nsmatchedOne = (dmi.XmlRootNamespace == null || reader.NamespaceURI == dmi.XmlRootNamespace);
+						if (nsmatchedOne)
+							break;
 					}
 				}
 				for (i = Math.Max (i, ordered); i < Members.Count; i++) { // ordered
 					if (dmi != null)
 						break;
-					if (reader.LocalName == Members [i].XmlName &&
-						(Members [i].XmlRootNamespace == null || reader.NamespaceURI == Members [i].XmlRootNamespace)) {
-						memberInd = i;
+					if (reader.LocalName == Members [i].XmlName) {
 						ordered = i;
+						memberInd = i;
 						dmi = Members [i];
-						break;
+						nsmatchedOne = (dmi.XmlRootNamespace == null || reader.NamespaceURI == dmi.XmlRootNamespace);
+						if (nsmatchedOne)
+							break;
 					}
 				}
-
+				
 				if (dmi == null) {
 					reader.Skip ();
+					reader.MoveToContent ();
 					continue;
 				}
+				if (filled [memberInd] && nsmatched [memberInd]) {
+					// The strictly-corresponding member (i.e. that matches namespace URI too, not only local name) already exists, so skip this element.
+					reader.Skip ();
+					reader.MoveToContent ();
+					continue;
+				}
+				nsmatched [memberInd] = nsmatchedOne;
 				SetValue (dmi, instance, deserializer.Deserialize (dmi.MemberType, reader));
 				filled [memberInd] = true;
 				reader.MoveToContent ();
@@ -381,6 +395,8 @@ namespace System.Runtime.Serialization
 
 	internal partial class XmlSerializableMap : SerializationMap
 	{
+		public override bool IsContractAllowedType { get { return true; } }
+
 		public XmlSerializableMap (Type type, QName qname, KnownTypeCollection knownTypes)
 			: base (type, qname, knownTypes)
 		{
@@ -419,6 +435,8 @@ namespace System.Runtime.Serialization
 		{
 		}
 
+		public override bool IsContractAllowedType { get { return true; } }
+
 		internal void Initialize ()
 		{
 			Type type = RuntimeType;
@@ -456,7 +474,7 @@ namespace System.Runtime.Serialization
 				if (!pi.CanRead || (!pi.CanWrite && !(map is ICollectionTypeMap)))
 					throw new InvalidDataContractException (String.Format (
 							"DataMember property '{0}' on type '{1}' must have both getter and setter.", pi, pi.DeclaringType));
-				data_members.Add (CreateDataMemberInfo (dma, pi, pi.PropertyType, qname.Namespace));
+				data_members.Add (CreateDataMemberInfo (dma, pi, pi.PropertyType, KnownTypeCollection.GetStaticQName (pi.DeclaringType).Namespace));
 			}
 
 			foreach (FieldInfo fi in type.GetFields (flags)) {
@@ -464,7 +482,7 @@ namespace System.Runtime.Serialization
 					GetDataMemberAttribute (fi);
 				if (dma == null)
 					continue;
-				data_members.Add (CreateDataMemberInfo (dma, fi, fi.FieldType, qname.Namespace));
+				data_members.Add (CreateDataMemberInfo (dma, fi, fi.FieldType, KnownTypeCollection.GetStaticQName (fi.DeclaringType).Namespace));
 			}
 
 			return data_members;
@@ -483,6 +501,8 @@ namespace System.Runtime.Serialization
 		{
 		}
 
+		public override bool IsContractAllowedType { get { return false; } }
+
 		internal void Initialize ()
 		{
 			Members.AddRange (GetDefaultMembers ());
@@ -502,7 +522,8 @@ namespace System.Runtime.Serialization
 					continue;
 				if (mi.GetCustomAttributes (typeof (IgnoreDataMemberAttribute), false).Length != 0)
 					continue;
-				l.Add (CreateDataMemberInfo (new DataMemberAttribute (), mi, mt, XmlName.Namespace));
+				string ns = KnownTypeCollection.GetStaticQName (mi.DeclaringType).Namespace;
+				l.Add (CreateDataMemberInfo (new DataMemberAttribute (), mi, mt, ns));
 			}
 			l.Sort (DataMemberInfo.DataMemberInfoComparer.Instance);
 			return l;
@@ -529,6 +550,8 @@ namespace System.Runtime.Serialization
 		internal override string CurrentNamespace {
 			get { return XmlName.Namespace; }
 		}
+
+		public override bool IsContractAllowedType { get { return true; } }
 	}
 
 	internal interface ICollectionTypeMap
@@ -574,6 +597,8 @@ namespace System.Runtime.Serialization
 			return null;
 		}
 
+		public override bool IsContractAllowedType { get { return false; } }
+
 		public override bool OutputXsiType {
 			get { return false; }
 		}
@@ -717,6 +742,8 @@ namespace System.Runtime.Serialization
 			get { return a != null && !String.IsNullOrEmpty (a.Namespace) ? a.Namespace : KnownTypeCollection.MSArraysNamespace; }
 		}
 
+		public override bool IsContractAllowedType { get { return a != null; } }
+
 		public Type KeyType { get { return key_type; } }
 		public Type ValueType { get { return value_type; } }
 
@@ -872,6 +899,8 @@ namespace System.Runtime.Serialization
 		{
 		}
 
+		public override bool IsContractAllowedType { get { return true; } }
+
 		public void Initialize ()
 		{
 			Members = GetMembers (RuntimeType, XmlName, false);
@@ -892,7 +921,7 @@ namespace System.Runtime.Serialization
 					if (fi.IsInitOnly)
 						throw new InvalidDataContractException (String.Format ("DataMember field {0} must not be read-only.", fi));
 					DataMemberAttribute dma = new DataMemberAttribute ();
-					data_members.Add (CreateDataMemberInfo (dma, fi, fi.FieldType, qname.Namespace));
+					data_members.Add (CreateDataMemberInfo (dma, fi, fi.FieldType, KnownTypeCollection.GetStaticQName (fi.DeclaringType).Namespace));
 				}
 			}
 
@@ -944,6 +973,8 @@ namespace System.Runtime.Serialization
 			}
 		}
 
+		public override bool IsContractAllowedType { get { return false; } }
+
 		private EnumMemberAttribute GetEnumMemberAttribute (
 			MemberInfo mi)
 		{
@@ -997,7 +1028,7 @@ namespace System.Runtime.Serialization
 
 			if (value != String.Empty) {
 				if (flag_attr && value.IndexOf (' ') != -1) {
-					long flags = 0l;
+					long flags = 0L;
 					foreach (string flag in value.Split (' ')) {
 						foreach (EnumMemberInfo emi in enum_members) {
 							if (emi.XmlName == flag) {
diff --git a/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization_test.dll.sources b/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization_test.dll.sources
index 3188183..39b5c26 100644
--- a/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization_test.dll.sources
+++ b/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization_test.dll.sources
@@ -1,3 +1,4 @@
+System.Runtime.Serialization/Bug666333Test.cs
 System.Runtime.Serialization/DataContractResolverTest.cs
 System.Runtime.Serialization/XmlObjectSerializerTest.cs
 System.Runtime.Serialization/XsdDataContractExporterTest.cs
diff --git a/mcs/class/System.Runtime.Serialization/System.Xml/ChangeLog b/mcs/class/System.Runtime.Serialization/System.Xml/ChangeLog
index 90e69b4..09a4fef 100644
--- a/mcs/class/System.Runtime.Serialization/System.Xml/ChangeLog
+++ b/mcs/class/System.Runtime.Serialization/System.Xml/ChangeLog
@@ -1,3 +1,19 @@
+2011-02-14  Miguel de Icaza  <miguel at gnome.org>
+
+	[670974] Use the underlying BaseStream to read bytes instead of
+	trying to peek a character.
+
+	Peeking a character as it turns out is a really bad idea as it
+	involves the encoder to pull characters. If the PeekChar happens
+	to read a byte that is part of a UTF8 string that needs more
+	characters to process we would end up with the reported crash.
+
+	Atsushi Enomoto tracked this down, and the fix is to use the
+	binaryreader.BaseStream to directly call into ReadByte and Read
+	without ever probing with PeekChar (). It is not really possible
+	to use BinaryReader.ReadByte since this one can throw on
+	end-of-buffer conditions instead of returning -1
+
 2010-12-20  Atsushi Eno  <atsushi at ximian.com>
 
 	Use DateTime ToBinary() and FromBinary() for DateTime
diff --git a/mcs/class/System.Runtime.Serialization/System.Xml/XmlBinaryDictionaryReader.cs b/mcs/class/System.Runtime.Serialization/System.Xml/XmlBinaryDictionaryReader.cs
index 2a42dfa..7f948e3 100644
--- a/mcs/class/System.Runtime.Serialization/System.Xml/XmlBinaryDictionaryReader.cs
+++ b/mcs/class/System.Runtime.Serialization/System.Xml/XmlBinaryDictionaryReader.cs
@@ -72,14 +72,12 @@ namespace System.Xml
 
 			public int ReadByte ()
 			{
-				if (reader.PeekChar () < 0)
-					return -1;
-				return reader.ReadByte ();
+				return reader.BaseStream.ReadByte ();
 			}
 
 			public int Read (byte [] data, int offset, int count)
 			{
-				return reader.Read (data, offset, count);
+				return reader.BaseStream.Read (data, offset, count);
 			}
 		}
 
diff --git a/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/Bug666333Test.cs b/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/Bug666333Test.cs
new file mode 100644
index 0000000..a459753
--- /dev/null
+++ b/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/Bug666333Test.cs
@@ -0,0 +1,359 @@
+using System;
+using System.Runtime.Serialization;
+using System.IO;
+using System.Diagnostics;
+using System.Xml.Serialization;
+using System.Globalization;
+using System.ComponentModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.Xml;
+using System.CodeDom.Compiler;
+using NUnit.Framework;
+
+namespace MonoTests.System.Runtime.Serialization
+{
+	[TestFixture]
+	public class Bug666333Test
+	{
+		[Test]
+		public void Bug666333 ()
+		{
+			// xml : original xml in the test
+			// xml2 : when it is *appropriately* serialized
+			// xml3 : mixed, d4p1:activeuser comes first
+			// xml4 : mixed, d4p1:activeuser comes second
+			// (Note that d4p1:activeuser is the actual element to be deserialized which takes precedence over urn:foo activeuser.)
+		
+			string xml = @"
+				<CheckLoginResponse xmlns='http://tempuri.org/'>
+					<playeractiveuser>
+						<activeuser>
+							<id>id</id>
+							<hkey>hkey</hkey>
+							<email>FOO at BAR.com</email>
+							<lastcheck>2011-01-21T22:50:52.02</lastcheck>
+						</activeuser>
+						<response>
+							<responsemessage>Acceso correcto, creado nuevo hkey!</responsemessage>
+							<responsecode>1</responsecode>
+							<langId>6</langId>
+						</response>
+					</playeractiveuser>
+				</CheckLoginResponse>
+				";
+
+			string xml2 = @"
+<CheckLoginResponse xmlns='http://tempuri.org/'>
+  <playeractiveuser xmlns:d4p1='http://schemas.datacontract.org/2004/07/' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
+    <d4p1:activeuser>
+      <d4p1:email i:nil='true' />
+      <d4p1:hkey i:nil='true' />
+      <d4p1:id>idd</d4p1:id>
+      <d4p1:lastcheck i:nil='true' />
+    </d4p1:activeuser>
+    <d4p1:response>
+      <d4p1:langId i:nil='true' />
+      <d4p1:responsecode>100</d4p1:responsecode>
+      <d4p1:responsemessage i:nil='true' />
+    </d4p1:response>
+  </playeractiveuser>
+</CheckLoginResponse>";
+
+			string xml3 = @"
+<CheckLoginResponse xmlns='http://tempuri.org/'>
+  <playeractiveuser xmlns:d4p1='http://schemas.datacontract.org/2004/07/' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
+    <d4p1:activeuser>
+      <d4p1:email i:nil='true' />
+      <d4p1:hkey i:nil='true' />
+      <d4p1:id>iddd</d4p1:id>
+      <d4p1:lastcheck i:nil='true' />
+    </d4p1:activeuser>
+    <activeuser xmlns='urn:foo'>
+      <email i:nil='true' />
+      <hkey i:nil='true' />
+      <id>idd</id>
+      <lastcheck i:nil='true' />
+    </activeuser>
+    <response xmlns='urn:foo'>
+      <langId i:nil='true' />
+      <responsecode>200</responsecode>
+      <responsemessage i:nil='true' />
+    </response>
+  </playeractiveuser>
+</CheckLoginResponse>";
+
+			string xml4 = @"
+<CheckLoginResponse xmlns='http://tempuri.org/'>
+  <playeractiveuser xmlns:d4p1='http://schemas.datacontract.org/2004/07/' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
+    <activeuser xmlns='urn:foo'>
+      <email i:nil='true' />
+      <hkey i:nil='true' />
+      <id>idd</id>
+      <lastcheck i:nil='true' />
+    </activeuser>
+    <d4p1:activeuser>
+      <d4p1:email i:nil='true' />
+      <d4p1:hkey i:nil='true' />
+      <d4p1:id>iddd</d4p1:id>
+      <d4p1:lastcheck i:nil='true' />
+    </d4p1:activeuser>
+    <response xmlns='urn:foo'>
+      <langId i:nil='true' />
+      <responsecode>200</responsecode>
+      <responsemessage i:nil='true' />
+    </response>
+  </playeractiveuser>
+</CheckLoginResponse>";
+			
+			var tm = TypedMessageConverter.Create (typeof (CheckLoginResponse), "urn:foo");
+			var m = Message.CreateMessage (MessageVersion.Default, "urn:foo", XmlReader.Create (new StringReader (xml)));
+			m = Message.CreateMessage (MessageVersion.Default, "urn:foo", XmlReader.Create (new StringReader (xml2)));
+			m = Message.CreateMessage (MessageVersion.Default, "urn:foo", XmlReader.Create (new StringReader (xml3)));
+			var clr = (CheckLoginResponse) tm.FromMessage (m);
+			Assert.IsNotNull (clr.playeractiveuser, "#1");
+			Assert.IsNotNull (clr.playeractiveuser.activeuser, "#2");
+			Assert.AreEqual ("iddd", clr.playeractiveuser.activeuser.id, "#3");
+
+			m = Message.CreateMessage (MessageVersion.Default, "urn:foo", XmlReader.Create (new StringReader (xml4)));
+			Assert.AreEqual ("iddd", clr.playeractiveuser.activeuser.id, "#4");
+	}
+
+	}
+}
+
+// Generated code
+
+
+[GeneratedCode("System.ServiceModel", "4.0.0.0"), DebuggerStepThrough, EditorBrowsable(EditorBrowsableState.Advanced), MessageContract(WrapperName="CheckLoginResponse", WrapperNamespace="http://tempuri.org/", IsWrapped=true)]
+public class CheckLoginResponse
+{
+    // Fields
+    [MessageBodyMember(Namespace="http://tempuri.org/", Order=0), XmlElement(IsNullable=true)]
+    public PlayerActiveUser playeractiveuser;
+
+    // Methods
+    public CheckLoginResponse()
+    {
+    }
+
+    public CheckLoginResponse(PlayerActiveUser playeractiveuser)
+    {
+        this.playeractiveuser = playeractiveuser;
+    }
+}
+
+
+[GeneratedCode("System.Xml", "4.0.30319.1"), DebuggerStepThrough, XmlType(Namespace="http://tempuri.org/")]
+public class PlayerActiveUser : INotifyPropertyChanged
+{
+    // Fields
+    private ActiveUserReference activeuserField;
+    //private PropertyChangedEventHandler PropertyChanged;
+    private Response responseField;
+
+    // Events
+    public event PropertyChangedEventHandler PropertyChanged;
+
+    // Methods
+    protected void RaisePropertyChanged(string propertyName)
+    {
+        PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
+        if (propertyChanged != null)
+        {
+            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
+        }
+    }
+
+    // Properties
+    [XmlElement(Order=0)]
+    public ActiveUserReference activeuser
+    {
+        get
+        {
+            return this.activeuserField;
+        }
+        set
+        {
+            this.activeuserField = value;
+            this.RaisePropertyChanged("activeuser");
+        }
+    }
+
+    [XmlElement(Order=1)]
+    public Response response
+    {
+
+        get
+        {
+            return this.responseField;
+        }
+        set
+        {
+            this.responseField = value;
+            this.RaisePropertyChanged("response");
+        }
+    }
+}
+
+
+[XmlType(Namespace="http://tempuri.org/"), GeneratedCode("System.Xml", "4.0.30319.1"), DebuggerStepThrough]
+public class Response : INotifyPropertyChanged
+{
+    // Fields
+    private int? langIdField;
+    //private PropertyChangedEventHandler PropertyChanged;
+    private int? responsecodeField;
+    private string responsemessageField;
+
+    // Events
+    public event PropertyChangedEventHandler PropertyChanged;
+
+    // Methods
+    protected void RaisePropertyChanged(string propertyName)
+    {
+        PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
+        if (propertyChanged != null)
+        {
+            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
+        }
+    }
+
+    // Properties
+    [XmlElement(IsNullable=true, Order=2)]
+    public int? langId
+    {
+        get
+        {
+            return this.langIdField;
+        }
+        set
+        {
+            this.langIdField = value;
+            this.RaisePropertyChanged("langId");
+        }
+    }
+
+    [XmlElement(IsNullable=true, Order=1)]
+    public int? responsecode
+    {
+        get
+        {
+            return this.responsecodeField;
+        }
+        set
+        {
+            this.responsecodeField = value;
+            this.RaisePropertyChanged("responsecode");
+        }
+    }
+
+    [XmlElement(Order=0)]
+    public string responsemessage
+    {
+        get
+        {
+            return this.responsemessageField;
+        }
+        set
+        {
+            this.responsemessageField = value;
+            this.RaisePropertyChanged("responsemessage");
+        }
+    }
+}
+
+
+[XmlType(Namespace="http://tempuri.org/"), DebuggerStepThrough, GeneratedCode("System.Xml", "4.0.30319.1")]
+public class ActiveUserReference : ESObject
+{
+    // Fields
+    private string emailField;
+    private string hkeyField;
+    private string idField;
+    private DateTime? lastcheckField;
+
+    // Properties
+    [XmlElement(Order=2)]
+    public string email
+    {
+        get
+        {
+            return this.emailField;
+        }
+        set
+        {
+            this.emailField = value;
+            base.RaisePropertyChanged("email");
+        }
+    }
+
+    [XmlElement(Order=1)]
+    public string hkey
+    {
+        get
+        {
+            return this.hkeyField;
+        }
+        set
+        {
+            this.hkeyField = value;
+            base.RaisePropertyChanged("hkey");
+        }
+    }
+
+    [XmlElement(Order=0)]
+    public string id
+    {
+        get
+        {
+            return this.idField;
+        }
+        set
+        {
+            this.idField = value;
+            base.RaisePropertyChanged("id");
+        }
+    }
+
+    [XmlElement(IsNullable=true, Order=3)]
+    public DateTime? lastcheck
+    {
+        get
+        {
+            return this.lastcheckField;
+        }
+        set
+        {
+            this.lastcheckField = value;
+            base.RaisePropertyChanged("lastcheck");
+        }
+    }
+}
+
+
+[XmlType(Namespace="http://tempuri.org/"), GeneratedCode("System.Xml", "4.0.30319.1"), XmlInclude(typeof(ActiveUserReference)), DebuggerStepThrough]
+public abstract class ESObject : INotifyPropertyChanged
+{
+    // Fields
+    //private PropertyChangedEventHandler PropertyChanged;
+
+    // Events
+    public event PropertyChangedEventHandler PropertyChanged;
+
+    // Methods
+    protected ESObject()
+    {
+    }
+
+    protected void RaisePropertyChanged(string propertyName)
+    {
+        PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
+        if (propertyChanged != null)
+        {
+            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
+        }
+    }
+}
+
diff --git a/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/ChangeLog b/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/ChangeLog
index 4ed2265..548b1bc 100644
--- a/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/ChangeLog
+++ b/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/ChangeLog
@@ -1,3 +1,43 @@
+2011-02-08  Atsushi Eno  <atsushi at ximian.com>
+
+	There's a tricky namespace-mismatching deserialization in .NET
+	implementation.
+
+	Fixed bug #666333.
+
+2011-02-08  Atsushi Eno  <atsushi at ximian.com>
+
+	Contract-based type must ensure that the base type is also
+	contract-based.
+
+	Fixed bug #661987 on WCF side.
+
+	Conflicts:
+
+	mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XmlObjectSerializerTest.cs
+
+2011-02-01  Atsushi Eno  <atsushi at ximian.com>
+
+	Members in the base type in different namespace are serialized in
+	base ns.
+
+	When the serializer serializes a Type B which is derived from A,
+	it used to serialize member M in A as in namespace_of_B, not in
+	namespace_of_A.
+
+	This should fix bug #652331.
+
+2011-02-01  Atsushi Eno  <atsushi at ximian.com>
+
+	Members in the base type in different namespace are serialized in
+	base ns.
+
+	When the serializer serializes a Type B which is derived from A,
+	it used to serialize member M in A as in namespace_of_B, not in
+	namespace_of_A.
+
+	This should fix bug #652331.
+
 2010-10-05  Atsushi Eno  <atsushi at ximian.com>
 
 	Fix DataContractResolver.ResolveName() support in deserializer.
diff --git a/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XmlObjectSerializerTest.cs b/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XmlObjectSerializerTest.cs
index 30e8783..98a7f79 100755
--- a/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XmlObjectSerializerTest.cs
+++ b/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XmlObjectSerializerTest.cs
@@ -1499,6 +1499,40 @@ namespace MonoTests.System.Runtime.Serialization
 			
 			var ds = (DataSet) x.ReadObject (r);
 		}
+
+		[Test]
+		[ExpectedException (typeof (InvalidDataContractException))] // BaseConstraintType1 is neither DataContract nor Serializable.
+		public void BaseConstraint1 ()
+		{
+			new DataContractSerializer (typeof (BaseConstraintType3)).WriteObject (XmlWriter.Create (TextWriter.Null), new BaseConstraintType3 ());
+		}
+
+		[Test]
+		public void BaseConstraint2 ()
+		{
+			new DataContractSerializer (typeof (BaseConstraintType4)).WriteObject (XmlWriter.Create (TextWriter.Null), new BaseConstraintType4 ());
+		}
+
+		[Test] // bug #652331
+		public void MembersNamespacesInBaseType ()
+		{
+			string xml1 = @"<Currency>JPY</Currency><Description i:nil=""true"" />";
+			string xml2 = @"<Currency xmlns=""http://schemas.datacontract.org/2004/07/SLProto5"">JPY</Currency><Description i:nil=""true"" xmlns=""http://schemas.datacontract.org/2004/07/SLProto5"" />";
+			Assert.AreEqual ("JPY", MembersNamespacesInBaseType_Part<SLProto5.CashAmount> (new SLProto5.CashAmount () { Currency = "JPY" }, xml1, "#1").Currency, "r#1");
+			Assert.AreEqual ("JPY", MembersNamespacesInBaseType_Part<SLProto5_Different.CashAmount> (new SLProto5_Different.CashAmount () { Currency = "JPY" }, xml2, "#2").Currency, "r#2");
+			Assert.AreEqual ("JPY", MembersNamespacesInBaseType_Part<SLProto5.CashAmountDC> (new SLProto5.CashAmountDC () { Currency = "JPY" }, xml1, "#3").Currency, "r#3");
+			Assert.AreEqual ("JPY", MembersNamespacesInBaseType_Part<SLProto5_Different.CashAmountDC> (new SLProto5_Different.CashAmountDC () { Currency = "JPY" }, xml2, "#4").Currency, "r#4");
+		}
+
+		T MembersNamespacesInBaseType_Part<T> (T instance, string expectedPart, string assert)
+		{
+			var ds = new DataContractSerializer (typeof (T));
+			var sw = new StringWriter ();
+			using (var w = XmlWriter.Create (sw))
+				ds.WriteObject (w, instance);
+			Assert.IsTrue (sw.ToString ().IndexOf (expectedPart) > 0, assert);
+			return (T) ds.ReadObject (XmlReader.Create (new StringReader (sw.ToString ())));
+		}
 	}
 	
 	[DataContract]
@@ -1800,6 +1834,25 @@ namespace MonoTests.System.Runtime.Serialization
 		[DataMember]
 		public string X = "x";
 	}
+
+	class BaseConstraintType1 // non-serializable
+	{
+	}
+	
+	[Serializable]
+	class BaseConstraintType2
+	{
+	}
+	
+	[DataContract]
+	class BaseConstraintType3 : BaseConstraintType1
+	{
+	}
+	
+	[DataContract]
+	class BaseConstraintType4 : BaseConstraintType2
+	{
+	}
 }
 
 [DataContract]
@@ -2005,4 +2058,43 @@ public class Child
 	public Parent Parent;
 }
 
+namespace SLProto5
+{
+	public class CashAmount : Amount
+	{
+	}
+
+	[DataContract]
+	public class CashAmountDC : AmountDC
+	{
+	}
+
+	public class Amount
+	{
+		public string Currency { get; set; }
+		public string Description { get; set; }
+	}
+
+	[DataContract]
+	public class AmountDC
+	{
+		[DataMember]
+		public string Currency { get; set; }
+		[DataMember]
+		public string Description { get; set; }
+	}
+}
+
+namespace SLProto5_Different
+{
+	public class CashAmount : SLProto5.Amount
+	{
+	}
+
+	[DataContract]
+	public class CashAmountDC : SLProto5.AmountDC
+	{
+	}
+}
+
 #endregion
diff --git a/mcs/class/System.ServiceModel.Discovery/ChangeLog b/mcs/class/System.ServiceModel.Discovery/ChangeLog
index b5d6de9..9baa13c 100644
--- a/mcs/class/System.ServiceModel.Discovery/ChangeLog
+++ b/mcs/class/System.ServiceModel.Discovery/ChangeLog
@@ -1,3 +1,20 @@
+2011-02-15  Atsushi Eno  <atsushi at ximian.com>
+
+	support UdpTranspoerSettings.MulticastInterfaceId. This should fix
+	bug #669328.
+
+2011-02-10  Atsushi Eno  <atsushi at ximian.com>
+
+	Fix wrong async completion handling in UDP channel receive.
+
+	After AsyncWaitHandle.Set(), order of filling results and
+	WaitOne() are undefined.
+
+2011-02-09  Atsushi Eno  <atsushi at ximian.com>
+
+	Recent ContractDescription fix uncovered wrong contracts in
+	discovery.
+
 2010-09-29  Atsushi Eno  <atsushi at ximian.com>
 
 	[wcf-discovery] ExclusiveAddressUse won't work. AcceptChannel()
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.Udp/UdpDuplexChannel.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.Udp/UdpDuplexChannel.cs
index 4a97e90..754cf51 100644
--- a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.Udp/UdpDuplexChannel.cs
+++ b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.Udp/UdpDuplexChannel.cs
@@ -123,7 +123,7 @@ namespace System.ServiceModel.Discovery.Udp
 			var ms = new MemoryStream ();
 			message_encoder.WriteMessage (message, ms);
 			// It seems .NET sends the same Message a couple of times so that the receivers don't miss it. So, do the same hack.
-			for (int i = 0; i < 6; i++) {
+			for (int i = 0; i < 3; i++) {
 				// FIXME: use MaxAnnouncementDelay. It is fixed now.
 				Thread.Sleep (rnd.Next (50, 500));
 				cli.Send (ms.GetBuffer (), (int) ms.Length);
@@ -159,19 +159,23 @@ namespace System.ServiceModel.Discovery.Udp
 
 			byte [] bytes = null;
 			IPEndPoint ip = new IPEndPoint (IPAddress.Any, 0);
+			ManualResetEvent wait = new ManualResetEvent (false);
 			var ar = client.BeginReceive (delegate (IAsyncResult result) {
-if (result == null) throw new ArgumentNullException ("result");
-				UdpClient cli = (UdpClient) result.AsyncState;
 				try {
-					bytes = cli.EndReceive (result, ref ip);
-				} catch (ObjectDisposedException) {
-					if (State == CommunicationState.Opened)
-						throw;
-					// Otherwise, called during shutdown. Ignore it.
+					UdpClient cli = (UdpClient) result.AsyncState;
+					try {
+						bytes = cli.EndReceive (result, ref ip);
+					} catch (ObjectDisposedException) {
+						if (State == CommunicationState.Opened)
+							throw;
+						// Otherwise, called during shutdown. Ignore it.
+					}
+				} finally {
+					wait.Set ();
 				}
 			}, client);
 
-			if (!ar.IsCompleted && !ar.AsyncWaitHandle.WaitOne (timeout))
+			if (!ar.IsCompleted && !wait.WaitOne (timeout))
 				return false;
 			if (bytes == null || bytes.Length == 0)
 				return false;
@@ -261,6 +265,9 @@ if (result == null) throw new ArgumentNullException ("result");
 			client.EnableBroadcast = true;
 
 			// FIXME: apply UdpTransportSetting here.
+			var settings = binding_element.TransportSettings;
+			if (settings.MulticastInterfaceId != null)
+				client.Client.SetSocketOption (SocketOptionLevel.Udp, SocketOptionName.MulticastInterface, settings.MulticastInterfaceId);
 		}
 		
 		Func<TimeSpan,Message> receive_delegate;
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.Version11/IDiscoveryTargetContract11.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.Version11/IDiscoveryTargetContract11.cs
index 73eb013..323dddf 100644
--- a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.Version11/IDiscoveryTargetContract11.cs
+++ b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.Version11/IDiscoveryTargetContract11.cs
@@ -41,21 +41,11 @@ namespace System.ServiceModel.Discovery.Version11
 
 		void EndFind (IAsyncResult result);
 
-		[OperationContract (Name = "ProbeMatches11", Action = MessageContracts11.ProbeMatchAction, AsyncPattern = true, IsOneWay = true)]
-		IAsyncResult BeginReplyFind (MessageContracts11.FindResponse message, AsyncCallback callback, object state);
-
-		void EndReplyFind (IAsyncResult result);
-
 		[OperationContract (Name = "Resolve11", Action = MessageContracts11.ResolveAction, AsyncPattern = true, IsOneWay = true)]
 		IAsyncResult BeginResolve (MessageContracts11.ResolveRequest message, AsyncCallback callback, object state);
 
 		void EndResolve (IAsyncResult result);
 
-		[OperationContract (Name = "ResolveMatches11", Action = MessageContracts11.ResolveMatchAction, AsyncPattern = true, IsOneWay = true)]
-		IAsyncResult BeginReplyResolve (MessageContracts11.ResolveResponse message, AsyncCallback callback, object state);
-
-		void EndReplyResolve (IAsyncResult result);
-
 		[OperationContract (Name = "Hello11", Action = MessageContracts11.HelloAction, IsOneWay = true, AsyncPattern = true)]
 		IAsyncResult BeginOnlineAnnouncement (MessageContracts11.OnlineAnnouncement message, AsyncCallback callback, object state);
 
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/ChangeLog b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/ChangeLog
index 6265535..6610dca 100644
--- a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/ChangeLog
+++ b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/ChangeLog
@@ -1,3 +1,13 @@
+2011-02-10  Atsushi Eno  <atsushi at ximian.com>
+
+	Fix a couple of addressing namespace fixes (found in April2005
+	version).
+
+2011-02-09  Atsushi Eno  <atsushi at ximian.com>
+
+	Recent ContractDescription fix uncovered wrong contracts in
+	discovery.
+
 2010-09-24  Atsushi Eno  <atsushi at ximian.com>
 
 	Assign identical operation name for each contract version so that
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/IAnnouncementContractApril2005.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/IAnnouncementContractApril2005.cs
index 06c853f..b22ca02 100644
--- a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/IAnnouncementContractApril2005.cs
+++ b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/IAnnouncementContractApril2005.cs
@@ -41,7 +41,7 @@ namespace System.ServiceModel.Discovery.VersionApril2005
 
 		void EndOnlineAnnouncement (IAsyncResult result);
 
-		[OperationContract (Name = "Bye", Action = MessageContractsApril2005.HelloAction, IsOneWay = true, AsyncPattern = true)]
+		[OperationContract (Name = "Bye", Action = MessageContractsApril2005.ByeAction, IsOneWay = true, AsyncPattern = true)]
 		IAsyncResult BeginOfflineAnnouncement (MessageContractsApril2005.OfflineAnnouncement message, AsyncCallback callback, object state);
 
 		void EndOfflineAnnouncement (IAsyncResult result);
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/IDiscoveryTargetContractApril2005.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/IDiscoveryTargetContractApril2005.cs
index baf4051..f869fc1 100644
--- a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/IDiscoveryTargetContractApril2005.cs
+++ b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/IDiscoveryTargetContractApril2005.cs
@@ -41,21 +41,11 @@ namespace System.ServiceModel.Discovery.VersionApril2005
 
 		void EndFind (IAsyncResult result);
 
-		[OperationContract (Name = "ProbeMatchesApril2005", Action = MessageContractsApril2005.ProbeMatchAction, AsyncPattern = true, IsOneWay = true)]
-		IAsyncResult BeginReplyFind (MessageContractsApril2005.FindResponse message, AsyncCallback callback, object state);
-
-		void EndReplyFind (IAsyncResult result);
-
 		[OperationContract (Name = "ResolveApril2005", Action = MessageContractsApril2005.ResolveAction, AsyncPattern = true, IsOneWay = true)]
 		IAsyncResult BeginResolve (MessageContractsApril2005.ResolveRequest message, AsyncCallback callback, object state);
 
 		void EndResolve (IAsyncResult result);
 
-		[OperationContract (Name = "ResolveMatchesApril2005", Action = MessageContractsApril2005.ResolveMatchAction, AsyncPattern = true, IsOneWay = true)]
-		IAsyncResult BeginReplyResolve (MessageContractsApril2005.ResolveResponse message, AsyncCallback callback, object state);
-
-		void EndReplyResolve (IAsyncResult result);
-
 		[OperationContract (Name = "HelloApril2005", Action = MessageContractsApril2005.HelloAction, IsOneWay = true, AsyncPattern = true)]
 		IAsyncResult BeginOnlineAnnouncement (MessageContractsApril2005.OnlineAnnouncement message, AsyncCallback callback, object state);
 
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/ChangeLog b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/ChangeLog
index a843b27..6a241b2 100644
--- a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/ChangeLog
+++ b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/ChangeLog
@@ -1,3 +1,8 @@
+2011-02-09  Atsushi Eno  <atsushi at ximian.com>
+
+	Recent ContractDescription fix uncovered wrong contracts in
+	discovery.
+
 2010-09-24  Atsushi Eno  <atsushi at ximian.com>
 
 	Assign identical operation name for each contract version so that
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/IDiscoveryTargetContractCD1.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/IDiscoveryTargetContractCD1.cs
index a8f65de..187d1ce 100644
--- a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/IDiscoveryTargetContractCD1.cs
+++ b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/IDiscoveryTargetContractCD1.cs
@@ -41,21 +41,11 @@ namespace System.ServiceModel.Discovery.VersionCD1
 
 		void EndFind (IAsyncResult result);
 
-		[OperationContract (Name = "ProbeMatchesCD1", Action = MessageContractsCD1.ProbeMatchAction, AsyncPattern = true, IsOneWay = true)]
-		IAsyncResult BeginReplyFind (MessageContractsCD1.FindResponse message, AsyncCallback callback, object state);
-
-		void EndReplyFind (IAsyncResult result);
-
 		[OperationContract (Name = "ResolveCD1", Action = MessageContractsCD1.ResolveAction, AsyncPattern = true, IsOneWay = true)]
 		IAsyncResult BeginResolve (MessageContractsCD1.ResolveRequest message, AsyncCallback callback, object state);
 
 		void EndResolve (IAsyncResult result);
 
-		[OperationContract (Name = "ResolveMatchesCD1", Action = MessageContractsCD1.ResolveMatchAction, AsyncPattern = true, IsOneWay = true)]
-		IAsyncResult BeginReplyResolve (MessageContractsCD1.ResolveResponse message, AsyncCallback callback, object state);
-
-		void EndReplyResolve (IAsyncResult result);
-
 		[OperationContract (Name = "HelloCD1", Action = MessageContractsCD1.HelloAction, IsOneWay = true, AsyncPattern = true)]
 		IAsyncResult BeginOnlineAnnouncement (MessageContractsCD1.OnlineAnnouncement message, AsyncCallback callback, object state);
 
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ChangeLog b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ChangeLog
index b50b682..52ba81d 100644
--- a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ChangeLog
+++ b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ChangeLog
@@ -1,3 +1,18 @@
+2011-02-15  Atsushi Eno  <atsushi at ximian.com>
+
+	support UdpTranspoerSettings.MulticastInterfaceId. This should fix
+	bug #669328.
+
+2011-02-10  Atsushi Eno  <atsushi at ximian.com>
+
+	Fix a couple of addressing namespace fixes (found in April2005
+	version).
+
+2011-02-09  Atsushi Eno  <atsushi at ximian.com>
+
+	Recent ContractDescription fix uncovered wrong contracts in
+	discovery.
+
 2011-01-08  Marek Safar  <marek.safar at gmail.com>
 
 	Fixed missing protected internal modifier
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryProxy.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryProxy.cs
index 46c4143..f430885 100755
--- a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryProxy.cs
+++ b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryProxy.cs
@@ -144,18 +144,6 @@ namespace System.ServiceModel.Discovery
 			OnEndFind (result);
 		}
 
-		IAsyncResult IDiscoveryTargetContract11.BeginReplyFind (MessageContracts11.FindResponse message, AsyncCallback callback, object state)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
-		void IDiscoveryTargetContract11.EndReplyFind (IAsyncResult result)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
 		IAsyncResult IDiscoveryTargetContract11.BeginResolve (MessageContracts11.ResolveRequest message, AsyncCallback callback, object state)
 		{
 			return OnBeginResolve (message.Body.ToResolveCriteria (), callback, state);
@@ -166,18 +154,6 @@ namespace System.ServiceModel.Discovery
 			OnEndResolve (result);
 		}
 
-		IAsyncResult IDiscoveryTargetContract11.BeginReplyResolve (MessageContracts11.ResolveResponse message, AsyncCallback callback, object state)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
-		void IDiscoveryTargetContract11.EndReplyResolve (IAsyncResult result)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
 		IAsyncResult IDiscoveryTargetContract11.BeginOnlineAnnouncement (MessageContracts11.OnlineAnnouncement msg, AsyncCallback callback, object state)
 		{
 			var edm = msg.EndpointDiscoveryMetadata != null ? msg.EndpointDiscoveryMetadata.ToEndpointDiscoveryMetadata () : null;
@@ -200,18 +176,6 @@ namespace System.ServiceModel.Discovery
 			OnEndFind (result);
 		}
 
-		IAsyncResult IDiscoveryTargetContractApril2005.BeginReplyFind (MessageContractsApril2005.FindResponse message, AsyncCallback callback, object state)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
-		void IDiscoveryTargetContractApril2005.EndReplyFind (IAsyncResult result)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
 		IAsyncResult IDiscoveryTargetContractApril2005.BeginResolve (MessageContractsApril2005.ResolveRequest message, AsyncCallback callback, object state)
 		{
 			return OnBeginResolve (message.Body.ToResolveCriteria (), callback, state);
@@ -222,18 +186,6 @@ namespace System.ServiceModel.Discovery
 			OnEndResolve (result);
 		}
 
-		IAsyncResult IDiscoveryTargetContractApril2005.BeginReplyResolve (MessageContractsApril2005.ResolveResponse message, AsyncCallback callback, object state)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
-		void IDiscoveryTargetContractApril2005.EndReplyResolve (IAsyncResult result)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
 		IAsyncResult IDiscoveryTargetContractApril2005.BeginOnlineAnnouncement (MessageContractsApril2005.OnlineAnnouncement msg, AsyncCallback callback, object state)
 		{
 			var edm = msg.EndpointDiscoveryMetadata != null ? msg.EndpointDiscoveryMetadata.ToEndpointDiscoveryMetadata () : null;
@@ -256,18 +208,6 @@ namespace System.ServiceModel.Discovery
 			OnEndFind (result);
 		}
 
-		IAsyncResult IDiscoveryTargetContractCD1.BeginReplyFind (MessageContractsCD1.FindResponse message, AsyncCallback callback, object state)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
-		void IDiscoveryTargetContractCD1.EndReplyFind (IAsyncResult result)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
 		IAsyncResult IDiscoveryTargetContractCD1.BeginResolve (MessageContractsCD1.ResolveRequest message, AsyncCallback callback, object state)
 		{
 			return OnBeginResolve (message.Body.ToResolveCriteria (), callback, state);
@@ -278,18 +218,6 @@ namespace System.ServiceModel.Discovery
 			OnEndResolve (result);
 		}
 
-		IAsyncResult IDiscoveryTargetContractCD1.BeginReplyResolve (MessageContractsCD1.ResolveResponse message, AsyncCallback callback, object state)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
-		void IDiscoveryTargetContractCD1.EndReplyResolve (IAsyncResult result)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
 		IAsyncResult IDiscoveryTargetContractCD1.BeginOnlineAnnouncement (MessageContractsCD1.OnlineAnnouncement msg, AsyncCallback callback, object state)
 		{
 			var edm = msg.EndpointDiscoveryMetadata != null ? msg.EndpointDiscoveryMetadata.ToEndpointDiscoveryMetadata () : null;
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryService.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryService.cs
index 428de8c..4e9b2c6 100755
--- a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryService.cs
+++ b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryService.cs
@@ -189,18 +189,6 @@ namespace System.ServiceModel.Discovery
 			cb.ReplyFind (CreateFindResponse11 ());
 		}
 
-		IAsyncResult IDiscoveryTargetContract11.BeginReplyFind (MessageContracts11.FindResponse message, AsyncCallback callback, object state)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
-		void IDiscoveryTargetContract11.EndReplyFind (IAsyncResult result)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
 		IAsyncResult IDiscoveryTargetContract11.BeginResolve (MessageContracts11.ResolveRequest message, AsyncCallback callback, object state)
 		{
 			return OnBeginResolve (message.Body.ToResolveCriteria (), callback, state);
@@ -211,18 +199,6 @@ namespace System.ServiceModel.Discovery
 			OnEndResolve (result);
 		}
 
-		IAsyncResult IDiscoveryTargetContract11.BeginReplyResolve (MessageContracts11.ResolveResponse message, AsyncCallback callback, object state)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
-		void IDiscoveryTargetContract11.EndReplyResolve (IAsyncResult result)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
 		IAsyncResult IDiscoveryTargetContract11.BeginOnlineAnnouncement (MessageContracts11.OnlineAnnouncement message, AsyncCallback callback, object state)
 		{
 			// is it expected to be invoked??
@@ -249,18 +225,6 @@ namespace System.ServiceModel.Discovery
 			cb.ReplyFind (CreateFindResponseApril2005 ());
 		}
 
-		IAsyncResult IDiscoveryTargetContractApril2005.BeginReplyFind (MessageContractsApril2005.FindResponse message, AsyncCallback callback, object state)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
-		void IDiscoveryTargetContractApril2005.EndReplyFind (IAsyncResult result)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
 		IAsyncResult IDiscoveryTargetContractApril2005.BeginResolve (MessageContractsApril2005.ResolveRequest message, AsyncCallback callback, object state)
 		{
 			return OnBeginResolve (message.Body.ToResolveCriteria (), callback, state);
@@ -271,18 +235,6 @@ namespace System.ServiceModel.Discovery
 			OnEndResolve (result);
 		}
 
-		IAsyncResult IDiscoveryTargetContractApril2005.BeginReplyResolve (MessageContractsApril2005.ResolveResponse message, AsyncCallback callback, object state)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
-		void IDiscoveryTargetContractApril2005.EndReplyResolve (IAsyncResult result)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
 		IAsyncResult IDiscoveryTargetContractApril2005.BeginOnlineAnnouncement (MessageContractsApril2005.OnlineAnnouncement message, AsyncCallback callback, object state)
 		{
 			// is it expected to be invoked??
@@ -309,18 +261,6 @@ namespace System.ServiceModel.Discovery
 			cb.ReplyFind (CreateFindResponseCD1 ());
 		}
 
-		IAsyncResult IDiscoveryTargetContractCD1.BeginReplyFind (MessageContractsCD1.FindResponse message, AsyncCallback callback, object state)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
-		void IDiscoveryTargetContractCD1.EndReplyFind (IAsyncResult result)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
 		IAsyncResult IDiscoveryTargetContractCD1.BeginResolve (MessageContractsCD1.ResolveRequest message, AsyncCallback callback, object state)
 		{
 			return OnBeginResolve (message.Body.ToResolveCriteria (), callback, state);
@@ -331,18 +271,6 @@ namespace System.ServiceModel.Discovery
 			OnEndResolve (result);
 		}
 
-		IAsyncResult IDiscoveryTargetContractCD1.BeginReplyResolve (MessageContractsCD1.ResolveResponse message, AsyncCallback callback, object state)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
-		void IDiscoveryTargetContractCD1.EndReplyResolve (IAsyncResult result)
-		{
-			// is it expected to be invoked??
-			throw new NotImplementedException ();
-		}
-
 		IAsyncResult IDiscoveryTargetContractCD1.BeginOnlineAnnouncement (MessageContractsCD1.OnlineAnnouncement message, AsyncCallback callback, object state)
 		{
 			// is it expected to be invoked??
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/EndpointDiscoveryMetadata.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/EndpointDiscoveryMetadata.cs
index 73faec9..4a0fdd2 100755
--- a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/EndpointDiscoveryMetadata.cs
+++ b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/EndpointDiscoveryMetadata.cs
@@ -53,8 +53,6 @@ namespace System.ServiceModel.Discovery
 		public Collection<Uri> Scopes { get; private set; }
 		public int Version { get; set; }
 
-		const string addrNS = "http://www.w3.org/2005/08/addressing";
-
 		internal static EndpointDiscoveryMetadata ReadXml (XmlReader reader, DiscoveryVersion version)
 		{
 			if (reader == null)
@@ -69,7 +67,11 @@ namespace System.ServiceModel.Discovery
 
 			// standard members
 			reader.MoveToContent ();
-			ret.Address = EndpointAddress.ReadFrom (AddressingVersion.WSAddressing10, reader, "EndpointReference", addrNS);
+
+			// it is possible due to InternalVisibleToAttribute...
+			string addrNS = version.MessageVersion.Addressing.Namespace;
+
+			ret.Address = EndpointAddress.ReadFrom (version.MessageVersion.Addressing, reader, "EndpointReference", addrNS);
 
 			reader.MoveToContent ();
 			if (reader.IsStartElement ("Types", version.Namespace))
@@ -101,7 +103,7 @@ namespace System.ServiceModel.Discovery
 
 			// standard members
 			if (Address != null)
-				Address.WriteTo (AddressingVersion.WSAddressing10, writer);
+				Address.WriteTo (version.MessageVersion.Addressing, writer);
 
 			writer.WriteStartElement ("d", "Types", version.Namespace);
 			int p = 0;
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ResolveCriteria.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ResolveCriteria.cs
index c47fa5e..e37de28 100755
--- a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ResolveCriteria.cs
+++ b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ResolveCriteria.cs
@@ -71,7 +71,7 @@ namespace System.ServiceModel.Discovery
 
 			// standard members
 			reader.MoveToContent ();
-			ret.Address = EndpointAddress.ReadFrom (AddressingVersion.WSAddressing10, reader);
+			ret.Address = EndpointAddress.ReadFrom (version.MessageVersion.Addressing, reader);
 
 			// non-standard members
 			for (reader.MoveToContent (); !reader.EOF && reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
@@ -97,7 +97,7 @@ namespace System.ServiceModel.Discovery
 				throw new ArgumentNullException ("writer");
 
 			// standard members
-			Address.WriteTo (AddressingVersion.WSAddressing10, writer);
+			Address.WriteTo (version.MessageVersion.Addressing, writer);
 
 			// non-standard members
 			writer.WriteStartElement ("Duration", SerializationNS);
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/UdpTransportSettings.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/UdpTransportSettings.cs
index d6032b1..78e0e42 100755
--- a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/UdpTransportSettings.cs
+++ b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/UdpTransportSettings.cs
@@ -54,6 +54,7 @@ namespace System.ServiceModel.Discovery
 			MaxPendingMessageCount = source.MaxPendingMessageCount;
 			MaxReceivedMessageSize = source.MaxReceivedMessageSize;
 			MaxUnicastRetransmitCount = source.MaxUnicastRetransmitCount;
+			MulticastInterfaceId = source.MulticastInterfaceId;
 			SocketReceiveBufferSize = source.SocketReceiveBufferSize;
 			TimeToLive = source.TimeToLive;
 		}
diff --git a/mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/ChangeLog b/mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/ChangeLog
index 17be62e..1db0f61 100644
--- a/mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/ChangeLog
+++ b/mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/ChangeLog
@@ -1,3 +1,15 @@
+2011-02-10  Atsushi Eno  <atsushi at ximian.com>
+
+	Fix wrong async completion handling in UDP channel receive.
+
+	After AsyncWaitHandle.Set(), order of filling results and
+	WaitOne() are undefined.
+
+2011-02-09  Atsushi Eno  <atsushi at ximian.com>
+
+	Recent ContractDescription fix uncovered wrong contracts in
+	discovery.
+
 2010-09-03  Atsushi Eno  <atsushi at ximian.com>
 
 	Ongoing Discovery duplex (UDP) implementation (not working yet).
diff --git a/mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/DiscoveryClientBindingElementTest.cs b/mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/DiscoveryClientBindingElementTest.cs
index 3f7c0a9..e7aa00d 100644
--- a/mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/DiscoveryClientBindingElementTest.cs
+++ b/mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/DiscoveryClientBindingElementTest.cs
@@ -70,7 +70,8 @@ namespace MonoTests.System.ServiceModel.Discovery
 			// could be either IPv4 or IPv6
 			Assert.AreEqual (new UdpDiscoveryEndpoint ().MulticastAddress, die.ListenUri, "#7");
 			Assert.AreEqual (ListenUriMode.Explicit, die.ListenUriMode, "#8");
-			Assert.AreEqual (5, die.Behaviors.Count, "#9");
+			// FIXME: enable (but the number should not matter; the functionality should rather matter. Those behaviors are internal in .NET)
+			// Assert.AreEqual (5, die.Behaviors.Count, "#9");
 
 			// default constructor
 			be = new DiscoveryClientBindingElement ();
@@ -144,7 +145,7 @@ namespace MonoTests.System.ServiceModel.Discovery
 			Assert.AreEqual (DiscoveryClientBindingElement.DiscoveryEndpointAddress, ch.RemoteAddress, "#1");
 		}
 
-		// This test takes a while, so I in face don't want to enable it ...
+		// This test takes a while, so I in fact don't want to enable it ...
 		[Test]
 		[ExpectedException (typeof (EndpointNotFoundException))]
 		public void RequestChannelOpenFails ()
@@ -156,9 +157,10 @@ namespace MonoTests.System.ServiceModel.Discovery
 			Assert.IsNull (cf.GetProperty<DiscoveryEndpoint> (), "#1");
 			var ch = cf.CreateChannel (DiscoveryClientBindingElement.DiscoveryEndpointAddress);
 			Assert.IsNull (ch.GetProperty<DiscoveryEndpoint> (), "#2");
-			ch.Open ();
+			ch.Open (TimeSpan.FromSeconds (80));
 		}
 
+		// This test takes a while, so I in fact don't want to enable it ...
 		[Test]
 		[ExpectedException (typeof (EndpointNotFoundException))]
 		public void RequestChannelOpenFails2 ()
@@ -168,7 +170,7 @@ namespace MonoTests.System.ServiceModel.Discovery
 			var cf = be.BuildChannelFactory<IDuplexSessionChannel> (bc);
 			cf.Open ();
 			var ch = cf.CreateChannel (DiscoveryClientBindingElement.DiscoveryEndpointAddress);
-			ch.Open ();
+			ch.Open (TimeSpan.FromSeconds (80));
 		}
 
 		[Test]
diff --git a/mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/ChangeLog b/mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/ChangeLog
index deaef73..deaaf4a 100644
--- a/mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/ChangeLog
+++ b/mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/ChangeLog
@@ -1,3 +1,11 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Work around a full-aot issue for monotouch System.Json
+
+2011-01-21  Atsushi Eno  <atsushi at ximian.com>
+
+	backport JavaScriptObjectDeserializer encoding detection fix.
+
 2010-10-29  Andreia Gaita  <shana at jitted.com>
 
 	[JsonWriter] Fix JsonWriter yet again. Behaviour of WriteRaw on
diff --git a/mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/JavaScriptObjectDeserializer.cs b/mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/JavaScriptObjectDeserializer.cs
index 495e79d..ae48edc 100644
--- a/mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/JavaScriptObjectDeserializer.cs
+++ b/mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/JavaScriptObjectDeserializer.cs
@@ -15,14 +15,19 @@ namespace System.Runtime.Serialization.Json
 		public class BufferedStreamReader : StreamReader
 		{
 			public BufferedStreamReader (Stream stream)
-				: base (stream, JavaScriptObjectDeserializer.DetectEncoding (stream.ReadByte (), stream.ReadByte ()))
+				: base (new BufferedStream (stream))
+			{
+			}
+			
+			BufferedStreamReader (BufferedStream stream)
+				: base (stream, JavaScriptObjectDeserializer.DetectEncoding (stream.first, stream.second))
 			{
 			}
 		}
 
 		class BufferedStream : Stream
 		{
-			int first, second;
+			internal int first, second;
 			long pos;
 			Stream source;
 
@@ -39,15 +44,23 @@ namespace System.Runtime.Serialization.Json
 					throw new ArgumentNullException ("buffer");
 				if (index < 0 || index >= buffer.Length)
 					throw new ArgumentOutOfRangeException ("index");
-				if (count < 0 || index + count >= buffer.Length)
+				if (count < 0 || index + count > buffer.Length)
 					throw new ArgumentOutOfRangeException ("count");
 
 				if (count == 0)
 					return 0;
-				if (pos < 2) {
-					buffer [pos] = pos == 0 ? (byte) first : (byte) second;
+				int iniCount = count;
+				if (pos == 0) {
+					buffer [index++] = (byte) first;
+					pos++;
+					if (--count == 0)
+						return iniCount;
+				}
+				if (pos == 1) {
+					buffer [index++] = (byte) second;
 					pos++;
-					return Read (buffer, index + 1, count - 1) + 1;
+					if (--count == 0)
+						return iniCount;
 				}
 				return source.Read (buffer, index, count);
 			}
@@ -128,16 +141,24 @@ namespace System.Runtime.Serialization.Json
 
 		public static Encoding DetectEncoding (int byte1, int byte2)
 		{
-			if (byte1 == 0) {
+			switch (byte1) {
+			case 0:
 				if (byte2 == 0)
 					throw new XmlException ("UTF-32BE is detected, which is not supported");
 				else
+					return Encoding.UTF8;
+			case 0xFE:
+				if (byte2 == 0xFF)
 					return Encoding.BigEndianUnicode;
-			} else {
-				if (byte2 == 0) // could be UTF-32LE, but there is no way to detect that only within two bytes.
+				else
+					return Encoding.UTF8;
+			case 0xFF:
+				if (byte2 == 0xFE) // could be UTF-32LE, but there is no way to detect that only within two bytes.
 					return Encoding.Unicode;
 				else
 					return Encoding.UTF8;
+			default:
+				return Encoding.UTF8;
 			}
 		}
 	}
diff --git a/mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/JavaScriptReader.cs b/mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/JavaScriptReader.cs
index 7460308..0a2de0c 100644
--- a/mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/JavaScriptReader.cs
+++ b/mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/JavaScriptReader.cs
@@ -80,7 +80,16 @@ namespace System.Runtime.Serialization.Json
 					if (c == '}')
 						break;
 				}
+#if MONOTOUCH
+				int idx = 0;
+				KeyValuePair<string, object> [] ret = new KeyValuePair<string, object>[obj.Count];
+				foreach (KeyValuePair <string, object> kvp in obj)
+					ret [idx++] = kvp;
+
+				return ret;
+#else
 				return obj.ToArray ();
+#endif
 			case 't':
 				Expect ("true");
 				return true;
diff --git a/mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/ChangeLog b/mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/ChangeLog
index 40efbaf..5669cec 100644
--- a/mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/ChangeLog
+++ b/mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/ChangeLog
@@ -1,3 +1,28 @@
+2011-01-20  Atsushi Eno  <atsushi at ximian.com>
+
+	Read body content if required. Fixed all issues in bug #656020.
+
+	Now it considers message content format and
+	IsWrapped[Request|Response] to retrieve XmlObjectSerializer.
+
+2011-01-19  Atsushi Eno  <atsushi at ximian.com>
+
+	Enable duplicate "UriMatched" error check, with couple of FIXMEs.
+
+	.NET is very unclear about those UriTemplate behavior. Too minor
+	to mind.
+
+2011-01-19  Atsushi Eno  <atsushi at ximian.com>
+
+	Fix template match logic to first check HTTP-method-matching ones.
+
+	Part of the fix for bug #656020.
+
+2011-01-19  Atsushi Eno  <atsushi at ximian.com>
+
+	Serialize non-mapped message parameter as body content. Part of
+	bug #656020 fix.
+
 2010-10-15  Marek Safar  <marek.safar at gmail.com>
 
 	Clean up few more warnings
diff --git a/mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/WebHttpDispatchOperationSelector.cs b/mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/WebHttpDispatchOperationSelector.cs
index 67735b8..eb4394c 100644
--- a/mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/WebHttpDispatchOperationSelector.cs
+++ b/mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/WebHttpDispatchOperationSelector.cs
@@ -26,6 +26,8 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 using System;
+using System.Collections.Generic;
+using System.Linq;
 using System.ServiceModel;
 using System.ServiceModel.Channels;
 using System.ServiceModel.Description;
@@ -39,7 +41,7 @@ namespace System.ServiceModel.Dispatcher
 	{
 		public const string HttpOperationSelectorUriMatchedPropertyName = "UriMatched";
 
-		UriTemplateTable table;
+		Dictionary<string,UriTemplateTable> tables = new Dictionary<string,UriTemplateTable> ();
 
 		protected WebHttpDispatchOperationSelector ()
 		{
@@ -52,41 +54,68 @@ namespace System.ServiceModel.Dispatcher
 			if (endpoint.Address == null)
 				throw new InvalidOperationException ("EndpointAddress must be set in the argument ServiceEndpoint");
 
-			table = new UriTemplateTable (endpoint.Address.Uri);
-
 			foreach (OperationDescription od in endpoint.Contract.Operations) {
 				WebAttributeInfo info = od.GetWebAttributeInfo ();
-				if (info != null)
+				if (info != null) {
+					UriTemplateTable table;
+					if (!tables.TryGetValue (info.Method, out table)) {
+						 table = new UriTemplateTable (endpoint.Address.Uri);
+						 tables.Add (info.Method, table);
+					}
 					table.KeyValuePairs.Add (new TemplateTablePair (info.BuildUriTemplate (od, null), od));
+				}
 			}
 		}
 
 		public string SelectOperation (ref Message message)
 		{
-			bool dummy;
-			return SelectOperation (ref message, out dummy);
+			// FIXME: uriMatched should be used to differentiate 404 and 405 (method not allowed)
+			bool uriMatched;
+			return SelectOperation (ref message, out uriMatched);
 		}
 
 		protected virtual string SelectOperation (ref Message message, out bool uriMatched)
 		{
 			if (message == null)
 				throw new ArgumentNullException ("message");
-			if (message.Properties.ContainsKey (WebBodyFormatMessageProperty.Name))
-				throw new ArgumentException ("There is already message property for Web body format");
+			if (message.Properties.ContainsKey (UriMatchedProperty.Name))
+				throw new ArgumentException (String.Format ("There is already a message property for template-matched URI '{0}'", UriMatchedProperty.Name));
 			uriMatched = false;
-			Uri to = message.Headers.To;
-			if (to == null)
-				return String.Empty;
+			var hp = (HttpRequestMessageProperty) message.Properties [HttpRequestMessageProperty.Name];
 
-			UriTemplateMatch match = table.MatchSingle (to);
 			OperationDescription od = null;
+			Message dummy = message; // since lambda expression prohibits ref variable...
+
+			Uri to = message.Headers.To;
+			// First, UriTemplateTable with corresponding HTTP method is tested. Then other tables can be tested for match.
+			UriTemplateTable table = null;
+			if (hp != null && hp.Method != null)
+				tables.TryGetValue (hp.Method, out table);
+			// FIXME: looks like To header does not matter on .NET. (But how to match then? I have no idea)
+			UriTemplateMatch match = to == null || table == null ? null : table.MatchSingle (to);
+			if (to != null && match == null) {
+				foreach (var tab in tables.Values)
+					if ((match = tab.MatchSingle (to)) != null) {
+						table = tab;
+						break;
+					}
+			}
+
 			if (match != null) {
 				uriMatched = true;
 				foreach (TemplateTablePair p in table.KeyValuePairs)
 					if (p.Key == match.Template)
 						od = p.Value as OperationDescription;
 			}
-			return od != null ? od.Name : String.Empty;
+			if (od != null)
+				message.Properties.Add (UriMatchedProperty.Name, new UriMatchedProperty ());
+
+			return uriMatched && od != null ? od.Name : String.Empty;
+		}
+
+		internal class UriMatchedProperty
+		{
+			public static string Name = "UriMatched"; // this is what .NET uses for MessageProperty that represents a matched URI.
 		}
 	}
 }
diff --git a/mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/WebMessageFormatter.cs b/mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/WebMessageFormatter.cs
index 239fbb8..6d2c2ab 100644
--- a/mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/WebMessageFormatter.cs
+++ b/mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/WebMessageFormatter.cs
@@ -99,6 +99,17 @@ namespace System.ServiceModel.Dispatcher
 			get { return info.IsBodyStyleSetExplicitly ? info.BodyStyle : behavior.DefaultBodyStyle; }
 		}
 
+		public bool IsRequestBodyWrapped {
+			get {
+				switch (BodyStyle) {
+				case WebMessageBodyStyle.Wrapped:
+				case WebMessageBodyStyle.WrappedRequest:
+					return true;
+				}
+				return BodyName != null;
+			}
+		}
+
 		public bool IsResponseBodyWrapped {
 			get {
 				switch (BodyStyle) {
@@ -139,6 +150,19 @@ namespace System.ServiceModel.Dispatcher
 			throw new SystemException ("INTERNAL ERROR: should not happen");
 		}
 
+		protected string GetMediaTypeString (WebContentFormat fmt)
+		{
+			switch (fmt) {
+			case WebContentFormat.Raw:
+				return "application/octet-stream";
+			case WebContentFormat.Json:
+				return "application/json";
+			case WebContentFormat.Xml:
+			default:
+				return "application/xml";
+			}
+		}
+
 		protected void CheckMessageVersion (MessageVersion messageVersion)
 		{
 			if (messageVersion == null)
@@ -156,24 +180,22 @@ namespace System.ServiceModel.Dispatcher
 			throw new SystemException ("INTERNAL ERROR: no corresponding message description for the specified direction: " + dir);
 		}
 
-		protected XmlObjectSerializer GetSerializer (WebContentFormat msgfmt)
+		protected XmlObjectSerializer GetSerializer (WebContentFormat msgfmt, bool isWrapped, MessagePartDescription part)
 		{
 			switch (msgfmt) {
 			case WebContentFormat.Xml:
-				if (IsResponseBodyWrapped)
-					return GetSerializer (ref xml_serializer, p => new DataContractSerializer (p.Type, p.Name, p.Namespace));
-				else
-					return GetSerializer (ref xml_serializer, p => new DataContractSerializer (p.Type));
-
+				if (xml_serializer == null)
+					xml_serializer = isWrapped ? new DataContractSerializer (part.Type, part.Name, part.Namespace) : new DataContractSerializer (part.Type);
+				return xml_serializer;
 			case WebContentFormat.Json:
 				// FIXME: after name argument they are hack
-#if !MOONLIGHT
-				if (IsResponseBodyWrapped)
-					return GetSerializer (ref json_serializer, p => new DataContractJsonSerializer (p.Type, BodyName ?? p.Name, null, 0x100000, false, null, true));
-				else
+				if (json_serializer == null)
+#if MOONLIGHT
+					json_serializer = new DataContractJsonSerializer (part.Type);
+#else
+					json_serializer = isWrapped ? new DataContractJsonSerializer (part.Type, BodyName ?? part.Name, null, 0x100000, false, null, true) : new DataContractJsonSerializer (part.Type);
 #endif
-					return GetSerializer (ref json_serializer, p => new DataContractJsonSerializer (p.Type));
-
+				return json_serializer;
 			default:
 				throw new NotImplementedException ();
 			}
@@ -181,13 +203,36 @@ namespace System.ServiceModel.Dispatcher
 
 		XmlObjectSerializer xml_serializer, json_serializer;
 
-		XmlObjectSerializer GetSerializer (ref XmlObjectSerializer serializer, Func<MessagePartDescription,XmlObjectSerializer> f)
+		protected object DeserializeObject (XmlObjectSerializer serializer, Message message, MessageDescription md, bool isWrapped, WebContentFormat fmt)
 		{
-			if (serializer == null) {
-				MessageDescription md = GetMessageDescription (MessageDirection.Output);
-				serializer = f (md.Body.ReturnValue);
+			// FIXME: handle ref/out parameters
+
+			var reader = message.GetReaderAtBodyContents ();
+
+			if (isWrapped) {
+				if (fmt == WebContentFormat.Json)
+					reader.ReadStartElement ("root", String.Empty); // note that the wrapper name is passed to the serializer.
+				else
+					reader.ReadStartElement (md.Body.WrapperName, md.Body.WrapperNamespace);
 			}
-			return serializer;
+
+			var ret = ReadObjectBody (serializer, reader);
+
+			if (isWrapped)
+				reader.ReadEndElement ();
+
+			return ret;
+		}
+		
+		protected object ReadObjectBody (XmlObjectSerializer serializer, XmlReader reader)
+		{
+#if NET_2_1
+			return (serializer is DataContractJsonSerializer) ?
+				((DataContractJsonSerializer) serializer).ReadObject (reader) :
+				((DataContractSerializer) serializer).ReadObject (reader, true);
+#else
+			return serializer.ReadObject (reader, true);
+#endif
 		}
 
 		internal class RequestClientFormatter : WebClientMessageFormatter
@@ -264,25 +309,37 @@ namespace System.ServiceModel.Dispatcher
 				if (parameters.Length != md.Body.Parts.Count)
 					throw new ArgumentException ("Parameter array length does not match the number of message body parts");
 
+				object msgpart = null;
+
 				for (int i = 0; i < parameters.Length; i++) {
 					var p = md.Body.Parts [i];
 					string name = p.Name.ToUpper (CultureInfo.InvariantCulture);
 					if (UriTemplate.PathSegmentVariableNames.Contains (name) ||
 					    UriTemplate.QueryValueVariableNames.Contains (name))
 						c.Add (name, parameters [i] != null ? Converter.ConvertValueToString (parameters [i], parameters [i].GetType ()) : null);
-					else
+					else {
 						// FIXME: bind as a message part
-						throw new NotImplementedException (String.Format ("parameter {0} is not contained in the URI template {1} {2} {3}", p.Name, UriTemplate, UriTemplate.PathSegmentVariableNames.Count, UriTemplate.QueryValueVariableNames.Count));
+						if (msgpart == null)
+							msgpart = parameters [i];
+						else
+							throw new  NotImplementedException (String.Format ("More than one parameters including {0} that are not contained in the URI template {1} was found.", p.Name, UriTemplate));
+					}
 				}
 
 				Uri to = UriTemplate.BindByName (Endpoint.Address.Uri, c);
 
-				Message ret = Message.CreateMessage (messageVersion, (string) null);
+				Message ret = Message.CreateMessage (messageVersion, (string) null, msgpart);
 				ret.Headers.To = to;
 
 				var hp = new HttpRequestMessageProperty ();
 				hp.Method = Info.Method;
 
+				WebMessageFormat msgfmt = Info.IsResponseFormatSetExplicitly ? Info.ResponseFormat : Behavior.DefaultOutgoingResponseFormat;
+				var contentFormat = ToContentFormat (msgfmt, msgpart);
+				string mediaType = GetMediaTypeString (contentFormat);
+				// FIXME: get encoding from somewhere
+				hp.Headers ["Content-Type"] = mediaType + "; charset=utf-8";
+
 #if !NET_2_1
 				if (WebOperationContext.Current != null)
 					WebOperationContext.Current.OutgoingRequest.Apply (hp);
@@ -306,32 +363,11 @@ namespace System.ServiceModel.Dispatcher
 				if (!message.Properties.ContainsKey (pname))
 					throw new SystemException ("INTERNAL ERROR: it expects WebBodyFormatMessageProperty existence");
 				var wp = (WebBodyFormatMessageProperty) message.Properties [pname];
-
-				var serializer = GetSerializer (wp.Format);
-
-				// FIXME: handle ref/out parameters
+				var fmt = wp != null ? wp.Format : WebContentFormat.Xml;
 
 				var md = GetMessageDescription (MessageDirection.Output);
-
-				var reader = message.GetReaderAtBodyContents ();
-
-				if (IsResponseBodyWrapped) {
-					if (wp.Format == WebContentFormat.Json)
-						reader.ReadStartElement ("root", String.Empty); // note that the wrapper name is passed to the serializer.
-					else
-						reader.ReadStartElement (md.Body.WrapperName, md.Body.WrapperNamespace);
-				}
-
-#if NET_2_1
-				var ret = (serializer is DataContractJsonSerializer) ?
-					((DataContractJsonSerializer) serializer).ReadObject (reader) :
-					((DataContractSerializer) serializer).ReadObject (reader, true);
-#else
-				var ret = serializer.ReadObject (reader, true);
-#endif
-
-				if (IsResponseBodyWrapped)
-					reader.ReadEndElement ();
+				var serializer = GetSerializer (wp.Format, IsResponseBodyWrapped, md.Body.ReturnValue);
+				var ret = DeserializeObject (serializer, message, md, IsResponseBodyWrapped, fmt);
 
 				return ret;
 			}
@@ -449,7 +485,6 @@ namespace System.ServiceModel.Dispatcher
 
 				WebMessageFormat msgfmt = Info.IsResponseFormatSetExplicitly ? Info.ResponseFormat : Behavior.DefaultOutgoingResponseFormat;
 
-				string mediaType = null;
 				XmlObjectSerializer serializer = null;
 
 				// FIXME: serialize ref/out parameters as well.
@@ -458,20 +493,19 @@ namespace System.ServiceModel.Dispatcher
 
 				switch (msgfmt) {
 				case WebMessageFormat.Xml:
-					serializer = GetSerializer (WebContentFormat.Xml);
-					mediaType = "application/xml";
+					serializer = GetSerializer (WebContentFormat.Xml, IsResponseBodyWrapped, md.Body.ReturnValue);
 					name = IsResponseBodyWrapped ? md.Body.WrapperName : null;
 					ns = IsResponseBodyWrapped ? md.Body.WrapperNamespace : null;
 					break;
 				case WebMessageFormat.Json:
-					serializer = GetSerializer (WebContentFormat.Json);
-					mediaType = "application/json";
+					serializer = GetSerializer (WebContentFormat.Json, IsResponseBodyWrapped, md.Body.ReturnValue);
 					name = IsResponseBodyWrapped ? (BodyName ?? md.Body.ReturnValue.Name) : null;
 					ns = String.Empty;
 					break;
 				}
 
 				var contentFormat = ToContentFormat (msgfmt, result);
+				string mediaType = GetMediaTypeString (contentFormat);
 				Message ret = contentFormat == WebContentFormat.Raw ? new RawMessage ((Stream) result) : Message.CreateMessage (MessageVersion.None, null, new WrappedBodyWriter (result, serializer, name, ns, contentFormat));
 
 				// Message properties
@@ -506,7 +540,8 @@ namespace System.ServiceModel.Dispatcher
 				}
 				
 				var wp = message.Properties [WebBodyFormatMessageProperty.Name] as WebBodyFormatMessageProperty;
-				if (wp != null && wp.Format == WebContentFormat.Raw) {
+				var fmt = wp != null ? wp.Format : WebContentFormat.Xml;
+				if (fmt == WebContentFormat.Raw) {
 					var rmsg = (RawMessage) message;
 					parameters [0] = rmsg.Stream;
 					return;
@@ -526,7 +561,12 @@ namespace System.ServiceModel.Dispatcher
 					var p = md.Body.Parts [i];
 					string name = p.Name.ToUpperInvariant ();
 					var str = match.BoundVariables [name];
-					parameters [i] = Converter.ConvertStringToValue (str, p.Type);
+					if (str != null)
+						parameters [i] = Converter.ConvertStringToValue (str, p.Type);
+					else {
+						var serializer = GetSerializer (fmt, IsRequestBodyWrapped, p);
+						parameters [i] = DeserializeObject (serializer, message, md, IsRequestBodyWrapped, fmt);
+					}
 				}
 			}
 		}
diff --git a/mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Dispatcher/ChangeLog b/mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Dispatcher/ChangeLog
old mode 100755
new mode 100644
index 4d17d55..ef36f4f
--- a/mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Dispatcher/ChangeLog
+++ b/mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Dispatcher/ChangeLog
@@ -1,3 +1,23 @@
+2011-01-20  Atsushi Eno  <atsushi at ximian.com>
+
+	Read body content if required. Fixed all issues in bug #656020.
+
+	Now it considers message content format and
+	IsWrapped[Request|Response] to retrieve XmlObjectSerializer.
+
+2011-01-19  Atsushi Eno  <atsushi at ximian.com>
+
+	Enable duplicate "UriMatched" error check, with couple of FIXMEs.
+
+	.NET is very unclear about those UriTemplate behavior. Too minor
+	to mind.
+
+2011-01-19  Atsushi Eno  <atsushi at ximian.com>
+
+	Fix template match logic to first check HTTP-method-matching ones.
+
+	Part of the fix for bug #656020.
+
 2010-05-24  Atsushi Enomoto  <atsushi at ximian.com>
 
 	* JsonQueryStringConverterTest.cs : add more tests for CanConvert()
diff --git a/mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Dispatcher/ChangeLog b/mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Dispatcher/ChangeLog.old
similarity index 100%
copy from mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Dispatcher/ChangeLog
copy to mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Dispatcher/ChangeLog.old
diff --git a/mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Dispatcher/WebHttpDispatchOperationSelectorTest.cs b/mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Dispatcher/WebHttpDispatchOperationSelectorTest.cs
index 222ae20..64e875b 100644
--- a/mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Dispatcher/WebHttpDispatchOperationSelectorTest.cs
+++ b/mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Dispatcher/WebHttpDispatchOperationSelectorTest.cs
@@ -57,6 +57,8 @@ namespace MonoTests.System.ServiceModel.Dispatcher
 			new WebHttpDispatchOperationSelector (se);
 		}
 
+		#region SelectOperation
+
 		[Test]
 		public void SelectOperation ()
 		{
@@ -64,14 +66,12 @@ namespace MonoTests.System.ServiceModel.Dispatcher
 		}
 
 		[Test]
-		[Category("NotWorking")]
 		public void SelectOperation2 ()
 		{
 			SelectOperationCore (Create2 ());
 		}
 
 		[Test]
-		[Category("NotWorking")]
 		public void SelectOperation3 ()
 		{
 			ContractDescription cd = ContractDescription.GetContract (typeof (MyService2));
@@ -135,12 +135,17 @@ namespace MonoTests.System.ServiceModel.Dispatcher
 
 		[Test]
 		[ExpectedException (typeof (ArgumentException))]
-		[Category ("NotWorking")]
 		public void SelectOperationCheckExistingProperty ()
 		{
 			var d = Create ();
-			var msg = Message.CreateMessage (MessageVersion.None, "http://temuri.org/MyService/Echo");
+			var msg = Message.CreateMessage (MessageVersion.None, "http://temuri.org/MyService/Echo"); // heh, I mistyped it and turned to prove that Action does not matter.
+			msg.Headers.To = new Uri ("http://localhost:8080/Echo");
+
+			// LAMESPEC: .NET does returns String.Empty, while we return the name of the operation (as IOperationSelector.SelectOperation is expected to do!)
+			// Assert.AreEqual (String.Empty, d.SelectOperation (ref msg), "#1");
 			d.SelectOperation (ref msg);
+
+			// The second invocation should raise the expected exception
 			d.SelectOperation (ref msg);
 		}
 
@@ -209,5 +214,63 @@ namespace MonoTests.System.ServiceModel.Dispatcher
 			//se.Contract.Operations [0].Behaviors.Add (new WebGetAttribute ());
 			return new MySelector (se);
 		}
+
+		#endregion
+
+		#region "bug #656020"
+
+		[DataContract]
+		public class User
+		{
+			[DataMember]
+			public string Name { get; set; }
+		}
+
+		[ServiceContract]
+		interface IHello
+		{
+			[WebGet(UriTemplate = "{name}?age={age}&blah={blah}")]
+			[OperationContract]
+			string SayHi (string name, int age, string blah);
+
+			[WebInvoke(UriTemplate = "blah")]
+			[OperationContract]
+			string SayHi2 (User user);
+		}
+
+		class Hello : IHello
+		{
+			public string SayHi (string name, int age, string blah)
+			{
+				return string.Format ("Hi {0}: {1}, {2}", name, age, blah == null);
+			}
+		
+			public string SayHi2 (User user)
+			{
+				return string.Format ("Hi {0}.", user.Name);
+			}
+		}
+
+		[Test]
+		public void WebMessageFormats ()
+		{
+			var host = new WebServiceHost (typeof (Hello));
+			host.AddServiceEndpoint (typeof (IHello), new WebHttpBinding (), "http://localhost:37564/");
+			host.Open ();
+			try {
+				// run client
+				using (ChannelFactory<IHello> factory = new ChannelFactory<IHello> (new WebHttpBinding (), "http://localhost:37564/"))
+				{
+					factory.Endpoint.Behaviors.Add (new WebHttpBehavior ());
+					IHello h = factory.CreateChannel ();
+					//Console.WriteLine(h.SayHi("Joe", 42, null));
+					Assert.AreEqual ("Hi Joe.", h.SayHi2 (new User { Name = "Joe" }), "#1");
+				}
+			} finally {
+				host.Close ();
+			}
+		}
+		
+		#endregion
 	}
 }
diff --git a/mcs/class/System.ServiceModel.Web/Test/System/ChangeLog b/mcs/class/System.ServiceModel.Web/Test/System/ChangeLog
index 6a7751b..102489f 100644
--- a/mcs/class/System.ServiceModel.Web/Test/System/ChangeLog
+++ b/mcs/class/System.ServiceModel.Web/Test/System/ChangeLog
@@ -1,3 +1,10 @@
+2011-01-19  Atsushi Eno  <atsushi at ximian.com>
+
+	Enable duplicate "UriMatched" error check, with couple of FIXMEs.
+
+	.NET is very unclear about those UriTemplate behavior. Too minor
+	to mind.
+
 2011-01-04  Marek Habersack  <grendel at twistedcode.net>
 
 	[wcf] UriTemplate must trim the first leading slash in the
diff --git a/mcs/class/System.ServiceModel.Web/Test/System/UriTemplateTest.cs b/mcs/class/System.ServiceModel.Web/Test/System/UriTemplateTest.cs
index 82105db..db6558a 100644
--- a/mcs/class/System.ServiceModel.Web/Test/System/UriTemplateTest.cs
+++ b/mcs/class/System.ServiceModel.Web/Test/System/UriTemplateTest.cs
@@ -320,6 +320,22 @@ namespace MonoTests.System
 		}
 
 		[Test]
+		[ExpectedException (typeof (ArgumentNullException))]
+		public void MatchNullArgument1 ()
+		{
+			var t = new UriTemplate ("/hooray");
+			t.Match (null, new Uri ("http://localhost/"));
+		}
+
+		[Test]
+		[ExpectedException (typeof (ArgumentNullException))]
+		public void MatchNullArgument2 ()
+		{
+			var t = new UriTemplate ("/hooray");
+			t.Match (new Uri ("http://localhost/"), null);
+		}
+
+		[Test]
 		public void MatchNoTemplateItem ()
 		{
 			var t = new UriTemplate ("/hooray");
diff --git a/mcs/class/System.ServiceModel/ChangeLog b/mcs/class/System.ServiceModel/ChangeLog
index 5a02813..e04fdb3 100644
--- a/mcs/class/System.ServiceModel/ChangeLog
+++ b/mcs/class/System.ServiceModel/ChangeLog
@@ -1,3 +1,11 @@
+2011-02-09  Atsushi Eno  <atsushi at ximian.com>
+
+	Support ServiceKnownTypes. Fixed another case on bug #652331.
+
+2011-01-21  Atsushi Eno  <atsushi at ximian.com>
+
+	And rename source file name.
+
 2010-11-04  Carlos Alberto Cortez  <calberto.cortez at gmail.com>
 
 	* System.ServiceModel_test.dll.sources: Add
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/ChangeLog b/mcs/class/System.ServiceModel/Mono.CodeGeneration/ChangeLog
old mode 100755
new mode 100644
index 4c6af3d..bcd30d8
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/ChangeLog
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/ChangeLog
@@ -1,3 +1,8 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	MonoTouch doesnt support SRE, so we need to disable this code on
+	MT
+
 2009-12-04  Sebastien Pouliot  <sebastien at ximian.com>
 
 	* CodeModule.cs: Silverlight does not allow AssemblyBuilderAccess.
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/ChangeLog b/mcs/class/System.ServiceModel/Mono.CodeGeneration/ChangeLog.old
similarity index 100%
copy from mcs/class/System.ServiceModel/Mono.CodeGeneration/ChangeLog
copy to mcs/class/System.ServiceModel/Mono.CodeGeneration/ChangeLog.old
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeAnd.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeAnd.cs
index c0cb338..128c5b9 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeAnd.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeAnd.cs
@@ -22,6 +22,7 @@
 //
 
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -113,4 +114,5 @@ namespace Mono.CodeGeneration
 			return typeof (bool);
 		}
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArgument.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArgument.cs
index f862b2f..c06d247 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArgument.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArgument.cs
@@ -1,5 +1,6 @@
 // created on 28/08/2004 at 17:07
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -36,3 +37,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArgumentReference.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArgumentReference.cs
index 752ed82..d256864 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArgumentReference.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArgumentReference.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -79,3 +80,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArithmeticOperation.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArithmeticOperation.cs
index 93bfbb2..92ddb5e 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArithmeticOperation.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArithmeticOperation.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -141,3 +142,4 @@ namespace Mono.CodeGeneration
 		}
 	}	
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArrayItem.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArrayItem.cs
index f5b05ad..b521345 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArrayItem.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArrayItem.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -174,3 +175,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArrayLength.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArrayLength.cs
index 9842c00..489004e 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArrayLength.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeArrayLength.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -56,3 +57,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeAssignment.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeAssignment.cs
index fc34a0a..49dcb11 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeAssignment.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeAssignment.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -70,3 +71,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBinaryComparison.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBinaryComparison.cs
index d8cb665..c60f58a 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBinaryComparison.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBinaryComparison.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -165,4 +166,5 @@ namespace Mono.CodeGeneration
 				gen.Emit (OpCodes.Bgt, label);
 		}
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBinaryOperation.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBinaryOperation.cs
index 50d034b..dc6d5ef 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBinaryOperation.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBinaryOperation.cs
@@ -1,5 +1,6 @@
 // created on 28/08/2004 at 17:30
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -36,3 +37,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBlock.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBlock.cs
index 92da989..4dfa1d0 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBlock.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBlock.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Collections;
 using System.Reflection;
@@ -86,3 +87,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBuilder.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBuilder.cs
index db01ee1..58de364 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBuilder.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeBuilder.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.IO;
 using System.Collections;
@@ -421,3 +422,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeCast.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeCast.cs
index 2f725b7..4610f4b 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeCast.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeCast.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -131,3 +132,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeClass.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeClass.cs
index 211d882..1327d5c 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeClass.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeClass.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.IO;
 using System.Collections;
@@ -346,3 +347,4 @@ namespace Mono.CodeGeneration
 	}
 }
 
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeCustomAttribute.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeCustomAttribute.cs
index 83f4384..b2c0519 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeCustomAttribute.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeCustomAttribute.cs
@@ -18,6 +18,7 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
+#if !MONOTOUCH
 using System;
 using System.IO;
 using System.Collections;
@@ -145,3 +146,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeDecrement.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeDecrement.cs
index 9345241..d7f488b 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeDecrement.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeDecrement.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -146,3 +147,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeEquals.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeEquals.cs
index 4b977c3..b9ea6dd 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeEquals.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeEquals.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -97,4 +98,5 @@ namespace Mono.CodeGeneration
 			return typeof (bool);
 		}
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeExpression.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeExpression.cs
index 8691161..066b279 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeExpression.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeExpression.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -196,3 +197,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeFieldReference.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeFieldReference.cs
index 6492d98..7beeffe 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeFieldReference.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeFieldReference.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -90,3 +91,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeFor.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeFor.cs
index 895bd32..123e556 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeFor.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeFor.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -82,3 +83,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeForeach.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeForeach.cs
index 0241614..8f7f6bf 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeForeach.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeForeach.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Collections;
 using System.Reflection;
@@ -122,3 +123,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeGenerationHelper.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeGenerationHelper.cs
index 7383752..d0defd9 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeGenerationHelper.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeGenerationHelper.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Collections;
 using System.Reflection.Emit;
@@ -207,3 +208,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeIf.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeIf.cs
index 95fe2a0..e860fd8 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeIf.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeIf.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -108,3 +109,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeIncrement.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeIncrement.cs
index 6cbf570..5967954 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeIncrement.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeIncrement.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -151,3 +152,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeIs.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeIs.cs
index 6e4eafd..c8f682b 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeIs.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeIs.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -94,3 +95,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeItem.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeItem.cs
index 442ee05..6e2586c 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeItem.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeItem.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -37,3 +38,4 @@ namespace Mono.CodeGeneration
 	{
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeLiteral.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeLiteral.cs
index 668ee33..152d7f8 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeLiteral.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeLiteral.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Globalization;
 using System.Reflection;
@@ -143,3 +144,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeMethod.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeMethod.cs
index 915271a..2bde317 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeMethod.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeMethod.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Collections;
 using System.IO;
@@ -226,3 +227,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeMethodCall.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeMethodCall.cs
index d834753..fc882c4 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeMethodCall.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeMethodCall.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -142,3 +143,4 @@ namespace Mono.CodeGeneration
 	}
 }
 
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeModule.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeModule.cs
index fa2286b..bf9b4bd 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeModule.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeModule.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.IO;
 using System.Collections;
@@ -78,3 +79,4 @@ namespace Mono.CodeGeneration
 	}
 }
 
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeNew.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeNew.cs
index addefc9..2e97c84 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeNew.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeNew.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -69,3 +70,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeNewArray.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeNewArray.cs
index 68b83a0..a7dd963 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeNewArray.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeNewArray.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -59,3 +60,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeNotEquals.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeNotEquals.cs
index 5470674..dcf9b3d 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeNotEquals.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeNotEquals.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -114,4 +115,5 @@ namespace Mono.CodeGeneration
 			return typeof (bool);
 		}
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeOr.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeOr.cs
index 1a0c5be..32b0ce2 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeOr.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeOr.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -114,4 +115,5 @@ namespace Mono.CodeGeneration
 			return typeof (bool);
 		}
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeProperty.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeProperty.cs
index 8ec6d62..0e79378 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeProperty.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeProperty.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Collections;
 using System.IO;
@@ -242,3 +243,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodePropertyReference.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodePropertyReference.cs
index e8c9e19..b268e83 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodePropertyReference.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodePropertyReference.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -61,3 +62,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeReturn.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeReturn.cs
index d29f1d0..ca9ecb3 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeReturn.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeReturn.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -62,3 +63,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeSelect.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeSelect.cs
index c38d167..ea83af5 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeSelect.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeSelect.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Collections;
 using System.Reflection;
@@ -86,3 +87,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeSelfIncrement.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeSelfIncrement.cs
index 3ebd292..90dd701 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeSelfIncrement.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeSelfIncrement.cs
@@ -1,5 +1,6 @@
 // created on 28/08/2004 at 17:30
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -90,3 +91,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeTryBlock.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeTryBlock.cs
index 3414e32..b917e14 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeTryBlock.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeTryBlock.cs
@@ -21,6 +21,7 @@
 // Copyright (C) 2009 Novell, Inc
 //
 
+#if !MONOTOUCH
 using System;
 using System.Collections;
 #if NET_2_0
@@ -123,3 +124,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeUnaryOperation.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeUnaryOperation.cs
index 10f5cde..b66493a 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeUnaryOperation.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeUnaryOperation.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -100,3 +101,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeValueReference.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeValueReference.cs
index 712d55c..52dd50b 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeValueReference.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeValueReference.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -32,3 +33,4 @@ namespace Mono.CodeGeneration
 		public abstract void GenerateSet (ILGenerator gen, CodeExpression value);
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeVariableDeclaration.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeVariableDeclaration.cs
index a96a077..93f8394 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeVariableDeclaration.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeVariableDeclaration.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -52,3 +53,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeVariableReference.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeVariableReference.cs
index 01fc93f..af682fb 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeVariableReference.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeVariableReference.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -78,3 +79,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeWhen.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeWhen.cs
index b5d1eb9..41fa2b1 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeWhen.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeWhen.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -84,3 +85,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeWhile.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeWhile.cs
index 0814a4c..d691cfe 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeWhile.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeWhile.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -76,3 +77,4 @@ namespace Mono.CodeGeneration
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeWriter.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeWriter.cs
index 31be509..ee9ff61 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeWriter.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeWriter.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.IO;
 
@@ -89,3 +90,4 @@ public class CodeWriter
 }
 
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/Mono.CodeGeneration/Exp.cs b/mcs/class/System.ServiceModel/Mono.CodeGeneration/Exp.cs
index f1fe56c..e67107a 100644
--- a/mcs/class/System.ServiceModel/Mono.CodeGeneration/Exp.cs
+++ b/mcs/class/System.ServiceModel/Mono.CodeGeneration/Exp.cs
@@ -21,6 +21,7 @@
 // Copyright (C) Lluis Sanchez Gual, 2004
 //
 
+#if !MONOTOUCH
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
@@ -96,3 +97,4 @@ namespace Mono.CodeGeneration
 		
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/ChangeLog b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/ChangeLog
index ec7b6d0..727c687 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/ChangeLog
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/ChangeLog
@@ -1,3 +1,11 @@
+2011-01-21  Atsushi Eno  <atsushi at ximian.com>
+
+	Avoid possible list modification error during close process.
+
+2011-01-21  Atsushi Eno  <atsushi at ximian.com>
+
+	Make sure to close session once the client opened one.
+
 2011-01-08  Marek Safar  <marek.safar at gmail.com>
 
 	Fixed missing protected internal modifier
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/HttpRequestChannel.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/HttpRequestChannel.cs
index 5f4ac53..df9ce82 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/HttpRequestChannel.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/HttpRequestChannel.cs
@@ -294,7 +294,7 @@ namespace System.ServiceModel.Channels
 
 		protected override void OnAbort ()
 		{
-			foreach (var web_request in web_requests)
+			foreach (var web_request in web_requests.ToArray ())
 				web_request.Abort ();
 			web_requests.Clear ();
 		}
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/TcpDuplexSessionChannel.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/TcpDuplexSessionChannel.cs
index 6bd6922..3f504b4 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/TcpDuplexSessionChannel.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/TcpDuplexSessionChannel.cs
@@ -219,6 +219,7 @@ namespace System.ServiceModel.Channels
 					Via = this.Via };
 				frame.ProcessPreambleInitiator ();
 				frame.ProcessPreambleAckInitiator ();
+				session = new TcpDuplexSession (this); // make sure to shutdown the session once it has initiated one.
 			} else {
 				// server side
 				Stream s = client.GetStream ();
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ChangeLog b/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ChangeLog
index 656223f..e3a3fe8 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ChangeLog
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ChangeLog
@@ -1,3 +1,10 @@
+2011-02-01  Atsushi Eno  <atsushi at ximian.com>
+
+	standard endpoint and protocol mapping support were lacking at
+	client side.
+
+	Turned out that they had nothing to do with #668089..
+
 2010-10-20  Atsushi Eno  <atsushi at ximian.com>
 
 	Forgot #if NET_4_0.
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ConfigUtil.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ConfigUtil.cs
index bb24e60..aec08d4 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ConfigUtil.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ConfigUtil.cs
@@ -99,6 +99,49 @@ namespace System.ServiceModel.Configuration
 		}
 
 #if NET_4_0
+		public static Binding GetBindingByProtocolMapping (Uri address)
+		{
+			ProtocolMappingElement el = ConfigUtil.ProtocolMappingSection.ProtocolMappingCollection [address.Scheme];
+			if (el == null)
+				return null;
+			return ConfigUtil.CreateBinding (el.Binding, el.BindingConfiguration);
+		}
+
+		public static ServiceEndpoint ConfigureStandardEndpoint (ContractDescription cd, ChannelEndpointElement element)
+		{
+			string kind = element.Kind;
+			string endpointConfiguration = element.EndpointConfiguration;
+
+			EndpointCollectionElement section = ConfigUtil.StandardEndpointsSection [kind];
+			if (section == null)
+				throw new ArgumentException (String.Format ("standard endpoint section for '{0}' was not found.", kind));
+
+			StandardEndpointElement e = section.GetDefaultStandardEndpointElement ();
+
+			ServiceEndpoint inst = e.CreateServiceEndpoint (cd);
+
+			foreach (StandardEndpointElement el in section.ConfiguredEndpoints) {
+				if (el.Name == endpointConfiguration) {
+					el.InitializeAndValidate (element);
+					el.ApplyConfiguration (inst, element);
+					break;
+				}
+			}
+			
+			return inst;
+		}
+
+		public static Type GetTypeFromConfigString (string name)
+		{
+			Type type = Type.GetType (name);
+			if (type != null)
+				return type;
+			foreach (var ass in AppDomain.CurrentDomain.GetAssemblies ())
+				if ((type = ass.GetType (name)) != null)
+					return type;
+			return null;
+		}
+
 		public static ServiceEndpoint ConfigureStandardEndpoint (ContractDescription cd, ServiceEndpointElement element)
 		{
 			string kind = element.Kind;
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Description/ChangeLog b/mcs/class/System.ServiceModel/System.ServiceModel.Description/ChangeLog
index 2ee7db9..26ad0f9 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Description/ChangeLog
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Description/ChangeLog
@@ -1,3 +1,14 @@
+2011-02-03  Atsushi Eno  <atsushi at ximian.com>
+
+	Now operations are collected per corresponding
+	ContractDescription.
+
+	This fixes naming of MessageDescription Action URI from its type.
+
+2011-02-02  Atsushi Eno  <atsushi at ximian.com>
+
+	Implement GetInheritedContracts(), towards bugfix #668089.
+
 2010-11-10  Marek Habersack  <grendel at twistedcode.net>
 
 	[wcf] .NET allows for service contract methods to be decorated
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescription.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescription.cs
index 6fd28c6..a5951a4 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescription.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescription.cs
@@ -29,6 +29,7 @@ using System;
 using System.Collections;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
+using System.Linq;
 using System.Net.Security;
 using System.Reflection;
 using System.Runtime.Serialization;
@@ -139,10 +140,15 @@ namespace System.ServiceModel.Description
 			set { session = value; }
 		}
 
-		[MonoTODO]
 		public Collection<ContractDescription> GetInheritedContracts ()
 		{
-			throw new NotImplementedException ();
+			var ret = new Collection<ContractDescription> ();
+			foreach (var it in ContractType.GetInterfaces ()) {
+				var icd = ContractDescriptionGenerator.GetContractInternal (it, null, null);
+				if (icd != null)
+					ret.Add (icd);
+			}
+			return ret;
 		}
 
 		internal ClientRuntime CreateClientRuntime (object callbackDispatchRuntime)
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescriptionGenerator.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescriptionGenerator.cs
index 758c027..91f084d 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescriptionGenerator.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescriptionGenerator.cs
@@ -132,13 +132,21 @@ namespace System.ServiceModel.Description
 
 		static ContractDescription GetContract (Type givenContractType, Type givenServiceType, Type serviceTypeForCallback)
 		{
+			var ret = GetContractInternal (givenContractType, givenServiceType, serviceTypeForCallback);
+			if (ret == null)
+				throw new InvalidOperationException (String.Format ("Attempted to get contract type from '{0}' which neither is a service contract nor does it inherit service contract.", serviceTypeForCallback ?? givenContractType));
+			return ret;
+		}
+
+		internal static ContractDescription GetContractInternal (Type givenContractType, Type givenServiceType, Type serviceTypeForCallback)
+		{
 			// FIXME: serviceType should be used for specifying attributes like OperationBehavior.
 
 			Type exactContractType = null;
 			ServiceContractAttribute sca = null;
 			Dictionary<Type, ServiceContractAttribute> contracts = 
 				GetServiceContractAttributes (serviceTypeForCallback ?? givenServiceType ?? givenContractType);
-			if (contracts.ContainsKey(givenContractType)) {
+			if (contracts.ContainsKey (givenContractType)) {
 				exactContractType = givenContractType;
 				sca = contracts [givenContractType];
 			} else {
@@ -158,7 +166,7 @@ namespace System.ServiceModel.Description
 				if (serviceTypeForCallback != null)
 					sca = contracts.Values.First ();
 				else
-					throw new InvalidOperationException (String.Format ("Attempted to get contract type from '{0}' which neither is a service contract nor does it inherit service contract.", serviceTypeForCallback ?? givenContractType));
+					return null; // no contract
 			}
 			string name = sca.Name ?? exactContractType.Name;
 			string ns = sca.Namespace ?? "http://tempuri.org/";
@@ -175,7 +183,14 @@ namespace System.ServiceModel.Description
 			if (sca.HasProtectionLevel)
 				cd.ProtectionLevel = sca.ProtectionLevel;
 
+			foreach (var icd in cd.GetInheritedContracts ()) {
+				FillOperationsForInterface (icd, icd.ContractType, givenServiceType, false);
+				foreach (var od in icd.Operations)
+					cd.Operations.Add (od);
+			}
+			
 			FillOperationsForInterface (cd, cd.ContractType, givenServiceType, false);
+			
 			if (cd.CallbackContractType != null && cd.CallbackContractType != cd.ContractType)
 				FillOperationsForInterface (cd, cd.CallbackContractType, null, true);
 
@@ -190,7 +205,7 @@ namespace System.ServiceModel.Description
 		static void FillOperationsForInterface (ContractDescription cd, Type exactContractType, Type givenServiceType, bool isCallback)
 		{
 			// FIXME: load Behaviors
-			MethodInfo [] contractMethods = exactContractType.IsInterface ? GetAllMethods (exactContractType) : exactContractType.GetMethods ();
+			MethodInfo [] contractMethods = /*exactContractType.IsInterface ? GetAllMethods (exactContractType) :*/ exactContractType.GetMethods (BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
 			MethodInfo [] serviceMethods = contractMethods;
 			if (givenServiceType != null && exactContractType.IsInterface) {
 				var l = new List<MethodInfo> ();
@@ -255,7 +270,7 @@ namespace System.ServiceModel.Description
 		{
 			string name = oca.Name ?? (oca.AsyncPattern ? mi.Name.Substring (5) : mi.Name);
 
-			OperationDescription od = cd.Operations.FirstOrDefault (o => o.Name == name);
+			OperationDescription od = isCallback ? null : cd.Operations.FirstOrDefault (o => o.Name == name);
 			if (od == null) {
 				od = new OperationDescription (name, cd);
 				od.IsOneWay = oca.IsOneWay;
@@ -282,8 +297,8 @@ namespace System.ServiceModel.Description
 				}
 				cd.Operations.Add (od);
 			}
-			else if (oca.AsyncPattern && od.BeginMethod != null && od.BeginMethod != mi ||
-				 !oca.AsyncPattern && od.SyncMethod != null && od.SyncMethod != mi)
+			else if ((oca.AsyncPattern && od.BeginMethod != null && od.BeginMethod != mi ||
+				 !oca.AsyncPattern && od.SyncMethod != null && od.SyncMethod != mi) && od.InCallbackContract == isCallback)
 				throw new InvalidOperationException (String.Format ("contract '{1}' cannot have two operations for '{0}' that have the identical names and different set of parameters.", name, cd.Name));
 
 			if (oca.AsyncPattern)
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Description/OperationDescriptionCollection.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Description/OperationDescriptionCollection.cs
index 5a0eae5..1680210 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Description/OperationDescriptionCollection.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Description/OperationDescriptionCollection.cs
@@ -60,16 +60,11 @@ namespace System.ServiceModel.Description
 
 		protected override void InsertItem (int index, OperationDescription item)
 		{
-			if (Find (item.Name) == null)
-				base.InsertItem (index, item);
-			else
-				throw new InvalidOperationException ("A contract cannot have two operations that have the identical names and different set of parameters.");
+			base.InsertItem (index, item);
 		}
 
 		protected override void SetItem (int index, OperationDescription item)
 		{
-			if (Find (item.Name) != null)
-				base.RemoveItem (index);
 			base.SetItem (index, item);
 		}
 	}
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/BaseMessagesFormatter.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/BaseMessagesFormatter.cs
index a4b5159..79af8ae 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/BaseMessagesFormatter.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/BaseMessagesFormatter.cs
@@ -111,6 +111,7 @@ namespace System.ServiceModel.Dispatcher
 		bool isAsync;
 		ParameterInfo [] requestMethodParams;
 		ParameterInfo [] replyMethodParams;
+		List<Type> operation_known_types = new List<Type> ();
 
 		public BaseMessagesFormatter (MessageDescriptionCollection messages)
 		{
@@ -133,6 +134,7 @@ namespace System.ServiceModel.Dispatcher
 			methodParams = desc.EndMethod.GetParameters ();
 			replyMethodParams = new ParameterInfo [methodParams.Length - 1];
 			Array.Copy (methodParams, replyMethodParams, replyMethodParams.Length);
+			operation_known_types.AddRange (desc.KnownTypes);
 		}
 
 		public static BaseMessagesFormatter Create (OperationDescription desc)
@@ -152,6 +154,10 @@ namespace System.ServiceModel.Dispatcher
 			return new DataContractMessagesFormatter (desc, dataAttr);
 		}
 
+		public IEnumerable<Type> OperationKnownTypes {
+			get { return operation_known_types; }
+		}
+
 		protected abstract Message PartsToMessage (
 			MessageDescription md, MessageVersion version, string action, object [] parts);
 		protected abstract object [] MessageToParts (MessageDescription md, Message message);
@@ -334,7 +340,6 @@ namespace System.ServiceModel.Dispatcher
 			return (object []) GetSerializer (md.Body).Deserialize (r);
 		}
 
-		// FIXME: Handle ServiceKnownTypes
 		XmlSerializer GetSerializer (MessageBodyDescription desc)
 		{
 			if (bodySerializers.ContainsKey (desc))
@@ -350,8 +355,10 @@ namespace System.ServiceModel.Dispatcher
 			foreach (MessagePartDescription partDesc in desc.Parts)
 				members [ind++] = CreateReflectionMember (partDesc, false);
 
-			// FIXME: Register known types into xmlImporter.
 			XmlReflectionImporter xmlImporter = new XmlReflectionImporter ();
+			// Register known types into xmlImporter.
+			foreach (var type in OperationKnownTypes)
+				xmlImporter.IncludeType (type);
 			XmlMembersMapping [] partsMapping = new XmlMembersMapping [1];
 			partsMapping [0] = xmlImporter.ImportMembersMapping (desc.WrapperName, desc.WrapperNamespace, members, true);
 			bodySerializers [desc] = XmlSerializer.FromMappings (partsMapping) [0];
@@ -440,12 +447,11 @@ namespace System.ServiceModel.Dispatcher
 			return parts;
 		}
 
-		// FIXME: Handle ServiceKnownTypes
 		XmlObjectSerializer GetSerializer (MessagePartDescription partDesc)
 		{
 			if (!serializers.ContainsKey (partDesc))
 				serializers [partDesc] = new DataContractSerializer (
-					partDesc.Type, partDesc.Name, partDesc.Namespace);
+					partDesc.Type, partDesc.Name, partDesc.Namespace, OperationKnownTypes);
 			return serializers [partDesc];
 		}
 
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChangeLog b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChangeLog
index 47ae55c..69f5ac5 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChangeLog
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChangeLog
@@ -1,3 +1,39 @@
+2011-02-09  Atsushi Eno  <atsushi at ximian.com>
+
+	Support ServiceKnownTypes. Fixed another case on bug #652331.
+
+2011-02-07  Atsushi Eno  <atsushi at ximian.com>
+
+	Open and close client/service runtime channels in chains. Fixed
+	bug #663278.
+
+2011-02-07  Atsushi Eno  <atsushi at ximian.com>
+
+	handle IsTerminating.
+
+2011-02-04  Atsushi Eno  <atsushi at ximian.com>
+
+	Callback contract should be distinguished from others for
+	DispatchOperation.
+
+2011-01-21  Atsushi Eno  <atsushi at ximian.com>
+
+	Fix regression, avoid null key.
+
+2011-01-21  Atsushi Eno  <atsushi at ximian.com>
+
+	And rename source file name.
+
+2011-01-21  Atsushi Eno  <atsushi at ximian.com>
+
+	Rename InstanceBhavior, too ambiguous among IXxxBehavior
+	interfaces.
+
+2011-01-21  Atsushi Eno  <atsushi at ximian.com>
+
+	Sessions should not be keyed by MessageId but be done by channel
+	SessionId.
+
 2010-10-20  Marek Habersack  <grendel at twistedcode.net>
 
 	[wcf] make /js and /jsdebug dispatchers work.
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/EndpointDispatcher.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/EndpointDispatcher.cs
index f34f892..2ad7f63 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/EndpointDispatcher.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/EndpointDispatcher.cs
@@ -124,7 +124,7 @@ namespace System.ServiceModel.Dispatcher
 			IsSystemEndpoint = se.IsSystemEndpoint;
 #endif
 
-			this.ContractFilter = GetContractFilter (se.Contract);
+			this.ContractFilter = GetContractFilter (se.Contract, isCallback);
 
 			this.DispatchRuntime.Type = serviceType;
 			
@@ -137,7 +137,7 @@ namespace System.ServiceModel.Dispatcher
 				ccd.FillClientOperations (db.CallbackClientRuntime, true);
 			}
 			foreach (OperationDescription od in se.Contract.Operations)
-				if (!db.Operations.Contains (od.Name))
+				if (od.InCallbackContract == isCallback/* && !db.Operations.Contains (od.Name)*/)
 					PopulateDispatchOperation (db, od);
 		}
 
@@ -153,6 +153,7 @@ namespace System.ServiceModel.Dispatcher
 				od.IsOneWay ?
 				new DispatchOperation (db, od.Name, reqA) :
 				new DispatchOperation (db, od.Name, reqA, resA);
+			o.IsTerminating = od.IsTerminating;
 			bool no_serialized_reply = od.IsOneWay;
 			foreach (MessageDescription md in od.Messages) {
 				if (md.IsRequest &&
@@ -191,17 +192,20 @@ namespace System.ServiceModel.Dispatcher
 			db.Operations.Add (o);
 		}
 
-		MessageFilter GetContractFilter (ContractDescription cd)
+		MessageFilter GetContractFilter (ContractDescription cd, bool isCallback)
 		{
 			List<string> actions = new List<string> ();
-			foreach (var od in cd.Operations)
+			foreach (var od in cd.Operations) {
 				foreach (var md in od.Messages)
-					if (md.IsRequest)
+					// For callback EndpointDispatcher (i.e. for duplex client), it should get "incoming" request for callback operations and "outgoing" response for non-callback operations.
+					// For non-callback EndpointDispatcher,  it should get "outgoing" request for non-callback operations and "incoming" response for callback operations.
+					if ((od.InCallbackContract == isCallback) == md.IsRequest) {
 						if (md.Action == "*")
 							return new MatchAllMessageFilter ();
 						else
 							actions.Add (md.Action);
-
+					}
+			}
 			return new ActionMessageFilter (actions.ToArray ());
 		}
 	}
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/FinalizeProcessingHandler.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/FinalizeProcessingHandler.cs
index 6828875..89cd265 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/FinalizeProcessingHandler.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/FinalizeProcessingHandler.cs
@@ -15,10 +15,11 @@ namespace System.ServiceModel.Dispatcher
 		}
 
 		void FinishRequest (MessageProcessingContext mrc)
-		{				
-			if (mrc.Operation != null &&  mrc.Operation.ReleaseInstanceAfterCall) {
+		{
+			if (mrc.Operation != null &&  mrc.Operation.IsTerminating && mrc.OperationContext.Channel.InputSession != null)
+				mrc.OperationContext.Channel.Close (); // FIXME: timeout?
+			if (mrc.Operation != null &&  mrc.Operation.ReleaseInstanceAfterCall)
 				mrc.InstanceContext.ReleaseServiceInstance ();
-			}
 			mrc.InstanceContext.CloseIfIdle ();			
 		}
 	}
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/InitializingHandler.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/InitializingHandler.cs
index e2d23f0..ef501c9 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/InitializingHandler.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/InitializingHandler.cs
@@ -30,7 +30,7 @@ namespace System.ServiceModel.Dispatcher
 				iCtx = new InstanceContext (dispatchRuntime.ChannelDispatcher.Host, null, false);
 			}
 
-			iCtx.Behavior = new InstanceBehavior (dispatchRuntime);
+			iCtx.InstanceManager = new InstanceManager (dispatchRuntime);
 			return iCtx;
 		}		
 	}
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/InputOrReplyRequestProcessor.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/InputOrReplyRequestProcessor.cs
index 1e8aeeb..950d338 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/InputOrReplyRequestProcessor.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/InputOrReplyRequestProcessor.cs
@@ -60,6 +60,7 @@ namespace System.ServiceModel.Dispatcher
 			}
 			else
 				contextChannel = new ServiceRuntimeChannel (reply_or_input, dispatch_runtime);
+			contextChannel.Open (); // FIXME: timeout?
 			OperationContext opCtx = new OperationContext (contextChannel);
 			opCtx.IncomingMessage = incoming;
 			opCtx.EndpointDispatcher = dispatch_runtime.EndpointDispatcher;
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/InstanceBehavior.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/InstanceBehavior.cs
deleted file mode 100644
index 1574c6c..0000000
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/InstanceBehavior.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using System.ServiceModel;
-using System.ServiceModel.Dispatcher;
-using System.ServiceModel.Channels;
-using System.Text;
-
-namespace System.ServiceModel.Dispatcher
-{
-	internal class InstanceBehavior
-	{
-		DispatchRuntime dispatch_runtime;
-
-		internal InstanceBehavior (DispatchRuntime runtime) {
-			dispatch_runtime = runtime;
-		}
-
-		internal void Initialize (InstanceContext iCtx) {
-			Message message = OperationContext.Current.IncomingMessage;
-			IContextChannel channel = OperationContext.Current.Channel;
-			if (dispatch_runtime.InstanceContextProvider != null) {
-				dispatch_runtime.InstanceContextProvider.InitializeInstanceContext (iCtx,
-													message,
-													channel);
-			}
-			foreach (IInstanceContextInitializer init in dispatch_runtime.InstanceContextInitializers)
-				init.Initialize (iCtx, message);					
-		}
-
-		internal object GetServiceInstance (InstanceContext ctx, Message m, ref bool createdByUserProvider) {
-			if (dispatch_runtime.InstanceProvider != null) {
-				createdByUserProvider = true;
-				return dispatch_runtime.InstanceProvider.GetInstance (ctx, m);
-			}
-			createdByUserProvider = false;
-			return Activator.CreateInstance (
-				dispatch_runtime.ChannelDispatcher.Host.Description.ServiceType, true);
-		}
-
-		internal IInstanceContextProvider InstanceContextProvider {
-			get {
-				return dispatch_runtime.InstanceContextProvider;
-			}
-		}
-
-		internal void ReleaseServiceInstance (InstanceContext ctx, object impl) 
-		{
-			if (ctx.IsUserProvidedInstance) {
-				dispatch_runtime.InstanceProvider.ReleaseInstance (ctx, impl);
-				
-			}
-		}
-	}
-}
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/InstanceManager.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/InstanceManager.cs
new file mode 100644
index 0000000..b4dfd68
--- /dev/null
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/InstanceManager.cs
@@ -0,0 +1,55 @@
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.ServiceModel;
+using System.ServiceModel.Dispatcher;
+using System.ServiceModel.Channels;
+using System.Text;
+
+namespace System.ServiceModel.Dispatcher
+{
+	internal class InstanceManager
+	{
+		DispatchRuntime dispatch_runtime;
+
+		internal InstanceManager (DispatchRuntime runtime) {
+			dispatch_runtime = runtime;
+		}
+
+		internal void Initialize (InstanceContext iCtx) {
+			Message message = OperationContext.Current.IncomingMessage;
+			IContextChannel channel = OperationContext.Current.Channel;
+			if (dispatch_runtime.InstanceContextProvider != null) {
+				dispatch_runtime.InstanceContextProvider.InitializeInstanceContext (iCtx,
+													message,
+													channel);
+			}
+			foreach (IInstanceContextInitializer init in dispatch_runtime.InstanceContextInitializers)
+				init.Initialize (iCtx, message);					
+		}
+
+		internal object GetServiceInstance (InstanceContext ctx, Message m, ref bool createdByUserProvider) {
+			if (dispatch_runtime.InstanceProvider != null) {
+				createdByUserProvider = true;
+				return dispatch_runtime.InstanceProvider.GetInstance (ctx, m);
+			}
+			createdByUserProvider = false;
+			return Activator.CreateInstance (
+				dispatch_runtime.ChannelDispatcher.Host.Description.ServiceType, true);
+		}
+
+		internal IInstanceContextProvider InstanceContextProvider {
+			get {
+				return dispatch_runtime.InstanceContextProvider;
+			}
+		}
+
+		internal void ReleaseServiceInstance (InstanceContext ctx, object impl) 
+		{
+			if (ctx.IsUserProvidedInstance) {
+				dispatch_runtime.InstanceProvider.ReleaseInstance (ctx, impl);
+				
+			}
+		}
+	}
+}
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/SessionInstanceContextProvider.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/SessionInstanceContextProvider.cs
index c5c64bb..aeef904 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/SessionInstanceContextProvider.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/SessionInstanceContextProvider.cs
@@ -36,7 +36,7 @@ namespace System.ServiceModel.Dispatcher
 	internal class SessionInstanceContextProvider : IInstanceContextProvider
 	{
 		ServiceHostBase host;
-		Dictionary<UniqueId,InstanceContext> pool = new Dictionary<UniqueId,InstanceContext> ();
+		Dictionary<string,InstanceContext> pool = new Dictionary<string,InstanceContext> ();
 
 		public SessionInstanceContextProvider (ServiceHostBase host)
 		{
@@ -46,15 +46,18 @@ namespace System.ServiceModel.Dispatcher
 		public InstanceContext GetExistingInstanceContext (Message message, IContextChannel channel)
 		{
 			InstanceContext ctx;
-			var key = message.Headers.RelatesTo;
-			return key != null && pool.TryGetValue (key, out ctx) ? ctx : null;
+			var key = channel.SessionId ?? String.Empty;
+			return pool.TryGetValue (key, out ctx) ? ctx : null;
 		}
 
 		public void InitializeInstanceContext (InstanceContext instanceContext, Message message, IContextChannel channel)
 		{
-			var key = message.Headers.MessageId;
-			if (key != null)
-				pool [key] = instanceContext;
+			var key = channel.SessionId ?? String.Empty;
+			pool [key] = instanceContext;
+			channel.Closed += delegate {
+				pool.Remove (key);
+				instanceContext.Close (); // FIXME: timeout?
+			};
 		}
 
 		public bool IsIdle (InstanceContext instanceContext)
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.dll.sources b/mcs/class/System.ServiceModel/System.ServiceModel.dll.sources
index 2115c75..6fcc1f9 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel.dll.sources
+++ b/mcs/class/System.ServiceModel/System.ServiceModel.dll.sources
@@ -693,7 +693,7 @@ System.ServiceModel.Dispatcher/XPathMessageContext.cs
 System.ServiceModel.Dispatcher/XPathMessageFilter.cs
 System.ServiceModel.Dispatcher/XPathMessageFilterTable.cs
 System.ServiceModel.Dispatcher/XPathNavigatorException.cs
-System.ServiceModel.Dispatcher/InstanceBehavior.cs
+System.ServiceModel.Dispatcher/InstanceManager.cs
 System.ServiceModel.MsmqIntegration/MsmqIntegrationBinding.cs
 System.ServiceModel.MsmqIntegration/MsmqIntegrationBindingElement.cs
 System.ServiceModel.MsmqIntegration/MsmqIntegrationMessageProperty.cs
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel/ChangeLog b/mcs/class/System.ServiceModel/System.ServiceModel/ChangeLog
index 4f10532..0d3628f 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel/ChangeLog
+++ b/mcs/class/System.ServiceModel/System.ServiceModel/ChangeLog
@@ -1,3 +1,49 @@
+2011-02-07  Atsushi Eno  <atsushi at ximian.com>
+
+	Open and close client/service runtime channels in chains. Fixed
+	bug #663278.
+
+2011-02-04  Atsushi Eno  <atsushi at ximian.com>
+
+	Duplex client has its own listener loop, so special care on reply
+	is needed.
+
+2011-02-04  Atsushi Eno  <atsushi at ximian.com>
+
+	Callback contract should be distinguished from others for
+	DispatchOperation.
+
+2011-02-01  Atsushi Eno  <atsushi at ximian.com>
+
+	standard endpoint and protocol mapping support were lacking at
+	client side.
+
+	Turned out that they had nothing to do with #668089..
+
+2011-01-22  Atsushi Eno  <atsushi at ximian.com>
+
+	Manage opened proxy channels and close them when ChannelFactory is
+	closed.
+
+2011-01-21  Atsushi Eno  <atsushi at ximian.com>
+
+	Implemented a couple of async methods in InstanceContext as well
+	as disposing.
+
+2011-01-21  Atsushi Eno  <atsushi at ximian.com>
+
+	Rename InstanceBhavior, too ambiguous among IXxxBehavior
+	interfaces.
+
+2011-01-31  Atsushi Eno  <atsushi at ximian.com>
+
+	add public NetTcpSecurity .ctor() and close #667429.
+
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	MonoTouch doesnt support SRE, so we need to disable this code on
+	MT
+
 2010-11-04  Carlos Alberto Cortez  <calberto.cortez at gmail.com>
 
 	* MsmqTransportSecurity.cs: Use the proper default values for this
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel/ChannelFactory.cs b/mcs/class/System.ServiceModel/System.ServiceModel/ChannelFactory.cs
index 4c6a3fd..80c04e0 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel/ChannelFactory.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel/ChannelFactory.cs
@@ -26,6 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 using System;
+using System.Collections.Generic;
 using System.Collections.ObjectModel;
 using System.ServiceModel.Channels;
 using System.ServiceModel.Description;
@@ -44,6 +45,7 @@ namespace System.ServiceModel
 
 		ServiceEndpoint service_endpoint;
 		IChannelFactory factory;
+		List<IClientChannel> opened_channels = new List<IClientChannel> ();
 
 		protected ChannelFactory ()
 		{
@@ -63,6 +65,10 @@ namespace System.ServiceModel
 			}
 		}
 
+		internal List<IClientChannel> OpenedChannels {
+			get { return opened_channels; }
+		}
+
 		public ServiceEndpoint Endpoint {
 			get { return service_endpoint; }
 		}
@@ -111,25 +117,45 @@ namespace System.ServiceModel
 
 			string contractName = Endpoint.Contract.ConfigurationName;
 			ClientSection client = ConfigUtil.ClientSection;
-			ChannelEndpointElement res = null;
+			ChannelEndpointElement endpoint = null;
+
 			foreach (ChannelEndpointElement el in client.Endpoints) {
 				if (el.Contract == contractName && (endpointConfig == el.Name || endpointConfig == "*")) {
-					if (res != null)
+					if (endpoint != null)
 						throw new InvalidOperationException (String.Format ("More then one endpoint matching contract {0} was found.", contractName));
-					res = el;
+					endpoint = el;
 				}
 			}
 
-			if (res == null)
+			if (endpoint == null)
 				throw new InvalidOperationException (String.Format ("Client endpoint configuration '{0}' was not found in {1} endpoints.", endpointConfig, client.Endpoints.Count));
 
+#if NET_4_0
+			var binding = String.IsNullOrEmpty (endpoint.Binding) ? null : ConfigUtil.CreateBinding (endpoint.Binding, endpoint.BindingConfiguration);
+			var contract = String.IsNullOrEmpty (endpoint.Contract) ? Endpoint.Contract : ContractDescription.GetContract (ConfigUtil.GetTypeFromConfigString (endpoint.Contract));
+
+			if (!String.IsNullOrEmpty (endpoint.Kind)) {
+				var se = ConfigUtil.ConfigureStandardEndpoint (contract, endpoint);
+				if (se.Binding == null)
+					se.Binding = binding;
+				if (se.Address == null && se.Binding != null) // standard endpoint might have empty address
+					se.Address = new EndpointAddress (endpoint.Address);
+				if (se.Binding == null && se.Address != null) // look for protocol mapping
+					se.Binding = ConfigUtil.GetBindingByProtocolMapping (se.Address.Uri);
+
+				service_endpoint = se;
+			} else {
+				if (binding == null && endpoint.Address != null) // look for protocol mapping
+					Endpoint.Binding = ConfigUtil.GetBindingByProtocolMapping (endpoint.Address);
+			}
+#endif
 			if (Endpoint.Binding == null)
-				Endpoint.Binding = ConfigUtil.CreateBinding (res.Binding, res.BindingConfiguration);
+				Endpoint.Binding = ConfigUtil.CreateBinding (endpoint.Binding, endpoint.BindingConfiguration);
 			if (Endpoint.Address == null)
-				Endpoint.Address = new EndpointAddress (res.Address);
+				Endpoint.Address = new EndpointAddress (endpoint.Address);
 
-			if (res.BehaviorConfiguration != "")
-				ApplyBehavior (res.BehaviorConfiguration);
+			if (endpoint.BehaviorConfiguration != "")
+				ApplyBehavior (endpoint.BehaviorConfiguration);
 #endif
 		}
 
@@ -341,8 +367,11 @@ namespace System.ServiceModel
 
 		protected override void OnClose (TimeSpan timeout)
 		{
+			DateTime start = DateTime.Now;
+			foreach (var ch in opened_channels.ToArray ())
+				ch.Close (timeout - (DateTime.Now - start));
 			if (OpenedChannelFactory != null)
-				OpenedChannelFactory.Close (timeout);
+				OpenedChannelFactory.Close (timeout - (DateTime.Now - start));
 		}
 
 		protected override void OnOpen (TimeSpan timeout)
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel/ChannelFactory_1.cs b/mcs/class/System.ServiceModel/System.ServiceModel/ChannelFactory_1.cs
index 7aef069..cea1f33 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel/ChannelFactory_1.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel/ChannelFactory_1.cs
@@ -146,7 +146,11 @@ namespace System.ServiceModel
 			// But since there is no remoting in SL2 (and we have
 			// no special magic), we have to use different approach
 			// that should work either.
-			object proxy = Activator.CreateInstance (type, new object [] {Endpoint, this, address ?? Endpoint.Address, via});
+			var proxy = (IClientChannel) Activator.CreateInstance (type, new object [] {Endpoint, this, address ?? Endpoint.Address, via});
+			OpenedChannels.Add (proxy);
+			proxy.Closed += delegate {
+				OpenedChannels.Remove (proxy);
+			};
 			return (TChannel) proxy;
 			} catch (TargetInvocationException ex) {
 				if (ex.InnerException != null)
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel/ClientProxyGenerator.cs b/mcs/class/System.ServiceModel/System.ServiceModel/ClientProxyGenerator.cs
index 91c74cc..76b8353 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel/ClientProxyGenerator.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel/ClientProxyGenerator.cs
@@ -25,6 +25,7 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
+#if !MONOTOUCH
 using System;
 using System.Collections.Generic;
 using System.Reflection;
@@ -304,3 +305,4 @@ namespace System.ServiceModel
 		}
 	}
 }
+#endif
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs b/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs
index 08e447d..0319091 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs
@@ -26,6 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 using System;
+using System.Collections.Generic;
 using System.Reflection;
 using System.Runtime.Serialization;
 using System.ServiceModel.Channels;
@@ -576,11 +577,15 @@ namespace System.ServiceModel.MonoInternal
 		{
 			if (RequestChannel != null)
 				return RequestChannel.Request (msg, timeout);
-			else {
-				DateTime startTime = DateTime.Now;
-				OutputChannel.Send (msg, timeout);
-				return ((IDuplexChannel) OutputChannel).Receive (timeout - (DateTime.Now - startTime));
-			}
+			else
+				return RequestCorrelated (msg, timeout, OutputChannel);
+		}
+
+		internal virtual Message RequestCorrelated (Message msg, TimeSpan timeout, IOutputChannel channel)
+		{
+			DateTime startTime = DateTime.Now;
+			OutputChannel.Send (msg, timeout);
+			return ((IDuplexChannel) channel).Receive (timeout - (DateTime.Now - startTime));
 		}
 
 		internal IAsyncResult BeginRequest (Message msg, TimeSpan timeout, AsyncCallback callback, object state)
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel/DuplexClientRuntimeChannel.cs b/mcs/class/System.ServiceModel/System.ServiceModel/DuplexClientRuntimeChannel.cs
index 01d044c..b576754 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel/DuplexClientRuntimeChannel.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel/DuplexClientRuntimeChannel.cs
@@ -26,6 +26,8 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 using System;
+using System.Collections.Generic;
+using System.Linq;
 using System.Reflection;
 using System.ServiceModel.Channels;
 using System.ServiceModel.Description;
@@ -93,6 +95,7 @@ namespace System.ServiceModel.MonoInternal
 		IAsyncResult loop_result;
 		AutoResetEvent loop_handle = new AutoResetEvent (false);
 		AutoResetEvent finish_handle = new AutoResetEvent (false);
+		AutoResetEvent receive_reply_handle = new AutoResetEvent (false);
 
 		protected override void OnOpen (TimeSpan timeout)
 		{
@@ -152,12 +155,28 @@ namespace System.ServiceModel.MonoInternal
 			}
 		}
 
-		void ProcessInput (IInputChannel input, Message message)
+		void ProcessInputCore (IInputChannel input, Message message)
 		{
-			try {
+				bool isReply = message != null && Contract.Operations.Any (od => !od.InCallbackContract && od.Messages.Any (md => md.Action == message.Headers.Action));
+				if (isReply) {
+					if (ReplyHandlerQueue.Count > 0) {
+						if (isReply) {
+							var h = ReplyHandlerQueue.Dequeue ();
+							h (message);
+							return;
+						}
+					}
+				}
+				
 				if (!MessageMatchesEndpointDispatcher (message, Runtime.CallbackDispatchRuntime.EndpointDispatcher))
 					throw new EndpointNotFoundException (String.Format ("The request message has the target '{0}' with action '{1}' which is not reachable in this service contract", message.Headers.To, message.Headers.Action));
 				new InputOrReplyRequestProcessor (Runtime.CallbackDispatchRuntime, input).ProcessInput (message);
+		}
+
+		void ProcessInput (IInputChannel input, Message message)
+		{
+			try {
+				ProcessInputCore (input, message);
 			} catch (Exception ex) {
 				// FIXME: log it.
 				Console.WriteLine (ex);
@@ -174,5 +193,23 @@ namespace System.ServiceModel.MonoInternal
 
 			return endpoint.ContractFilter.Match (req);
 		}
+		
+		internal override Message RequestCorrelated (Message msg, TimeSpan timeout, IOutputChannel channel)
+		{
+			DateTime startTime = DateTime.Now;
+			Message ret = null;
+			ManualResetEvent wait = new ManualResetEvent (false);
+			Action<Message> handler = delegate (Message reply) {
+				ret = reply;
+				wait.Set ();
+			};
+			ReplyHandlerQueue.Enqueue (handler);
+			channel.Send (msg, timeout);
+			if (ret == null && !wait.WaitOne (timeout - (DateTime.Now - startTime)))
+				throw new TimeoutException ();
+			return ret;
+		}
+		
+		internal Queue<Action<Message>> ReplyHandlerQueue = new Queue<Action<Message>> ();
 	}
 }
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel/InstanceContext.cs b/mcs/class/System.ServiceModel/System.ServiceModel/InstanceContext.cs
index 92eae06..136ccdb 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel/InstanceContext.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel/InstanceContext.cs
@@ -32,14 +32,13 @@ using System.ServiceModel.Dispatcher;
 
 namespace System.ServiceModel
 {
-	[MonoTODO]
 	public sealed class InstanceContext : CommunicationObject,
 		IExtensibleObject<InstanceContext>
 	{
 		ServiceHostBase host;
 		object implementation;
 		int manual_flow_limit;
-		InstanceBehavior _behavior;
+		InstanceManager instance_manager;
 		bool is_user_instance_provider;
 		bool is_user_context_provider;
 
@@ -55,12 +54,12 @@ namespace System.ServiceModel
 		{
 		}
 
-		public InstanceContext (ServiceHostBase host,
-			object implementation) : this(host, implementation, true)
-		{}
+		public InstanceContext (ServiceHostBase host, object implementation)
+			: this (host, implementation, true)
+		{
+		}
 
-		internal InstanceContext(ServiceHostBase host, 
-			object implementation, bool userContextProvider)
+		internal InstanceContext (ServiceHostBase host, object implementation, bool userContextProvider)
 		{
 			this.host = host;
 			this.implementation = implementation;
@@ -74,18 +73,12 @@ namespace System.ServiceModel
 		}
 
 		internal bool IsUserProvidedContext {
-			get {
-				return is_user_context_provider;				
-			}
+			get { return is_user_context_provider; }
 		}
 
-		internal InstanceBehavior Behavior {
-			get {
-				return _behavior;
-			}
-			set {
-				_behavior = value;
-			}
+		internal InstanceManager InstanceManager {
+			get { return instance_manager; }
+			set { instance_manager = value; }
 		}
 
 		protected internal override TimeSpan DefaultCloseTimeout {
@@ -124,8 +117,8 @@ namespace System.ServiceModel
 
 		public object GetServiceInstance (Message message)
 		{
-			if (implementation == null && Behavior != null) {
-				implementation = Behavior.GetServiceInstance (this, message, ref is_user_instance_provider);				
+			if (implementation == null && instance_manager != null) {
+				implementation = instance_manager.GetServiceInstance (this, message, ref is_user_instance_provider);				
 			}
 			return implementation;				
 		}
@@ -136,9 +129,9 @@ namespace System.ServiceModel
 		}
 
 		internal void CloseIfIdle () {
-			if (Behavior.InstanceContextProvider != null && !IsUserProvidedContext) {
-				if (!Behavior.InstanceContextProvider.IsIdle (this)) {
-					Behavior.InstanceContextProvider.NotifyIdle (IdleCallback, this);
+			if (instance_manager.InstanceContextProvider != null && !IsUserProvidedContext) {
+				if (!instance_manager.InstanceContextProvider.IsIdle (this)) {
+					instance_manager.InstanceContextProvider.NotifyIdle (IdleCallback, this);
 				}
 				else {
 					if (State != CommunicationState.Closed)
@@ -158,24 +151,33 @@ namespace System.ServiceModel
 		}
 
 		public void ReleaseServiceInstance ()
-		{			
-			Behavior.ReleaseServiceInstance (this, implementation);
+		{
+			instance_manager.ReleaseServiceInstance (this, implementation);
+			// FIXME: should Dispose() be invoked here?
 			implementation = null;
 		}
 
+		void DisposeInstance ()
+		{
+			var disp = implementation as IDisposable;
+			if (disp != null)
+				disp.Dispose ();
+		}
+
 		protected override void OnAbort ()
 		{
+			DisposeInstance ();
 		}
 
-		[MonoTODO]
 		protected override void OnFaulted ()
 		{
+			DisposeInstance ();
 			base.OnFaulted ();
 		}
 
-		[MonoTODO]
 		protected override void OnClosed ()
 		{
+			DisposeInstance ();
 			base.OnClosed ();
 		}
 
@@ -188,18 +190,23 @@ namespace System.ServiceModel
 		protected override void OnOpening ()
 		{
 			base.OnOpening ();
-			if (Behavior != null)
-				Behavior.Initialize (this);
+			if (instance_manager != null)
+				instance_manager.Initialize (this);
 		}
 
+		Action<TimeSpan> open_delegate, close_delegate;
+
 		protected override IAsyncResult OnBeginOpen (
 			TimeSpan timeout, AsyncCallback callback, object state)
 		{
-			throw new NotImplementedException ();
+			if (open_delegate == null)
+				open_delegate = new Action<TimeSpan> (OnOpen);
+			return open_delegate.BeginInvoke (timeout, callback, state);
 		}
 
 		protected override void OnEndOpen (IAsyncResult result)
 		{
+			open_delegate.EndInvoke (result);
 		}
 
 		protected override void OnOpen (TimeSpan timeout)
@@ -209,15 +216,18 @@ namespace System.ServiceModel
 		protected override IAsyncResult OnBeginClose (
 			TimeSpan timeout, AsyncCallback callback, object state)
 		{
-			throw new NotImplementedException ();
+			if (close_delegate == null)
+				close_delegate = new Action<TimeSpan> (OnClose);
+			return close_delegate.BeginInvoke (timeout, callback, state);
 		}
 
 		protected override void OnEndClose (IAsyncResult result)
 		{
+			close_delegate.EndInvoke (result);
 		}
 
 		protected override void OnClose (TimeSpan timeout)
 		{
-		}		
+		}
 	}
 }
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel/NetTcpSecurity.cs b/mcs/class/System.ServiceModel/System.ServiceModel/NetTcpSecurity.cs
index c5065a1..1864625 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel/NetTcpSecurity.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel/NetTcpSecurity.cs
@@ -33,6 +33,12 @@ namespace System.ServiceModel
 {
 	public sealed class NetTcpSecurity
 	{
+#if NET_4_0
+		public NetTcpSecurity ()
+		{
+		}
+#endif
+
 		internal NetTcpSecurity (SecurityMode mode)
 		{
 			this.mode = mode;
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel/ServiceHostBase.cs b/mcs/class/System.ServiceModel/System.ServiceModel/ServiceHostBase.cs
index 2c67788..70bb18d 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel/ServiceHostBase.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel/ServiceHostBase.cs
@@ -380,7 +380,7 @@ namespace System.ServiceModel
 			// behaviors
 			AddServiceBehaviors (service.BehaviorConfiguration, true);
 
-			// services
+			// endpoints
 			foreach (ServiceEndpointElement endpoint in service.Endpoints) {
 				ServiceEndpoint se;
 
@@ -395,13 +395,13 @@ namespace System.ServiceModel
 					if (se.Address == null && se.Binding != null) // standard endpoint might have empty address
 						se.Address = new EndpointAddress (CreateUri (se.Binding.Scheme, endpoint.Address));
 					if (se.Binding == null && se.Address != null) // look for protocol mapping
-						se.Binding = GetBindingByProtocolMapping (se.Address.Uri);
+						se.Binding = ConfigUtil.GetBindingByProtocolMapping (se.Address.Uri);
 
 					AddServiceEndpoint (se);
 				}
 				else {
 					if (binding == null && endpoint.Address != null) // look for protocol mapping
-						binding = GetBindingByProtocolMapping (endpoint.Address);
+						binding = ConfigUtil.GetBindingByProtocolMapping (endpoint.Address);
 					se = AddServiceEndpoint (endpoint.Contract, binding, endpoint.Address);
 				}
 #else
@@ -419,16 +419,6 @@ namespace System.ServiceModel
 			}
 		}
 
-#if NET_4_0
-		Binding GetBindingByProtocolMapping (Uri address)
-		{
-			ProtocolMappingElement el = ConfigUtil.ProtocolMappingSection.ProtocolMappingCollection [address.Scheme];
-			if (el == null)
-				return null;
-			return ConfigUtil.CreateBinding (el.Binding, el.BindingConfiguration);
-		}
-#endif
-
 		private ServiceElement GetServiceElement() {
 			Type serviceType = Description.ServiceType;
 			if (serviceType == null)
@@ -506,7 +496,7 @@ namespace System.ServiceModel
 						foreach (var baddr in BaseAddresses) {
 							if (!baddr.IsAbsoluteUri)
 								continue;
-							var binding = GetBindingByProtocolMapping (baddr);
+							var binding = ConfigUtil.GetBindingByProtocolMapping (baddr);
 							if (binding == null)
 								continue;
 							AddServiceEndpoint (iface.FullName, binding, baddr);
@@ -694,6 +684,8 @@ namespace System.ServiceModel
 			foreach (IEndpointBehavior b in endPoint.Behaviors)
 				b.ApplyDispatchBehavior (endPoint, ed);
 			foreach (OperationDescription operation in endPoint.Contract.Operations) {
+				if (operation.InCallbackContract)
+					continue; // irrelevant
 				foreach (IOperationBehavior b in operation.Behaviors)
 					b.ApplyDispatchBehavior (operation, ed.DispatchRuntime.Operations [operation.Name]);
 			}
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel/ServiceRuntimeChannel.cs b/mcs/class/System.ServiceModel/System.ServiceModel/ServiceRuntimeChannel.cs
index 49403d9..351fa5b 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel/ServiceRuntimeChannel.cs
+++ b/mcs/class/System.ServiceModel/System.ServiceModel/ServiceRuntimeChannel.cs
@@ -118,6 +118,7 @@ namespace System.ServiceModel.MonoInternal
 		public ServiceRuntimeChannel (IChannel channel, DispatchRuntime runtime)
 		{
 			this.channel = channel;
+			channel.Closing += delegate { Close (); };
 			this.runtime = runtime;
 		}
 
@@ -197,7 +198,8 @@ namespace System.ServiceModel.MonoInternal
 
 		protected override void OnClose (TimeSpan timeout)
 		{
-			channel.Close (timeout);
+			if (channel.State == CommunicationState.Opened)
+				channel.Close (timeout);
 		}
 
 		protected override IAsyncResult OnBeginOpen (
@@ -213,7 +215,8 @@ namespace System.ServiceModel.MonoInternal
 
 		protected override void OnOpen (TimeSpan timeout)
 		{
-			channel.Open (timeout);
+			if (channel.State == CommunicationState.Created)
+				channel.Open (timeout);
 		}
 
 		// IChannel
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel_test.dll.sources b/mcs/class/System.ServiceModel/System.ServiceModel_test.dll.sources
index 450f647..d1e0575 100644
--- a/mcs/class/System.ServiceModel/System.ServiceModel_test.dll.sources
+++ b/mcs/class/System.ServiceModel/System.ServiceModel_test.dll.sources
@@ -121,6 +121,7 @@ System.ServiceModel.Description/TypedMessageConverterTest.cs
 System.ServiceModel.Description/WsdlExporterTest.cs
 System.ServiceModel.Description/WsdlImporterTest.cs
 System.ServiceModel.Dispatcher/ActionFilterTest.cs
+System.ServiceModel.Dispatcher/Bug652331Test.cs
 System.ServiceModel.Dispatcher/ChannelDispatcherTest.cs
 System.ServiceModel.Dispatcher/DispatchOperationTest.cs
 System.ServiceModel.Dispatcher/DispatchRuntimeTest.cs
diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/ChangeLog b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/ChangeLog
index 7096857..7b1358f 100644
--- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/ChangeLog
+++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/ChangeLog
@@ -1,3 +1,14 @@
+2011-02-03  Atsushi Eno  <atsushi at ximian.com>
+
+	Now operations are collected per corresponding
+	ContractDescription.
+
+	This fixes naming of MessageDescription Action URI from its type.
+
+2011-02-02  Atsushi Eno  <atsushi at ximian.com>
+
+	Implement GetInheritedContracts(), towards bugfix #668089.
+
 2010-10-08  Atsushi Eno  <atsushi at ximian.com>
 
 	Do not reject contract from the same method, could happen by a
diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/ContractDescriptionTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/ContractDescriptionTest.cs
index a44b6a1..27cb06d 100644
--- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/ContractDescriptionTest.cs
+++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/ContractDescriptionTest.cs
@@ -27,6 +27,7 @@
 //
 using System;
 using System.Collections.ObjectModel;
+using System.Linq;
 using System.Net.Security;
 using System.Reflection;
 using System.ServiceModel;
@@ -422,13 +423,31 @@ namespace MonoTests.System.ServiceModel.Description
 		}
 		
 		[Test]
-		public static void MultipleContractsInTypeHierarchy ()
+		public void MultipleContractsInTypeHierarchy ()
 		{
 			ContractDescription.GetContract (typeof (DuplicateCheckClassWrapper.ServiceInterface));
 
 			var host = new ServiceHost (typeof (DuplicateCheckClassWrapper.DummyService)); // fine in MS, fails in Mono with "A contract cannot have two operations that have the identical names and different set of parameters"
 		}
 
+		[Test]
+		public void GetInheritedContracts ()
+		{
+			var cd = ContractDescription.GetContract (typeof (IService));
+			var ccd = cd.GetInheritedContracts ();
+			Assert.AreEqual (1, ccd.Count, "#1");
+			Assert.AreEqual (typeof (IServiceBase), ccd [0].ContractType, "#2");
+		}
+
+		[Test]
+		public void InheritedContractAndNamespaces ()
+		{
+			var cd = ContractDescription.GetContract (typeof (IService));
+			Assert.IsTrue (cd.Operations.Any (od => od.Messages.Any (md => md.Action == "http://tempuri.org/IServiceBase/Say")), "#1"); // inherited
+			Assert.IsTrue (cd.Operations.Any (od => od.SyncMethod == typeof (IService).GetMethod ("Join") && od.Messages.Any (md => md.Action == "http://tempuri.org/IService/Join")), "#2"); // self
+			Assert.IsTrue (cd.Operations.Any (od => od.SyncMethod == typeof (IService2).GetMethod ("Join") && od.Messages.Any (md => md.Action == "http://tempuri.org/IService/Join")), "#3"); // callback
+		}
+
 		// It is for testing attribute search in interfaces.
 		public class Foo : IFoo
 		{
@@ -664,5 +683,33 @@ namespace MonoTests.System.ServiceModel.Description
 				public void Foo() { }
 			}
 		}
+
+		[ServiceContract]
+		public interface IServiceBase
+		{
+			[OperationContract (IsOneWay = true)]
+			void Say (string word);
+		}
+
+		[ServiceContract (CallbackContract = typeof (IService2))]
+		public interface IService : IServiceBase
+		{
+			[OperationContract]
+			void Join ();
+		}
+
+		[ServiceContract]
+		public interface IServiceBase2
+		{
+			[OperationContract (IsOneWay = true)]
+			void Say (string word);
+		}
+
+		[ServiceContract]
+		public interface IService2 : IServiceBase2
+		{
+			[OperationContract]
+			void Join ();
+		}
 	}
 }
diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/Bug652331Test.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/Bug652331Test.cs
new file mode 100644
index 0000000..d0e0ea0
--- /dev/null
+++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/Bug652331Test.cs
@@ -0,0 +1,378 @@
+//
+// Authors:
+//	David Straw
+//	Atsushi Enomoto <atsushi at ximian.com>
+//
+// Copyright (C) 2011 Novell, Inc.  http://www.novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.ServiceModel;
+using System.ServiceModel.Description;
+using System.Threading;
+using NUnit.Framework;
+
+using WebServiceMoonlightTest.ServiceReference1;
+
+namespace MonoTests.System.ServiceModel.Dispatcher
+{
+	[TestFixture]
+	public class Bug652331Test
+	{
+		[Test]
+		public void Bug652331_2 () // test in one of the comment
+		{
+			// Init service
+			ServiceHost serviceHost = new ServiceHost (typeof (Service1), new Uri ("http://localhost:37564/Service1"));
+			serviceHost.AddServiceEndpoint (typeof (IService1), new BasicHttpBinding (), string.Empty);
+
+			// Enable metadata exchange (WSDL publishing)
+			var mexBehavior = new ServiceMetadataBehavior ();
+			mexBehavior.HttpGetEnabled = true;
+			serviceHost.Description.Behaviors.Add (mexBehavior);
+			serviceHost.AddServiceEndpoint (typeof (IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding (), "mex");
+
+			serviceHost.Open ();
+
+			try {
+				// client
+				var binding = new BasicHttpBinding ();
+				var remoteAddress = new EndpointAddress ("http://localhost:37564/Service1");
+				var client = new Service1Client (binding, remoteAddress);
+
+				var wait = new ManualResetEvent (false);
+				client.GetDataCompleted += delegate (object o, GetDataCompletedEventArgs e) {
+					if (e.Error != null)
+						throw e.Error;
+					Assert.AreEqual ("A", ((DataType1) e.Result).Id, "#1");
+					wait.Set ();
+				};
+
+				client.GetDataAsync ();
+				if (!wait.WaitOne (TimeSpan.FromSeconds (10)))
+					Assert.Fail ("timeout");
+			} finally {
+				serviceHost.Close ();
+			}
+		}
+
+		public class Service1 : IService1
+		{
+			public object GetData ()
+			{
+				return new DataType1 { Id = "A" };
+			}
+
+			Func<object> d;
+			public IAsyncResult BeginGetData (AsyncCallback callback, object state)
+			{
+				if (d == null)
+				d = new Func<object> (GetData);
+				return d.BeginInvoke (callback, state);
+			}
+
+			public object EndGetData (IAsyncResult result)
+			{
+				return d.EndInvoke (result);
+			}
+		}
+	}
+}
+
+// below are part of autogenerated code in comment #1 on bug #652331.
+
+namespace WebServiceMoonlightTest.ServiceReference1 {
+
+    [System.Diagnostics.DebuggerStepThroughAttribute()]
+    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
+    [System.Runtime.Serialization.DataContractAttribute(Name="DataType1", Namespace="http://mynamespace")]
+    public partial class DataType1 : object, System.ComponentModel.INotifyPropertyChanged {
+        
+        private string IdField;
+        
+        [System.Runtime.Serialization.DataMemberAttribute()]
+        public string Id {
+            get {
+                return this.IdField;
+            }
+            set {
+                if ((object.ReferenceEquals(this.IdField, value) != true)) {
+                    this.IdField = value;
+                    this.RaisePropertyChanged("Id");
+                }
+            }
+        }
+        
+        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
+        
+        protected void RaisePropertyChanged(string propertyName) {
+            System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
+            if ((propertyChanged != null)) {
+                propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
+            }
+        }
+    }
+    
+    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
+    [System.ServiceModel.ServiceContractAttribute(Namespace="http://mynamespace", ConfigurationName="ServiceReference1.IService1")]
+[ServiceKnownType (typeof (DataType1))]
+    public interface IService1 {
+        
+        [System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://mynamespace/IService1/GetData", ReplyAction="http://mynamespace/IService1/GetDataResponse")]
+        [System.ServiceModel.ServiceKnownTypeAttribute(typeof(WebServiceMoonlightTest.ServiceReference1.DataType1))]
+        System.IAsyncResult BeginGetData(System.AsyncCallback callback, object asyncState);
+        
+        object EndGetData(System.IAsyncResult result);
+    }
+    
+    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
+    public interface IService1Channel : WebServiceMoonlightTest.ServiceReference1.IService1, System.ServiceModel.IClientChannel {
+    }
+    
+    [System.Diagnostics.DebuggerStepThroughAttribute()]
+    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
+    public partial class GetDataCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
+        
+        private object[] results;
+        
+        public GetDataCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : 
+                base(exception, cancelled, userState) {
+            this.results = results;
+        }
+        
+        public object Result {
+            get {
+                base.RaiseExceptionIfNecessary();
+                return ((object)(this.results[0]));
+            }
+        }
+    }
+    
+    [System.Diagnostics.DebuggerStepThroughAttribute()]
+    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
+    public partial class Service1Client : System.ServiceModel.ClientBase<WebServiceMoonlightTest.ServiceReference1.IService1>, WebServiceMoonlightTest.ServiceReference1.IService1 {
+        
+        private BeginOperationDelegate onBeginGetDataDelegate;
+        
+        private EndOperationDelegate onEndGetDataDelegate;
+        
+        private System.Threading.SendOrPostCallback onGetDataCompletedDelegate;
+        
+        private BeginOperationDelegate onBeginOpenDelegate;
+        
+        private EndOperationDelegate onEndOpenDelegate;
+        
+        private System.Threading.SendOrPostCallback onOpenCompletedDelegate;
+        
+        private BeginOperationDelegate onBeginCloseDelegate;
+        
+        private EndOperationDelegate onEndCloseDelegate;
+        
+        private System.Threading.SendOrPostCallback onCloseCompletedDelegate;
+        
+        public Service1Client() {
+        }
+        
+        public Service1Client(string endpointConfigurationName) : 
+                base(endpointConfigurationName) {
+        }
+        
+        public Service1Client(string endpointConfigurationName, string remoteAddress) : 
+                base(endpointConfigurationName, remoteAddress) {
+        }
+        
+        public Service1Client(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
+                base(endpointConfigurationName, remoteAddress) {
+        }
+        
+        public Service1Client(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
+                base(binding, remoteAddress) {
+        }
+        
+/*
+        public System.Net.CookieContainer CookieContainer {
+            get {
+                System.ServiceModel.Channels.IHttpCookieContainerManager httpCookieContainerManager = this.InnerChannel.GetProperty<System.ServiceModel.Channels.IHttpCookieContainerManager>();
+                if ((httpCookieContainerManager != null)) {
+                    return httpCookieContainerManager.CookieContainer;
+                }
+                else {
+                    return null;
+                }
+            }
+            set {
+                System.ServiceModel.Channels.IHttpCookieContainerManager httpCookieContainerManager = this.InnerChannel.GetProperty<System.ServiceModel.Channels.IHttpCookieContainerManager>();
+                if ((httpCookieContainerManager != null)) {
+                    httpCookieContainerManager.CookieContainer = value;
+                }
+                else {
+                    throw new System.InvalidOperationException("Unable to set the CookieContainer. Please make sure the binding contains an HttpC" +
+                            "ookieContainerBindingElement.");
+                }
+            }
+        }
+*/
+        
+        public event System.EventHandler<GetDataCompletedEventArgs> GetDataCompleted;
+        
+        public event System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs> OpenCompleted;
+        
+        public event System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs> CloseCompleted;
+        
+        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
+        System.IAsyncResult WebServiceMoonlightTest.ServiceReference1.IService1.BeginGetData(System.AsyncCallback callback, object asyncState) {
+            return base.Channel.BeginGetData(callback, asyncState);
+        }
+        
+        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
+        object WebServiceMoonlightTest.ServiceReference1.IService1.EndGetData(System.IAsyncResult result) {
+            return base.Channel.EndGetData(result);
+        }
+        
+        private System.IAsyncResult OnBeginGetData(object[] inValues, System.AsyncCallback callback, object asyncState) {
+            return ((WebServiceMoonlightTest.ServiceReference1.IService1)(this)).BeginGetData(callback, asyncState);
+        }
+        
+        private object[] OnEndGetData(System.IAsyncResult result) {
+            object retVal = ((WebServiceMoonlightTest.ServiceReference1.IService1)(this)).EndGetData(result);
+            return new object[] {
+                    retVal};
+        }
+        
+        private void OnGetDataCompleted(object state) {
+            if ((this.GetDataCompleted != null)) {
+                InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
+                this.GetDataCompleted(this, new GetDataCompletedEventArgs(e.Results, e.Error, e.Cancelled, e.UserState));
+            }
+        }
+        
+        public void GetDataAsync() {
+            this.GetDataAsync(null);
+        }
+        
+        public void GetDataAsync(object userState) {
+            if ((this.onBeginGetDataDelegate == null)) {
+                this.onBeginGetDataDelegate = new BeginOperationDelegate(this.OnBeginGetData);
+            }
+            if ((this.onEndGetDataDelegate == null)) {
+                this.onEndGetDataDelegate = new EndOperationDelegate(this.OnEndGetData);
+            }
+            if ((this.onGetDataCompletedDelegate == null)) {
+                this.onGetDataCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnGetDataCompleted);
+            }
+            base.InvokeAsync(this.onBeginGetDataDelegate, null, this.onEndGetDataDelegate, this.onGetDataCompletedDelegate, userState);
+        }
+        
+        private System.IAsyncResult OnBeginOpen(object[] inValues, System.AsyncCallback callback, object asyncState) {
+            return ((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(callback, asyncState);
+        }
+        
+        private object[] OnEndOpen(System.IAsyncResult result) {
+            ((System.ServiceModel.ICommunicationObject)(this)).EndOpen(result);
+            return null;
+        }
+        
+        private void OnOpenCompleted(object state) {
+            if ((this.OpenCompleted != null)) {
+                InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
+                this.OpenCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState));
+            }
+        }
+        
+        public void OpenAsync() {
+            this.OpenAsync(null);
+        }
+        
+        public void OpenAsync(object userState) {
+            if ((this.onBeginOpenDelegate == null)) {
+                this.onBeginOpenDelegate = new BeginOperationDelegate(this.OnBeginOpen);
+            }
+            if ((this.onEndOpenDelegate == null)) {
+                this.onEndOpenDelegate = new EndOperationDelegate(this.OnEndOpen);
+            }
+            if ((this.onOpenCompletedDelegate == null)) {
+                this.onOpenCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnOpenCompleted);
+            }
+            base.InvokeAsync(this.onBeginOpenDelegate, null, this.onEndOpenDelegate, this.onOpenCompletedDelegate, userState);
+        }
+        
+        private System.IAsyncResult OnBeginClose(object[] inValues, System.AsyncCallback callback, object asyncState) {
+            return ((System.ServiceModel.ICommunicationObject)(this)).BeginClose(callback, asyncState);
+        }
+        
+        private object[] OnEndClose(System.IAsyncResult result) {
+            ((System.ServiceModel.ICommunicationObject)(this)).EndClose(result);
+            return null;
+        }
+        
+        private void OnCloseCompleted(object state) {
+            if ((this.CloseCompleted != null)) {
+                InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
+                this.CloseCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState));
+            }
+        }
+        
+        public void CloseAsync() {
+            this.CloseAsync(null);
+        }
+        
+        public void CloseAsync(object userState) {
+            if ((this.onBeginCloseDelegate == null)) {
+                this.onBeginCloseDelegate = new BeginOperationDelegate(this.OnBeginClose);
+            }
+            if ((this.onEndCloseDelegate == null)) {
+                this.onEndCloseDelegate = new EndOperationDelegate(this.OnEndClose);
+            }
+            if ((this.onCloseCompletedDelegate == null)) {
+                this.onCloseCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnCloseCompleted);
+            }
+            base.InvokeAsync(this.onBeginCloseDelegate, null, this.onEndCloseDelegate, this.onCloseCompletedDelegate, userState);
+        }
+        
+/*
+        protected override WebServiceMoonlightTest.ServiceReference1.IService1 CreateChannel() {
+            return new Service1ClientChannel(this);
+        }
+        
+        private class Service1ClientChannel : ChannelBase<WebServiceMoonlightTest.ServiceReference1.IService1>, WebServiceMoonlightTest.ServiceReference1.IService1 {
+            
+            public Service1ClientChannel(System.ServiceModel.ClientBase<WebServiceMoonlightTest.ServiceReference1.IService1> client) : 
+                    base(client) {
+            }
+            
+            public System.IAsyncResult BeginGetData(System.AsyncCallback callback, object asyncState) {
+                object[] _args = new object[0];
+                System.IAsyncResult _result = base.BeginInvoke("GetData", _args, callback, asyncState);
+                return _result;
+            }
+            
+            public object EndGetData(System.IAsyncResult result) {
+                object[] _args = new object[0];
+                object _result = ((object)(base.EndInvoke("GetData", _args, result)));
+                return _result;
+            }
+        }
+*/
+    }
+}
diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/ChangeLog b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/ChangeLog
index 72e0a40..3059ef3 100644
--- a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/ChangeLog
+++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/ChangeLog
@@ -1,3 +1,7 @@
+2011-02-09  Atsushi Eno  <atsushi at ximian.com>
+
+	Support ServiceKnownTypes. Fixed another case on bug #652331.
+
 2010-09-29  Atsushi Eno  <atsushi at ximian.com>
 
 	Fix the issue that callback contract often gets confused by
diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel/ChangeLog b/mcs/class/System.ServiceModel/Test/System.ServiceModel/ChangeLog
index 9e43056..8fee1c7 100644
--- a/mcs/class/System.ServiceModel/Test/System.ServiceModel/ChangeLog
+++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel/ChangeLog
@@ -1,3 +1,8 @@
+2011-02-07  Atsushi Eno  <atsushi at ximian.com>
+
+	Open and close client/service runtime channels in chains. Fixed
+	bug #663278.
+
 2010-11-04  Carlos Alberto Cortez  <calberto.cortez at gmail.com>
 
 	* MsmqTransportSecurityTest.cs: New test file.
diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel/IntegratedConnectionTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel/IntegratedConnectionTest.cs
index 7273340..9369eaf 100644
--- a/mcs/class/System.ServiceModel/Test/System.ServiceModel/IntegratedConnectionTest.cs
+++ b/mcs/class/System.ServiceModel/Test/System.ServiceModel/IntegratedConnectionTest.cs
@@ -34,6 +34,8 @@ using System.Runtime.Serialization;
 using System.ServiceModel;
 using System.ServiceModel.Channels;
 using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+using System.Threading;
 using System.Xml;
 using NUnit.Framework;
 
@@ -134,6 +136,81 @@ namespace MonoTests.System.ServiceModel
 					host.Close ();
 			}
 		}
+
+		[ServiceContract(SessionMode = SessionMode.Required)]
+		interface IFoo3
+		{
+			[OperationContract]
+			int GetInstanceCounter ();
+		}
+
+			[ServiceBehavior (InstanceContextMode = InstanceContextMode.PerSession)]
+		class Foo3 : IFoo3, IDisposable
+		{
+			public static int CreatedInstances { get; set; }
+			public static int DisposedInstances { get; set; }
+
+			public static int InstanceCounter {
+				get { return CreatedInstances - DisposedInstances; }
+			}
+
+			public Foo3 ()
+			{
+				CreatedInstances++;
+			}
+
+			public int GetInstanceCounter ()
+			{
+				return InstanceCounter;
+			}
+
+			public virtual void Dispose ()
+			{
+				DisposedInstances++;
+			}
+
+		}
+
+		private void TestSessionbehaviour (Binding binding, Uri address)
+		{
+			ServiceHost host = new ServiceHost (typeof (Foo3), address);
+			host.AddServiceEndpoint (typeof (IFoo3), binding, address);
+			host.Description.Behaviors.Add (new ServiceThrottlingBehavior () { MaxConcurrentSessions = 1 });
+			Foo3.CreatedInstances = Foo3.DisposedInstances = 0; // Reset
+			host.Open ();
+			Assert.AreEqual (0, Foo3.InstanceCounter, "Initial state wrong"); // just to be sure
+			var cd = (ChannelDispatcher) host.ChannelDispatchers [0];
+			for (int i = 1; i <= 3; ++i) {
+				var factory = new ChannelFactory<IFoo3Client> (binding, address.ToString ());
+				var proxy = factory.CreateChannel ();
+				Assert.AreEqual (1, proxy.GetInstanceCounter (), "One server instance after first call in session #" + i);
+				Assert.AreEqual (1, proxy.GetInstanceCounter (), "One server instance after second call in session #" + i);
+				factory.Close (); // should close session even when no IsTerminating method has been invoked
+				Thread.Sleep (500); // give WCF time to dispose service object
+				Assert.AreEqual (0, Foo3.InstanceCounter, "Service instances must be disposed after channel is closed");
+				Assert.AreEqual (i, Foo3.CreatedInstances, "One new instance per session");
+			}
+			host.Close ();
+		}
+
+		interface IFoo3Client : IFoo3, IClientChannel {}
+
+		[Test (Description = "Tests InstanceContextMode.PerSession behavior for NetTcp binding")]
+		public void TestSessionInstancesNetTcp ()
+		{
+			Binding binding = new NetTcpBinding (SecurityMode.None, false);
+			Uri address = new Uri (binding.Scheme + "://localhost:9999/test");
+			TestSessionbehaviour (binding, address);
+		}
+
+		[Test (Description = "Tests InstanceContextMode.PerSession behavior for WsHttp binding")]
+		[Category ("NotWorking")] // no working WSHttpBinding in mono.
+		public void TestSessionInstancesWsHttp ()
+		{
+			Binding binding = new WSHttpBinding (SecurityMode.None, true);
+			Uri address = new Uri (binding.Scheme + "://localhost:9999/test");
+			TestSessionbehaviour(binding, address);
+		}
 	}
 
 	#region SimpleConnection classes
diff --git a/mcs/class/System.Web.Routing/System.Web.Routing/ChangeLog b/mcs/class/System.Web.Routing/System.Web.Routing/ChangeLog
index 48cfc9f..ee012d1 100644
--- a/mcs/class/System.Web.Routing/System.Web.Routing/ChangeLog
+++ b/mcs/class/System.Web.Routing/System.Web.Routing/ChangeLog
@@ -1,3 +1,8 @@
+2011-01-22  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net,routing] Fix for bug #651966. Regular expression
+	constraints must be treated as absolute regexps.
+
 2011-01-14  Marek Habersack  <grendel at twistedcode.net>
 
 	[asp.net] Make StopRoutingHandler actually stop the routing
diff --git a/mcs/class/System.Web.Routing/System.Web.Routing/Route.cs b/mcs/class/System.Web.Routing/System.Web.Routing/Route.cs
index cd25545..e817e0a 100644
--- a/mcs/class/System.Web.Routing/System.Web.Routing/Route.cs
+++ b/mcs/class/System.Web.Routing/System.Web.Routing/Route.cs
@@ -150,8 +150,22 @@ namespace System.Web.Routing
 			string s = constraint as string;
 			if (s != null) {
 				string v = values [parameterName] as string;
-				if (!String.IsNullOrEmpty (v))
+				if (!String.IsNullOrEmpty (v)) {
+					int slen = s.Length;
+					if (slen > 0) {
+						// Bug #651966 - regexp constraints must be treated
+						// as absolute expressions
+						if (s [0] != '^') {
+							s = "^" + s;
+							slen++;
+						}
+						
+						if (s [slen - 1] != '$')
+							s += "$";
+					}
+
 					return Regex.Match (v, s).Success;
+				}
 				return false;
 			}
 
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 6891907..2a18717 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,8 @@
+2011-01-22  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net,routing] Fix for bug #651966. Regular expression
+	constraints must be treated as absolute regexps.
+
 2011-01-14  Marek Habersack  <grendel at twistedcode.net>
 
 	[asp.net] Make StopRoutingHandler actually stop the routing
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 3f704f1..ded39b1 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
@@ -960,6 +960,25 @@ namespace MonoTests.System.Web.Routing
 			Assert.IsNull (rd, "#2");
 		}
 
+		[Test (Description="Bug #651966")]
+		public void GetRouteData47 ()
+		{
+			var r = new Route ("Foo/{id}", new StopRoutingHandler ()) {
+				Defaults = new RouteValueDictionary (new {
+					controller = "Foo",
+					action = "Retrieve"
+				}),
+				Constraints = new RouteValueDictionary (new {
+					id = @"\d{1,10}"
+				})
+			};
+			
+			var hc = new HttpContextStub ("/Foo/x123", String.Empty);
+			var rd = r.GetRouteData (hc);
+
+			Assert.IsNull (rd, "#1");
+		}
+		
 		[Test]
 		[ExpectedException (typeof (ArgumentNullException))]
 		public void GetVirtualPathNullContext ()
diff --git a/mcs/class/System.Web.Services/System.Web.Services.Description/BasicProfileChecker.cs b/mcs/class/System.Web.Services/System.Web.Services.Description/BasicProfileChecker.cs
index c9d73c2..e862414 100644
--- a/mcs/class/System.Web.Services/System.Web.Services.Description/BasicProfileChecker.cs
+++ b/mcs/class/System.Web.Services/System.Web.Services.Description/BasicProfileChecker.cs
@@ -142,7 +142,7 @@ namespace System.Web.Services.Description
 
 		public override void Check (ConformanceCheckContext ctx, BindingCollection value) {
 			foreach (Binding b in value)
-				foreach (ServiceDescriptionFormatExtension ext in b.Extensions)
+				foreach (object ext in b.Extensions)
 					if (ext.GetType () == typeof (SoapBinding))
 						return;
 
diff --git a/mcs/class/System.Web.Services/System.Web.Services.Description/ChangeLog b/mcs/class/System.Web.Services/System.Web.Services.Description/ChangeLog
index 690c634..208cc1b 100644
--- a/mcs/class/System.Web.Services/System.Web.Services.Description/ChangeLog
+++ b/mcs/class/System.Web.Services/System.Web.Services.Description/ChangeLog
@@ -1,3 +1,16 @@
+2011-02-04  Ankit Jain  <radical at corewars.org>
+
+	*
+	class/System.Web.Services/System.Web.Services.Description/BasicProfileChecker.cs:
+	Extensions can be XmlElement or ServiceDescriptionFormatExtension.
+	*
+	class/System.Web.Services/System.Web.Services.Description/ServiceDescription.cs:
+	(AddExtensionNamespaces): Likewise. Also, ignore namespaces from
+	XmlElement, as we retain and write them out as-is.
+	(WriteExtension): Emit the XmlElement as-is. *
+	class/System.Web.Services/Test/System.Web.Services.Description/ServiceDescriptionTest.cs:
+	Update to write out the wsdl also.
+
 2010-09-08  Jb Evain  <jbevain at gmail.com>
 
 	Fix the monodroid and monotouch profile builds
diff --git a/mcs/class/System.Web.Services/System.Web.Services.Description/ServiceDescription.cs b/mcs/class/System.Web.Services/System.Web.Services.Description/ServiceDescription.cs
index fb0aab5..eee8a30 100644
--- a/mcs/class/System.Web.Services/System.Web.Services.Description/ServiceDescription.cs
+++ b/mcs/class/System.Web.Services/System.Web.Services.Description/ServiceDescription.cs
@@ -339,8 +339,13 @@ namespace System.Web.Services.Description
 		
 		void AddExtensionNamespaces (XmlSerializerNamespaces ns, ServiceDescriptionFormatExtensionCollection extensions)
 		{
-			foreach (ServiceDescriptionFormatExtension ext in extensions)
+			foreach (object o in extensions)
 			{
+				ServiceDescriptionFormatExtension ext = o as ServiceDescriptionFormatExtension;
+				if (ext == null)
+					// o can be XmlElement, skipping that
+					continue;
+
 				ExtensionInfo einf = ExtensionManager.GetFormatExtensionInfo (ext.GetType ());
 				foreach (XmlQualifiedName qname in einf.NamespaceDeclarations)
 					ns.Add (qname.Name, qname.Namespace);
@@ -352,8 +357,12 @@ namespace System.Web.Services.Description
 			ServiceDescriptionFormatExtensionCollection extensions = ExtensionManager.GetExtensionPoint (ob);
 			if (extensions != null)
 			{
-				foreach (ServiceDescriptionFormatExtension ext in extensions)
-					WriteExtension (writer, ext);
+				foreach (object o in extensions) {
+					if (o is ServiceDescriptionFormatExtension)
+						WriteExtension (writer, (ServiceDescriptionFormatExtension)o);
+					else if (o is XmlElement)
+						((XmlElement)o).WriteTo (writer);
+				}
 			}
 		}
 		
diff --git a/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ChangeLog b/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ChangeLog
index 5bc256e..9d5a3d0 100644
--- a/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ChangeLog
+++ b/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ChangeLog
@@ -1,3 +1,7 @@
+2011-02-04  Ankit Jain  <radical at corewars.org>
+
+	[webservices] Extensions can be unknown XmlElements also, fix.
+
 2009-06-26  Robert Jordan  <robertj at gmx.net>
 
 	* *.cs: Upgrade to new NUnit style.
diff --git a/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ChangeLog b/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Web.Services/Test/System.Web.Services.Description/ChangeLog
copy to mcs/class/System.Web.Services/Test/System.Web.Services.Description/ChangeLog.old
diff --git a/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ServiceDescriptionTest.cs b/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ServiceDescriptionTest.cs
index 7ebfc51..99fe6c6 100644
--- a/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ServiceDescriptionTest.cs
+++ b/mcs/class/System.Web.Services/Test/System.Web.Services.Description/ServiceDescriptionTest.cs
@@ -141,6 +141,14 @@ namespace MonoTests.System.Web.Services.Description
 		    Assert.AreEqual (typeof (SoapAddressBinding), sd.Services [0].Ports [0].Extensions [0].GetType ());	
 		    CheckXmlElement (sd.Services [0].Ports [0].Extensions [1], "portElem");
 
+		    string out_file = Path.GetTempFileName ();
+		    try {
+			    using (FileStream out_fs = new FileStream(out_file, FileMode.Create))
+				    sd.Write (out_fs);
+		    } finally {
+			    if (!String.IsNullOrEmpty (out_file))
+				    File.Delete (out_file);
+		    }
 		}
 
 		void CheckExtensions (DocumentableItem di, string elemName, string val)
diff --git a/mcs/class/System.Web/Assembly/AssemblyInfo.cs b/mcs/class/System.Web/Assembly/AssemblyInfo.cs
index d62fb7f..e8c1a57 100644
--- a/mcs/class/System.Web/Assembly/AssemblyInfo.cs
+++ b/mcs/class/System.Web/Assembly/AssemblyInfo.cs
@@ -91,6 +91,8 @@ using System.Web.UI;
 [assembly: TypeForwardedTo (typeof (System.Web.Security.MembershipUserCollection))]
 [assembly: TypeForwardedTo (typeof (System.Web.Security.MembershipProviderCollection))]
 [assembly: TypeForwardedTo (typeof (System.Web.Security.MembershipProvider))]
+
+[assembly: InternalsVisibleTo ("Microsoft.Web.Infrastructure, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
 #endif
 
 [assembly: InternalsVisibleTo ("System.Web.Extensions, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
diff --git a/mcs/class/System.Web/Assembly/ChangeLog b/mcs/class/System.Web/Assembly/ChangeLog
index ed5c7c8..62ce371 100644
--- a/mcs/class/System.Web/Assembly/ChangeLog
+++ b/mcs/class/System.Web/Assembly/ChangeLog
@@ -1,3 +1,8 @@
+2011-01-17  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] System.Web and Microsoft.Web.Infrastructure are now
+	friends
+
 2011-01-08  Marek Safar  <marek.safar at gmail.com>
 
 	Fixed missing protected internal modifier
diff --git a/mcs/class/System.Web/ChangeLog b/mcs/class/System.Web/ChangeLog
index 329c323..956d271 100644
--- a/mcs/class/System.Web/ChangeLog
+++ b/mcs/class/System.Web/ChangeLog
@@ -1,3 +1,19 @@
+2011-02-09  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Implemented CustomErrorsRedirectMode
+
+2011-01-31  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Implemented 4.0 types
+	System.Web.Security.{MachineKey,MachineKeyProtection} plus tests
+
+2011-01-17  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Implemented BuildManager.GetObjectFactory
+
+	This method is not used by Mono internally but is called by MVC
+	v3.
+
 2011-01-13  Marek Habersack  <grendel at twistedcode.net>
 
 	[asp.net] Implemented the 4.0 type,
diff --git a/mcs/class/System.Web/System.Web.Caching/Cache.cs b/mcs/class/System.Web/System.Web.Caching/Cache.cs
index e7fdfcf..a5695e7 100644
--- a/mcs/class/System.Web/System.Web.Caching/Cache.cs
+++ b/mcs/class/System.Web/System.Web.Caching/Cache.cs
@@ -147,6 +147,9 @@ namespace System.Web.Caching
 				return null;
 
 			CacheItem ret = cache [key];
+			if (ret == null)
+				return null;
+			
 			if (timedItems != null)
 				timedItems.OnItemDisable (ret);
 			
diff --git a/mcs/class/System.Web/System.Web.Caching/ChangeLog b/mcs/class/System.Web/System.Web.Caching/ChangeLog
index 289250e..cd87729 100644
--- a/mcs/class/System.Web/System.Web.Caching/ChangeLog
+++ b/mcs/class/System.Web/System.Web.Caching/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-20  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Don't throw NREX when a cache item to be removed is null
+
 2010-11-19  Marek Habersack  <grendel at twistedcode.net>
 
 	[asp.net] Disabled array clearing on heap resize in
diff --git a/mcs/class/System.Web/System.Web.Compilation/AppCodeCompiler.cs b/mcs/class/System.Web/System.Web.Compilation/AppCodeCompiler.cs
index 3a288b6..fef2068 100644
--- a/mcs/class/System.Web/System.Web.Compilation/AppCodeCompiler.cs
+++ b/mcs/class/System.Web/System.Web.Compilation/AppCodeCompiler.cs
@@ -34,6 +34,7 @@ using System.CodeDom.Compiler;
 using System.Configuration;
 using System.Collections;
 using System.Collections.Generic;
+using System.Collections.Specialized;
 using System.Globalization;
 using System.IO;
 using System.Reflection;
@@ -80,8 +81,9 @@ namespace System.Web.Compilation
 				if (asm == null)
 					throw new HttpException (String.Format ("Unable to find assembly {0}", assemblyName), error);
 
-				assemblyCache.Add (assemblyName, asm.Location);
-				return asm.Location;
+				string path = new Uri (asm.CodeBase).LocalPath;
+				assemblyCache.Add (assemblyName, path);
+				return path;
 			}
 		}
 	}
@@ -221,8 +223,15 @@ namespace System.Web.Compilation
 			CompilerParameters parameters = compilerInfo.CreateDefaultCompilerParameters ();
 			parameters.IncludeDebugInformation = compilationSection.Debug;
 			
-			if (binAssemblies != null && binAssemblies.Length > 0)
-				parameters.ReferencedAssemblies.AddRange (binAssemblies);
+			if (binAssemblies != null && binAssemblies.Length > 0) {
+				StringCollection parmRefAsm = parameters.ReferencedAssemblies;
+				foreach (string binAsm in binAssemblies) {
+					if (parmRefAsm.Contains (binAsm))
+						continue;
+					
+					parmRefAsm.Add (binAsm);
+				}
+			}
 			
 			if (compilationSection != null) {
 				foreach (AssemblyInfo ai in compilationSection.Assemblies)
@@ -273,7 +282,7 @@ namespace System.Web.Compilation
 		
 		VirtualPath PhysicalToVirtual (string file)
 		{
-			return new VirtualPath (file.Replace (HttpRuntime.AppDomainAppPath, "/").Replace (Path.DirectorySeparatorChar, '/'));
+			return new VirtualPath (file.Replace (HttpRuntime.AppDomainAppPath, "~/").Replace (Path.DirectorySeparatorChar, '/'));
 		}
 		
 		BuildProvider GetBuildProviderFor (string file, BuildProviderCollection buildProviders)
diff --git a/mcs/class/System.Web/System.Web.Compilation/AssemblyBuilder.cs b/mcs/class/System.Web/System.Web.Compilation/AssemblyBuilder.cs
index 7efab25..cd52c4b 100644
--- a/mcs/class/System.Web/System.Web.Compilation/AssemblyBuilder.cs
+++ b/mcs/class/System.Web/System.Web.Compilation/AssemblyBuilder.cs
@@ -740,7 +740,6 @@ namespace System.Web.Compilation
 		{
 			if (options == null)
 				throw new ArgumentNullException ("options");
-
 			options.TempFiles = temp_files;
 			if (options.OutputAssembly == null)
 				options.OutputAssembly = OutputAssemblyName;
@@ -797,18 +796,30 @@ namespace System.Web.Compilation
 				options.EmbeddedResources.Add (de.Value);
 
 			AddAssemblyReference (BuildManager.GetReferencedAssemblies ());
+			List <Assembly> referencedAssemblies = ReferencedAssemblies;
+			StringCollection optRefAsm = options.ReferencedAssemblies;
+			Type appType = HttpApplicationFactory.AppType;
+			if (appType != null && !referencedAssemblies.Contains (appType.Assembly))
+				referencedAssemblies.Add (appType.Assembly);
+
 			foreach (Assembly refasm in ReferencedAssemblies) {
 				string path = new Uri (refasm.CodeBase).LocalPath;
-				options.ReferencedAssemblies.Add (path);
+				string originalPath = refasm.Location;
+				if (!optRefAsm.Contains (path) && !optRefAsm.Contains (originalPath))
+					optRefAsm.Add (path);
 			}
+
+			
 			
 			results = provider.CompileAssemblyFromFile (options, files.ToArray ());
 
 			if (results.NativeCompilerReturnValue != 0) {
 				string fileText = null;
+				CompilerErrorCollection errors = results.Errors;
 				try {
-					using (StreamReader sr = File.OpenText (results.Errors [0].FileName)) {
-						fileText = sr.ReadToEnd ();
+					if (errors != null && errors.Count > 0) {
+						using (StreamReader sr = File.OpenText (results.Errors [0].FileName))
+							fileText = sr.ReadToEnd ();
 					}
 				} catch (Exception) {}
 				
@@ -821,11 +832,16 @@ namespace System.Web.Compilation
 				Console.WriteLine ("\nErrors:");
 				foreach (CompilerError err in results.Errors)
 					Console.WriteLine (err);
-				Console.WriteLine ("File name: {0}", results.Errors [0].FileName);
-				Console.WriteLine ("File text:\n{0}\n", fileText);
+				if (errors != null && errors.Count > 0)
+					Console.WriteLine ("File name: {0}", results.Errors [0].FileName);
+				else
+					Console.WriteLine ("File name not available");
+				if (!String.IsNullOrEmpty (fileText))
+					Console.WriteLine ("File text:\n{0}\n", fileText);
+				else
+					Console.WriteLine ("No file text available");
 				Console.WriteLine ("********************************************************************");
 #endif
-				
 				throw new CompilationException (virtualPath != null ? virtualPath.Original : String.Empty, results, fileText);
 			}
 			
diff --git a/mcs/class/System.Web/System.Web.Compilation/BuildManager.cs b/mcs/class/System.Web/System.Web.Compilation/BuildManager.cs
index 31d8723..fc4db7f 100644
--- a/mcs/class/System.Web/System.Web.Compilation/BuildManager.cs
+++ b/mcs/class/System.Web/System.Web.Compilation/BuildManager.cs
@@ -117,6 +117,10 @@ namespace System.Web.Compilation
 		}
 
 #if NET_4_0
+		internal static bool CompilingTopLevelAssemblies {
+			get; set;
+		}
+		
 		internal static bool PreStartMethodsRunning {
 			get { return preStartMethodsRunning; }
 		}
@@ -217,6 +221,7 @@ namespace System.Web.Compilation
 			
 			string [] parts;
 			int skip = -1;
+			string appVirtualRoot = VirtualPathUtility.AppendTrailingSlash (HttpRuntime.AppDomainAppVirtualPath);
 			foreach (string vpath in precompiled.Keys) {
 				parts = vpath.Split ('/');
 				for (int i = 0; i < parts.Length; i++) {
@@ -225,7 +230,7 @@ namespace System.Web.Compilation
 					// The path must be rooted, otherwise PhysicalPath returned
 					// below will be relative to the current request path and
 					// File.Exists will return a false negative. See bug #546053
-					string test_path = "/" + String.Join ("/", parts, i, parts.Length - i);
+					string test_path = appVirtualRoot + String.Join ("/", parts, i, parts.Length - i);
 					VirtualPath result = GetAbsoluteVirtualPath (test_path);
 					if (result != null && File.Exists (result.PhysicalPath)) {
 						skip = i - 1;
@@ -624,8 +629,8 @@ namespace System.Web.Compilation
 		public static Type GetGlobalAsaxType ()
 		{
 			Type ret = HttpApplicationFactory.AppType;
-			if (!preStartMethodsRunning)
-				throw new InvalidOperationException ("This method cannot be called during the application's pre-start initialization stage.");
+			if (ret == null)
+				return typeof (HttpApplication);
 			
 			return ret;
 		}
@@ -667,10 +672,39 @@ namespace System.Web.Compilation
 				dynamicallyRegisteredAssemblies.Add (assembly);
 		}
 
-		[MonoTODO ("A no-op until we use IWebObjectFactory internally. Always returns null.")]
+		[MonoDocumentationNote ("Not used by Mono internally. Needed for MVC3")]
 		public static IWebObjectFactory GetObjectFactory (string virtualPath, bool throwIfNotFound)
 		{
-			return null;
+			if (CompilingTopLevelAssemblies)
+				throw new HttpException ("Method must not be called while compiling the top level assemblies.");
+
+			Type type;
+			if (is_precompiled) {
+				type = GetPrecompiledType (virtualPath);
+				if (type == null) {
+					if (throwIfNotFound)
+						throw new HttpException (String.Format ("Virtual path '{0}' not found in precompiled application type cache.", virtualPath));
+					else
+						return null;
+				}
+				return new SimpleWebObjectFactory (type);
+			}
+
+			Exception compileException = null;
+			try {
+				type = GetCompiledType (virtualPath);
+			} catch (Exception ex) {
+				compileException = ex;
+				type = null;
+			}
+			
+			if (type == null) {
+				if (throwIfNotFound)
+					throw new HttpException (String.Format ("Virtual path '{0}' does not exist.", virtualPath), compileException);
+				return null;
+			}
+			
+			return new SimpleWebObjectFactory (type);
 		}
 #endif
 		public static object CreateInstanceFromVirtualPath (string virtualPath, Type requiredBaseType)
@@ -1114,20 +1148,61 @@ namespace System.Web.Compilation
 		{
 			return GetType (typeName, throwOnError, false);
 		}
-
+		
 		public static Type GetType (string typeName, bool throwOnError, bool ignoreCase)
 		{
+			if (String.IsNullOrEmpty (typeName))
+				throw new HttpException ("Type name must not be empty.");
+			
 			Type ret = null;
+			Exception ex = null;
 			try {
-				foreach (Assembly asm in TopLevel_Assemblies) {
-					ret = asm.GetType (typeName, throwOnError, ignoreCase);
+				string wantedAsmName;
+				string wantedTypeName;
+				int comma = typeName.IndexOf (',');
+
+				if (comma > 0 && comma < typeName.Length - 1) {
+					var aname = new AssemblyName (typeName.Substring (comma + 1));
+					wantedAsmName = aname.ToString ();
+					wantedTypeName = typeName.Substring (0, comma);
+				} else {
+					wantedAsmName = null;
+					wantedTypeName = typeName;
+				}
+
+				var assemblies = new List <Assembly> ();
+				assemblies.AddRange (BuildManager.GetReferencedAssemblies () as List <Assembly>);
+				assemblies.AddRange (TopLevel_Assemblies);
+				Type appType = HttpApplicationFactory.AppType;
+				if (appType != null)
+					assemblies.Add (appType.Assembly);
+				
+				foreach (Assembly asm in assemblies) {
+					if (asm == null)
+						continue;
+
+					if (wantedAsmName != null) {
+						// So dumb...
+						if (String.Compare (wantedAsmName, asm.GetName ().ToString (), StringComparison.Ordinal) == 0) {
+							ret = asm.GetType (wantedTypeName, throwOnError, ignoreCase);
+							if (ret != null)
+								return ret;
+						}
+						continue;
+					}
+					
+					ret = asm.GetType (wantedTypeName, false, ignoreCase);
 					if (ret != null)
-						break;
+						return ret;
 				}
-			} catch (Exception ex) {
-				throw new HttpException ("Failed to find the specified type.", ex);
+			} catch (Exception e) {
+				ex = e;
 			}
-			return ret;
+
+			if (throwOnError)
+				throw new HttpException ("Failed to find the specified type.", ex);
+
+			return null;
 		}
 
 		public static ICollection GetVirtualPathDependencies (string virtualPath)
@@ -1389,11 +1464,11 @@ namespace System.Web.Compilation
 			if (suppressDebugModeMessages)
 				return;
 			
-			Console.WriteLine ();
-			Console.WriteLine ("******* DEBUG MODE MESSAGE *******");
-			Console.WriteLine (msg);
-			Console.WriteLine ("******* DEBUG MODE MESSAGE *******");
-			Console.WriteLine ();
+			Console.Error.WriteLine ();
+			Console.Error.WriteLine ("******* DEBUG MODE MESSAGE *******");
+			Console.Error.WriteLine (msg);
+			Console.Error.WriteLine ("******* DEBUG MODE MESSAGE *******");
+			Console.Error.WriteLine ();
 		}
 
 		static void StoreInCache (BuildProvider bp, Assembly compiledAssembly, CompilerResults results)
diff --git a/mcs/class/System.Web/System.Web.Compilation/ChangeLog b/mcs/class/System.Web/System.Web.Compilation/ChangeLog
index 4f766ba..6aa4a78 100644
--- a/mcs/class/System.Web/System.Web.Compilation/ChangeLog
+++ b/mcs/class/System.Web/System.Web.Compilation/ChangeLog
@@ -1,3 +1,47 @@
+2011-02-09  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Fix for bug #669048. Fix up virtual precompiled app
+	virtual paths with the virtual root of the current app
+
+2011-02-09  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Be more careful with errors collection when compilation
+	fails.
+
+2011-01-24  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Global.asax assembly must be passed as reference when
+	compiling. BuildManager.GetType improvements.
+
+	When user has their own global application class (global.asax is
+	present) the assembly produced from it must be passed as reference
+	to the compiler. BuildManager.GetType now supports fully-qualified
+	type names for 'typeName' and searches for the type in the
+	top-level assemblies, the global.asax assembly and in the
+	assemblies specified in as references in web.config.
+
+	All of this fixes certain MVC3+Razor applications.
+
+2011-01-20  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Avoid passing duplicate assemblies on mcs command line.
+
+2011-01-20  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	[System.Web] Razor works now (modulo DB)
+
+2011-01-20  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Do not throw NREX when firstError is null in
+	ErrorMessage getter
+
+2011-01-17  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Implemented BuildManager.GetObjectFactory
+
+	This method is not used by Mono internally but is called by MVC
+	v3.
+
 2010-11-03  Marek Habersack  <grendel at twistedcode.net>
 
 	[asp.net] Use faster string comparison in caches in
diff --git a/mcs/class/System.Web/System.Web.Compilation/CompilationException.cs b/mcs/class/System.Web/System.Web.Compilation/CompilationException.cs
index 4acce3f..4aacf11 100644
--- a/mcs/class/System.Web/System.Web.Compilation/CompilationException.cs
+++ b/mcs/class/System.Web/System.Web.Compilation/CompilationException.cs
@@ -124,11 +124,14 @@ namespace System.Web.Compilation
 						firstError = err;
 						break;
 					};
-					
-					errmsg = firstError.ToString ();
-					int idx = errmsg.IndexOf (" : error ");
-					if (idx > -1)
-						errmsg = errmsg.Substring (idx + 9);
+
+					if (firstError != null) {
+						errmsg = firstError.ToString ();
+						int idx = errmsg.IndexOf (" : error ");
+						if (idx > -1)
+							errmsg = errmsg.Substring (idx + 9);
+					} else
+						errmsg = String.Empty;
 				}
 
 				return errmsg;
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 df28ee9..ed14541 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,12 @@
+2011-02-09  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Implemented CustomErrorsRedirectMode
+
+2011-02-03  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] HttpRuntimeSection.RequestPathInvalidCharacters default
+	value is different
+
 2011-01-10  Marek Habersack  <grendel at twistedcode.net>
 
 	[asp.net,mcs] Fixed 'protected internal' build errors and removed
diff --git a/mcs/class/System.Web/System.Web.Configuration_2.0/CustomErrorsRedirectMode.cs b/mcs/class/System.Web/System.Web.Configuration_2.0/CustomErrorsRedirectMode.cs
new file mode 100644
index 0000000..49656c0
--- /dev/null
+++ b/mcs/class/System.Web/System.Web.Configuration_2.0/CustomErrorsRedirectMode.cs
@@ -0,0 +1,37 @@
+//
+// Authors:
+//   Marek Habersack <grendel at twistedcode.net>
+//
+// Copyright (C) 2011 Novell, Inc (http://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.Web.Configuration
+{
+	public enum CustomErrorsRedirectMode
+	{
+		ResponseRedirect,
+		ResponseRewrite
+	}
+}
diff --git a/mcs/class/System.Web/System.Web.Configuration_2.0/CustomErrorsSection.cs b/mcs/class/System.Web/System.Web.Configuration_2.0/CustomErrorsSection.cs
index 1df2713..2fcad9f 100644
--- a/mcs/class/System.Web/System.Web.Configuration_2.0/CustomErrorsSection.cs
+++ b/mcs/class/System.Web/System.Web.Configuration_2.0/CustomErrorsSection.cs
@@ -4,7 +4,7 @@
 // Authors:
 //	Chris Toshok (toshok at ximian.com)
 //
-// (C) 2005 Novell, Inc (http://www.novell.com)
+// (C) 2011 Novell, Inc (http://www.novell.com)
 //
 
 //
@@ -32,33 +32,36 @@ using System;
 using System.Configuration;
 using System.Xml;
 
-#if NET_2_0
-
-namespace System.Web.Configuration {
-
+namespace System.Web.Configuration
+{
 	public sealed class CustomErrorsSection : ConfigurationSection
 	{
 		static ConfigurationProperty defaultRedirectProp;
 		static ConfigurationProperty errorsProp;
 		static ConfigurationProperty modeProp;
+		static ConfigurationProperty redirectModeProp;
 		static ConfigurationPropertyCollection properties;
 
 		static CustomErrorsSection ()
 		{
 			defaultRedirectProp = new ConfigurationProperty ("defaultRedirect", typeof (string), null);
-			errorsProp = new ConfigurationProperty ("", typeof (CustomErrorCollection), null,
+			errorsProp = new ConfigurationProperty (String.Empty, typeof (CustomErrorCollection), null,
 								null, PropertyHelper.DefaultValidator,
 								ConfigurationPropertyOptions.IsDefaultCollection);
 			modeProp = new ConfigurationProperty ("mode", typeof (CustomErrorsMode), CustomErrorsMode.RemoteOnly,
 							      new GenericEnumConverter (typeof (CustomErrorsMode)),
 							      PropertyHelper.DefaultValidator,
 							      ConfigurationPropertyOptions.None);
+			redirectModeProp = new ConfigurationProperty ("redirectMode", typeof (CustomErrorsRedirectMode), CustomErrorsRedirectMode.ResponseRedirect,
+								      new GenericEnumConverter (typeof (CustomErrorsRedirectMode)),
+								      PropertyHelper.DefaultValidator, ConfigurationPropertyOptions.None);
+			
 			properties = new ConfigurationPropertyCollection ();
 
 			properties.Add (defaultRedirectProp);
 			properties.Add (errorsProp);
 			properties.Add (modeProp);
-
+			properties.Add (redirectModeProp);
 		}
 
 		// Why override?
@@ -90,6 +93,12 @@ namespace System.Web.Configuration {
 			set { base[modeProp] = value; }
 		}
 
+		[ConfigurationProperty ("redirectMode", DefaultValue = CustomErrorsRedirectMode.ResponseRedirect)]
+		public CustomErrorsRedirectMode RedirectMode {
+			get { return (CustomErrorsRedirectMode) base [redirectModeProp]; }
+			set { base [redirectModeProp] = value; }
+		}
+
 		protected internal override ConfigurationPropertyCollection Properties {
 			get { return properties; }
 		}
@@ -98,5 +107,3 @@ namespace System.Web.Configuration {
 
 }
 
-#endif
-
diff --git a/mcs/class/System.Web/System.Web.Configuration_2.0/HttpRuntimeSection.cs b/mcs/class/System.Web/System.Web.Configuration_2.0/HttpRuntimeSection.cs
index 7e4da39..46c8b0a 100644
--- a/mcs/class/System.Web/System.Web.Configuration_2.0/HttpRuntimeSection.cs
+++ b/mcs/class/System.Web/System.Web.Configuration_2.0/HttpRuntimeSection.cs
@@ -118,7 +118,7 @@ namespace System.Web.Configuration
 										PropertyHelper.IntFromZeroToMaxValidator,
 										ConfigurationPropertyOptions.None);
 #if NET_4_0
-			requestPathInvalidCharactersProp = new ConfigurationProperty ("requestPathInvalidCharacters", typeof (string), ",*,%,&,:,\\,?");
+			requestPathInvalidCharactersProp = new ConfigurationProperty ("requestPathInvalidCharacters", typeof (string), "<,>,*,%,&,:,\\,?");
 			requestValidationTypeProp = new ConfigurationProperty ("requestValidationType", typeof (string),"System.Web.Util.RequestValidator",
 									       TypeDescriptor.GetConverter (typeof (string)),
 									       PropertyHelper.NonEmptyStringValidator,
diff --git a/mcs/class/System.Web/System.Web.Hosting/ChangeLog b/mcs/class/System.Web/System.Web.Hosting/ChangeLog
index e278c6d..50c4917 100644
--- a/mcs/class/System.Web/System.Web.Hosting/ChangeLog
+++ b/mcs/class/System.Web/System.Web.Hosting/ChangeLog
@@ -1,3 +1,22 @@
+2011-01-31  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Ignore directories that don't exist instead of throwing.
+
+2011-01-27  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] A bunch of fixes related to the default
+	VirtualPathProvider (needed for Orchard)
+
+	* DefaultVirtualDirectory is now more careful when snipping off
+	parts of the path passed to its constructor. Before removing the
+	file part it checks whether the file indeed exists. Also sealed
+	the class and made it use generic List instead of ArrayList *
+	HttpRequest does not normalize mapped paths when converting them
+	to absolute ones. This is to avoid errors when path like
+	"~/bin/../../file.txt" is passed to MapPath. *
+	VirtualPathUtility.ToAbsolute overload with normalize parameter
+	really doesn't normalize the resulting path now.
+
 2010-02-18  Marek Habersack  <mhabersack at novell.com>
 
 	* HostingEnvironment.cs: removed SetHostingId and added internal
diff --git a/mcs/class/System.Web/System.Web.Hosting/ChangeLog b/mcs/class/System.Web/System.Web.Hosting/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Web/System.Web.Hosting/ChangeLog
copy to mcs/class/System.Web/System.Web.Hosting/ChangeLog.old
diff --git a/mcs/class/System.Web/System.Web.Hosting/DefaultVirtualDirectory.cs b/mcs/class/System.Web/System.Web.Hosting/DefaultVirtualDirectory.cs
index e269832..d04029d 100644
--- a/mcs/class/System.Web/System.Web.Hosting/DefaultVirtualDirectory.cs
+++ b/mcs/class/System.Web/System.Web.Hosting/DefaultVirtualDirectory.cs
@@ -6,7 +6,7 @@
 //
 
 //
-// Copyright (c) 2006 Novell, Inc (http://www.novell.com)
+// Copyright (c) 2006-2011 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
@@ -28,15 +28,14 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
-
 using System;
 using System.Collections;
+using System.Collections.Generic;
 using System.IO;
 
 namespace System.Web.Hosting {
 
-	class DefaultVirtualDirectory : VirtualDirectory
+	sealed class DefaultVirtualDirectory : VirtualDirectory
 	{
 		string phys_dir;
 		string virtual_dir;
@@ -50,33 +49,43 @@ namespace System.Web.Hosting {
 		{
 			if (phys_dir == null) {
 				string vpath = VirtualPath;
-				virtual_dir = VirtualPathUtility.GetDirectory (vpath);
-				phys_dir = HostingEnvironment.MapPath (virtual_dir);
+				string path = HostingEnvironment.MapPath (vpath);
+				if (File.Exists (path)) {
+					virtual_dir = VirtualPathUtility.GetDirectory (vpath);
+					phys_dir = HostingEnvironment.MapPath (virtual_dir);
+				} else {
+					virtual_dir = VirtualPathUtility.AppendTrailingSlash (vpath);
+					phys_dir = path;
+				}
 			}
 		}
 
-		ArrayList AddDirectories (ArrayList list, string dir)
+		List <VirtualFileBase> AddDirectories (List <VirtualFileBase> list, string dir)
 		{
-			foreach (string name in Directory.GetDirectories (phys_dir)) {
-				string vdir = VirtualPathUtility.Combine (virtual_dir, Path.GetFileName (name));
-				list.Add (new DefaultVirtualDirectory (vdir));
-			}
+			if (String.IsNullOrEmpty (dir) || !Directory.Exists (dir))
+				return list;
+			
+			foreach (string name in Directory.GetDirectories (phys_dir))
+				list.Add (new DefaultVirtualDirectory (VirtualPathUtility.Combine (virtual_dir, Path.GetFileName (name))));
+
 			return list;
 		}
 
-		ArrayList AddFiles (ArrayList list, string dir)
+		List <VirtualFileBase> AddFiles (List <VirtualFileBase> list, string dir)
 		{
-			foreach (string name in Directory.GetFiles (phys_dir)) {
-				string vdir = VirtualPathUtility.Combine (virtual_dir, Path.GetFileName (name));
-				list.Add (new DefaultVirtualFile (vdir));
-			}
+			if (String.IsNullOrEmpty (dir) || !Directory.Exists (dir))
+				return list;
+			
+			foreach (string name in Directory.GetFiles (phys_dir))
+				list.Add (new DefaultVirtualFile (VirtualPathUtility.Combine (virtual_dir, Path.GetFileName (name))));
+
 			return list;
 		}
 
 		public override IEnumerable Children {
 			get {
 				Init ();
-				ArrayList list = new ArrayList ();
+				var list = new List <VirtualFileBase> ();
 				AddDirectories (list, phys_dir);
 				return AddFiles (list, phys_dir);
 			}
@@ -85,19 +94,17 @@ namespace System.Web.Hosting {
 		public override IEnumerable Directories {
 			get {
 				Init ();
-				ArrayList list = new ArrayList ();
-				return AddDirectories (list, phys_dir);
+				return AddDirectories (new List <VirtualFileBase> (), phys_dir);
 			}
 		}
 		
 		public override IEnumerable Files {
 			get {
 				Init ();
-				ArrayList list = new ArrayList ();
-				return AddFiles (list, phys_dir);
+				return AddFiles (new List <VirtualFileBase> (), phys_dir);
 			}
 		}
 	}
 }
-#endif
+
 
diff --git a/mcs/class/System.Web/System.Web.Security/ChangeLog b/mcs/class/System.Web/System.Web.Security/ChangeLog
index ad26291..56fbdb4 100644
--- a/mcs/class/System.Web/System.Web.Security/ChangeLog
+++ b/mcs/class/System.Web/System.Web.Security/ChangeLog
@@ -1,3 +1,17 @@
+2011-02-01  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] FormsAuthenticationTicket.FromByteArray stops early if
+	it is passed a null parameter
+
+2011-01-31  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Implemented 4.0 types
+	System.Web.Security.{MachineKey,MachineKeyProtection} plus tests
+
+2011-01-20  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	[System.Web] Razor works now (modulo DB)
+
 2010-10-28  Marek Habersack  <grendel at twistedcode.net>
 
 	[asp.net] Cosmetics + dead code removal
diff --git a/mcs/class/System.Web/System.Web.Security/FormsAuthenticationTicket.cs b/mcs/class/System.Web/System.Web.Security/FormsAuthenticationTicket.cs
index 38c5ed9..5adad78 100644
--- a/mcs/class/System.Web/System.Web.Security/FormsAuthenticationTicket.cs
+++ b/mcs/class/System.Web/System.Web.Security/FormsAuthenticationTicket.cs
@@ -87,6 +87,9 @@ namespace System.Web.Security
 
 		internal static FormsAuthenticationTicket FromByteArray (byte [] bytes)
 		{
+			if (bytes == null)
+				throw new ArgumentNullException ("bytes");
+			
 			MemoryStream ms = new MemoryStream (bytes);
 			BinaryReader reader = new BinaryReader (ms);
 			FormsAuthenticationTicket ticket = new FormsAuthenticationTicket ();
diff --git a/mcs/class/System.Web/System.Web.Security/MachineKey.cs b/mcs/class/System.Web/System.Web.Security/MachineKey.cs
new file mode 100644
index 0000000..636997e
--- /dev/null
+++ b/mcs/class/System.Web/System.Web.Security/MachineKey.cs
@@ -0,0 +1,108 @@
+//
+// Authors:
+//   Marek Habersack <grendel at twistedcode.net>
+//
+// (C) 2011 Novell, Inc (http://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.Web;
+using System.Web.Configuration;
+using System.Web.Util;
+
+namespace System.Web.Security 
+{
+	public static class MachineKey
+	{
+		public static byte[] Decode (string encodedData, MachineKeyProtection protectionOption)
+		{
+			if (encodedData == null)
+				throw new ArgumentNullException ("encodedData");
+
+			int dlen = encodedData.Length;
+			if (dlen == 0 || dlen % 2 == 1)
+				throw new ArgumentException ("encodedData");
+
+			byte[] data = MachineKeySectionUtils.GetBytes (encodedData, dlen);
+			if (data == null || data.Length == 0)
+				throw new ArgumentException ("encodedData");
+			
+			var config = WebConfigurationManager.GetWebApplicationSection ("system.web/machineKey") as MachineKeySection;
+			byte[] result = null;
+			Exception ex = null;
+			try {
+				switch (protectionOption) {
+					case MachineKeyProtection.All:
+						result = MachineKeySectionUtils.VerifyDecrypt (config, data);
+						break;
+
+					case MachineKeyProtection.Encryption:
+						result = MachineKeySectionUtils.Decrypt (config, data);
+						break;
+
+					case MachineKeyProtection.Validation:
+						result = MachineKeySectionUtils.Verify (config, data);
+						break;
+
+					default:
+						return MachineKeySectionUtils.GetBytes (encodedData, dlen);
+				}
+			} catch (Exception e) {
+				ex = e;
+			}
+			
+			if (result == null || ex != null)
+				throw new HttpException ("Unable to verify passed data.", ex);
+			
+			return result;
+		}
+
+		public static string Encode (byte[] data, MachineKeyProtection protectionOption)
+		{
+			if (data == null)
+				throw new ArgumentNullException ("data");
+
+			var config = WebConfigurationManager.GetWebApplicationSection ("system.web/machineKey") as MachineKeySection;
+			byte[] result;
+			switch (protectionOption) {
+				case MachineKeyProtection.All:
+					result = MachineKeySectionUtils.EncryptSign (config, data);
+					break;
+
+				case MachineKeyProtection.Encryption:
+					result = MachineKeySectionUtils.Encrypt (config, data);
+					break;
+
+				case MachineKeyProtection.Validation:
+					result = MachineKeySectionUtils.Sign (config, data);
+					break;
+
+				default:
+					return String.Empty;
+			}
+			
+			return MachineKeySectionUtils.GetHexString (result);
+		}
+	}
+}
diff --git a/mcs/class/System.Web/System.Web.Security/MachineKeyProtection.cs b/mcs/class/System.Web/System.Web.Security/MachineKeyProtection.cs
new file mode 100644
index 0000000..f8865b5
--- /dev/null
+++ b/mcs/class/System.Web/System.Web.Security/MachineKeyProtection.cs
@@ -0,0 +1,41 @@
+//
+// Authors:
+//   Marek Habersack <grendel at twistedcode.net>
+//
+// (C) 2011 Novell, Inc (http://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.Web.Security 
+{
+	public enum MachineKeyProtection
+	{
+		All,
+		Encryption,
+		Validation
+	}
+}
+
+	
\ No newline at end of file
diff --git a/mcs/class/System.Web/System.Web.Security/Roles.cs b/mcs/class/System.Web/System.Web.Security/Roles.cs
index a2944cc..e309ff6 100644
--- a/mcs/class/System.Web/System.Web.Security/Roles.cs
+++ b/mcs/class/System.Web/System.Web.Security/Roles.cs
@@ -236,6 +236,7 @@ namespace System.Web.Security {
 
 		public static bool Enabled {
 			get { return config.Enabled; }
+			set { config.Enabled = value; }
 		}
 
 		public static int MaxCachedResults {
diff --git a/mcs/class/System.Web/System.Web.Util/ChangeLog b/mcs/class/System.Web/System.Web.Util/ChangeLog
index 5b1db6a..ed37db8 100644
--- a/mcs/class/System.Web/System.Web.Util/ChangeLog
+++ b/mcs/class/System.Web/System.Web.Util/ChangeLog
@@ -1,3 +1,10 @@
+2011-01-17  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Implemented BuildManager.GetObjectFactory
+
+	This method is not used by Mono internally but is called by MVC
+	v3.
+
 2010-12-09  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
 
 	Get system.web/httpRuntime only once
diff --git a/mcs/class/System.Web/System.Web.Util/SimpleWebObjectFactory.cs b/mcs/class/System.Web/System.Web.Util/SimpleWebObjectFactory.cs
new file mode 100644
index 0000000..1135477
--- /dev/null
+++ b/mcs/class/System.Web/System.Web.Util/SimpleWebObjectFactory.cs
@@ -0,0 +1,49 @@
+//
+// Authors:
+//      Marek Habersack <grendel at twistedcode.net>
+//
+// (C) 2011 Novell, Inc (http://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.Web.Util
+{
+	sealed class SimpleWebObjectFactory : IWebObjectFactory
+	{
+		Type type;
+		
+		public SimpleWebObjectFactory (Type type)
+		{
+			this.type = type;
+		}
+		
+		public object CreateInstance ()
+		{
+			if (type == null)
+				return null;
+
+			return Activator.CreateInstance (type);
+		}
+	}
+}
diff --git a/mcs/class/System.Web/System.Web.dll.sources b/mcs/class/System.Web/System.Web.dll.sources
index b465084..015e69b 100644
--- a/mcs/class/System.Web/System.Web.dll.sources
+++ b/mcs/class/System.Web/System.Web.dll.sources
@@ -150,6 +150,7 @@ System.Web.Configuration_2.0/CustomError.cs
 System.Web.Configuration_2.0/CustomErrorCollection.cs
 System.Web.Configuration_2.0/CustomErrorsMode.cs
 System.Web.Configuration_2.0/CustomErrorsSection.cs
+System.Web.Configuration_2.0/CustomErrorsRedirectMode.cs
 System.Web.Configuration_2.0/DeploymentSection.cs
 System.Web.Configuration_2.0/EventMappingSettings.cs
 System.Web.Configuration_2.0/EventMappingSettingsCollection.cs
diff --git a/mcs/class/System.Web/System.Web/ChangeLog b/mcs/class/System.Web/System.Web/ChangeLog
index 8facd24..ac676e8 100644
--- a/mcs/class/System.Web/System.Web/ChangeLog
+++ b/mcs/class/System.Web/System.Web/ChangeLog
@@ -1,3 +1,57 @@
+2011-02-09  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Implemented CustomErrorsRedirectMode
+
+2011-01-31  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Handle wrapped ThreadAbortException
+
+	Third party ProcessRequest() like the one from Razor can wrap a
+	ThreadAbortException originated from response.Redirect().
+
+2011-01-27  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] A bunch of fixes related to the default
+	VirtualPathProvider (needed for Orchard)
+
+	* DefaultVirtualDirectory is now more careful when snipping off
+	parts of the path passed to its constructor. Before removing the
+	file part it checks whether the file indeed exists. Also sealed
+	the class and made it use generic List instead of ArrayList *
+	HttpRequest does not normalize mapped paths when converting them
+	to absolute ones. This is to avoid errors when path like
+	"~/bin/../../file.txt" is passed to MapPath. *
+	VirtualPathUtility.ToAbsolute overload with normalize parameter
+	really doesn't normalize the resulting path now.
+
+2011-01-19  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net,mvc] Make unobtrustive request validation in MVC v3
+	possible
+
+	Validation is enabled early in the pipeline during request.
+	ValidationUtility makes sure that validation is indeed enabled and
+	replaces the default form and query string collections with a lazy
+	version which will validate values only when an existing key is
+	found and requested.
+
+2011-01-17  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Introduced unvalidated versions of Form and QueryString
+	properties for MVC3
+
+2011-01-17  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Implemented BuildManager.GetObjectFactory
+
+	This method is not used by Mono internally but is called by MVC
+	v3.
+
+2011-01-17  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Added internal property InputValidationEnabled to report
+	whether the user enabled validation for current request.
+
 2011-01-17  Marek Habersack  <grendel at twistedcode.net>
 
 	[asp.net] (4.0) Validate the form data in Form getter
diff --git a/mcs/class/System.Web/System.Web/HttpApplication.cs b/mcs/class/System.Web/System.Web/HttpApplication.cs
index 022817f..202c4f8 100644
--- a/mcs/class/System.Web/System.Web/HttpApplication.cs
+++ b/mcs/class/System.Web/System.Web/HttpApplication.cs
@@ -956,7 +956,13 @@ namespace System.Web
 				stop_processing = true;
 				PipelineDone ();
 			} catch (Exception e) {
-				ProcessError (e);
+				ThreadAbortException inner = e.InnerException as ThreadAbortException;
+				if (inner != null && FlagEnd.Value == inner.ExceptionState && !HttpRuntime.DomainUnloading) {
+					context.ClearError ();
+					Thread.ResetAbort ();
+				} else {
+					ProcessError (e);
+				}
 				stop_processing = true;
 				PipelineDone ();
 			}
@@ -1717,29 +1723,34 @@ namespace System.Web
 		bool RedirectCustomError (ref HttpException httpEx)
 		{
 			try {
-			if (!context.IsCustomErrorEnabledUnsafe)
-				return false;
+				if (!context.IsCustomErrorEnabledUnsafe)
+					return false;
 			
-			CustomErrorsSection config = (CustomErrorsSection)WebConfigurationManager.GetSection ("system.web/customErrors");			
-			if (config == null) {
-				if (context.ErrorPage != null)
-					return RedirectErrorPage (context.ErrorPage);
+				CustomErrorsSection config = (CustomErrorsSection)WebConfigurationManager.GetSection ("system.web/customErrors");			
+				if (config == null) {
+					if (context.ErrorPage != null)
+						return RedirectErrorPage (context.ErrorPage);
 				
-				return false;
-			}
-			
-			CustomError err = config.Errors [context.Response.StatusCode.ToString()];
-			string redirect = err == null ? null : err.Redirect;
-			if (redirect == null) {
-				redirect = context.ErrorPage;
-				if (redirect == null)
-					redirect = config.DefaultRedirect;
-			}
+					return false;
+				}
 			
-			if (redirect == null)
-				return false;
+				CustomError err = config.Errors [context.Response.StatusCode.ToString()];
+				string redirect = err == null ? null : err.Redirect;
+				if (redirect == null) {
+					redirect = context.ErrorPage;
+					if (redirect == null)
+						redirect = config.DefaultRedirect;
+				}
 			
-			return RedirectErrorPage (redirect);
+				if (redirect == null)
+					return false;
+
+				if (config.RedirectMode == CustomErrorsRedirectMode.ResponseRewrite) {
+					context.Server.Execute (redirect);
+					return true;
+				}
+				
+				return RedirectErrorPage (redirect);
 			}
 			catch (Exception ex) {
 				httpEx = HttpException.NewWithCode (500, String.Empty, ex, WebEventCodes.WebErrorOtherError);
diff --git a/mcs/class/System.Web/System.Web/HttpApplicationFactory.cs b/mcs/class/System.Web/System.Web/HttpApplicationFactory.cs
index 6a34f2d..2a46b6a 100644
--- a/mcs/class/System.Web/System.Web/HttpApplicationFactory.cs
+++ b/mcs/class/System.Web/System.Web/HttpApplicationFactory.cs
@@ -406,6 +406,7 @@ namespace System.Web
 					}
 #if NET_4_0
 					BuildManager.CallPreStartMethods ();
+					BuildManager.CompilingTopLevelAssemblies = true;
 #endif
 #if !TARGET_J2EE
 					AppResourcesCompiler ac = new AppResourcesCompiler (context);
@@ -447,7 +448,9 @@ namespace System.Web
 						app_browsers_files = Directory.GetFiles (app_browsers_path, "*.browser");
 					}
 #endif
-
+#if NET_4_0
+					BuildManager.CompilingTopLevelAssemblies = false;
+#endif
 					app_type = BuildManager.GetPrecompiledApplicationType ();
 					if (app_type == null && app_file != null) {
 #if TARGET_J2EE
diff --git a/mcs/class/System.Web/System.Web/HttpRequest.cs b/mcs/class/System.Web/System.Web/HttpRequest.cs
index 8c1e488..07c1c4a 100644
--- a/mcs/class/System.Web/System.Web/HttpRequest.cs
+++ b/mcs/class/System.Web/System.Web/HttpRequest.cs
@@ -108,6 +108,9 @@ namespace System.Web
 		static readonly UrlMappingCollection urlMappings;
 		readonly static char [] queryTrimChars = {'?'};
 #if NET_4_0
+		bool lazyFormValidation;
+		bool lazyQueryStringValidation;
+		bool inputValidationEnabled;
 		RequestContext requestContext;
 		
 		static bool validateRequestNewMode;
@@ -115,6 +118,10 @@ namespace System.Web
 			get { return validateRequestNewMode; }
 		}
 
+		internal bool InputValidationEnabled {
+			get { return inputValidationEnabled; }
+		}
+		
 		private static char[] RequestPathInvalidCharacters {
 			get; set;
 		}
@@ -686,8 +693,8 @@ namespace System.Web
 
 			return String.Compare (ContentType, ct, true, Helpers.InvariantCulture) == 0;
 		}
-		
-		public NameValueCollection Form {
+
+		internal WebROCollection FormUnvalidated {
 			get {
 				if (form == null){
 					form = new WebROCollection ();
@@ -702,12 +709,21 @@ namespace System.Web
 					form.Protect ();
 				}
 
+				return form;
+			}
+		}
+		
+		public NameValueCollection Form {
+			get {
+				NameValueCollection form = FormUnvalidated;
 #if NET_4_0
 				if (validateRequestNewMode && !checked_form) {
-					// Setting this before calling the validator prevents
-					// possible endless recursion
-					checked_form = true;
-					ValidateNameValueCollection ("Form", form, RequestValidationSource.Form);
+					if (!lazyFormValidation) {
+						// Setting this before calling the validator prevents
+						// possible endless recursion
+						checked_form = true;
+						ValidateNameValueCollection ("Form", form, RequestValidationSource.Form);
+					}
 				} else
 #endif
 					if (validate_form && !checked_form){
@@ -1123,7 +1139,7 @@ namespace System.Web
 			}
 		}
 
-		public NameValueCollection QueryString {
+		internal WebROCollection QueryStringUnvalidated {
 			get {
 				if (query_string_nvc == null) {
 					query_string_nvc = new WebROCollection ();
@@ -1137,12 +1153,22 @@ namespace System.Web
 					
 					query_string_nvc.Protect();
 				}
+
+				return query_string_nvc;
+			}
+		}
+		
+		public NameValueCollection QueryString {
+			get {
+				NameValueCollection query_string_nvc = QueryStringUnvalidated;
 #if NET_4_0
 				if (validateRequestNewMode && !checked_query_string) {
-					// Setting this before calling the validator prevents
-					// possible endless recursion
-					checked_query_string = true;
-					ValidateNameValueCollection ("QueryString", query_string_nvc, RequestValidationSource.QueryString);
+					if (!lazyQueryStringValidation) {
+						// Setting this before calling the validator prevents
+						// possible endless recursion
+						checked_query_string = true;
+						ValidateNameValueCollection ("QueryString", query_string_nvc, RequestValidationSource.QueryString);
+					}
 				} else
 #endif
 					if (validate_query_string && !checked_query_string) {
@@ -1361,9 +1387,9 @@ namespace System.Web
 					baseVirtualDir = appVirtualPath;
 				virtualPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (baseVirtualDir), virtualPath);
 				if (!VirtualPathUtility.IsAbsolute (virtualPath))
-					virtualPath = VirtualPathUtility.ToAbsolute (virtualPath);
+					virtualPath = VirtualPathUtility.ToAbsolute (virtualPath, false);
 			} else if (!VirtualPathUtility.IsAbsolute (virtualPath))
-				virtualPath = VirtualPathUtility.ToAbsolute (virtualPath);
+				virtualPath = VirtualPathUtility.ToAbsolute (virtualPath, false);
 
 			bool isAppVirtualPath = String.Compare (virtualPath, appVirtualPath, RuntimeHelpers.StringComparison) == 0;
 			appVirtualPath = VirtualPathUtility.AppendTrailingSlash (appVirtualPath);
@@ -1437,6 +1463,9 @@ namespace System.Web
 			validate_cookies = true;
 			validate_query_string = true;
 			validate_form = true;
+#if NET_4_0
+			inputValidationEnabled = true;
+#endif
 		}
 #if NET_4_0
 		internal void Validate ()
@@ -1462,6 +1491,9 @@ namespace System.Web
 						);
 				}
 			}
+
+			if (validateRequestNewMode)
+				ValidateInput ();
 		}
 #endif
 #region internal routines
@@ -1526,7 +1558,23 @@ namespace System.Web
 			string path = UrlComponents.Path;
 			UrlComponents.Path = path + PathInfo;
 		}
+#if NET_4_0
+		internal void SetFormCollection (WebROCollection coll, bool lazyValidation)
+		{
+			if (coll == null)
+				return;
+			form = coll;
+			lazyFormValidation = lazyValidation;
+		}
 
+		internal void SetQueryStringCollection (WebROCollection coll, bool lazyValidation)
+		{
+			if (coll == null)
+				return;
+			query_string_nvc = coll;
+			lazyQueryStringValidation = lazyValidation;
+		}
+#endif
 		// Headers is ReadOnly, so we need this hack for cookie-less sessions.
 		internal void SetHeader (string name, string value)
 		{
@@ -1667,12 +1715,23 @@ namespace System.Web
 		
 			throw new HttpRequestValidationException (msg);
 		}
-
-
+#if NET_4_0
+		internal static void ValidateString (string key, string value, RequestValidationSource source)
+		{
+			if (String.IsNullOrEmpty (value))
+				return;
+#pragma warning disable 219
+			int ignore;
+#pragma warning restore 219
+			if (IsInvalidString (value, out ignore))
+				ThrowValidationException (source.ToString (), key, value);
+		}
+#endif
 		internal static bool IsInvalidString (string val)
 		{
+#pragma warning disable 219
 			int validationFailureIndex;
-
+#pragma warning restore 219
 			return IsInvalidString (val, out validationFailureIndex);
 		}
 
diff --git a/mcs/class/System.Web/System.Web/VirtualPathUtility.cs b/mcs/class/System.Web/System.Web/VirtualPathUtility.cs
index a58a8fe..12bcf8a 100644
--- a/mcs/class/System.Web/System.Web/VirtualPathUtility.cs
+++ b/mcs/class/System.Web/System.Web/VirtualPathUtility.cs
@@ -253,7 +253,7 @@ namespace System.Web {
 			if (virtualPath.Length == 1 && virtualPath [0] == '~')
 				return apppath;
 
-			return ToAbsolute (virtualPath,apppath);
+			return ToAbsolute (virtualPath, apppath, normalize);
 		}
 
 		// If virtualPath is: 
diff --git a/mcs/class/System.Web/System.Web_test.dll.sources b/mcs/class/System.Web/System.Web_test.dll.sources
index c3349a1..fd634af 100644
--- a/mcs/class/System.Web/System.Web_test.dll.sources
+++ b/mcs/class/System.Web/System.Web_test.dll.sources
@@ -379,6 +379,7 @@ System.Web.Security/FormsAuthenticationEventArgsCas.cs
 System.Web.Security/FormsAuthenticationModuleCas.cs
 System.Web.Security/FormsAuthenticationTicketCas.cs
 System.Web.Security/FormsIdentityCas.cs
+System.Web.Security/MachineKeyTest.cs
 System.Web.Security/PassportAuthenticationEventArgsCas.cs
 System.Web.Security/PassportAuthenticationModuleCas.cs
 System.Web.Security/PassportIdentityCas.cs
diff --git a/mcs/class/System.Web/Test/System.Web.Compilation/BuildManagerTest.cs b/mcs/class/System.Web/Test/System.Web.Compilation/BuildManagerTest.cs
index 88eafa0..7a748e6 100644
--- a/mcs/class/System.Web/Test/System.Web.Compilation/BuildManagerTest.cs
+++ b/mcs/class/System.Web/Test/System.Web.Compilation/BuildManagerTest.cs
@@ -43,6 +43,7 @@ namespace MonoTests.System.Web.Compilation
 	{
 #if NET_4_0
 		[Test]
+		[Ignore ("Pending investigation if it is indeed the correct test.")]
 		public void GetGlobalAsaxType ()
 		{
 			AssertExtensions.Throws<InvalidOperationException> (() => {
diff --git a/mcs/class/System.Web/Test/System.Web.Compilation/ChangeLog b/mcs/class/System.Web/Test/System.Web.Compilation/ChangeLog
index f865761..aecd4db 100644
--- a/mcs/class/System.Web/Test/System.Web.Compilation/ChangeLog
+++ b/mcs/class/System.Web/Test/System.Web.Compilation/ChangeLog
@@ -1,3 +1,17 @@
+2011-01-24  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Global.asax assembly must be passed as reference when
+	compiling. BuildManager.GetType improvements.
+
+	When user has their own global application class (global.asax is
+	present) the assembly produced from it must be passed as reference
+	to the compiler. BuildManager.GetType now supports fully-qualified
+	type names for 'typeName' and searches for the type in the
+	top-level assemblies, the global.asax assembly and in the
+	assemblies specified in as references in web.config.
+
+	All of this fixes certain MVC3+Razor applications.
+
 2011-01-10  Marek Safar  <marek.safar at gmail.com>
 
 	Fixed more protected internal modifiers
diff --git a/mcs/class/System.Web/Test/System.Web.Security/ChangeLog b/mcs/class/System.Web/Test/System.Web.Security/ChangeLog
index f3655f3..bde6c23 100644
--- a/mcs/class/System.Web/Test/System.Web.Security/ChangeLog
+++ b/mcs/class/System.Web/Test/System.Web.Security/ChangeLog
@@ -1,3 +1,8 @@
+2011-01-31  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Implemented 4.0 types
+	System.Web.Security.{MachineKey,MachineKeyProtection} plus tests
+
 2010-10-27  Marek Habersack  <grendel at twistedcode.net>
 
 	[asp.net] Fix for bug #643847. Membership.CreateUser overloads
diff --git a/mcs/class/System.Web/Test/System.Web.Security/MachineKeyTest.cs b/mcs/class/System.Web/Test/System.Web.Security/MachineKeyTest.cs
new file mode 100644
index 0000000..f00e5c5
--- /dev/null
+++ b/mcs/class/System.Web/Test/System.Web.Security/MachineKeyTest.cs
@@ -0,0 +1,171 @@
+//
+// Authors:
+//   Marek Habersack <grendel at twistedcode.net>
+//
+// (C) 2011 Novell, Inc (http://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.
+//
+#if NET_4_0
+using System;
+using System.Text;
+using System.Web.Security;
+
+using MonoTests.Common;
+using NUnit.Framework;
+
+namespace MonoTests.System.Web.Security
+{
+	[TestFixture]
+	public class MachineKeyTest
+	{
+		[Test]
+		[MonoTODO ("Find out why the difference in result sizes exists between .NET and Mono")]
+		public void Encode ()
+		{
+#if DOT_NET
+			const int ALL_EXPECTED_SIZE = 192;
+			const int ENCRYPTION_EXPECTED_SIZE = 128;
+#else
+			const int ALL_EXPECTED_SIZE = 128;
+			const int ENCRYPTION_EXPECTED_SIZE = 64;
+#endif
+			const int VALIDATION_EXPECTED_SIZE = 64;
+			
+			AssertExtensions.Throws<ArgumentNullException> (() => {
+				MachineKey.Encode (null, MachineKeyProtection.All);
+			}, "#A1-1");
+
+			string result = MachineKey.Encode (new byte[] {}, (MachineKeyProtection)12345);
+			Assert.IsNotNull (result, "#A1-1");
+			Assert.AreEqual (0, result.Length, "#A1-2");
+
+			result = MachineKey.Encode (new byte[] {}, MachineKeyProtection.All);
+			Assert.IsNotNull (result, "#B1-1");
+			Assert.AreEqual (ALL_EXPECTED_SIZE, result.Length, "#B1-2");
+
+			result = MachineKey.Encode (new byte [] { }, MachineKeyProtection.Encryption);
+			Assert.IsNotNull (result, "#C1-1");
+			Assert.AreEqual (ENCRYPTION_EXPECTED_SIZE, result.Length, "#C1-2");
+
+			result = MachineKey.Encode (new byte [] { }, MachineKeyProtection.Validation);
+			Assert.IsNotNull (result, "#D1-1");
+			Assert.AreEqual (VALIDATION_EXPECTED_SIZE, result.Length, "#D1-2");
+		}
+
+		[Test]
+		public void Decode ()
+		{
+			byte[] decoded;
+
+			AssertExtensions.Throws<ArgumentNullException> (() => {
+				MachineKey.Decode (null, MachineKeyProtection.All);
+			}, "#A1-1");
+
+			AssertExtensions.Throws<ArgumentException> (() => {
+				decoded = MachineKey.Decode (String.Empty, MachineKeyProtection.All);
+			}, "#A1-2");
+
+			var sb = new StringBuilder ().Append ('0', 192);
+			decoded = MachineKey.Decode (sb.ToString (), (MachineKeyProtection)12345);
+			Assert.IsNotNull (decoded, "#A2-1");
+			Assert.AreEqual (96, decoded.Length, "#A2-2");
+
+			sb = new StringBuilder ().Append ('0', 128);
+			decoded = MachineKey.Decode (sb.ToString (), (MachineKeyProtection) 12345);
+			Assert.IsNotNull (decoded, "#A3-1");
+			Assert.AreEqual (64, decoded.Length, "#A3-2");
+
+			sb = new StringBuilder ().Append ('0', 96);
+			decoded = MachineKey.Decode (sb.ToString (), (MachineKeyProtection) 12345);
+			Assert.IsNotNull (decoded, "#A4-1");
+			Assert.AreEqual (48, decoded.Length, "#A4-2");
+
+			sb = new StringBuilder ().Append ('0', 10);
+			decoded = MachineKey.Decode (sb.ToString (), (MachineKeyProtection) 12345);
+			Assert.IsNotNull (decoded, "#A5-1");
+			Assert.AreEqual (5, decoded.Length, "#A5-2");
+
+			AssertExtensions.Throws<ArgumentException> (() => {
+				decoded = MachineKey.Decode ("test", MachineKeyProtection.All);
+			}, "#B1-1");
+
+			AssertExtensions.Throws<ArgumentException> (() => {
+				decoded = MachineKey.Decode ("test", MachineKeyProtection.Encryption);
+			}, "#B1-2");
+
+			AssertExtensions.Throws<ArgumentException> (() => {
+				decoded = MachineKey.Decode ("test", MachineKeyProtection.Validation);
+			}, "#B1-3");
+
+			sb = new StringBuilder ().Append ('0', 1);
+			try {
+				decoded = MachineKey.Decode (sb.ToString (), MachineKeyProtection.All);
+				Assert.Fail ("#C1-2 [no exception]");
+			} catch (ArgumentException) {
+				// success
+			} catch {
+				Assert.Fail ("#C1-2 [invalid exception]");
+			}
+
+			sb = new StringBuilder ().Append ('0', 2);
+			try {
+				decoded = MachineKey.Decode (sb.ToString (), MachineKeyProtection.All);
+			} catch (ArgumentException ex) {
+				Console.WriteLine (ex);
+				Assert.Fail ("#C1-3");
+			} catch {
+				// success
+			}
+
+			sb = new StringBuilder ().Append ('0', 193);
+			try {
+				decoded = MachineKey.Decode (sb.ToString (), MachineKeyProtection.All);
+				Assert.Fail ("#C2-1 [no exception]");
+			} catch (ArgumentException) {
+				// success
+			} catch {
+				Assert.Fail ("#C2-1 [invalid exception]");
+			}
+
+			sb = new StringBuilder ().Append ('0', 129);
+			try {
+				decoded = MachineKey.Decode (sb.ToString (), MachineKeyProtection.All);
+				Assert.Fail ("#C3-1 [no exception]");
+			} catch (ArgumentException) {
+				// success
+			} catch {
+				Assert.Fail ("#C3-2 [invalid exception]");
+			}
+
+			sb = new StringBuilder ().Append ('0', 64);
+			try {
+				decoded = MachineKey.Decode (sb.ToString (), MachineKeyProtection.All);
+			} catch (ArgumentException) {
+				Assert.Fail ("#C4-1");
+			} catch {
+				// Success
+			}
+		}
+	}
+}
+#endif
\ No newline at end of file
diff --git a/mcs/class/System.Web/Test/mainsoft/NunitWeb/NunitWeb/ChangeLog b/mcs/class/System.Web/Test/mainsoft/NunitWeb/NunitWeb/ChangeLog
index 80c0bfa..136f519 100644
--- a/mcs/class/System.Web/Test/mainsoft/NunitWeb/NunitWeb/ChangeLog
+++ b/mcs/class/System.Web/Test/mainsoft/NunitWeb/NunitWeb/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-20  Marek Habersack  <grendel at twistedcode.net>
+
+	[asp.net] Avoid passing duplicate assemblies on mcs command line.
+
 2011-01-10  Marek Safar  <marek.safar at gmail.com>
 
 	Fixed another missing protected internal modifier
diff --git a/mcs/class/System.Web/Test/mainsoft/NunitWeb/NunitWeb/WebTest.cs b/mcs/class/System.Web/Test/mainsoft/NunitWeb/NunitWeb/WebTest.cs
index 3496770..d7d386c 100644
--- a/mcs/class/System.Web/Test/mainsoft/NunitWeb/NunitWeb/WebTest.cs
+++ b/mcs/class/System.Web/Test/mainsoft/NunitWeb/NunitWeb/WebTest.cs
@@ -544,7 +544,7 @@ namespace MonoTests.SystemWeb.Framework
 
 		private static void CopyAssembly (Assembly ass, string dir)
 		{
-			if (ass.GlobalAssemblyCache)
+			if (ass.GlobalAssemblyCache || ass.FullName.StartsWith ("mscorlib"))
 				return;
 			string oldfn = ass.Location;
 			if (oldfn.EndsWith (".exe"))
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 0cd8a34..fa07f81 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
@@ -18,6 +18,8 @@ System.Web.Compilation/FolderLevelBuildProviderAppliesTo.cs
 System.Web.Compilation/FolderLevelBuildProviderAppliesToAttribute.cs
 System.Web.Compilation/RouteUrlExpressionBuilder.cs
 System.Web.Compilation/RouteValueExpressionBuilder.cs
+System.Web.Security/MachineKey.cs
+System.Web.Security/MachineKeyProtection.cs
 System.Web.SessionState_2.0/SessionStateBehavior.cs
 System.Web.Routing/PageRouteHandler.cs
 System.Web.UI/ClientIDMode.cs
@@ -37,6 +39,7 @@ System.Web.UI.WebControls/RouteParameter.cs
 System.Web.UI.WebControls/StyleBlock.cs
 System.Web.UI.WebControls/WizardLayoutContainer.cs
 System.Web.UI.WebControls/WizardLayoutNavigationContainer.cs
+System.Web.Util/SimpleWebObjectFactory.cs
 System.Web.Util/RequestValidationSource.cs
 System.Web.Util/RequestValidator.cs
 
diff --git a/mcs/class/System.XML/Mono.Xml.Schema/ChangeLog b/mcs/class/System.XML/Mono.Xml.Schema/ChangeLog
index b37b4bd..07cba21 100644
--- a/mcs/class/System.XML/Mono.Xml.Schema/ChangeLog
+++ b/mcs/class/System.XML/Mono.Xml.Schema/ChangeLog
@@ -1,3 +1,11 @@
+2011-02-08  Atsushi Eno  <atsushi at ximian.com>
+
+	Simple content restriction was not validated when it is in further
+	reference.
+
+	Fixed bug #595947. It was complexType [base]-> complexType
+	[base]-> simpleType.
+
 2010-11-29  Atsushi Eno  <atsushi at ximian.com>
 
 	Return different instances of XmlSchemaInfo for each validated
diff --git a/mcs/class/System.XML/Mono.Xml.Schema/XsdValidatingReader.cs b/mcs/class/System.XML/Mono.Xml.Schema/XsdValidatingReader.cs
index 8eea3d3..2e2637f 100644
--- a/mcs/class/System.XML/Mono.Xml.Schema/XsdValidatingReader.cs
+++ b/mcs/class/System.XML/Mono.Xml.Schema/XsdValidatingReader.cs
@@ -523,6 +523,16 @@ namespace Mono.Xml.Schema
 					dt = st.Datatype;
 				} else {
 					ComplexType ct = Context.ActualType as ComplexType;
+					var ctsm = ct.ContentModel as XmlSchemaSimpleContent;
+					if (ctsm != null) {
+						var scr = ctsm.Content as XmlSchemaSimpleContentRestriction;
+						if (scr != null)
+							st = FindSimpleBaseType (scr.BaseType ?? FindType (scr.BaseTypeName));
+						var sce = ctsm.Content as XmlSchemaSimpleContentExtension;
+						if (sce != null)
+							st = FindSimpleBaseType (FindType (sce.BaseTypeName));
+					}
+
 					dt = ct.Datatype;
 					switch (ct.ContentType) {
 					case XmlSchemaContentType.ElementOnly:
@@ -552,6 +562,16 @@ namespace Mono.Xml.Schema
 			shouldValidateCharacters = false;
 		}
 
+		SimpleType FindSimpleBaseType (XmlSchemaType xt)
+		{
+			var st = xt as SimpleType;
+			if (st != null)
+				return st;
+			if (xt == null)
+				return null;
+			return FindSimpleBaseType (xt.BaseXmlSchemaType);
+		}
+
 		// 3.14.4 String Valid 
 		private void AssessStringValid (SimpleType st,
 			XsDatatype dt, string value)
diff --git a/mcs/class/System.XML/System.Xml.Schema/ChangeLog b/mcs/class/System.XML/System.Xml.Schema/ChangeLog
index 4baa422..9d015ce 100644
--- a/mcs/class/System.XML/System.Xml.Schema/ChangeLog
+++ b/mcs/class/System.XML/System.Xml.Schema/ChangeLog
@@ -1,3 +1,28 @@
+2011-01-31  Atsushi Eno  <atsushi at ximian.com>
+
+	Fix bug #661400 - fix complicated namespace resolution issue.
+
+	Namespaces in nested external schemas have to be validated against
+	immediately-containing schema. If there is a schema A with urn:x
+	targetNamespace imports a schema B with urn:y targetNamespace
+	which in turn includes another schema C, then C must be validated
+	its namespace against B, not A.
+
+2011-02-08  Atsushi Eno  <atsushi at ximian.com>
+
+	Simple content restriction was not validated when it is in further
+	reference.
+
+	Fixed bug #595947. It was complexType [base]-> complexType
+	[base]-> simpleType.
+
+2011-02-08  Atsushi Eno  <atsushi at ximian.com>
+
+	For complexType simpleContent restriction, fill attributes from
+	base type.
+
+	Part of bugfix #595947.
+
 2010-11-30  Atsushi Eno  <atsushi at ximian.com>
 
 	Use AttributeSchemaType as it is 2.0 API. This fixes incorrectly
diff --git a/mcs/class/System.XML/System.Xml.Schema/XmlSchema.cs b/mcs/class/System.XML/System.Xml.Schema/XmlSchema.cs
index 04d59d3..109ba90 100644
--- a/mcs/class/System.XML/System.Xml.Schema/XmlSchema.cs
+++ b/mcs/class/System.XML/System.Xml.Schema/XmlSchema.cs
@@ -92,6 +92,7 @@ namespace System.Xml.Schema
 			groups = new XmlSchemaObjectTable();
 			notations = new XmlSchemaObjectTable();
 			schemaTypes = new XmlSchemaObjectTable();
+			compilationItems = new XmlSchemaObjectCollection ();
 		}
 
 		#region Properties
@@ -360,7 +361,6 @@ namespace System.Xml.Schema
 
 			// Compile the content of this schema
 
-			compilationItems = new XmlSchemaObjectCollection ();
 			for (int i = 0; i < Items.Count; i++) {
 				compilationItems.Add (Items [i]);
 			}
@@ -574,7 +574,7 @@ namespace System.Xml.Schema
 			} else if (includedSchema != null) {
 				if (TargetNamespace == null && 
 					includedSchema.TargetNamespace != null) {
-					error (handler, "Target namespace is required to include a schema which has its own target namespace");
+					includedSchema.error (handler, String.Format ("On {0} element, targetNamespace is required to include a schema which has its own target namespace", ext.GetType ().Name));
 					return;
 				}
 				else if (TargetNamespace != null && 
@@ -591,11 +591,13 @@ namespace System.Xml.Schema
 		void AddExternalComponentsTo (XmlSchema s, XmlSchemaObjectCollection items, ValidationEventHandler handler, Hashtable handledUris, XmlResolver resolver, XmlSchemaSet col)
 		{
 			foreach (XmlSchemaExternal ext in s.Includes)
-				ProcessExternal (handler, handledUris, resolver, ext, col);
-//				if (ext.Schema != null)
-//					AddExternalComponentsTo (ext.Schema, items);
-			foreach (XmlSchemaObject obj in s.Items)
+				s.ProcessExternal (handler, handledUris, resolver, ext, col);
+			foreach (XmlSchemaObject obj in s.compilationItems)
 				items.Add (obj);
+			// Items might be already resolved (recursive schema imports), or might not be (other cases), so we add items only when appropriate here. (duplicate check is anyways done elsewhere)
+			foreach (XmlSchemaObject obj in s.Items)
+				if (!items.Contains (obj))
+					items.Add (obj);
 		}
 
 		internal bool IsNamespaceAbsent (string ns)
diff --git a/mcs/class/System.XML/System.Xml.Schema/XmlSchemaComplexType.cs b/mcs/class/System.XML/System.Xml.Schema/XmlSchemaComplexType.cs
index 9ee6609..d53928f 100644
--- a/mcs/class/System.XML/System.Xml.Schema/XmlSchemaComplexType.cs
+++ b/mcs/class/System.XML/System.Xml.Schema/XmlSchemaComplexType.cs
@@ -857,11 +857,12 @@ namespace System.Xml.Schema
 			}
 			// complexType/simpleContent/restriction
 			if (scr != null) {
-				// Attributes
-				baseAnyAttribute = baseComplexType != null ? baseComplexType.AttributeWildcard : null;
-
+				// attributes
 				localAnyAttribute = scr.AnyAttribute;
-				if (localAnyAttribute != null && baseAnyAttribute != null)
+				this.attributeWildcard = localAnyAttribute;
+				if (baseComplexType != null)
+					baseAnyAttribute = baseComplexType.AttributeWildcard;
+				if (baseAnyAttribute != null && localAnyAttribute != null)
 					// 1.3 attribute wildcard subset. (=> 3.10.6)
 					localAnyAttribute.ValidateWildcardSubset (baseAnyAttribute, h, schema);
 				// 3.4.6 :: 5.1. Beware that There is an errata for 5.1!!
@@ -872,6 +873,11 @@ namespace System.Xml.Schema
 				errorCount += XmlSchemaUtil.ValidateAttributesResolved (
 					this.attributeUses, h, schema, scr.Attributes, 
 					scr.AnyAttribute, ref attributeWildcard, null, false);
+				foreach (DictionaryEntry entry in baseComplexType.AttributeUses) {
+					XmlSchemaAttribute attr = (XmlSchemaAttribute) entry.Value;
+					if (attributeUses [attr.QualifiedName] == null)
+						XmlSchemaUtil.AddToTable (attributeUses, attr, attr.QualifiedName, h);
+				}
 			}
 
 			// Common process of AttributeWildcard.
diff --git a/mcs/class/System.XML/System.Xml.Schema/XmlSchemaValidator.cs b/mcs/class/System.XML/System.Xml.Schema/XmlSchemaValidator.cs
index 602287a..727004d 100644
--- a/mcs/class/System.XML/System.Xml.Schema/XmlSchemaValidator.cs
+++ b/mcs/class/System.XML/System.Xml.Schema/XmlSchemaValidator.cs
@@ -1026,6 +1026,16 @@ namespace System.Xml.Schema
 					dt = st.Datatype;
 				} else {
 					ComplexType ct = Context.ActualType as ComplexType;
+					var ctsm = ct.ContentModel as XmlSchemaSimpleContent;
+					if (ctsm != null) {
+						var scr = ctsm.Content as XmlSchemaSimpleContentRestriction;
+						if (scr != null)
+							st = FindSimpleBaseType (scr.BaseType ?? FindType (scr.BaseTypeName));
+						var sce = ctsm.Content as XmlSchemaSimpleContentExtension;
+						if (sce != null)
+							st = FindSimpleBaseType (FindType (sce.BaseTypeName));
+					}
+
 					dt = ct.Datatype;
 					switch (ct.ContentType) {
 					case XmlSchemaContentType.ElementOnly:
@@ -1069,6 +1079,16 @@ namespace System.Xml.Schema
 			return ret;
 		}
 
+		SimpleType FindSimpleBaseType (XmlSchemaType xt)
+		{
+			var st = xt as SimpleType;
+			if (st != null)
+				return st;
+			if (xt == null)
+				return null;
+			return FindSimpleBaseType (xt.BaseXmlSchemaType);
+		}
+
 		// 3.14.4 String Valid 
 		private object AssessStringValid (SimpleType st,
 			XsDatatype dt, string value)
diff --git a/mcs/class/System.XML/System.Xml/ChangeLog b/mcs/class/System.XML/System.Xml/ChangeLog
index 752d1e5..2b51eb7 100644
--- a/mcs/class/System.XML/System.Xml/ChangeLog
+++ b/mcs/class/System.XML/System.Xml/ChangeLog
@@ -1,3 +1,21 @@
+2011-02-03  Marek Habersack  <grendel at twistedcode.net>
+
+	[xml]
+	XmlReaderSettings.{DtdProcessing,MaxCharactersFromEntities,MaxCharactersInDocument}
+	are present in 3.5+
+
+	With the exception of DtdProcessing, the properties are part of
+	.NET 3.5+. DtdProcessing appeared in 4.0.
+
+2011-01-31  Atsushi Eno  <atsushi at ximian.com>
+
+	Do not return DocumentFragment from AppendChild() etc. Fixed bug
+	#666249.
+
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
 2011-01-06  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
 
 	Revert
diff --git a/mcs/class/System.XML/System.Xml/XmlNode.cs b/mcs/class/System.XML/System.Xml/XmlNode.cs
index 115d778..3dc9cea 100644
--- a/mcs/class/System.XML/System.Xml/XmlNode.cs
+++ b/mcs/class/System.XML/System.Xml/XmlNode.cs
@@ -540,10 +540,13 @@ namespace System.Xml
 
 			if (newChild.NodeType == XmlNodeType.DocumentFragment) {
 				// This recursively invokes events. (It is compatible with MS implementation.)
-				while (newChild.FirstChild != null)
-					this.InsertBefore (newChild.FirstChild, refChild);
-			}
-			else {
+				XmlNode ret = null;
+				while (newChild.FirstChild != null) {
+					var c = this.InsertBefore (newChild.FirstChild, refChild);
+					ret = ret ?? c;
+				}
+				return ret;
+			} else {
 				XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
 				newLinkedChild.parentNode = this;
 
@@ -585,8 +588,8 @@ namespace System.Xml
 
 				if (raiseEvent)
 					ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
+				return newChild;
 			}
-			return newChild;
 		}
 
 		private void CheckNodeInsertion (XmlNode newChild, XmlNode refChild)
diff --git a/mcs/class/System.XML/System.Xml/XmlReaderSettings.cs b/mcs/class/System.XML/System.Xml/XmlReaderSettings.cs
index 0ae140e..b209cae 100644
--- a/mcs/class/System.XML/System.Xml/XmlReaderSettings.cs
+++ b/mcs/class/System.XML/System.Xml/XmlReaderSettings.cs
@@ -60,11 +60,11 @@ namespace System.Xml
 		private ValidationType validationType;
 #endif
 		private XmlResolver xmlResolver;
-#if MOONLIGHT || NET_4_0
+#if NET_4_0
 		private DtdProcessing dtdProcessing;
+#endif
 		private long maxCharactersFromEntities;
 		private long maxCharactersInDocument;
-#endif
 
 		public XmlReaderSettings ()
 		{
@@ -118,7 +118,7 @@ namespace System.Xml
 			get { return conformance; }
 			set { conformance = value; }
 		}
-#if MOONLIGHT || NET_4_0
+#if NET_4_0
 		public DtdProcessing DtdProcessing {
 			get { return dtdProcessing; }
 			set {
@@ -126,7 +126,7 @@ namespace System.Xml
 				prohibitDtd = (value == DtdProcessing.Prohibit);
 			}
 		}
-
+#endif
 		public long MaxCharactersFromEntities {
 			get { return maxCharactersFromEntities; }
 			set { maxCharactersFromEntities = value; }
@@ -137,7 +137,6 @@ namespace System.Xml
 			get { return maxCharactersInDocument; }
 			set { maxCharactersInDocument = value; }
 		}
-#endif
 
 		public bool IgnoreComments {
 			get { return ignoreComments; }
diff --git a/mcs/class/System.XML/System.Xml/XmlWriterSettings.cs b/mcs/class/System.XML/System.Xml/XmlWriterSettings.cs
index 62a1640..7d8fa4f 100644
--- a/mcs/class/System.XML/System.Xml/XmlWriterSettings.cs
+++ b/mcs/class/System.XML/System.Xml/XmlWriterSettings.cs
@@ -155,7 +155,7 @@ namespace System.Xml
 			//set { outputMethod = value; }
 		}
 
-#if MOONLIGHT || NET_4_0
+#if MOONLIGHT || MOBILE || NET_4_0
 		public
 #else
 		internal
diff --git a/mcs/class/System.XML/Test/System.Xml.Schema/ChangeLog b/mcs/class/System.XML/Test/System.Xml.Schema/ChangeLog
index 2cfab9e..cbf2e0a 100644
--- a/mcs/class/System.XML/Test/System.Xml.Schema/ChangeLog
+++ b/mcs/class/System.XML/Test/System.Xml.Schema/ChangeLog
@@ -1,3 +1,21 @@
+2011-01-31  Atsushi Eno  <atsushi at ximian.com>
+
+	Fix bug #661400 - fix complicated namespace resolution issue.
+
+	Namespaces in nested external schemas have to be validated against
+	immediately-containing schema. If there is a schema A with urn:x
+	targetNamespace imports a schema B with urn:y targetNamespace
+	which in turn includes another schema C, then C must be validated
+	its namespace against B, not A.
+
+2011-02-08  Atsushi Eno  <atsushi at ximian.com>
+
+	Simple content restriction was not validated when it is in further
+	reference.
+
+	Fixed bug #595947. It was complexType [base]-> complexType
+	[base]-> simpleType.
+
 2010-11-16  myeisha  <github at quasiparticle.net>
 
 	Add testcase for multiple missing IDs
diff --git a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaTests.cs b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaTests.cs
index cc8eed2..0e91387 100644
--- a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaTests.cs
+++ b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaTests.cs
@@ -627,5 +627,12 @@ namespace MonoTests.System.Xml
 			while (reader.Read()) {}
 		}
 #endif
+
+		[Test]
+		public void TestImportSchemaThatIncludesAnother ()
+		{
+			XmlSchema xs = GetSchema ("Test/XmlFiles/xsd/importNamespaceTest2.xsd");
+			xs.Compile (null);
+		}
 	}
 }
diff --git a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaValidatorTests.cs b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaValidatorTests.cs
index 9d5da5f..01a0840 100644
--- a/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaValidatorTests.cs
+++ b/mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaValidatorTests.cs
@@ -328,6 +328,45 @@ namespace MonoTests.System.Xml
 			document.Schemas.Add (schema);
 			document.Validate (null);
 		}
+
+		[Test]
+		public void FacetsOnBaseSimpleContentRestriction ()
+		{
+			XmlReaderSettings settings = new XmlReaderSettings ();
+			settings.Schemas.Add (null, "Test/XmlFiles/595947.xsd");
+			settings.ValidationType = ValidationType.Schema;
+			settings.Schemas.Compile ();
+
+			Validate ("TEST 1.1", 1, "0123456789", "0123456789", settings, false);
+			Validate ("TEST 1.2", 1, "0123456789***", "0123456789", settings, true);
+			Validate ("TEST 1.3", 1, "0123456789", "0123456789***", settings, true);
+
+			Validate ("TEST 2.1", 2, "0123456789", "0123456789", settings, false);
+			Validate ("TEST 2.2", 2, "0123456789***", "0123456789", settings, true);
+			Validate ("TEST 2.3", 2, "0123456789", "0123456789***", settings, true);
+
+			Validate ("TEST 3.1", 3, "0123456789", "0123456789", settings, false);
+			Validate ("TEST 3.2", 3, "0123456789***", "0123456789", settings, true);
+			Validate ("TEST 3.3", 3, "0123456789", "0123456789***", settings, true);
+		}
+
+		void Validate (string testName, int testNumber, string idValue, string elementValue, XmlReaderSettings settings, bool shouldFail)
+		{
+			string content = string.Format ("<MyTest{0} Id=\"{1}\">{2}</MyTest{0}>", testNumber, idValue, elementValue);
+			try
+			{
+				XmlReader reader = XmlReader.Create (new StringReader (content), settings);
+				XmlDocument document = new XmlDocument ();
+				document.Load (reader);
+				document.Validate (null);
+			} catch (Exception e) {
+				if (!shouldFail)
+					throw;
+				return;
+			}
+			if (shouldFail)
+				Assert.Fail (testName + " should fail");
+		}
 	}
 }
 
diff --git a/mcs/class/System.XML/Test/System.Xml/ChangeLog b/mcs/class/System.XML/Test/System.Xml/ChangeLog
index 6357fd8..04bcede 100644
--- a/mcs/class/System.XML/Test/System.Xml/ChangeLog
+++ b/mcs/class/System.XML/Test/System.Xml/ChangeLog
@@ -1,3 +1,8 @@
+2011-01-31  Atsushi Eno  <atsushi at ximian.com>
+
+	Do not return DocumentFragment from AppendChild() etc. Fixed bug
+	#666249.
+
 2011-01-05  Atsushi Eno  <atsushi at ximian.com>
 
 	Fix ToDateTime() with serialization mode to not mess hour based on
diff --git a/mcs/class/System.XML/Test/System.Xml/XmlDocumentFragmentTests.cs b/mcs/class/System.XML/Test/System.Xml/XmlDocumentFragmentTests.cs
index c61f72d..5b45029 100644
--- a/mcs/class/System.XML/Test/System.Xml/XmlDocumentFragmentTests.cs
+++ b/mcs/class/System.XML/Test/System.Xml/XmlDocumentFragmentTests.cs
@@ -57,11 +57,12 @@ namespace MonoTests.System.Xml
 			fragment.AppendChild (document.CreateElement ("div"));
 
 			// appending fragment to element
-			body.AppendChild (fragment);
+			XmlNode ret = body.AppendChild (fragment);
 			Assert.IsNotNull (body.FirstChild, "#AppendFragmentToElement.Exist");
 			Assert.AreEqual (XmlNodeType.Element, body.FirstChild.NodeType, "#AppendFragmentToElement.ChildIsElement");
 			Assert.AreEqual ("p", body.FirstChild.Name, "#AppendFragmentToElement.FirstChild");
 			Assert.AreEqual ("div", body.LastChild.Name, "#AppendFragmentToElement.LastChild");
+			Assert.AreEqual ("p", ret.LocalName, "#AppendFragmentToElement.ReturnValue");
 		}
 
 		[Test]
diff --git a/mcs/class/System.XML/Test/XmlFiles/ChangeLog b/mcs/class/System.XML/Test/XmlFiles/ChangeLog
index a298d6e..7168041 100644
--- a/mcs/class/System.XML/Test/XmlFiles/ChangeLog
+++ b/mcs/class/System.XML/Test/XmlFiles/ChangeLog
@@ -1,3 +1,11 @@
+2011-02-08  Atsushi Eno  <atsushi at ximian.com>
+
+	Simple content restriction was not validated when it is in further
+	reference.
+
+	Fixed bug #595947. It was complexType [base]-> complexType
+	[base]-> simpleType.
+
 2009-04-22  Atsushi Enomoto <atsushi at ximian.com>
 
 	* 496192.xml, 496192.xsd : new test files.
diff --git a/mcs/class/System.XML/Test/XmlFiles/ChangeLog b/mcs/class/System.XML/Test/XmlFiles/ChangeLog.old
similarity index 100%
copy from mcs/class/System.XML/Test/XmlFiles/ChangeLog
copy to mcs/class/System.XML/Test/XmlFiles/ChangeLog.old
diff --git a/mcs/class/System.XML/Test/XmlFiles/xsd/ChangeLog b/mcs/class/System.XML/Test/XmlFiles/xsd/ChangeLog
index 1ee824d..e24e914 100644
--- a/mcs/class/System.XML/Test/XmlFiles/xsd/ChangeLog
+++ b/mcs/class/System.XML/Test/XmlFiles/xsd/ChangeLog
@@ -1,3 +1,13 @@
+2011-01-31  Atsushi Eno  <atsushi at ximian.com>
+
+	Fix bug #661400 - fix complicated namespace resolution issue.
+
+	Namespaces in nested external schemas have to be validated against
+	immediately-containing schema. If there is a schema A with urn:x
+	targetNamespace imports a schema B with urn:y targetNamespace
+	which in turn includes another schema C, then C must be validated
+	its namespace against B, not A.
+
 2010-03-15  Atsushi Enomoto  <atsushi at ximian.com>
 
 	* 584664b.xsd, 584664a.xml, 584664b.xml, 584664a.xsd: new test files
diff --git a/mcs/class/System.XML/Test/XmlFiles/xsd/ChangeLog b/mcs/class/System.XML/Test/XmlFiles/xsd/ChangeLog.old
similarity index 100%
copy from mcs/class/System.XML/Test/XmlFiles/xsd/ChangeLog
copy to mcs/class/System.XML/Test/XmlFiles/xsd/ChangeLog.old
diff --git a/mcs/class/System.XML/Test/XmlFiles/xsd/imcludedNamespace2.xsd b/mcs/class/System.XML/Test/XmlFiles/xsd/imcludedNamespace2.xsd
new file mode 100644
index 0000000..ee0b2c8
--- /dev/null
+++ b/mcs/class/System.XML/Test/XmlFiles/xsd/imcludedNamespace2.xsd
@@ -0,0 +1,5 @@
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:y"
+  xmlns="urn:y">
+  <xs:element name="foo" />
+</xs:schema>
+
diff --git a/mcs/class/System.XML/Test/XmlFiles/xsd/importNamespaceTest2.xsd b/mcs/class/System.XML/Test/XmlFiles/xsd/importNamespaceTest2.xsd
new file mode 100644
index 0000000..b12e1ce
--- /dev/null
+++ b/mcs/class/System.XML/Test/XmlFiles/xsd/importNamespaceTest2.xsd
@@ -0,0 +1,5 @@
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:x"
+  xmlns="urn:x" xmlns:y="urn:y">
+  <xs:import namespace="urn:y" schemaLocation="importedNamespace2.xsd" />
+  <xs:element name="foo" type="y:foo" />
+</xs:schema>
diff --git a/mcs/class/System.XML/Test/XmlFiles/xsd/importedNamespace2.xsd b/mcs/class/System.XML/Test/XmlFiles/xsd/importedNamespace2.xsd
new file mode 100644
index 0000000..0ea6046
--- /dev/null
+++ b/mcs/class/System.XML/Test/XmlFiles/xsd/importedNamespace2.xsd
@@ -0,0 +1,4 @@
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:y"
+  xmlns="urn:y" xmlns:x="urn:x" />
+  <xs:include schemaLocation="includedNamespace2.xsd" />
+</xs:schema>
diff --git a/mcs/class/System.Xml.Linq/System.Xml.Linq/ChangeLog b/mcs/class/System.Xml.Linq/System.Xml.Linq/ChangeLog
index 20ec53a..20338f1 100644
--- a/mcs/class/System.Xml.Linq/System.Xml.Linq/ChangeLog
+++ b/mcs/class/System.Xml.Linq/System.Xml.Linq/ChangeLog
@@ -1,3 +1,12 @@
+2011-01-31  Atsushi Eno  <atsushi at ximian.com>
+
+	Fixed bug #666872; XElement.Changed and .Changing were not
+	triggered.
+
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
 2010-12-22  Atsushi Eno  <atsushi at ximian.com>
 
 	Fix incorrect internal node cleanup in MoveToRoot(). Fixed bug
diff --git a/mcs/class/System.Xml.Linq/System.Xml.Linq/SaveOptions.cs b/mcs/class/System.Xml.Linq/System.Xml.Linq/SaveOptions.cs
index f0a4d4e..f9065f6 100644
--- a/mcs/class/System.Xml.Linq/System.Xml.Linq/SaveOptions.cs
+++ b/mcs/class/System.Xml.Linq/System.Xml.Linq/SaveOptions.cs
@@ -33,7 +33,7 @@ namespace System.Xml.Linq
 	{
 		None = 0,
 		DisableFormatting = 1,
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		OmitDuplicateNamespaces = 2
 #endif
 	}
diff --git a/mcs/class/System.Xml.Linq/System.Xml.Linq/XContainer.cs b/mcs/class/System.Xml.Linq/System.Xml.Linq/XContainer.cs
index 7a49543..40db239 100644
--- a/mcs/class/System.Xml.Linq/System.Xml.Linq/XContainer.cs
+++ b/mcs/class/System.Xml.Linq/System.Xml.Linq/XContainer.cs
@@ -71,10 +71,16 @@ namespace System.Xml.Linq
 				return;
 
 			foreach (object o in XUtil.ExpandArray (content))
+			{
 				if (!OnAddingObject (o, false, last, false))
+				{
+					OnAddingObject ();
 					AddNode (XUtil.ToNode (o));
+					OnAddedObject ();
+				}
+			}
 		}
-
+		
 		void AddNode (XNode n)
 		{
 			CheckChildType (n, false);
@@ -121,7 +127,7 @@ namespace System.Xml.Linq
 		{
 			return false;
 		}
-
+		
 		public XmlWriter CreateWriter ()
 		{
 			return new XNodeWriter (this);
diff --git a/mcs/class/System.Xml.Linq/System.Xml.Linq/XElement.cs b/mcs/class/System.Xml.Linq/System.Xml.Linq/XElement.cs
index 16c969c..bf3483e 100644
--- a/mcs/class/System.Xml.Linq/System.Xml.Linq/XElement.cs
+++ b/mcs/class/System.Xml.Linq/System.Xml.Linq/XElement.cs
@@ -454,7 +454,7 @@ namespace System.Xml.Linq
 			}
 		}
 
-#if MOONLIGHT || NET_4_0
+#if MOONLIGHT || MOBILE || NET_4_0
 		public static XElement Load (Stream stream)
 		{
 			return Load (stream, LoadOptions.None);
@@ -536,7 +536,7 @@ namespace System.Xml.Linq
 
 			if ((options & SaveOptions.DisableFormatting) == SaveOptions.None)
 				s.Indent = true;
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			if ((options & SaveOptions.OmitDuplicateNamespaces) == SaveOptions.OmitDuplicateNamespaces)
 				s.NamespaceHandling |= NamespaceHandling.OmitDuplicates;
 #endif
@@ -556,7 +556,7 @@ namespace System.Xml.Linq
 			
 			if ((options & SaveOptions.DisableFormatting) == SaveOptions.None)
 				s.Indent = true;
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			if ((options & SaveOptions.OmitDuplicateNamespaces) == SaveOptions.OmitDuplicateNamespaces)
 				s.NamespaceHandling |= NamespaceHandling.OmitDuplicates;
 #endif
@@ -570,7 +570,7 @@ namespace System.Xml.Linq
 			WriteTo (w);
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public void Save (Stream stream)
 		{
 			Save (stream, SaveOptions.None);
diff --git a/mcs/class/System.Xml.Linq/System.Xml.Linq/XObject.cs b/mcs/class/System.Xml.Linq/System.Xml.Linq/XObject.cs
index 1f80220..1bcf96a 100644
--- a/mcs/class/System.Xml.Linq/System.Xml.Linq/XObject.cs
+++ b/mcs/class/System.Xml.Linq/System.Xml.Linq/XObject.cs
@@ -162,5 +162,21 @@ namespace System.Xml.Linq
 			if ((options & LoadOptions.SetBaseUri) != LoadOptions.None)
 				BaseUri = r.BaseURI;
 		}
+		
+		internal virtual void OnAddingObject ()
+		{
+			if (Parent != null)
+				Parent.OnAddingObject ();
+			if (Changing != null)
+				Changing.Invoke (this, null);
+		}
+		
+		internal virtual void OnAddedObject ()
+		{
+			if (Parent != null)
+				Parent.OnAddedObject ();
+			if (Changed != null)
+				Changed.Invoke (this, null);
+		}
 	}
 }
diff --git a/mcs/class/System.Xml.Linq/Test/System.Xml.Linq/ChangeLog b/mcs/class/System.Xml.Linq/Test/System.Xml.Linq/ChangeLog
index 937106c..9de2691 100644
--- a/mcs/class/System.Xml.Linq/Test/System.Xml.Linq/ChangeLog
+++ b/mcs/class/System.Xml.Linq/Test/System.Xml.Linq/ChangeLog
@@ -1,3 +1,8 @@
+2011-01-31  Atsushi Eno  <atsushi at ximian.com>
+
+	Fixed bug #666872; XElement.Changed and .Changing were not
+	triggered.
+
 2010-04-23  Jonathan Pobst  <monkey at jpobst.com>
 
 	* XAttributeTest.cs, XElementTest.cs: Try to standardize DST usage
diff --git a/mcs/class/System.Xml.Linq/Test/System.Xml.Linq/ChangeLog b/mcs/class/System.Xml.Linq/Test/System.Xml.Linq/ChangeLog.old
similarity index 100%
copy from mcs/class/System.Xml.Linq/Test/System.Xml.Linq/ChangeLog
copy to mcs/class/System.Xml.Linq/Test/System.Xml.Linq/ChangeLog.old
diff --git a/mcs/class/System.Xml.Linq/Test/System.Xml.Linq/XElementTest.cs b/mcs/class/System.Xml.Linq/Test/System.Xml.Linq/XElementTest.cs
index b951dc6..67583eb 100644
--- a/mcs/class/System.Xml.Linq/Test/System.Xml.Linq/XElementTest.cs
+++ b/mcs/class/System.Xml.Linq/Test/System.Xml.Linq/XElementTest.cs
@@ -1601,5 +1601,60 @@ namespace MonoTests.System.Xml.Linq
 </rt>";
 			Assert.AreEqual (xml, root.ToString ().Replace ("\r\n", "\n"), "#1");
 		}
+		
+		private class EventHandler
+		{
+			public bool ChangingInvoked { get; private set; }
+			
+			public bool HasChanged { get; private set; }
+			
+			public void OnChanging (object node, XObjectChangeEventArgs args)
+			{
+				ChangingInvoked = true;
+			}
+			
+			public void OnChanged (object node, XObjectChangeEventArgs args)
+			{
+				HasChanged = true;
+			}
+		}
+		
+		[Test]
+		public void Add_ToRootNode_ChangeTriggers ()
+		{
+			var inputXml = "<root><a><b /></a></root>";
+			var reader = XmlReader.Create (new StringReader (inputXml), new XmlReaderSettings ());
+			XDocument doc = XDocument.Load (reader);
+			var eventHandler = new EventHandler ();
+			doc.Root.Changing += eventHandler.OnChanging;
+			doc.Root.Changed += eventHandler.OnChanged;
+			
+			var newElement = XElement.Parse ("<c/>");
+			
+			doc.Root.Add (newElement);
+			
+			Assert.IsTrue (eventHandler.ChangingInvoked, "OnChanging not triggered");
+			Assert.IsTrue (eventHandler.HasChanged, "OnChanged not triggered");
+		}
+
+		[Test]
+		public void Add_ToChildNode_ChangeTriggersOnRoot ()
+		{
+			var inputXml = "<root><a><b /></a></root>";
+			var reader = XmlReader.Create (new StringReader (inputXml), new XmlReaderSettings ());
+			XDocument doc = XDocument.Load (reader);
+			var eventHandler = new EventHandler ();
+			
+			var newElement = XElement.Parse ("<c/>");
+			doc.Root.Add (newElement);
+
+			doc.Root.Changing += eventHandler.OnChanging;
+			doc.Root.Changed += eventHandler.OnChanged;
+			var nextNewElement = XElement.Parse ("<d/>");
+			newElement.Add (nextNewElement);
+			
+			Assert.IsTrue (eventHandler.ChangingInvoked, "OnChanging not triggered");
+			Assert.IsTrue (eventHandler.HasChanged, "OnChanged not triggered");
+		}
 	}
 }
diff --git a/mcs/class/System/ChangeLog b/mcs/class/System/ChangeLog
index fa7cdba..c98255d 100644
--- a/mcs/class/System/ChangeLog
+++ b/mcs/class/System/ChangeLog
@@ -1,3 +1,9 @@
+2011-01-20  Miguel de Icaza  <miguel at gnome.org>
+
+	[sockets] Implement DuplicateAndClose and Socket
+	(SocketInformation) constructor for in-process socket passing
+	(AppDomains)
+
 2011-01-04  Marek Habersack  <grendel at twistedcode.net>
 
 	[system] Unbreak a 4.0 System.ServiceModel test.
diff --git a/mcs/class/System/System.Net.Mail/ChangeLog b/mcs/class/System/System.Net.Mail/ChangeLog
index b1eaa4d..1619af1 100644
--- a/mcs/class/System/System.Net.Mail/ChangeLog
+++ b/mcs/class/System/System.Net.Mail/ChangeLog
@@ -1,3 +1,14 @@
+2011-02-08  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	[SmtpClient] Don't send empty display name.
+
+	If there's no display name, don't send '""'. Fixes bug #670475.
+
+2011-01-25  Marek Habersack  <grendel at twistedcode.net>
+
+	[system] SmtpClient implements IDisposable on 4.0 (a no-op for
+	now)
+
 2010-10-31  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
 
 	Check that the default from is not empty
diff --git a/mcs/class/System/System.Net.Mail/SmtpClient.cs b/mcs/class/System/System.Net.Mail/SmtpClient.cs
index f1e1de3..46a812d 100644
--- a/mcs/class/System/System.Net.Mail/SmtpClient.cs
+++ b/mcs/class/System/System.Net.Mail/SmtpClient.cs
@@ -57,6 +57,9 @@ using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X
 
 namespace System.Net.Mail {
 	public class SmtpClient
+#if NET_4_0
+	: IDisposable
+#endif
 	{
 		#region Fields
 
@@ -255,7 +258,18 @@ namespace System.Net.Mail {
 		#endregion // Events 
 
 		#region Methods
+#if NET_4_0
+		public void Dispose ()
+		{
+			Dispose (true);
+		}
 
+		[MonoTODO ("Does nothing at the moment.")]
+		protected virtual void Dispose (bool disposing)
+		{
+			// TODO: We should close all the connections and abort any async operations here
+		}
+#endif
 		private void CheckState ()
 		{
 			if (messageInProcess != null)
@@ -264,8 +278,11 @@ namespace System.Net.Mail {
 		
 		private static string EncodeAddress(MailAddress address)
 		{
-			string encodedDisplayName = ContentType.EncodeSubjectRFC2047 (address.DisplayName, Encoding.UTF8);
-			return "\"" + encodedDisplayName + "\" <" + address.Address + ">";
+			if (!String.IsNullOrEmpty (address.DisplayName)) {
+				string encodedDisplayName = ContentType.EncodeSubjectRFC2047 (address.DisplayName, Encoding.UTF8);
+				return "\"" + encodedDisplayName + "\" <" + address.Address + ">";
+			}
+			return address.ToString ();
 		}
 
 		private static string EncodeAddresses(MailAddressCollection addresses)
diff --git a/mcs/class/System/System.Net.Sockets/ChangeLog b/mcs/class/System/System.Net.Sockets/ChangeLog
index 1d16c3f..a57d41f 100644
--- a/mcs/class/System/System.Net.Sockets/ChangeLog
+++ b/mcs/class/System/System.Net.Sockets/ChangeLog
@@ -1,3 +1,20 @@
+2011-02-11  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	[Socket] Fix invalid cast
+
+	Fix invalid cast when canceling pending operations due to
+	socket.Close.
+
+2011-01-20  Miguel de Icaza  <miguel at gnome.org>
+
+	Do not build the Socket passing on Mobile systems
+
+2011-01-20  Miguel de Icaza  <miguel at gnome.org>
+
+	[sockets] Implement DuplicateAndClose and Socket
+	(SocketInformation) constructor for in-process socket passing
+	(AppDomains)
+
 2011-01-06  Zoltan Varga  <vargaz at gmail.com>
 
 	Change some usages of ArrayList to List<T> to avoid calls to the
diff --git a/mcs/class/System/System.Net.Sockets/Socket.cs b/mcs/class/System/System.Net.Sockets/Socket.cs
index 6cc289c..0ba381d 100644
--- a/mcs/class/System/System.Net.Sockets/Socket.cs
+++ b/mcs/class/System/System.Net.Sockets/Socket.cs
@@ -180,30 +180,26 @@ namespace System.Net.Sockets
 			}
 		}
 
-
-		[MonoTODO]
+#if !MOBILE
 		public Socket (SocketInformation socketInformation)
 		{
-			throw new NotImplementedException ("SocketInformation not figured out yet");
+			var options = socketInformation.Options;
+			islistening = (options & SocketInformationOptions.Listening) != 0;
+			connected   = (options & SocketInformationOptions.Connected) != 0;
+			blocking    = (options & SocketInformationOptions.NonBlocking) == 0;
+			useoverlappedIO = (options & SocketInformationOptions.UseOnlyOverlappedIO) != 0;
 
-			// ifdef to avoid the warnings.
-#if false
-			//address_family = socketInformation.address_family;
-			//socket_type = socketInformation.socket_type;
-			//protocol_type = socketInformation.protocol_type;
-			address_family = AddressFamily.InterNetwork;
-			socket_type = SocketType.Stream;
-			protocol_type = ProtocolType.IP;
+			var result = Mono.DataConverter.Unpack ("iiiil", socketInformation.ProtocolInformation, 0);
 			
-			int error;
-			socket = Socket_internal (address_family, socket_type, protocol_type, out error);
-			if (error != 0)
-				throw new SocketException (error);
-
+			address_family = (AddressFamily) (int) result [0];
+			socket_type = (SocketType) (int) result [1];
+			protocol_type = (ProtocolType) (int) result [2];
+			isbound = (ProtocolType) (int) result [3] != 0;
+			socket = (IntPtr) (long) result [4];
 			SocketDefaults ();
-#endif
 		}
-
+#endif
+	
 #if !TARGET_JVM
 		// Returns the amount of data waiting to be read on socket
 		[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -1320,17 +1316,24 @@ namespace System.Net.Sockets
 			}
 		}
 
-		[MonoTODO ("Not implemented")]
+#if !MOBILE
+		[MonoLimitation ("We do not support passing sockets across processes, we merely allow this API to pass the socket across AppDomains")]
 		public SocketInformation DuplicateAndClose (int targetProcessId)
 		{
-			/* Need to serialize this socket into a
-			 * SocketInformation struct, but must study
-			 * the MS implementation harder to figure out
-			 * behaviour as documentation is lacking
-			 */
-			throw new NotImplementedException ();
-		}
+			var si = new SocketInformation ();
+			si.Options =
+				(islistening ? SocketInformationOptions.Listening : 0) |
+				(connected ? SocketInformationOptions.Connected : 0) |
+				(blocking ? 0 : SocketInformationOptions.NonBlocking) |
+				(useoverlappedIO ? SocketInformationOptions.UseOnlyOverlappedIO : 0);
+
+			si.ProtocolInformation = Mono.DataConverter.Pack ("iiiil", (int)address_family, (int)socket_type, (int)protocol_type, isbound ? 1 : 0, (long)socket);
+			socket = (IntPtr) (-1);
 
+			return si;
+		}
+#endif
+	
 		public Socket EndAccept (IAsyncResult result)
 		{
 			int bytes;
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 157e668..32019a6 100644
--- a/mcs/class/System/System.Net.Sockets/Socket_2_1.cs
+++ b/mcs/class/System/System.Net.Sockets/Socket_2_1.cs
@@ -201,7 +201,8 @@ namespace System.Net.Sockets {
 
 				WaitCallback cb;
 				for (int i = 0; i < pending.Length; i++) {
-					SocketAsyncResult ares = (SocketAsyncResult) pending [i];
+					Worker worker = (Worker) pending [i];
+					SocketAsyncResult ares = worker.result;
 					cb = new WaitCallback (ares.CompleteDisposed);
 					ThreadPool.QueueUserWorkItem (cb, null);
 				}
diff --git a/mcs/class/System/System.Net/ChangeLog b/mcs/class/System/System.Net/ChangeLog
index 2a916d3..19d1f31 100644
--- a/mcs/class/System/System.Net/ChangeLog
+++ b/mcs/class/System/System.Net/ChangeLog
@@ -1,3 +1,57 @@
+2011-02-13  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	[HttpWebRequest] Avoid nullref on empty cookie header.
+
+	If the Set-Cookie header is empty, the cookie instance is not
+	created. Fixes bug #670189.
+
+2011-02-13  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	[HttpListenre] Avoid multiple calls to Close()
+
+	HttpListenerResponse could be calling HttpConnection.Close() more
+	than once.
+
+2011-02-10  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	[HttpWebRequest] Can't ignore erros here
+
+2011-02-10  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	[HttpWebRequest] Error handling for POST/PUT
+
+	When we get an error from the server before writing an entire
+	unbuffered response, the server might close the connection leading
+	to write errors. Ignore those and return the actual HTTP status
+	code from the original server error.
+
+2011-01-31  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Allow forcing HTTP protocol version
+
+	If the version is manually set, ignore the version from the
+	service point when set.
+
+	Fixes bug #668199.
+
+2011-01-27  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	[HttpListener] Set each cookie in its own header
+
+	Send a Set-Cookie header per cookie instead of a Set-Cookie2 with
+	multiple cookies.
+
+	Fixes bug #667550.
+
+2011-01-21  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	[HttpListener] Fix incorrect 411 error
+
+	Don't send a 411 for unknown methods without content length. No
+	need to assign input_stream until requested.
+
+	Fixes bug #666251.
+
 2010-12-06  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
 
 	Workaround bug in AcquireWriterLock
diff --git a/mcs/class/System/System.Net/HttpListenerRequest.cs b/mcs/class/System/System.Net/HttpListenerRequest.cs
index 491a7a8..9019115 100644
--- a/mcs/class/System/System.Net/HttpListenerRequest.cs
+++ b/mcs/class/System/System.Net/HttpListenerRequest.cs
@@ -58,14 +58,11 @@ namespace System.Net {
 		bool ka_set;
 		bool keep_alive;
 		static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
-		static readonly string [] no_body_methods = new string [] {
-			"GET", "HEAD", "DELETE" };
 
 		internal HttpListenerRequest (HttpListenerContext context)
 		{
 			this.context = context;
 			headers = new WebHeaderCollection ();
-			input_stream = Stream.Null;
 			version = HttpVersion.Version10;
 		}
 
@@ -169,32 +166,25 @@ namespace System.Net {
 
 			CreateQueryString (url.Query);
 
-			string t_encoding = null;
 			if (version >= HttpVersion.Version11) {
-				t_encoding = Headers ["Transfer-Encoding"];
+				string t_encoding = Headers ["Transfer-Encoding"];
+				is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
 				// 'identity' is not valid!
-				if (t_encoding != null && t_encoding != "chunked") {
+				if (t_encoding != null && !is_chunked) {
 					context.Connection.SendError (null, 501);
 					return;
 				}
 			}
 
-			is_chunked = (t_encoding == "chunked");
-
-			foreach (string m in no_body_methods)
-				if (string.Compare (method, m, StringComparison.InvariantCultureIgnoreCase) == 0)
-					return;
-
 			if (!is_chunked && !cl_set) {
-				context.Connection.SendError (null, 411);
-				return;
-			}
-
-			if (is_chunked || content_length > 0) {
-				input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
+				if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
+				    String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
+					context.Connection.SendError (null, 411);
+					return;
+				}
 			}
 
-			if (Headers ["Expect"] == "100-continue") {
+			if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
 				ResponseStream output = context.Connection.GetResponseStream ();
 				output.InternalWrite (_100continue, 0, _100continue.Length);
 			}
@@ -369,7 +359,16 @@ namespace System.Net {
 		}
 
 		public Stream InputStream {
-			get { return input_stream; }
+			get {
+				if (input_stream == null) {
+					if (is_chunked || content_length > 0)
+						input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
+					else
+						input_stream = Stream.Null;
+				}
+
+				return input_stream;
+			}
 		}
 
 		[MonoTODO ("Always returns false")]
diff --git a/mcs/class/System/System.Net/HttpListenerResponse.cs b/mcs/class/System/System.Net/HttpListenerResponse.cs
index 3d46500..4e98842 100644
--- a/mcs/class/System/System.Net/HttpListenerResponse.cs
+++ b/mcs/class/System/System.Net/HttpListenerResponse.cs
@@ -331,8 +331,8 @@ namespace System.Net {
 
 		void Close (bool force)
 		{
-			context.Connection.Close (force);
 			disposed = true;
+			context.Connection.Close (force);
 		}
 
 		public void Close ()
@@ -471,20 +471,13 @@ namespace System.Net {
 				headers.SetInternal ("Location", location);
 
 			if (cookies != null) {
-				bool firstDone = false;
-				StringBuilder cookieSB = new StringBuilder ();
-				foreach (Cookie cookie in cookies) {
-					if (firstDone)
-						cookieSB.Append (",");
-					firstDone = true;
-					cookieSB.Append (cookie.ToClientString ());
-				}
-				headers.SetInternal("Set-Cookie2", cookieSB.ToString ());
+				foreach (Cookie cookie in cookies)
+					headers.SetInternal ("Set-Cookie", cookie.ToClientString ());
 			}
 
 			StreamWriter writer = new StreamWriter (ms, encoding);
 			writer.Write ("HTTP/{0} {1} {2}\r\n", version, status_code, status_description);
-			string headers_str = headers.ToString ();
+			string headers_str = headers.ToStringMultiValue ();
 			writer.Write (headers_str);
 			writer.Flush ();
 			int preamble = encoding.GetPreamble ().Length;
diff --git a/mcs/class/System/System.Net/HttpWebRequest.cs b/mcs/class/System/System.Net/HttpWebRequest.cs
index 0aa0f03..a23657c 100644
--- a/mcs/class/System/System.Net/HttpWebRequest.cs
+++ b/mcs/class/System/System.Net/HttpWebRequest.cs
@@ -75,6 +75,7 @@ namespace System.Net
 		bool preAuthenticate;
 		bool usedPreAuth;
 		Version version = HttpVersion.Version11;
+		bool force_version;
 		Version actualVersion;
 		IWebProxy proxy;
 		bool sendChunked;
@@ -450,6 +451,7 @@ namespace System.Net
 				if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
 					throw new ArgumentException ("value");
 
+				force_version = true;
 				version = value; 
 			}
 		}
@@ -1073,7 +1075,7 @@ namespace System.Net
 									   actualUri.PathAndQuery);
 			}
 			
-			if (servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
+			if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
 				actualVersion = servicePoint.ProtocolVersion;
 			} else {
 				actualVersion = version;
@@ -1178,7 +1180,11 @@ namespace System.Net
 				// The request has not been completely sent and we got here!
 				// We should probably just close and cause an error in any case,
 				saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse); 
-				webResponse.ReadAll ();
+				if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
+					webResponse.ReadAll ();
+				} else {
+					writeStream.IgnoreIOErrors = true;
+				}
 			}
 		}
 
@@ -1221,11 +1227,9 @@ namespace System.Net
 			}
 
 			if (wexc == null && (method == "POST" || method == "PUT")) {
-				lock (locker) {
-					CheckSendError (data);
-					if (saved_exc != null)
-						wexc = (WebException) saved_exc;
-				}
+				CheckSendError (data);
+				if (saved_exc != null)
+					wexc = (WebException) saved_exc;
 			}
 
 			WebAsyncResult r = asyncRead;
@@ -1241,7 +1245,8 @@ namespace System.Net
 			if (r != null) {
 				if (wexc != null) {
 					haveResponse = true;
-					r.SetCompleted (false, wexc);
+					if (!r.IsCompleted)
+						r.SetCompleted (false, wexc);
 					r.DoCallback ();
 					return;
 				}
diff --git a/mcs/class/System/System.Net/HttpWebResponse.cs b/mcs/class/System/System.Net/HttpWebResponse.cs
index 9747da9..0a542bf 100644
--- a/mcs/class/System/System.Net/HttpWebResponse.cs
+++ b/mcs/class/System/System.Net/HttpWebResponse.cs
@@ -421,6 +421,9 @@ namespace System.Net
 				}
 			}
 
+			if (cookie == null)
+				return;
+
 			if (cookieCollection == null)
 				cookieCollection = new CookieCollection ();
 
diff --git a/mcs/class/System/System.Net/WebConnectionStream.cs b/mcs/class/System/System.Net/WebConnectionStream.cs
index 4b261d5..c890e48 100644
--- a/mcs/class/System/System.Net/WebConnectionStream.cs
+++ b/mcs/class/System/System.Net/WebConnectionStream.cs
@@ -46,7 +46,7 @@ namespace System.Net
 		int readBufferSize;
 		int contentLength;
 		int totalRead;
-		long totalWritten;
+		internal long totalWritten;
 		bool nextReadCalled;
 		int pendingReads;
 		int pendingWrites;
@@ -65,6 +65,7 @@ namespace System.Net
 		int read_timeout;
 		int write_timeout;
 		AsyncCallback cb_wrapper; // Calls to ReadCallbackWrapper or WriteCallbacWrapper
+		internal bool IgnoreIOErrors;
 
 		public WebConnectionStream (WebConnection cnc)
 		{
@@ -292,7 +293,10 @@ namespace System.Net
 				result.InnerAsyncResult = r;
 				result.DoCallback ();
 			} else {
-				EndWrite (r);
+				try {
+					EndWrite (r);
+				} catch {
+				}
 			}
 		}
 
@@ -530,7 +534,14 @@ namespace System.Net
 				size = chunkSize;
 			}
 
-			result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
+			try {
+				result.InnerAsyncResult = cnc.BeginWrite (request, buffer, offset, size, callback, result);
+			} catch (Exception) {
+				if (!IgnoreIOErrors)
+					throw;
+				result.SetCompleted (true, 0);
+				result.DoCallback ();
+			}
 			totalWritten += size;
 			return result;
 		}
@@ -582,9 +593,13 @@ namespace System.Net
 				result.SetCompleted (false, 0);
 				result.DoCallback ();
 			} catch (Exception e) {
-				result.SetCompleted (false, e);
+				if (IgnoreIOErrors)
+					result.SetCompleted (false, 0);
+				else
+					result.SetCompleted (false, e);
 				result.DoCallback ();
-				throw;
+				if (!IgnoreIOErrors)
+					throw;
 			} finally {
 				if (sendChunked) {
 					lock (locker) {
diff --git a/mcs/class/System/System.Net/WebHeaderCollection.cs b/mcs/class/System/System.Net/WebHeaderCollection.cs
index 16f7753..f5c4787 100644
--- a/mcs/class/System/System.Net/WebHeaderCollection.cs
+++ b/mcs/class/System/System.Net/WebHeaderCollection.cs
@@ -310,6 +310,30 @@ namespace System.Net
 			return Encoding.UTF8.GetBytes(ToString ());
 		}
 
+		internal string ToStringMultiValue ()
+		{
+			StringBuilder sb = new StringBuilder();
+
+			int count = base.Count;
+			for (int i = 0; i < count ; i++) {
+				string key = GetKey (i);
+				if (IsMultiValue (key)) {
+					foreach (string v in GetValues (i)) {
+						sb.Append (key)
+						  .Append (": ")
+						  .Append (v)
+						  .Append ("\r\n");
+					}
+				} else {
+					sb.Append (key)
+					  .Append (": ")
+					  .Append (Get (i))
+					  .Append ("\r\n");
+				}
+			 }
+			return sb.Append("\r\n").ToString();
+		}
+
 		public override string ToString ()
 		{
 			StringBuilder sb = new StringBuilder();
@@ -320,7 +344,7 @@ namespace System.Net
 				  .Append (": ")
 				  .Append (Get (i))
 				  .Append ("\r\n");
-				  
+
 			return sb.Append("\r\n").ToString();
 		}
 #if !TARGET_JVM
diff --git a/mcs/class/System/System.Security.Cryptography.X509Certificates/ChangeLog b/mcs/class/System/System.Security.Cryptography.X509Certificates/ChangeLog
index f25192c..cbcd0c4 100644
--- a/mcs/class/System/System.Security.Cryptography.X509Certificates/ChangeLog
+++ b/mcs/class/System/System.Security.Cryptography.X509Certificates/ChangeLog
@@ -1,3 +1,8 @@
+2011-02-11  Sebastien Pouliot  <sebastien at ximian.com>
+
+	Continue X509Chain processing even if the local machine directory
+	does not exists
+
 2010-10-05  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
 
 	X509Chain always uses the LM store
diff --git a/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Chain.cs b/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Chain.cs
index c892907..b0bea7c 100644
--- a/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Chain.cs
+++ b/mcs/class/System/System.Security.Cryptography.X509Certificates/X509Chain.cs
@@ -888,7 +888,9 @@ namespace System.Security.Cryptography.X509Certificates {
 		{
 			string subject = caCertificate.SubjectName.Decode (X500DistinguishedNameFlags.None);
 			string ski = GetSubjectKeyIdentifier (caCertificate);
-			MX.X509Crl result = CheckCrls (subject, ski, LMCAStore.Store.Crls);
+
+			// consider that the LocalMachine directories could not exists... and cannot be created by the user
+			MX.X509Crl result = (LMCAStore.Store == null) ? null : CheckCrls (subject, ski, LMCAStore.Store.Crls);
 			if (result != null)
 				return result;
 			if (location == StoreLocation.CurrentUser) {
@@ -896,7 +898,9 @@ namespace System.Security.Cryptography.X509Certificates {
 				if (result != null)
 					return result;
 			}
-			result = CheckCrls (subject, ski, LMRootStore.Store.Crls);
+
+			// consider that the LocalMachine directories could not exists... and cannot be created by the user
+			result = (LMRootStore.Store == null) ? null : CheckCrls (subject, ski, LMRootStore.Store.Crls);
 			if (result != null)
 				return result;
 			if (location == StoreLocation.CurrentUser) {
diff --git a/mcs/class/System/System.dll.sources b/mcs/class/System/System.dll.sources
index 90be83c..507a7d3 100644
--- a/mcs/class/System/System.dll.sources
+++ b/mcs/class/System/System.dll.sources
@@ -1047,4 +1047,4 @@ System.Collections.Concurrent/ConcurrentBag.cs
 
 ../corlib/System.Collections/CollectionDebuggerView.cs
 ../corlib/System.Collections.Generic/CollectionDebuggerView.cs
-
+../corlib/Mono/DataConverter.cs
diff --git a/mcs/class/System/System/ChangeLog b/mcs/class/System/System/ChangeLog
index 8967b72..3797c90 100644
--- a/mcs/class/System/System/ChangeLog
+++ b/mcs/class/System/System/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
 2010-11-18  Sebastien Pouliot  <sebastien at ximian.com>
 
 	* System/Uri.cs: Add support for 'safe' unescaping rules *
diff --git a/mcs/class/System/System/Uri.cs b/mcs/class/System/System/Uri.cs
index a03bbc1..f414bc8 100644
--- a/mcs/class/System/System/Uri.cs
+++ b/mcs/class/System/System/Uri.cs
@@ -326,7 +326,7 @@ namespace System {
 				query = relativeUri.Substring (pos);
 				if (!userEscaped)
 					query = EscapeString (query);
-#if !NET_4_0 && !MOONLIGHT
+#if !NET_4_0 && !MOONLIGHT && !MOBILE
 				consider_query = query.Length > 0;
 #endif
 				relativeUri = pos == 0 ? String.Empty : relativeUri.Substring (0, pos);
@@ -1004,7 +1004,7 @@ namespace System {
 		//
 		public Uri MakeRelativeUri (Uri uri)
 		{
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			if (uri == null)
 				throw new ArgumentNullException ("uri");
 #endif
@@ -2011,7 +2011,7 @@ namespace System {
 
 		public bool IsBaseOf (Uri uri)
 		{
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			if (uri == null)
 				throw new ArgumentNullException ("uri");
 #endif
@@ -2182,7 +2182,7 @@ namespace System {
 			result = null;
 			if ((baseUri == null) || !baseUri.IsAbsoluteUri)
 				return false;
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			if (relativeUri == null)
 				return false;
 #endif
diff --git a/mcs/class/WebMatrix.Data/Assembly/AssemblyInfo.cs b/mcs/class/WebMatrix.Data/Assembly/AssemblyInfo.cs
new file mode 100644
index 0000000..8326708
--- /dev/null
+++ b/mcs/class/WebMatrix.Data/Assembly/AssemblyInfo.cs
@@ -0,0 +1,18 @@
+//
+// AssemblyInfo.cs
+//
+// Author:
+//   Andreas Nahr (ClassDevelopment at A-SoftTech.com)
+//
+// (C) 2003 Ximian, Inc.  http://www.ximian.com
+// (C) 2004 Novell (http://www.novell.com)
+//
+
+using System;
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+[assembly: AssemblyVersion (Consts.FxVersion)]
+
+[assembly: AssemblyDelaySign (true)]
+[assembly: AssemblyKeyFile ("../mono.pub")]
diff --git a/mcs/class/WebMatrix.Data/Makefile b/mcs/class/WebMatrix.Data/Makefile
new file mode 100644
index 0000000..1bca6fb
--- /dev/null
+++ b/mcs/class/WebMatrix.Data/Makefile
@@ -0,0 +1,10 @@
+thisdir = class/WebMatrix.Data
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = WebMatrix.Data.dll
+
+include ../../build/library.make
+
+LIB_MCS_FLAGS += -r:$(corlib) -r:System.dll -r:System.Data.dll -r:System.Core.dll -r:System.Configuration.dll
+TEST_MCS_FLAGS += -r:System.dll -r:System.Data.dll -r:Mono.Data.Sqlite.dll
diff --git a/mcs/class/WebMatrix.Data/Test/WebMatrix.Data/ConnectionEventArgsTests.cs b/mcs/class/WebMatrix.Data/Test/WebMatrix.Data/ConnectionEventArgsTests.cs
new file mode 100644
index 0000000..8c24401
--- /dev/null
+++ b/mcs/class/WebMatrix.Data/Test/WebMatrix.Data/ConnectionEventArgsTests.cs
@@ -0,0 +1,54 @@
+// 
+// ConnectionEventArgsTests.cs
+//  
+// Author:
+//       Jérémie "garuma" Laval <jeremie.laval at gmail.com>
+// 
+// Copyright (c) 2011 Novell
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#if NET_4_0
+
+using System;
+using System.Data.Common;
+using System.Data.SqlClient;
+
+using WebMatrix.Data;
+
+using NUnit.Framework;
+
+namespace MonoTests.WebMatrix.Data
+{
+	[TestFixtureAttribute]
+	public class ConnectionEventArgsTests
+	{
+		[Test]
+		public void InstantiateTest ()
+		{
+			var evtArgs = new ConnectionEventArgs (null);
+			Assert.IsNull (evtArgs.Connection, "#1");
+
+			var conn = new SqlConnection ();
+			evtArgs = new ConnectionEventArgs (conn);
+			Assert.AreEqual (conn, evtArgs.Connection, "#2");
+		}
+	}
+}
+#endif
\ No newline at end of file
diff --git a/mcs/class/WebMatrix.Data/Test/WebMatrix.Data/DatabaseTests.cs b/mcs/class/WebMatrix.Data/Test/WebMatrix.Data/DatabaseTests.cs
new file mode 100644
index 0000000..135d4de
--- /dev/null
+++ b/mcs/class/WebMatrix.Data/Test/WebMatrix.Data/DatabaseTests.cs
@@ -0,0 +1,117 @@
+// 
+// DatabaseTests.cs
+//  
+// Author:
+//       Jérémie "garuma" Laval <jeremie.laval at gmail.com>
+// 
+// Copyright (c) 2011 Novell
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#if NET_4_0
+
+using System;
+using System.IO;
+using System.Linq;
+using System.Data.Common;
+using System.Collections.Generic;
+
+using WebMatrix.Data;
+
+using NUnit.Framework;
+
+namespace MonoTests.WebMatrix.Data
+{
+	[TestFixtureAttribute]
+	public class DatabaseTests
+	{
+		Database database;
+		string dbPath;
+
+		[SetUp]
+		public void Setup ()
+		{
+			dbPath = Path.Combine ("Test", "testsqlite.db");
+			database = Database.OpenConnectionString ("Data Source="+dbPath+";Version=3;", "Mono.Data.Sqlite");
+		}
+
+		[Test]
+		public void QuerySingleTest ()
+		{
+			var result = database.QuerySingle ("select * from memos where Text=@0 limit 1", "Grendel");
+
+			Assert.IsNotNull (result);
+			Assert.AreEqual ("Grendel", result.Text);
+			Assert.AreEqual (5, result.Priority);
+		}
+
+		[Test]
+		public void SimpleQueryTest ()
+		{
+			var result = database.Query ("select * from memos");
+
+			Assert.IsNotNull (result);
+			Assert.AreEqual (5, result.Count ());
+
+			var col1 = new string[] { "Webmatrix", "Grendel", "Garuma", "jpobst", "Gonzalo" };
+			var col2 = new object[] { 10, 5, -1, 6, 4 };
+			int index = 0;
+
+			foreach (var row in result) {
+				Assert.AreEqual (col1[index], row.Text);
+				Assert.AreEqual (col2[index], row.Priority);
+				index++;
+			}
+		}
+
+		[Test]
+		public void InsertTest ()
+		{
+			string newPath = dbPath + ".tmp";
+			File.Copy (dbPath, newPath, true);
+
+			database = Database.OpenConnectionString ("Data Source="+newPath+";Version=3;", "Mono.Data.Sqlite");
+			database.Execute ("insert into memos values ('foo', @0);", 42);
+
+			Assert.AreEqual (42, database.QueryValue ("select Priority from memos where Text='foo'"));
+			Assert.AreEqual (6, database.GetLastInsertId ());
+
+			File.Delete (newPath);
+		}
+
+		[Test]
+		public void QueryValueTest ()
+		{
+			var res = database.QueryValue ("select Priority from memos where Text='Webmatrix'");
+			Assert.AreEqual (10, res);
+		}
+
+		[Test]
+		public void ConnectionOpenedTest ()
+		{
+			bool opened = false;
+			Database.ConnectionOpened += (sender, e) => opened = sender == database;
+
+			var result = database.QuerySingle ("select * from memos where Text=@0 limit 1", "Grendel");
+
+			Assert.IsTrue (opened);
+		}
+	}
+}
+#endif
diff --git a/mcs/class/WebMatrix.Data/Test/WebMatrix.Data/DynamicRecordTests.cs b/mcs/class/WebMatrix.Data/Test/WebMatrix.Data/DynamicRecordTests.cs
new file mode 100644
index 0000000..c180ca2
--- /dev/null
+++ b/mcs/class/WebMatrix.Data/Test/WebMatrix.Data/DynamicRecordTests.cs
@@ -0,0 +1,99 @@
+// 
+// DynamicRecordTests.cs
+//  
+// Author:
+//       Jérémie "garuma" Laval <jeremie.laval at gmail.com>
+// 
+// Copyright (c) 2011 Novell
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#if NET_4_0
+
+using System;
+using System.Collections.Generic;
+
+using WebMatrix.Data;
+
+using NUnit.Framework;
+
+namespace MonoTests.WebMatrix.Data
+{
+	[TestFixtureAttribute]
+	public class DynamicRecordTests
+	{
+		DynamicRecord record;
+
+		[SetUp]
+		public void Setup ()
+		{
+			var fields = new Dictionary<string, object> () {
+				{ "foo", 1 },
+				{ "bar", 4.1f },
+				{ "foobar", "foobar" }
+			};
+			record = new DynamicRecord (fields);
+		}
+
+		[Test]
+		public void ColumnsTest ()
+		{
+			var columns = record.Columns;
+			Assert.AreEqual (3, columns.Count);
+
+			Assert.AreEqual ("foo", columns[0]);
+			Assert.AreEqual ("bar", columns[1]);
+			Assert.AreEqual ("foobar", columns[2]);
+		}
+
+		[Test]
+		public void AccessByNameTest ()
+		{
+			Assert.AreEqual (1, record["foo"]);
+			Assert.AreEqual (4.1f, record["bar"]);
+			Assert.AreEqual ("foobar", record["foobar"]);
+		}
+
+		[Test]
+		public void AccessByIndexTest ()
+		{
+			Assert.AreEqual (1, record[0]);
+			Assert.AreEqual (4.1f, record[1]);
+			Assert.AreEqual ("foobar", record[2]);
+		}
+
+		[Test]
+		public void AccesByDynamicTest ()
+		{
+			dynamic r = record;
+
+			Assert.AreEqual (1, r.foo);
+			Assert.AreEqual (4.1f, r.bar);
+			Assert.AreEqual ("foobar", r.foobar);
+		}
+
+		[Test]
+		public void GetDynamicMemberNamesTest ()
+		{
+			var expected = new string[] { "foo", "bar", "foobar" };
+			CollectionAssert.AreEquivalent (expected, record.GetDynamicMemberNames ());
+		}
+	}
+}
+#endif
diff --git a/mcs/class/WebMatrix.Data/WebMatrix.Data.dll.sources b/mcs/class/WebMatrix.Data/WebMatrix.Data.dll.sources
new file mode 100644
index 0000000..ba3b4e6
--- /dev/null
+++ b/mcs/class/WebMatrix.Data/WebMatrix.Data.dll.sources
@@ -0,0 +1,6 @@
+../../build/common/Consts.cs
+../../build/common/Locale.cs
+Assembly/AssemblyInfo.cs
+WebMatrix.Data/ConnectionEventArgs.cs
+WebMatrix.Data/DynamicRecord.cs
+WebMatrix.Data/Database.cs
diff --git a/mcs/class/WebMatrix.Data/WebMatrix.Data/ConnectionEventArgs.cs b/mcs/class/WebMatrix.Data/WebMatrix.Data/ConnectionEventArgs.cs
new file mode 100644
index 0000000..83c45be
--- /dev/null
+++ b/mcs/class/WebMatrix.Data/WebMatrix.Data/ConnectionEventArgs.cs
@@ -0,0 +1,49 @@
+//
+// ConnectionEventArgs.cs
+//
+// Copyright (c) 2011 Novell
+//
+// Authors:
+//     Jérémie "garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+
+#if NET_4_0
+
+using System;
+using System.Data.Common;
+
+namespace WebMatrix.Data
+{
+	public class ConnectionEventArgs : EventArgs
+	{
+		public ConnectionEventArgs (DbConnection connection)
+		{
+			Connection = connection;
+		}
+
+		public DbConnection Connection {
+			get;
+			private set;
+		}
+	}
+}
+
+#endif
\ No newline at end of file
diff --git a/mcs/class/WebMatrix.Data/WebMatrix.Data/Database.cs b/mcs/class/WebMatrix.Data/WebMatrix.Data/Database.cs
new file mode 100644
index 0000000..be77519
--- /dev/null
+++ b/mcs/class/WebMatrix.Data/WebMatrix.Data/Database.cs
@@ -0,0 +1,242 @@
+//
+// Database.cs
+//
+// Copyright (c) 2011 Novell
+//
+// Authors:
+//     Jérémie "garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+
+#if NET_4_0
+
+using System;
+using System.Linq;
+using System.Threading;
+using System.Dynamic;
+using System.Data.Common;
+using System.Configuration;
+using System.ComponentModel;
+using System.Collections.Generic;
+
+namespace WebMatrix.Data
+{
+	public class Database : IDisposable
+	{
+		public static event EventHandler<ConnectionEventArgs> ConnectionOpened;
+
+		bool opened;
+		DbConnection connection;
+		readonly string providerName;
+
+		static readonly Dictionary<string, string> lastInsertedIdStmts = new Dictionary<string, string> ();
+
+		static Database ()
+		{
+			// Add your own DB-specific way to do so
+			lastInsertedIdStmts.Add ("System.Data.SqlClient", "select @@IDENTITY;");
+			lastInsertedIdStmts.Add ("Mono.Data.Sqlite", "select last_insert_rowid ();");
+			lastInsertedIdStmts.Add ("MySql.Data", "SELECT LAST_INSERT_ID();");
+			lastInsertedIdStmts.Add ("Npgsql", "SELECT lastval();");
+		}
+
+		private Database (DbConnection connection, string providerName)
+		{
+			this.connection = connection;
+			this.providerName = providerName;
+		}
+
+		public static Database Open (string name)
+		{
+			var config = ConfigurationManager.ConnectionStrings[name];
+			if (config == null)
+				throw new ArgumentException ("name", string.Format ("Database with name {0} doesn't exist", name));
+
+			return OpenConnectionString (config.ConnectionString, config.ProviderName);
+		}
+
+		public static Database OpenConnectionString (string connectionString)
+		{
+			return OpenConnectionString (connectionString, "System.Data.SqlClient");
+		}
+
+		public static Database OpenConnectionString (string connectionString, string providerName)
+		{
+			var factory = DbProviderFactories.GetFactory (providerName);
+			var conn = factory.CreateConnection ();
+			conn.ConnectionString = connectionString;
+
+			return new Database (conn, providerName);
+		}
+
+		public void Close ()
+		{
+			opened = false;
+			connection.Close ();
+		}
+
+		public void Dispose ()
+		{
+			Dispose (true);
+		}
+
+		protected virtual void Dispose (bool disposing)
+		{
+			if (disposing) {
+				if (opened)
+					connection.Close ();
+				connection.Dispose ();
+			}
+		}
+
+		public int Execute (string commandText, params object[] args)
+		{
+			var command = PrepareCommand (commandText);
+			PrepareCommandParameters (command, args);
+
+			EnsureConnectionOpened ();
+
+			var result = command.ExecuteNonQuery ();
+
+			command.Dispose ();
+
+			return result;
+		}
+
+		public IEnumerable<dynamic> Query (string commandText, params object[] args)
+		{
+			var result = QueryInternal (commandText, args, false);
+
+			return result != null ? result.Select (r => new DynamicRecord (r)) : null;
+		}
+
+		public dynamic QuerySingle (string commandText, params object[] args)
+		{
+			var result = QueryInternal (commandText, args, true);
+
+			return result != null ? new DynamicRecord (result[0]) : null;
+		}
+
+		List<Dictionary<string, object>> QueryInternal (string commandText, object[] args, bool unique)
+		{
+			EnsureConnectionOpened ();
+
+			var command = PrepareCommand (commandText);
+			PrepareCommandParameters (command, args);
+			string[] columnsNames;
+			var rows = new List<Dictionary<string, object>> ();
+
+			using (var reader = command.ExecuteReader ()) {
+				if (!reader.Read () || !reader.HasRows)
+					return null;
+
+				columnsNames = new string [reader.FieldCount];
+
+				do {				
+					var fields = new Dictionary<string, object> ();
+
+					for (int i = 0; i < reader.FieldCount; ++i) {
+						if (columnsNames[i] == null)
+							columnsNames[i] = reader.GetName (i);
+
+						fields[columnsNames[i]] = reader[i];
+					}
+
+					rows.Add (fields);
+				} while (!unique && reader.Read ());
+			}
+
+			command.Dispose ();
+
+			return rows;
+		}
+
+		public object QueryValue (string commandText, params object[] args)
+		{
+			EnsureConnectionOpened ();
+
+			var command = PrepareCommand (commandText);
+			PrepareCommandParameters (command, args);
+
+			var result = command.ExecuteScalar ();
+
+			command.Dispose ();
+
+			return result;
+		}
+
+		public object GetLastInsertId ()
+		{
+			string sql;
+			if (!lastInsertedIdStmts.TryGetValue (providerName, out sql))
+				throw new NotSupportedException ("This operation is not available for your database");
+
+			return QueryValue (sql);
+		}
+
+		DbCommand PrepareCommand (string commandText)
+		{
+			var command = connection.CreateCommand ();
+			command.CommandText = commandText;
+
+			return command;
+		}
+
+		static void PrepareCommandParameters (DbCommand command, object[] args)
+		{
+			if (args.Length == 0)
+				return;
+
+			int index = 0;
+
+			foreach (var arg in args) {
+				var param = command.CreateParameter ();
+				param.ParameterName = "@" + index;
+				param.Value = args[index++];
+				command.Parameters.Add (param);
+			}
+		}
+
+		static void TriggerConnectionOpened (Database self, DbConnection connection)
+		{
+			EventHandler<ConnectionEventArgs> evt = ConnectionOpened;
+			if (evt != null)
+				evt (self, new ConnectionEventArgs (connection));
+		}
+
+		void EnsureConnectionOpened ()
+		{
+			if (opened)
+				return;
+
+			connection.Open ();
+			opened = true;
+			TriggerConnectionOpened (this, connection);
+		}
+
+		public DbConnection Connection {
+			get {
+				return connection;
+			}
+		}		
+	}
+}
+
+#endif
\ No newline at end of file
diff --git a/mcs/class/WebMatrix.Data/WebMatrix.Data/DynamicRecord.cs b/mcs/class/WebMatrix.Data/WebMatrix.Data/DynamicRecord.cs
new file mode 100644
index 0000000..417c3e4
--- /dev/null
+++ b/mcs/class/WebMatrix.Data/WebMatrix.Data/DynamicRecord.cs
@@ -0,0 +1,137 @@
+//
+// DynamicRecord.cs
+//
+// Copyright (c) 2011 Novell
+//
+// Authors:
+//     Jérémie "garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+
+#if NET_4_0
+
+using System;
+using System.Dynamic;
+using System.Data.Common;
+using System.Collections.Generic;
+using System.ComponentModel;
+
+namespace WebMatrix.Data
+{
+	public sealed class DynamicRecord : DynamicObject, ICustomTypeDescriptor
+	{
+		readonly Dictionary<string, object> fields;
+
+		internal DynamicRecord (Dictionary<string, object> fields)
+		{
+			this.fields = fields;
+			Columns = new List<string> (fields.Keys).AsReadOnly ();
+		}
+
+		public IList<string> Columns {
+			get;
+			private set;
+		}
+
+		public object this[string name] {
+			get {
+				return fields[name];
+			}
+		}
+
+		public object this[int index] {
+			get {				
+				return fields[Columns[index]];
+			}
+		}
+
+		public override IEnumerable<string> GetDynamicMemberNames ()
+		{
+			return fields.Keys;
+		}
+
+		public override bool TryGetMember (GetMemberBinder binder, out object result)
+		{
+			return fields.TryGetValue (binder.Name, out result);
+		}
+
+		AttributeCollection ICustomTypeDescriptor.GetAttributes ()
+		{
+			return null;
+		}
+
+		string ICustomTypeDescriptor.GetClassName ()
+		{
+			return null;
+		}
+
+		string ICustomTypeDescriptor.GetComponentName ()
+		{
+			return null;
+		}
+
+		TypeConverter ICustomTypeDescriptor.GetConverter ()
+		{
+			return null;
+		}
+
+		EventDescriptor ICustomTypeDescriptor.GetDefaultEvent ()
+		{
+			return null;
+		}
+
+		PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty ()
+		{
+			return null;
+		}
+
+		Object ICustomTypeDescriptor.GetEditor (Type editorBaseType)
+		{
+			return null;
+		}
+
+		Object ICustomTypeDescriptor.GetPropertyOwner (PropertyDescriptor pd)
+		{
+			return null;
+		}
+
+		EventDescriptorCollection ICustomTypeDescriptor.GetEvents ()
+		{
+			return null;
+		}
+
+		EventDescriptorCollection ICustomTypeDescriptor.GetEvents (Attribute[] attributes)
+		{
+			return null;
+		}
+
+		PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties ()
+		{
+			return null;
+		}
+
+		PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties (Attribute[] attributes)
+		{
+			return null;
+		}
+	}
+}
+
+#endif
\ No newline at end of file
diff --git a/mcs/class/WebMatrix.Data/WebMatrix.Data_test.dll.sources b/mcs/class/WebMatrix.Data/WebMatrix.Data_test.dll.sources
new file mode 100644
index 0000000..927528a
--- /dev/null
+++ b/mcs/class/WebMatrix.Data/WebMatrix.Data_test.dll.sources
@@ -0,0 +1,4 @@
+WebMatrix.Data/ConnectionEventArgsTests.cs
+WebMatrix.Data/DynamicRecordTests.cs
+../WebMatrix.Data/DynamicRecord.cs
+WebMatrix.Data/DatabaseTests.cs
diff --git a/mcs/class/WindowsBase/ChangeLog b/mcs/class/WindowsBase/ChangeLog
index 6959562..b3324bf 100644
--- a/mcs/class/WindowsBase/ChangeLog
+++ b/mcs/class/WindowsBase/ChangeLog
@@ -1,3 +1,8 @@
+2011-02-01  Atsushi Eno  <atsushi at ximian.com>
+
+	in NET_4_0, remove types that went into System.Xaml.dll. Change
+	build order.
+
 2010-11-06  Marek Safar  <marek.safar at gmail.com>
 
 	Add missing default ctor call
diff --git a/mcs/class/WindowsBase/Makefile b/mcs/class/WindowsBase/Makefile
index 83b7315..80c477d 100644
--- a/mcs/class/WindowsBase/Makefile
+++ b/mcs/class/WindowsBase/Makefile
@@ -9,5 +9,8 @@ TEST_MCS_FLAGS = -unsafe -r:WindowsBase.dll
 ifeq (2.0, $(FRAMEWORK_VERSION))
 LIB_MCS_FLAGS += -d:NET_3_0
 endif
+ifeq (4.0, $(FRAMEWORK_VERSION))
+LIB_MCS_FLAGS += -d:NET_4_0 -r:System.Xaml.dll
+endif
 
 include ../../build/library.make
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/AmbientAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/AmbientAttribute.cs
index b3b631f..04ce079 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/AmbientAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/AmbientAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -28,4 +29,5 @@ namespace System.Windows.Markup {
 	[AttributeUsage (AttributeTargets.Property)]
 	public class AmbientAttribute : Attribute {
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/ConstructorArgumentAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/ConstructorArgumentAttribute.cs
index 07ebd9c..dacda05 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/ConstructorArgumentAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/ConstructorArgumentAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -42,4 +43,5 @@ namespace System.Windows.Markup {
 		string argumentName;
 	}
 
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/ContentPropertyAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/ContentPropertyAttribute.cs
index 23f85a1..9be1751 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/ContentPropertyAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/ContentPropertyAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -46,3 +47,4 @@ namespace System.Windows.Markup {
 		}
 	}
 }
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/ContentWrapperAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/ContentWrapperAttribute.cs
index 8dbb4f6..888e901 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/ContentWrapperAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/ContentWrapperAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -62,3 +63,4 @@ namespace System.Windows.Markup {
 	}
 
 }
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/DateTimeValueSerializer.cs b/mcs/class/WindowsBase/System.Windows.Markup/DateTimeValueSerializer.cs
index 3c92141..b7a604a 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/DateTimeValueSerializer.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/DateTimeValueSerializer.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -64,3 +65,4 @@ namespace System.Windows.Markup {
 	}
 
 }
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/DependsOnAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/DependsOnAttribute.cs
index 6e19d6e..817dca4 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/DependsOnAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/DependsOnAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -47,3 +48,4 @@ namespace System.Windows.Markup {
 	}
 
 }
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/DictionaryKeyPropertyAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/DictionaryKeyPropertyAttribute.cs
index aac7d89..0f6ce9b 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/DictionaryKeyPropertyAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/DictionaryKeyPropertyAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -38,4 +39,5 @@ namespace System.Windows.Markup {
 			get; private set;
 		}
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/IComponentConnector.cs b/mcs/class/WindowsBase/System.Windows.Markup/IComponentConnector.cs
index ed4832c..69edc72 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/IComponentConnector.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/IComponentConnector.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -32,4 +33,5 @@ namespace System.Windows.Markup {
 
 		void InitializeComponent ();
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/INameScope.cs b/mcs/class/WindowsBase/System.Windows.Markup/INameScope.cs
index 5124eca..75e2a5c 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/INameScope.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/INameScope.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -33,4 +34,5 @@ namespace System.Windows.Markup {
 		void RegisterName (string name, object scopedElement);
 		void UnregisterName (string name);
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/IValueSerializerContext.cs b/mcs/class/WindowsBase/System.Windows.Markup/IValueSerializerContext.cs
index 58e8e50..62faad6 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/IValueSerializerContext.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/IValueSerializerContext.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -32,4 +33,5 @@ namespace System.Windows.Markup {
 		ValueSerializer GetValueSerializerFor (PropertyDescriptor descriptor);
 		ValueSerializer GetValueSerializerFor (Type type);
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/IXamlTypeResolver.cs b/mcs/class/WindowsBase/System.Windows.Markup/IXamlTypeResolver.cs
index a7dce69..9a053d5 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/IXamlTypeResolver.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/IXamlTypeResolver.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -30,4 +31,5 @@ namespace System.Windows.Markup {
 	public interface IXamlTypeResolver {
 		Type Resolve (string qualifiedTypeName);
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/MarkupExtension.cs b/mcs/class/WindowsBase/System.Windows.Markup/MarkupExtension.cs
index 195e88e..4126496 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/MarkupExtension.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/MarkupExtension.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -36,3 +37,4 @@ namespace System.Windows.Markup {
 		public abstract object ProvideValue (IServiceProvider serviceProvider);
 	}
 }
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/MarkupExtensionReturnTypeAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/MarkupExtensionReturnTypeAttribute.cs
index 57987dd..975aa4b 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/MarkupExtensionReturnTypeAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/MarkupExtensionReturnTypeAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -57,3 +58,4 @@ namespace System.Windows.Markup {
 	}
 
 }
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/NameScopePropertyAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/NameScopePropertyAttribute.cs
index 21d8e7d..8d6b7cd 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/NameScopePropertyAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/NameScopePropertyAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -51,4 +52,5 @@ namespace System.Windows.Markup {
 		}
 	}
 
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/RootNamespaceAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/RootNamespaceAttribute.cs
index 656c35d..353a9ad 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/RootNamespaceAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/RootNamespaceAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -41,4 +42,5 @@ namespace System.Windows.Markup {
 
 		string nameSpace;
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/RuntimeNamePropertyAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/RuntimeNamePropertyAttribute.cs
index 23d41bf..1f0c738 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/RuntimeNamePropertyAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/RuntimeNamePropertyAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -41,4 +42,5 @@ namespace System.Windows.Markup {
 
 		string name;
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/TrimSurroundingWhitespaceAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/TrimSurroundingWhitespaceAttribute.cs
index 71676dc..b486f04 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/TrimSurroundingWhitespaceAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/TrimSurroundingWhitespaceAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -31,4 +32,5 @@ namespace System.Windows.Markup {
 	public sealed class TrimSurroundingWhitespaceAttribute : Attribute
 	{
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/UidPropertyAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/UidPropertyAttribute.cs
index 8b4ea27..1407866 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/UidPropertyAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/UidPropertyAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -38,4 +39,5 @@ namespace System.Windows.Markup {
 			private set;
 		}
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/UsableDuringInitializationAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/UsableDuringInitializationAttribute.cs
index bae9747..f865ab3 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/UsableDuringInitializationAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/UsableDuringInitializationAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -38,4 +39,5 @@ namespace System.Windows.Markup {
 			private set;
 		}
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/ValueSerializer.cs b/mcs/class/WindowsBase/System.Windows.Markup/ValueSerializer.cs
index 38bc4a6..435499d 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/ValueSerializer.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/ValueSerializer.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -167,3 +168,4 @@ namespace System.Windows.Markup {
 	}
 
 }
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/ValueSerializerAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/ValueSerializerAttribute.cs
index 0c1d704..7f3fd90 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/ValueSerializerAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/ValueSerializerAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -55,4 +56,5 @@ namespace System.Windows.Markup {
 
 		Type valueSerializerType;
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/WhitespaceSignificantCollectionAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/WhitespaceSignificantCollectionAttribute.cs
index 899f8c2..a5b9206 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/WhitespaceSignificantCollectionAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/WhitespaceSignificantCollectionAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -31,4 +32,5 @@ namespace System.Windows.Markup {
 	public sealed class WhitespaceSignificantCollectionAttribute : Attribute
 	{
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/XmlLangPropertyAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/XmlLangPropertyAttribute.cs
index 914ecc7..777be0e 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/XmlLangPropertyAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/XmlLangPropertyAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -41,4 +42,5 @@ namespace System.Windows.Markup {
 
 		string name;
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/XmlnsCompatibleWithAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/XmlnsCompatibleWithAttribute.cs
index 2377c32..52b9426 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/XmlnsCompatibleWithAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/XmlnsCompatibleWithAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -47,4 +48,5 @@ namespace System.Windows.Markup {
 		string newNamespace;
 		string oldNamespace;
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/XmlnsDefinitionAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/XmlnsDefinitionAttribute.cs
index 88acdc6..15512ea 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/XmlnsDefinitionAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/XmlnsDefinitionAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -53,4 +54,5 @@ namespace System.Windows.Markup {
 		string clrNamespace;
 		string assemblyName;
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/WindowsBase/System.Windows.Markup/XmlnsPrefixAttribute.cs b/mcs/class/WindowsBase/System.Windows.Markup/XmlnsPrefixAttribute.cs
index 0d77d67..eccd70a 100644
--- a/mcs/class/WindowsBase/System.Windows.Markup/XmlnsPrefixAttribute.cs
+++ b/mcs/class/WindowsBase/System.Windows.Markup/XmlnsPrefixAttribute.cs
@@ -1,3 +1,4 @@
+#if !NET_4_0
 // 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
@@ -47,4 +48,5 @@ namespace System.Windows.Markup {
 		string prefix;
 		string xmlNamespace;
 	}
-}
\ No newline at end of file
+}
+#endif
diff --git a/mcs/class/corlib/ChangeLog b/mcs/class/corlib/ChangeLog
index 5ca429a..ee80f14 100644
--- a/mcs/class/corlib/ChangeLog
+++ b/mcs/class/corlib/ChangeLog
@@ -1,3 +1,41 @@
+2010-09-24  Kyle Ambroff  <kyle at ambroff.com>
+
+	version tolerant serialization fails with missing primitive
+	members
+
+	Modifies ObjectReader so that when it encounters a primitive typed
+	member in an object stream which has no corresponding member in
+	the app domain, it will read the value anyway and throw it away.
+	That way it can read the next block from the stream.
+
+	Added a unit test which passes with the changes to ObjectReader.
+
+	Fixes bug #641821.
+
+2010-12-04  Kenneth Bell  <ken.git at chezbell.org.uk>
+
+	Implement RawSecurityDescriptor.
+
+	* Marshals to/from SDDL and binary form.
+
+	* Supports 'Common' ACEs and 'Object' ACEs
+
+2010-12-04  Kenneth Bell  <ken.git at chezbell.org.uk>
+
+	Implement SecurityIdentifier and improve NTAccount.
+
+	* Only translates between SecurityIdentifier and NTAccount for
+	well-known accounts.
+
+	* NTAccount changed to not upper-case values to match behaviour
+	observed in Microsoft's .NET (see also unit tests)
+
+	* Add unit tests for both classes
+
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
 2011-01-07  Jérémie Laval  <jeremie.laval at gmail.com>
 
 	Remove now unused internal classes
diff --git a/mcs/class/corlib/Makefile b/mcs/class/corlib/Makefile
index 94aacb2..6d4ea0b 100644
--- a/mcs/class/corlib/Makefile
+++ b/mcs/class/corlib/Makefile
@@ -95,6 +95,8 @@ test-vts:
 		$(vtsdir)/$(vts)TestLib/4.0/Address.cs
 	$(MCS) -target:library \
 		$(vtsdir)/$(vts)TestLib/5.0/Address.cs
+	$(MCS) -target:library \
+		$(vtsdir)/$(vts)TestLib/6.0/Address.cs
 run-test-vts: test-vts
 	$(TEST_RUNTIME) $(RUNTIME_FLAGS) $(TEST_HARNESS) -noshadow \
 		$(vtsdir)/BinarySerializationOverVersions.exe 
diff --git a/mcs/class/corlib/Mono.Security.X509/ChangeLog b/mcs/class/corlib/Mono.Security.X509/ChangeLog
index 1e54994..9028c19 100644
--- a/mcs/class/corlib/Mono.Security.X509/ChangeLog
+++ b/mcs/class/corlib/Mono.Security.X509/ChangeLog
@@ -1,3 +1,17 @@
+2011-02-11  Sebastien Pouliot  <sebastien at ximian.com>
+
+	* corlib/Mono.Security.X509/X509Store.cs: *
+	Mono.Security/Mono.Security.X509/X509Store.cs: Fix key pair
+	persistence to load key pairs from the same location (machine or
+	user) as the requested certificate. This avoids an internal
+	exception (on missing local machine directory) that stop the
+	evaluation of the certificate validity (i.e. no user store check)
+	*
+	System/System.Security.Cryptography.X509Certificates/X509Chain.cs:
+	Ensure that a missing local machine directory does not result in a
+	NRE while loading CRL (which would fail the certificate being
+	validated)
+
 2010-11-03  Sebastien Pouliot  <sebastien at ximian.com>
 
 	* mcs/class/corlib/Mono.Security.X509/X509Store.cs: *
diff --git a/mcs/class/corlib/Mono.Security.X509/X509Store.cs b/mcs/class/corlib/Mono.Security.X509/X509Store.cs
index 6b7ebc6..c4bb4b9 100644
--- a/mcs/class/corlib/Mono.Security.X509/X509Store.cs
+++ b/mcs/class/corlib/Mono.Security.X509/X509Store.cs
@@ -232,7 +232,8 @@ namespace Mono.Security.X509 {
 			// If privateKey it's available, load it too..
 			CspParameters cspParams = new CspParameters ();
 			cspParams.KeyContainerName = CryptoConvert.ToHex (cert.Hash);
-			cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
+			if (_storePath.StartsWith (X509StoreManager.LocalMachinePath))
+				cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
 			KeyPairPersistence kpp = new KeyPairPersistence (cspParams);
 
 			if (!kpp.Load ())
diff --git a/mcs/class/corlib/System.Collections.Concurrent.Partitioners/ChangeLog b/mcs/class/corlib/System.Collections.Concurrent.Partitioners/ChangeLog
index d310e92..86e1229 100644
--- a/mcs/class/corlib/System.Collections.Concurrent.Partitioners/ChangeLog
+++ b/mcs/class/corlib/System.Collections.Concurrent.Partitioners/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Add pfx to the mobile profile
+
 2010-12-07  Jérémie Laval  <jeremie.laval at gmail.com>
 
 	Fix behavior of Partitioner.Create when more than one partition is
diff --git a/mcs/class/corlib/System.Collections.Concurrent.Partitioners/EnumerablePartitioner.cs b/mcs/class/corlib/System.Collections.Concurrent.Partitioners/EnumerablePartitioner.cs
index d236fee..3834a0b 100644
--- a/mcs/class/corlib/System.Collections.Concurrent.Partitioners/EnumerablePartitioner.cs
+++ b/mcs/class/corlib/System.Collections.Concurrent.Partitioners/EnumerablePartitioner.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 using System.Threading;
diff --git a/mcs/class/corlib/System.Collections.Concurrent.Partitioners/ListPartitioner.cs b/mcs/class/corlib/System.Collections.Concurrent.Partitioners/ListPartitioner.cs
index 79a54f5..ee9c3e5 100644
--- a/mcs/class/corlib/System.Collections.Concurrent.Partitioners/ListPartitioner.cs
+++ b/mcs/class/corlib/System.Collections.Concurrent.Partitioners/ListPartitioner.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 using System.Collections.Generic;
diff --git a/mcs/class/corlib/System.Collections.Concurrent.Partitioners/UserRangePartitioner.cs b/mcs/class/corlib/System.Collections.Concurrent.Partitioners/UserRangePartitioner.cs
index 954324c..8d4a75f 100644
--- a/mcs/class/corlib/System.Collections.Concurrent.Partitioners/UserRangePartitioner.cs
+++ b/mcs/class/corlib/System.Collections.Concurrent.Partitioners/UserRangePartitioner.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 using System.Threading;
diff --git a/mcs/class/corlib/System.Collections.Concurrent/ChangeLog b/mcs/class/corlib/System.Collections.Concurrent/ChangeLog
index ad80610..ef0b635 100644
--- a/mcs/class/corlib/System.Collections.Concurrent/ChangeLog
+++ b/mcs/class/corlib/System.Collections.Concurrent/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Add pfx to the mobile profile
+
 2011-01-07  Jérémie Laval  <jeremie.laval at gmail.com>
 
 	Remove now unused internal classes
diff --git a/mcs/class/corlib/System.Collections.Concurrent/ConcurrentDictionary.cs b/mcs/class/corlib/System.Collections.Concurrent/ConcurrentDictionary.cs
index 9ee890e..97f16c6 100644
--- a/mcs/class/corlib/System.Collections.Concurrent/ConcurrentDictionary.cs
+++ b/mcs/class/corlib/System.Collections.Concurrent/ConcurrentDictionary.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 using System.Threading;
diff --git a/mcs/class/corlib/System.Collections.Concurrent/ConcurrentOrderedList.cs b/mcs/class/corlib/System.Collections.Concurrent/ConcurrentOrderedList.cs
index d9644a7..fd12335 100644
--- a/mcs/class/corlib/System.Collections.Concurrent/ConcurrentOrderedList.cs
+++ b/mcs/class/corlib/System.Collections.Concurrent/ConcurrentOrderedList.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 using System.Threading;
diff --git a/mcs/class/corlib/System.Collections.Concurrent/ConcurrentQueue.cs b/mcs/class/corlib/System.Collections.Concurrent/ConcurrentQueue.cs
index 2593381..1be5ccf 100644
--- a/mcs/class/corlib/System.Collections.Concurrent/ConcurrentQueue.cs
+++ b/mcs/class/corlib/System.Collections.Concurrent/ConcurrentQueue.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 using System.Threading;
diff --git a/mcs/class/corlib/System.Collections.Concurrent/ConcurrentStack.cs b/mcs/class/corlib/System.Collections.Concurrent/ConcurrentStack.cs
index 920435b..2e059b6 100644
--- a/mcs/class/corlib/System.Collections.Concurrent/ConcurrentStack.cs
+++ b/mcs/class/corlib/System.Collections.Concurrent/ConcurrentStack.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 using System.Threading;
diff --git a/mcs/class/corlib/System.Collections.Concurrent/IProducerConsumerCollection.cs b/mcs/class/corlib/System.Collections.Concurrent/IProducerConsumerCollection.cs
index 4f991e2..853234c 100644
--- a/mcs/class/corlib/System.Collections.Concurrent/IProducerConsumerCollection.cs
+++ b/mcs/class/corlib/System.Collections.Concurrent/IProducerConsumerCollection.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Collections;
 using System.Collections.Generic;
diff --git a/mcs/class/corlib/System.Collections.Concurrent/OrderablePartitioner.cs b/mcs/class/corlib/System.Collections.Concurrent/OrderablePartitioner.cs
index b1368dd..4a0da43 100644
--- a/mcs/class/corlib/System.Collections.Concurrent/OrderablePartitioner.cs
+++ b/mcs/class/corlib/System.Collections.Concurrent/OrderablePartitioner.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 using System.Collections.Generic;
diff --git a/mcs/class/corlib/System.Collections.Concurrent/Partitioner.cs b/mcs/class/corlib/System.Collections.Concurrent/Partitioner.cs
index 92b5665..7bdd6c3 100644
--- a/mcs/class/corlib/System.Collections.Concurrent/Partitioner.cs
+++ b/mcs/class/corlib/System.Collections.Concurrent/Partitioner.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 using System.Collections.Generic;
diff --git a/mcs/class/corlib/System.Collections.Concurrent/SplitOrderedList.cs b/mcs/class/corlib/System.Collections.Concurrent/SplitOrderedList.cs
index 8399ebe..eff1f0c 100644
--- a/mcs/class/corlib/System.Collections.Concurrent/SplitOrderedList.cs
+++ b/mcs/class/corlib/System.Collections.Concurrent/SplitOrderedList.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0 || INSIDE_SYSTEM_WEB
+#if NET_4_0 || INSIDE_SYSTEM_WEB || MOBILE
 
 using System;
 using System.Threading;
diff --git a/mcs/class/corlib/System.Collections/ChangeLog b/mcs/class/corlib/System.Collections/ChangeLog
index 49f6156..f4c51a1 100644
--- a/mcs/class/corlib/System.Collections/ChangeLog
+++ b/mcs/class/corlib/System.Collections/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Add pfx to the mobile profile
+
 2010-04-15  Jérémie Laval  <jeremie.laval at gmail.com>
 
 	* IStructuralComparable.cs:
diff --git a/mcs/class/corlib/System.Collections/ChangeLog b/mcs/class/corlib/System.Collections/ChangeLog.old
similarity index 100%
copy from mcs/class/corlib/System.Collections/ChangeLog
copy to mcs/class/corlib/System.Collections/ChangeLog.old
diff --git a/mcs/class/corlib/System.Collections/IStructuralComparable.cs b/mcs/class/corlib/System.Collections/IStructuralComparable.cs
index f7695f9..d78267b 100644
--- a/mcs/class/corlib/System.Collections/IStructuralComparable.cs
+++ b/mcs/class/corlib/System.Collections/IStructuralComparable.cs
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if MOONLIGHT || NET_4_0
+#if MOONLIGHT || NET_4_0 || MOBILE
 
 using System;
 
diff --git a/mcs/class/corlib/System.Collections/IStructuralEquatable.cs b/mcs/class/corlib/System.Collections/IStructuralEquatable.cs
index a3d4ef5..a824da3 100644
--- a/mcs/class/corlib/System.Collections/IStructuralEquatable.cs
+++ b/mcs/class/corlib/System.Collections/IStructuralEquatable.cs
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if MOONLIGHT || NET_4_0
+#if MOONLIGHT || NET_4_0 || MOBILE
 
 using System;
 
diff --git a/mcs/class/corlib/System.Globalization/ChangeLog b/mcs/class/corlib/System.Globalization/ChangeLog
index ab6283c..2179827 100644
--- a/mcs/class/corlib/System.Globalization/ChangeLog
+++ b/mcs/class/corlib/System.Globalization/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
 2011-01-06  Zoltan Varga  <vargaz at gmail.com>
 
 	Change some usages of ArrayList to List<T> to avoid calls to the
diff --git a/mcs/class/corlib/System.Globalization/CultureNotFoundException.cs b/mcs/class/corlib/System.Globalization/CultureNotFoundException.cs
index e1aa052..bd1ed14 100644
--- a/mcs/class/corlib/System.Globalization/CultureNotFoundException.cs
+++ b/mcs/class/corlib/System.Globalization/CultureNotFoundException.cs
@@ -26,7 +26,7 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 using System;
 using System.Runtime.InteropServices;
diff --git a/mcs/class/corlib/System.Globalization/TimeSpanStyles.cs b/mcs/class/corlib/System.Globalization/TimeSpanStyles.cs
index 4c15ce2..18b3c92 100644
--- a/mcs/class/corlib/System.Globalization/TimeSpanStyles.cs
+++ b/mcs/class/corlib/System.Globalization/TimeSpanStyles.cs
@@ -26,7 +26,7 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 using System;
 
diff --git a/mcs/class/corlib/System.IO/ChangeLog b/mcs/class/corlib/System.IO/ChangeLog
index 6fcbbda..24655ab 100644
--- a/mcs/class/corlib/System.IO/ChangeLog
+++ b/mcs/class/corlib/System.IO/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
 2011-01-06  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
 
 	[windows] Improve drive search
diff --git a/mcs/class/corlib/System.IO/Directory.cs b/mcs/class/corlib/System.IO/Directory.cs
index 8596157..d1617c6 100644
--- a/mcs/class/corlib/System.IO/Directory.cs
+++ b/mcs/class/corlib/System.IO/Directory.cs
@@ -503,7 +503,7 @@ namespace System.IO
 			return result;
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public static string[] GetFileSystemEntries (string path, string searchPattern, SearchOption searchOption)
 		{
 			// Take the simple way home:
diff --git a/mcs/class/corlib/System.IO/DirectoryInfo.cs b/mcs/class/corlib/System.IO/DirectoryInfo.cs
index 0e214a0..c419f7d 100644
--- a/mcs/class/corlib/System.IO/DirectoryInfo.cs
+++ b/mcs/class/corlib/System.IO/DirectoryInfo.cs
@@ -378,7 +378,7 @@ namespace System.IO {
 		}
 #endif
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 		public IEnumerable<DirectoryInfo> EnumerateDirectories ()
 		{
diff --git a/mcs/class/corlib/System.IO/FileStream.cs b/mcs/class/corlib/System.IO/FileStream.cs
index 62fec8e..2073d7f 100644
--- a/mcs/class/corlib/System.IO/FileStream.cs
+++ b/mcs/class/corlib/System.IO/FileStream.cs
@@ -845,7 +845,7 @@ namespace System.IO
 			FlushBuffer ();
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public virtual void Flush (bool flushToDisk)
 		{
 			FlushBuffer ();
diff --git a/mcs/class/corlib/System.IO/Path.cs b/mcs/class/corlib/System.IO/Path.cs
index fefa577..510859a 100644
--- a/mcs/class/corlib/System.IO/Path.cs
+++ b/mcs/class/corlib/System.IO/Path.cs
@@ -747,7 +747,7 @@ namespace System.IO {
 			return String.Compare (subset, slast, path, slast, subset.Length - slast) == 0;
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public
 #else
                 internal
@@ -787,7 +787,7 @@ namespace System.IO {
 			return ret.ToString ();
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public
 #else
                 internal
@@ -806,7 +806,7 @@ namespace System.IO {
 			return Combine (new string [] { path1, path2, path3 });
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public
 #else
                 internal
diff --git a/mcs/class/corlib/System.Reflection.Emit/AssemblyBuilder.cs b/mcs/class/corlib/System.Reflection.Emit/AssemblyBuilder.cs
index 5f49190..a2fad67 100644
--- a/mcs/class/corlib/System.Reflection.Emit/AssemblyBuilder.cs
+++ b/mcs/class/corlib/System.Reflection.Emit/AssemblyBuilder.cs
@@ -1216,7 +1216,7 @@ namespace System.Reflection.Emit
 			throw new NotImplementedException ();
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public override Type GetType (string name, bool throwOnError, bool ignoreCase)
 		{
 			if (name == null)
diff --git a/mcs/class/corlib/System.Reflection.Emit/ChangeLog b/mcs/class/corlib/System.Reflection.Emit/ChangeLog
index a264099..8bbb7d7 100644
--- a/mcs/class/corlib/System.Reflection.Emit/ChangeLog
+++ b/mcs/class/corlib/System.Reflection.Emit/ChangeLog
@@ -1,3 +1,11 @@
+2011-02-01  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	* DynamicMethod.cs: No longer finalizable.
+
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
 2011-01-06  Zoltan Varga  <vargaz at gmail.com>
 
 	Change some usages of ArrayList to List<T> to avoid calls to the
diff --git a/mcs/class/corlib/System.Reflection.Emit/DynamicMethod.cs b/mcs/class/corlib/System.Reflection.Emit/DynamicMethod.cs
index 9af5601..6fb1600 100644
--- a/mcs/class/corlib/System.Reflection.Emit/DynamicMethod.cs
+++ b/mcs/class/corlib/System.Reflection.Emit/DynamicMethod.cs
@@ -127,9 +127,6 @@ namespace System.Reflection.Emit {
 		[MethodImplAttribute(MethodImplOptions.InternalCall)]
 		private extern void create_dynamic_method (DynamicMethod m);
 
-		[MethodImplAttribute(MethodImplOptions.InternalCall)]
-		private extern void destroy_dynamic_method (DynamicMethod m);
-
 		private void CreateDynMethod () {
 			if (mhandle.Value == IntPtr.Zero) {
 				if (ilgen == null || ilgen.ILOffset == 0)
@@ -158,11 +155,6 @@ namespace System.Reflection.Emit {
 			}
 		}
 
-		~DynamicMethod ()
-		{
-			destroy_dynamic_method (this);
-		}
-
 		[ComVisible (true)]
 		public Delegate CreateDelegate (Type delegateType)
 		{
diff --git a/mcs/class/corlib/System.Reflection.Emit/ModuleBuilder.cs b/mcs/class/corlib/System.Reflection.Emit/ModuleBuilder.cs
index 2be3940..f951d4f 100644
--- a/mcs/class/corlib/System.Reflection.Emit/ModuleBuilder.cs
+++ b/mcs/class/corlib/System.Reflection.Emit/ModuleBuilder.cs
@@ -824,7 +824,7 @@ namespace System.Reflection.Emit {
 			throw new NotImplementedException ();
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public override	Assembly Assembly {
 			get { return assemblyb; }
 		}
diff --git a/mcs/class/corlib/System.Reflection/Assembly.cs b/mcs/class/corlib/System.Reflection/Assembly.cs
index 89d3871..e7f34d9 100644
--- a/mcs/class/corlib/System.Reflection/Assembly.cs
+++ b/mcs/class/corlib/System.Reflection/Assembly.cs
@@ -76,7 +76,7 @@ namespace System.Reflection {
 		private bool fromByteArray;
 		private string assemblyName;
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		protected
 #else
 		internal
@@ -506,6 +506,13 @@ namespace System.Reflection {
 #endif
 
 #if NET_4_0
+		public static Assembly UnsafeLoadFrom (String assemblyFile)
+		{
+			return LoadFrom (assemblyFile);
+		}
+#endif
+
+#if NET_4_0
 		[Obsolete]
 #endif
 		public static Assembly LoadFile (String path, Evidence securityEvidence)
@@ -608,7 +615,7 @@ namespace System.Reflection {
 
 		[MonoTODO ("Not implemented")]
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		virtual
 #endif
 		Module LoadModule (string moduleName, byte [] rawModule, byte [] rawSymbolStore)
@@ -663,7 +670,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		virtual
 #endif
 		Object CreateInstance (String typeName, Boolean ignoreCase,
@@ -753,7 +760,7 @@ namespace System.Reflection {
 		[MonoTODO ("Currently it always returns zero")]
 		[ComVisible (false)]
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		virtual
 #endif
 		long HostContext {
@@ -792,7 +799,7 @@ namespace System.Reflection {
 		}
 		
 #if NET_4_0
-#if MOONLIGHT
+#if MOONLIGHT || MOBILE
 		public virtual IList<CustomAttributeData> GetCustomAttributesData () {
 			return CustomAttributeData.GetCustomAttributes (this);
 		}
@@ -890,7 +897,7 @@ namespace System.Reflection {
 		}
 #endif
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		static Exception CreateNIE ()
 		{
 			return new NotImplementedException ("Derived classes must implement it");
diff --git a/mcs/class/corlib/System.Reflection/Binder.cs b/mcs/class/corlib/System.Reflection/Binder.cs
index 615db74..244169a 100644
--- a/mcs/class/corlib/System.Reflection/Binder.cs
+++ b/mcs/class/corlib/System.Reflection/Binder.cs
@@ -182,22 +182,31 @@ namespace System.Reflection
 			static void AdjustArguments (MethodBase selected, ref object [] args)
 			{
 				var parameters = selected.GetParameters ();
-				if (parameters.Length == 0)
+				var parameters_length = parameters.Length;
+				if (parameters_length == 0)
 					return;
 
 				var last_parameter = parameters [parameters.Length - 1];
+				Type last_parameter_type = last_parameter.ParameterType;
 				if (!Attribute.IsDefined (last_parameter, typeof (ParamArrayAttribute)))
 					return;
 
-				var adjusted = new object [parameters.Length];
-				Array.Copy (args, adjusted, parameters.Length - 1);
-
-				var param_args_count = args.Length + 1 - parameters.Length;
-				var params_args = Array.CreateInstance (last_parameter.ParameterType.GetElementType (), param_args_count);
-
+				var args_length = args.Length;
+				var param_args_count = args_length + 1 - parameters_length;
+				var first_vararg_index = args_length - param_args_count;
+				if (first_vararg_index < args_length) {
+					var first_vararg = args [first_vararg_index];
+					if (first_vararg != null && first_vararg.GetType () == last_parameter_type)
+						return;
+				}
+				
+				var params_args = Array.CreateInstance (last_parameter_type.GetElementType (), param_args_count);
 				for (int i = 0; i < param_args_count; i++)
-					params_args.SetValue (args [args.Length - param_args_count + i], i);
+					params_args.SetValue (args [first_vararg_index + i], i);
 
+				var adjusted = new object [parameters_length];
+				Array.Copy (args, adjusted, parameters_length - 1);
+				
 				adjusted [adjusted.Length - 1] = params_args;
 				args = adjusted;
 			}
diff --git a/mcs/class/corlib/System.Reflection/ChangeLog b/mcs/class/corlib/System.Reflection/ChangeLog
index f19c705..85ffe2c 100644
--- a/mcs/class/corlib/System.Reflection/ChangeLog
+++ b/mcs/class/corlib/System.Reflection/ChangeLog
@@ -1,3 +1,20 @@
+2011-02-03  Marek Habersack  <grendel at twistedcode.net>
+
+	[reflection] Default binder's AdjustArguments method treats
+	ParamArray parameters which are already arrays properly
+
+	Such parameters are not adjusted as it would lead to an
+	InvalidCastException whenever an attempt to set an array index's
+	value would be made.
+
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
+2011-01-21  Zoltan Varga  <vargaz at gmail.com>
+
+	Add NET 4.0 Assembly.UnsafeLoadFrom () method.
+
 2011-01-06  Zoltan Varga  <vargaz at gmail.com>
 
 	Change some usages of ArrayList to List<T> to avoid calls to the
diff --git a/mcs/class/corlib/System.Reflection/Module.cs b/mcs/class/corlib/System.Reflection/Module.cs
index d266d34..a3e7fda 100644
--- a/mcs/class/corlib/System.Reflection/Module.cs
+++ b/mcs/class/corlib/System.Reflection/Module.cs
@@ -48,7 +48,7 @@ namespace System.Reflection {
 	[Serializable]
 	[ClassInterfaceAttribute (ClassInterfaceType.None)]
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 	public abstract class Module : ISerializable, ICustomAttributeProvider, _Module {
 #else
 	public partial class Module : ISerializable, ICustomAttributeProvider, _Module {
@@ -75,7 +75,7 @@ namespace System.Reflection {
 		}
 
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		protected
 #else
 		internal
@@ -321,7 +321,7 @@ namespace System.Reflection {
 
 #endif
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 		public virtual Assembly Assembly {
 			get { throw CreateNIE (); }
diff --git a/mcs/class/corlib/System.Reflection/MonoAssembly.cs b/mcs/class/corlib/System.Reflection/MonoAssembly.cs
index 410e192..8bfead7 100644
--- a/mcs/class/corlib/System.Reflection/MonoAssembly.cs
+++ b/mcs/class/corlib/System.Reflection/MonoAssembly.cs
@@ -35,7 +35,7 @@ using System.Collections.Generic;
 
 namespace System.Reflection {
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 	[ComVisible (true)]
 	[ComDefaultInterfaceAttribute (typeof (_Assembly))]
 	[Serializable]
@@ -45,7 +45,7 @@ namespace System.Reflection {
 	public partial class Assembly {
 #endif
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		Type GetType (string name, bool throwOnError, bool ignoreCase)
@@ -57,7 +57,7 @@ namespace System.Reflection {
 			throw new ArgumentException ("name", "Name cannot be empty");
 
 			res = InternalGetType (null, name, throwOnError, ignoreCase);
-#if !(NET_4_0 || MOONLIGHT)
+#if !(NET_4_0 || MOONLIGHT || MOBILE)
 			if (res is TypeBuilder) {
 				if (throwOnError)
 					throw new TypeLoadException (string.Format ("Could not load type '{0}' from assembly '{1}'", name, this));
@@ -68,7 +68,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		Module GetModule (String name)
@@ -88,7 +88,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		AssemblyName[] GetReferencedAssemblies () {
@@ -96,7 +96,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		Module[] GetModules (bool getResourceModules) {
@@ -115,7 +115,7 @@ namespace System.Reflection {
 
 		[MonoTODO ("Always returns the same as GetModules")]
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		Module[] GetLoadedModules (bool getResourceModules)
@@ -124,7 +124,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		Assembly GetSatelliteAssembly (CultureInfo culture)
@@ -133,7 +133,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		Assembly GetSatelliteAssembly (CultureInfo culture, Version version)
@@ -144,7 +144,7 @@ namespace System.Reflection {
 		//FIXME remove GetManifestModule under v4, it's a v2 artifact
 		[ComVisible (false)]
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		Module ManifestModule {
diff --git a/mcs/class/corlib/System.Reflection/MonoModule.cs b/mcs/class/corlib/System.Reflection/MonoModule.cs
index 19b07af..97e3481 100644
--- a/mcs/class/corlib/System.Reflection/MonoModule.cs
+++ b/mcs/class/corlib/System.Reflection/MonoModule.cs
@@ -38,7 +38,7 @@ using System.Security.Permissions;
 
 namespace System.Reflection {
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 	[ComVisible (true)]
 	[ComDefaultInterfaceAttribute (typeof (_Module))]
 	[Serializable]
@@ -49,7 +49,7 @@ namespace System.Reflection {
 #endif
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		Assembly Assembly {
@@ -57,7 +57,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		// Note: we do not ask for PathDiscovery because no path is returned here.
@@ -67,7 +67,7 @@ namespace System.Reflection {
 		}
 	
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		string ScopeName {
@@ -75,7 +75,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		int MDStreamVersion {
@@ -87,7 +87,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		Guid ModuleVersionId {
@@ -96,7 +96,7 @@ namespace System.Reflection {
 			}
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public override
 #else
 		public virtual
@@ -113,7 +113,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		bool IsResource()
@@ -121,7 +121,7 @@ namespace System.Reflection {
 			return is_resource;
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public override
 #else
 		public virtual
@@ -136,7 +136,7 @@ namespace System.Reflection {
 			return filtered.ToArray ();
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public override
 #else
 		public virtual
@@ -146,7 +146,7 @@ namespace System.Reflection {
 			return MonoCustomAttrs.GetCustomAttributes (this, inherit);
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public override
 #else
 		public virtual
@@ -156,7 +156,7 @@ namespace System.Reflection {
 			return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public override
 #else
 		public virtual
@@ -170,7 +170,7 @@ namespace System.Reflection {
 			return (globalType != null) ? globalType.GetField (name, bindingAttr) : null;
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public override
 #else
 		public virtual
@@ -184,7 +184,7 @@ namespace System.Reflection {
 			return (globalType != null) ? globalType.GetFields (bindingFlags) : new FieldInfo [0];
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public override
 #else
 		public virtual
@@ -193,7 +193,7 @@ namespace System.Reflection {
 			get { return get_MetadataToken (this); }
 		}
 		protected
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #else
 		virtual
@@ -212,7 +212,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		MethodInfo[] GetMethods (BindingFlags bindingFlags) {
@@ -223,7 +223,7 @@ namespace System.Reflection {
 			return (globalType != null) ? globalType.GetMethods (bindingFlags) : new MethodInfo [0];
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public override
 #else
 		public virtual
@@ -232,7 +232,7 @@ namespace System.Reflection {
 			ModuleHandle.GetPEKind (out peKind, out machine);
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public override
 #else
 		public virtual
@@ -246,7 +246,7 @@ namespace System.Reflection {
 			return assembly.InternalGetType (this, className, throwOnError, ignoreCase);
 		}
 	
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public override
 #else
 		public virtual
@@ -257,7 +257,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
@@ -271,7 +271,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
@@ -286,7 +286,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
@@ -300,7 +300,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		string ResolveString (int metadataToken) {
@@ -314,7 +314,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
@@ -328,7 +328,7 @@ namespace System.Reflection {
 		}
 
 		public
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		override
 #endif
 		byte[] ResolveSignature (int metadataToken) {
@@ -358,7 +358,7 @@ namespace System.Reflection {
 		}
 #endif
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public override
 #else
 		public virtual
@@ -368,7 +368,7 @@ namespace System.Reflection {
 			return InternalGetTypes ();
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public override IList<CustomAttributeData> GetCustomAttributesData () {
 			return CustomAttributeData.GetCustomAttributes (this);
 		}
diff --git a/mcs/class/corlib/System.Runtime.CompilerServices/ChangeLog b/mcs/class/corlib/System.Runtime.CompilerServices/ChangeLog
index 3b18c5a..9bc3a63 100644
--- a/mcs/class/corlib/System.Runtime.CompilerServices/ChangeLog
+++ b/mcs/class/corlib/System.Runtime.CompilerServices/ChangeLog
@@ -1,3 +1,11 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Add pfx to the mobile profile
+
 2010-11-08  Marek Safar  <marek.safar at gmail.com>
 
 	API compatibility work
diff --git a/mcs/class/corlib/System.Runtime.CompilerServices/ConditionalWeakTable.cs b/mcs/class/corlib/System.Runtime.CompilerServices/ConditionalWeakTable.cs
index 171cd12..4abb40f 100644
--- a/mcs/class/corlib/System.Runtime.CompilerServices/ConditionalWeakTable.cs
+++ b/mcs/class/corlib/System.Runtime.CompilerServices/ConditionalWeakTable.cs
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 using System;
 using System.Collections;
 
diff --git a/mcs/class/corlib/System.Runtime.CompilerServices/ReferenceAssemblyAttribute.cs b/mcs/class/corlib/System.Runtime.CompilerServices/ReferenceAssemblyAttribute.cs
index 0d1358f..20ed7a8 100644
--- a/mcs/class/corlib/System.Runtime.CompilerServices/ReferenceAssemblyAttribute.cs
+++ b/mcs/class/corlib/System.Runtime.CompilerServices/ReferenceAssemblyAttribute.cs
@@ -25,7 +25,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 using System;
 using System.Runtime.InteropServices;
diff --git a/mcs/class/corlib/System.Runtime.CompilerServices/TypeForwardedFromAttribute.cs b/mcs/class/corlib/System.Runtime.CompilerServices/TypeForwardedFromAttribute.cs
index fcfe428..9881d0f 100644
--- a/mcs/class/corlib/System.Runtime.CompilerServices/TypeForwardedFromAttribute.cs
+++ b/mcs/class/corlib/System.Runtime.CompilerServices/TypeForwardedFromAttribute.cs
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 namespace System.Runtime.CompilerServices
 {
diff --git a/mcs/class/corlib/System.Runtime.InteropServices/ChangeLog b/mcs/class/corlib/System.Runtime.InteropServices/ChangeLog
index 80641c7..73f497b 100644
--- a/mcs/class/corlib/System.Runtime.InteropServices/ChangeLog
+++ b/mcs/class/corlib/System.Runtime.InteropServices/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-22  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Fix Dispose()
+
 2010-12-15  Marek Safar  <marek.safar at gmail.com>
 
 	Some .net 4.0 api compatibility fixes
diff --git a/mcs/class/corlib/System.Runtime.InteropServices/CriticalHandle.cs b/mcs/class/corlib/System.Runtime.InteropServices/CriticalHandle.cs
index 479dc44..ce50aff 100644
--- a/mcs/class/corlib/System.Runtime.InteropServices/CriticalHandle.cs
+++ b/mcs/class/corlib/System.Runtime.InteropServices/CriticalHandle.cs
@@ -47,17 +47,14 @@ namespace System.Runtime.InteropServices
 			if (_disposed)
 				return;
 
-			_disposed = true;
-			if (IsInvalid)
-				return;
-
-			if (disposing == true && !IsInvalid){
-				if (!ReleaseHandle ()) {
+			if (!IsInvalid){
+				if (!_disposed && !ReleaseHandle ()) {
 					GC.SuppressFinalize (this);
 				} else {
 					// Failed in release...
 				}
 			}
+			_disposed = true;
 		}
 
 		[ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
diff --git a/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ChangeLog b/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ChangeLog
index a0f9e17..6f1e854 100644
--- a/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ChangeLog
+++ b/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ChangeLog
@@ -1,3 +1,17 @@
+2010-09-24  Kyle Ambroff  <kyle at ambroff.com>
+
+	version tolerant serialization fails with missing primitive
+	members
+
+	Modifies ObjectReader so that when it encounters a primitive typed
+	member in an object stream which has no corresponding member in
+	the app domain, it will read the value anyway and throw it away.
+	That way it can read the next block from the stream.
+
+	Added a unit test which passes with the changes to ObjectReader.
+
+	Fixes bug #641821.
+
 2010-10-20  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
 
 	Able to read MS serialized nullable<primitive>
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 cf068a2..fd9c533 100644
--- a/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs
+++ b/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs
@@ -294,13 +294,22 @@ namespace System.Runtime.Serialization.Formatters.Binary
 				
 			info = metadata.NeedsSerializationInfo ? new SerializationInfo(metadata.Type, new FormatterConverter()) : null;
 
-   			if (metadata.MemberNames != null)
+			if (metadata.MemberNames != null) {
 				for (int n=0; n<metadata.FieldCount; n++)
 					ReadValue (reader, objectInstance, objectId, info, metadata.MemberTypes[n], metadata.MemberNames[n], null, null);
-			else
-				for (int n=0; n<metadata.FieldCount; n++)
+			} else
+				for (int n=0; n<metadata.FieldCount; n++) {
 					if (metadata.MemberInfos [n] != null)
-					ReadValue (reader, objectInstance, objectId, info, metadata.MemberTypes[n], metadata.MemberInfos[n].Name, metadata.MemberInfos[n], null);
+						ReadValue (reader, objectInstance, objectId, info, metadata.MemberTypes[n], metadata.MemberInfos[n].Name, metadata.MemberInfos[n], null);
+					else if (BinaryCommon.IsPrimitive(metadata.MemberTypes[n])) {
+						// Since the member info is null, the type in this
+						// domain does not have this type. Even though we
+						// are not going to store the value, we will read
+						// it from the stream so that we can advance to the
+						// next block.
+						ReadPrimitiveTypeValue (reader,	metadata.MemberTypes[n]);
+					}
+				}
 		}
 
 		private void RegisterObject (long objectId, object objectInstance, SerializationInfo info, long parentObjectId, MemberInfo parentObjectMemeber, int[] indices)
diff --git a/mcs/class/corlib/System.Security.AccessControl/ChangeLog b/mcs/class/corlib/System.Security.AccessControl/ChangeLog
index 624c9f3..e1179b8 100644
--- a/mcs/class/corlib/System.Security.AccessControl/ChangeLog
+++ b/mcs/class/corlib/System.Security.AccessControl/ChangeLog
@@ -1,3 +1,11 @@
+2010-12-04  Kenneth Bell  <ken.git at chezbell.org.uk>
+
+	Implement RawSecurityDescriptor.
+
+	* Marshals to/from SDDL and binary form.
+
+	* Supports 'Common' ACEs and 'Object' ACEs
+
 2010-12-15  Marek Safar  <marek.safar at gmail.com>
 
 	Some .net 4.0 api compatibility fixes
diff --git a/mcs/class/corlib/System.Security.AccessControl/CommonAce.cs b/mcs/class/corlib/System.Security.AccessControl/CommonAce.cs
index f524eeb..fefa04b 100644
--- a/mcs/class/corlib/System.Security.AccessControl/CommonAce.cs
+++ b/mcs/class/corlib/System.Security.AccessControl/CommonAce.cs
@@ -4,6 +4,7 @@
 // Authors:
 //	Dick Porter  <dick at ximian.com>
 //	Atsushi Enomoto  <atsushi at ximian.com>
+//	Kenneth Bell
 //
 // Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com)
 //
@@ -27,40 +28,129 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+using System.Globalization;
 using System.Security.Principal;
 
 namespace System.Security.AccessControl {
-	public sealed class CommonAce : QualifiedAce
-	{
+	public sealed class CommonAce : QualifiedAce {
 		public CommonAce (AceFlags flags, AceQualifier qualifier,
-				  int accessMask, SecurityIdentifier sid,
-				  bool isCallback, byte[] opaque)
-				: base (InheritanceFlags.None, PropagationFlags.None, qualifier, isCallback, opaque)
+		                  int accessMask, SecurityIdentifier sid,
+		                  bool isCallback, byte[] opaque)
+			: base(ConvertType (qualifier, isCallback),
+			       flags,
+			       opaque)
 		{
 			AccessMask = accessMask;
 			SecurityIdentifier = sid;
 		}
-		
-		[MonoTODO]
-		public override int BinaryLength
+
+		internal CommonAce (AceType type, AceFlags flags, int accessMask,
+		                    SecurityIdentifier sid, byte[] opaque)
+			: base(type, flags, opaque)
 		{
+			AccessMask = accessMask;
+			SecurityIdentifier = sid;
+		}
+
+		internal CommonAce(byte[] binaryForm, int offset)
+			: base(binaryForm, offset)
+		{
+			int len = ReadUShort(binaryForm, offset + 2);
+			if (offset > binaryForm.Length - len)
+				throw new ArgumentException("Invalid ACE - truncated", "binaryForm");
+			if (len < 8 + SecurityIdentifier.MinBinaryLength)
+				throw new ArgumentException("Invalid ACE", "binaryForm");
+			
+			AccessMask = ReadInt(binaryForm, offset + 4);
+			SecurityIdentifier = new SecurityIdentifier(binaryForm,
+			                                            offset + 8);
+			
+			int opaqueLen = len - (8 + SecurityIdentifier.BinaryLength);
+			if (opaqueLen > 0) {
+				byte[] opaque = new byte[opaqueLen];
+				Array.Copy(binaryForm,
+				           offset + 8 + SecurityIdentifier.BinaryLength,
+				           opaque, 0, opaqueLen);
+			}
+		}
+
+		public override int BinaryLength {
 			get {
-				throw new NotImplementedException ();
+				return 8 + SecurityIdentifier.BinaryLength
+					+ OpaqueLength;
 			}
 		}
 
-		[MonoTODO]
 		public override void GetBinaryForm (byte[] binaryForm,
-						    int offset)
+		                                    int offset)
 		{
-			throw new NotImplementedException ();
+			int len = BinaryLength;
+			binaryForm[offset] = (byte)this.AceType;
+			binaryForm[offset + 1] = (byte)this.AceFlags;
+			WriteUShort ((ushort)len, binaryForm, offset + 2);
+			WriteInt (AccessMask, binaryForm, offset + 4);
+			
+			SecurityIdentifier.GetBinaryForm (binaryForm,
+			                                  offset + 8);
+			
+			byte[] opaque = GetOpaque ();
+			if (opaque != null)
+				Array.Copy (opaque, 0, binaryForm,
+				            offset + 8 + SecurityIdentifier.BinaryLength,
+				            opaque.Length);
 		}
-		
-		[MonoTODO]
+
 		public static int MaxOpaqueLength (bool isCallback)
 		{
-			throw new NotImplementedException ();
+			// Varies by platform?
+			return 65459;
+		}
+
+		internal override string GetSddlForm ()
+		{
+			if (OpaqueLength != 0)
+				throw new NotImplementedException (
+					"Unable to convert conditional ACEs to SDDL");
+			
+			return string.Format (CultureInfo.InvariantCulture,
+			                      "({0};{1};{2};;;{3})",
+			                      GetSddlAceType (AceType),
+			                      GetSddlAceFlags (AceFlags),
+			                      GetSddlAccessRights (AccessMask),
+			                      SecurityIdentifier.GetSddlForm ());
+		}
+
+		private static AceType ConvertType (AceQualifier qualifier,
+		                                    bool isCallback)
+		{
+			switch (qualifier) {
+			case AceQualifier.AccessAllowed:
+				if (isCallback)
+					return AceType.AccessAllowedCallback;
+				else
+					return AceType.AccessAllowed;
+				
+			case AceQualifier.AccessDenied:
+				if (isCallback)
+					return AceType.AccessDeniedCallback;
+				else
+					return AceType.AccessDenied;
+				
+			case AceQualifier.SystemAlarm:
+				if (isCallback)
+					return AceType.SystemAlarmCallback;
+				else
+					return AceType.SystemAlarm;
+				
+			case AceQualifier.SystemAudit:
+				if (isCallback)
+					return AceType.SystemAuditCallback;
+				else
+					return AceType.SystemAudit;
+				
+			default:
+				throw new ArgumentException ("Unrecognized ACE qualifier: " + qualifier, "qualifier");
+			}
 		}
 	}
 }
-
diff --git a/mcs/class/corlib/System.Security.AccessControl/CommonAcl.cs b/mcs/class/corlib/System.Security.AccessControl/CommonAcl.cs
index 03b2ad7..948d279 100644
--- a/mcs/class/corlib/System.Security.AccessControl/CommonAcl.cs
+++ b/mcs/class/corlib/System.Security.AccessControl/CommonAcl.cs
@@ -111,6 +111,11 @@ namespace System.Security.AccessControl {
 		{
 			throw new NotImplementedException ();
 		}
+		
+		internal override string GetSddlForm(ControlFlags sdFlags, bool isDacl)
+		{
+			throw new NotImplementedException();
+		}
 	}
 }
 
diff --git a/mcs/class/corlib/System.Security.AccessControl/CompoundAce.cs b/mcs/class/corlib/System.Security.AccessControl/CompoundAce.cs
index ef52c5c..891eada 100644
--- a/mcs/class/corlib/System.Security.AccessControl/CompoundAce.cs
+++ b/mcs/class/corlib/System.Security.AccessControl/CompoundAce.cs
@@ -33,13 +33,12 @@ namespace System.Security.AccessControl
 {
 	public sealed class CompoundAce : KnownAce
 	{
-		CompoundAceType compound_ace_type;
+		private CompoundAceType compound_ace_type;
 		
 		public CompoundAce (AceFlags flags, int accessMask, CompoundAceType compoundAceType, SecurityIdentifier sid)
-			: base (InheritanceFlags.None, PropagationFlags.None)
+			: base (AceType.AccessAllowedCompound, flags)
 		{
 			this.compound_ace_type = compoundAceType;
-			this.AceFlags = flags;
 			this.AccessMask = accessMask;
 			this.SecurityIdentifier = sid;
 		}
@@ -62,6 +61,11 @@ namespace System.Security.AccessControl
 		{
 			throw new NotImplementedException ();
 		}
+		
+		internal override string GetSddlForm ()
+		{
+			throw new NotImplementedException();
+		}
 	}
 }
 
diff --git a/mcs/class/corlib/System.Security.AccessControl/CustomAce.cs b/mcs/class/corlib/System.Security.AccessControl/CustomAce.cs
index 29f7546..46c17e3 100644
--- a/mcs/class/corlib/System.Security.AccessControl/CustomAce.cs
+++ b/mcs/class/corlib/System.Security.AccessControl/CustomAce.cs
@@ -29,53 +29,56 @@
 
 using System.Collections;
 
-namespace System.Security.AccessControl
-{
-	public sealed class CustomAce : GenericAce
-	{
-		public CustomAce (AceType type, AceFlags flags, byte [] opaque)
-			: base (type)
-		{
-			AceFlags = flags;
+namespace System.Security.AccessControl {
+	public sealed class CustomAce : GenericAce {
+		private byte[] opaque;
 
+		public CustomAce (AceType type, AceFlags flags, byte[] opaque)
+			: base(type, flags)
+		{
 			/* FIXME: check length of opaque >
 			 * MaxOpaqueLength or !multiple of 4
-			 */
-			 SetOpaque (opaque);
+			 */			
+			SetOpaque (opaque);
 		}
 
-		byte [] opaque;
-
 		[MonoTODO]
 		public static readonly int MaxOpaqueLength;
-		
+
 		[MonoTODO]
 		public override int BinaryLength {
-			get { throw new NotImplementedException (); }
+			get {
+				throw new NotImplementedException ();
+			}
 		}
-		
+
 		public int OpaqueLength {
 			get { return opaque.Length; }
 		}
 
 		[MonoTODO]
 		public override void GetBinaryForm (byte[] binaryForm,
-						    int offset)
+		                                    int offset)
 		{
 			throw new NotImplementedException ();
 		}
-		
-		public byte [] GetOpaque ()
+
+		public byte[] GetOpaque ()
 		{
-			return (byte []) opaque.Clone ();
+			return (byte[])opaque.Clone ();
 		}
-		
-		public void SetOpaque (byte [] opaque)
+
+		public void SetOpaque (byte[] opaque)
 		{
 			if (opaque == null)
-				throw new ArgumentNullException ("opaque");
-			this.opaque = (byte []) opaque.Clone ();
+				this.opaque = null;
+			else
+				this.opaque = (byte[])opaque.Clone ();
 		}
-	}
-}
 
+		internal override string GetSddlForm ()
+		{
+			throw new NotSupportedException ();
+		}
+	}
+}
\ No newline at end of file
diff --git a/mcs/class/corlib/System.Security.AccessControl/GenericAce.cs b/mcs/class/corlib/System.Security.AccessControl/GenericAce.cs
index 67217ae..a86eb3f 100644
--- a/mcs/class/corlib/System.Security.AccessControl/GenericAce.cs
+++ b/mcs/class/corlib/System.Security.AccessControl/GenericAce.cs
@@ -4,6 +4,7 @@
 // Authors:
 //	Dick Porter  <dick at ximian.com>
 //	Atsushi Enomoto  <atsushi at ximian.com>
+//	Kenneth Bell
 //
 // Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com)
 //
@@ -27,33 +28,41 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-using System.Collections;
+using System.Globalization;
+using System.Security.Principal;
+using System.Text;
 
 namespace System.Security.AccessControl {
 	public abstract class GenericAce
 	{
-		internal GenericAce (InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
-		{
-			inheritance = inheritanceFlags;
-			propagation = propagationFlags;
-		}
-
-		internal GenericAce (AceType type)
+		private AceFlags ace_flags;
+		private AceType ace_type;
+		
+		internal GenericAce (AceType type, AceFlags flags)
 		{
-			if (type <= AceType.MaxDefinedAceType) {
+			if (type > AceType.MaxDefinedAceType) {
 				throw new ArgumentOutOfRangeException ("type");
 			}
+			
 			this.ace_type = type;
+			this.ace_flags = flags;
 		}
-
-		InheritanceFlags inheritance;
-		PropagationFlags propagation;
-		AceFlags aceflags;
-		AceType ace_type;
-
+		
+		internal GenericAce(byte[] binaryForm, int offset)
+		{
+			if (binaryForm == null)
+				throw new ArgumentNullException("binaryForm");
+			
+			if (offset < 0 || offset > binaryForm.Length - 2)
+				throw new ArgumentOutOfRangeException("offset", offset, "Offset out of range");
+			
+			ace_type = (AceType)binaryForm[offset];
+			ace_flags = (AceFlags)binaryForm[offset + 1];
+		}
+		
 		public AceFlags AceFlags {
-			get { return aceflags; }
-			set { aceflags = value; }
+			get { return ace_flags; }
+			set { ace_flags = value; }
 		}
 		
 		public AceType AceType {
@@ -63,9 +72,9 @@ namespace System.Security.AccessControl {
 		public AuditFlags AuditFlags {
 			get {
 				AuditFlags ret = AuditFlags.None;
-				if ((aceflags & AceFlags.SuccessfulAccess) != 0)
+				if ((ace_flags & AceFlags.SuccessfulAccess) != 0)
 					ret |= AuditFlags.Success;
-				if ((aceflags & AceFlags.FailedAccess) != 0)
+				if ((ace_flags & AceFlags.FailedAccess) != 0)
 					ret |= AuditFlags.Failure;
 				return ret;
 			}
@@ -74,57 +83,378 @@ namespace System.Security.AccessControl {
 		public abstract int BinaryLength { get; }
 
 		public InheritanceFlags InheritanceFlags {
-			get { return inheritance; }
+			get {
+				InheritanceFlags ret = InheritanceFlags.None;
+				if ((ace_flags & AceFlags.ObjectInherit) != 0)
+					ret |= InheritanceFlags.ObjectInherit;
+				if ((ace_flags & AceFlags.ContainerInherit) != 0)
+					ret |= InheritanceFlags.ContainerInherit;
+				return ret;
+			}
 		}
 
-		[MonoTODO]
 		public bool IsInherited {
-			get { return(false); }
+			get { return (ace_flags & AceFlags.Inherited) != AceFlags.None; }
 		}
 
 		public PropagationFlags PropagationFlags {
-			get { return propagation; }
+			get {
+				PropagationFlags ret = PropagationFlags.None;
+				if ((ace_flags & AceFlags.InheritOnly) != 0)
+					ret |= PropagationFlags.InheritOnly;
+				if ((ace_flags & AceFlags.NoPropagateInherit) != 0)
+					ret |= PropagationFlags.NoPropagateInherit;
+				return ret;
+			}
 		}
 		
-		[MonoTODO]
 		public GenericAce Copy ()
 		{
-			throw new NotImplementedException ();
+			byte[] buffer = new byte[BinaryLength];
+			GetBinaryForm(buffer, 0);
+			return GenericAce.CreateFromBinaryForm(buffer, 0);
 		}
 		
-		[MonoTODO]
 		public static GenericAce CreateFromBinaryForm (byte[] binaryForm, int offset)
 		{
-			throw new NotImplementedException ();
+			if (binaryForm == null)
+				throw new ArgumentNullException("binaryForm");
+			
+			if (offset < 0 || offset > binaryForm.Length - 1)
+				throw new ArgumentOutOfRangeException("offset", offset, "Offset out of range");
+			
+			AceType type = (AceType)binaryForm[offset];
+			if (IsObjectType(type))
+				return new ObjectAce(binaryForm, offset);
+			else
+				return new CommonAce(binaryForm, offset);
 		}
 
-		[MonoTODO]
 		public override sealed bool Equals (object o)
 		{
-			throw new NotImplementedException ();
+			return this == (o as GenericAce);
 		}
 
-		[MonoTODO]
 		public abstract void GetBinaryForm (byte[] binaryForm, int offset);
 
-		[MonoTODO]
 		public override sealed int GetHashCode ()
 		{
-			throw new NotImplementedException ();
+			byte[] buffer = new byte[BinaryLength];
+			GetBinaryForm(buffer, 0);
+			
+			int code = 0;
+			for(int i = 0; i < buffer.Length; ++i)
+			{
+				code = (code << 3) | ((code >> 29) & 0x7);
+				code ^= ((int)buffer[i]) & 0xff;
+			}
+			
+			return code;
+		}
+
+		public static bool operator== (GenericAce left, GenericAce right)
+		{
+			if(((object)left) == null)
+				return((object)right) == null;
+			
+			if(((object)right) == null)
+				return false;
+			
+			int leftLen = left.BinaryLength;
+			int rightLen = right.BinaryLength;
+			if( leftLen != rightLen)
+				return false;
+			
+			byte[] leftBuffer = new byte[leftLen];
+			byte[] rightBuffer = new byte[rightLen];
+			left.GetBinaryForm(leftBuffer, 0);
+			right.GetBinaryForm(rightBuffer, 0);
+			
+			for(int i = 0; i < leftLen; ++i) {
+				if(leftBuffer[i] != rightBuffer[i])
+					return false;
+			}
+			
+			return true;
+		}
+
+		public static bool operator!= (GenericAce left, GenericAce right)
+		{
+			if(((object)left) == null)
+				return((object)right) != null;
+			
+			if(((object)right) == null)
+				return true;
+			
+			int leftLen = left.BinaryLength;
+			int rightLen = right.BinaryLength;
+			if( leftLen != rightLen)
+				return true;
+			
+			byte[] leftBuffer = new byte[leftLen];
+			byte[] rightBuffer = new byte[rightLen];
+			left.GetBinaryForm(leftBuffer, 0);
+			right.GetBinaryForm(rightBuffer, 0);
+			
+			for(int i = 0; i < leftLen; ++i) {
+				if(leftBuffer[i] != rightBuffer[i])
+					return true;
+			}
+			
+			return false;
+		}
+		
+		internal abstract string GetSddlForm();
+		
+		static internal GenericAce CreateFromSddlForm (string sddlForm, ref int pos)
+		{
+			if (sddlForm[pos] != '(')
+				throw new ArgumentException ("Invalid SDDL string.", "sddlForm");
+			
+			int endPos = sddlForm.IndexOf (')', pos);
+			if (endPos < 0)
+				throw new ArgumentException ("Invalid SDDL string.", "sddlForm");
+			
+			int count = endPos - (pos + 1);
+			string elementsStr = sddlForm.Substring (pos + 1,
+			                                         count);
+			elementsStr = elementsStr.ToUpperInvariant ();
+			string[] elements = elementsStr.Split (';');
+			if (elements.Length != 6)
+				throw new ArgumentException ("Invalid SDDL string.", "sddlForm");
+			
+
+			ObjectAceFlags objFlags = ObjectAceFlags.None;
+				
+			AceType type = ParseSddlAceType (elements[0]);
+
+			AceFlags flags = ParseSddlAceFlags (elements[1]);
+
+			int accessMask = ParseSddlAccessRights (elements[2]);
+
+			Guid objectType = Guid.Empty;
+			if (!string.IsNullOrEmpty (elements[3])) {
+				objectType = new Guid(elements[3]);
+				objFlags |= ObjectAceFlags.ObjectAceTypePresent;
+			}
+			
+			Guid inhObjectType = Guid.Empty;
+			if (!string.IsNullOrEmpty (elements[4])) {
+				inhObjectType = new Guid(elements[4]);
+				objFlags |= ObjectAceFlags.InheritedObjectAceTypePresent;
+			}
+			
+			SecurityIdentifier sid
+				= new SecurityIdentifier (elements[5]);
+			
+			if (type == AceType.AccessAllowedCallback
+			    || type == AceType.AccessDeniedCallback)
+				throw new NotImplementedException ("Conditional ACEs not supported");
+			
+			pos = endPos + 1;
+			
+			if (IsObjectType(type))
+				return new ObjectAce(type, flags, accessMask, sid, objFlags, objectType, inhObjectType, null);
+			else {
+				if (objFlags != ObjectAceFlags.None)
+					throw new ArgumentException( "Invalid SDDL string.", "sddlForm");
+				return new CommonAce (type, flags, accessMask, sid, null);
+			}
+		}
+		
+		private static bool IsObjectType(AceType type)
+		{
+			return type == AceType.AccessAllowedCallbackObject
+				|| type == AceType.AccessAllowedObject
+				|| type == AceType.AccessDeniedCallbackObject
+				|| type == AceType.AccessDeniedObject
+				|| type == AceType.SystemAlarmCallbackObject
+				|| type == AceType.SystemAlarmObject
+				|| type == AceType.SystemAuditCallbackObject
+				|| type == AceType.SystemAuditObject;
+		}
+
+		protected static string GetSddlAceType (AceType type)
+		{
+			switch (type) {
+			case AceType.AccessAllowed:
+				return "A";
+			case AceType.AccessDenied:
+				return "D";
+			case AceType.AccessAllowedObject:
+				return "OA";
+			case AceType.AccessDeniedObject:
+				return "OD";
+			case AceType.SystemAudit:
+				return "AU";
+			case AceType.SystemAlarm:
+				return "AL";
+			case AceType.SystemAuditObject:
+				return "OU";
+			case AceType.SystemAlarmObject:
+				return "OL";
+			case AceType.AccessAllowedCallback:
+				return "XA";
+			case AceType.AccessDeniedCallback:
+				return "XD";
+			default:
+				throw new ArgumentException ("Unable to convert to SDDL ACE type: " + type, "type");
+			}
+		}
+
+		private static AceType ParseSddlAceType (string type)
+		{
+			switch (type) {
+			case "A":
+				return AceType.AccessAllowed;
+			case "D":
+				return AceType.AccessDenied;
+			case "OA":
+				return AceType.AccessAllowedObject;
+			case "OD":
+				return AceType.AccessDeniedObject;
+			case "AU":
+				return AceType.SystemAudit;
+			case "AL":
+				return AceType.SystemAlarm;
+			case "OU":
+				return AceType.SystemAuditObject;
+			case "OL":
+				return AceType.SystemAlarmObject;
+			case "XA":
+				return AceType.AccessAllowedCallback;
+			case "XD":
+				return AceType.AccessDeniedCallback;
+			default:
+				throw new ArgumentException ("Unable to convert SDDL to ACE type: " + type, "type");
+			}
+		}
+
+		protected static string GetSddlAceFlags (AceFlags flags)
+		{
+			StringBuilder result = new StringBuilder ();
+			if ((flags & AceFlags.ObjectInherit) != 0)
+				result.Append ("OI");
+			if ((flags & AceFlags.ContainerInherit) != 0)
+				result.Append ("CI");
+			if ((flags & AceFlags.NoPropagateInherit) != 0)
+				result.Append ("NP");
+			if ((flags & AceFlags.InheritOnly) != 0)
+				result.Append ("IO");
+			if ((flags & AceFlags.Inherited) != 0)
+				result.Append ("ID");
+			if ((flags & AceFlags.SuccessfulAccess) != 0)
+				result.Append ("SA");
+			if ((flags & AceFlags.FailedAccess) != 0)
+				result.Append ("FA");
+			return result.ToString ();
+		}
+
+		private static AceFlags ParseSddlAceFlags (string flags)
+		{
+			AceFlags ret = AceFlags.None;
+			
+			int pos = 0;
+			while (pos < flags.Length - 1) {
+				string flag = flags.Substring (pos, 2);
+				switch (flag) {
+				case "CI":
+					ret |= AceFlags.ContainerInherit;
+					break;
+				case "OI":
+					ret |= AceFlags.ObjectInherit;
+					break;
+				case "NP":
+					ret |= AceFlags.NoPropagateInherit;
+					break;
+				case "IO":
+					ret |= AceFlags.InheritOnly;
+					break;
+				case "ID":
+					ret |= AceFlags.Inherited;
+					break;
+				case "SA":
+					ret |= AceFlags.SuccessfulAccess;
+					break;
+				case "FA":
+					ret |= AceFlags.FailedAccess;
+					break;
+				default:
+					throw new ArgumentException ("Invalid SDDL string.", "flags");
+				}
+				
+				pos += 2;
+			}
+			
+			if (pos != flags.Length)
+				throw new ArgumentException ("Invalid SDDL string.", "flags");
+			
+			return ret;
 		}
 
-		[MonoTODO]
-		public static bool operator== (GenericAce left,
-					       GenericAce right)
+		private static int ParseSddlAccessRights (string accessMask)
+		{
+			if (accessMask.StartsWith ("0X")) {
+				return int.Parse (accessMask.Substring (2),
+				                  NumberStyles.HexNumber,
+				                  CultureInfo.InvariantCulture);
+			} else if (Char.IsDigit (accessMask, 0)) {
+				return int.Parse (accessMask,
+				                  NumberStyles.Integer,
+				                  CultureInfo.InvariantCulture);
+			} else {
+				return ParseSddlAliasRights (accessMask);
+			}
+		}
+		
+		private static int ParseSddlAliasRights(string accessMask)
+		{
+			int ret = 0;
+			
+			int pos = 0;
+			while (pos < accessMask.Length - 1) {
+				string flag = accessMask.Substring (pos, 2);
+				SddlAccessRight right = SddlAccessRight.LookupByName(flag);
+				if (right == null)
+					throw new ArgumentException ("Invalid SDDL string.", "accessMask");
+				
+				ret |= right.Value;
+				pos += 2;
+			}
+			
+			if (pos != accessMask.Length)
+				throw new ArgumentException ("Invalid SDDL string.", "accessMask");
+			
+			return ret;
+		}
+		
+		internal static ushort ReadUShort (byte[] buffer, int offset)
+		{
+			return (ushort)((((int)buffer[offset + 0]) << 0)
+			                | (((int)buffer[offset + 1]) << 8));
+		}
+		
+		internal static int ReadInt (byte[] buffer, int offset)
+		{
+			return (((int)buffer[offset + 0]) << 0)
+				| (((int)buffer[offset + 1]) << 8)
+				| (((int)buffer[offset + 2]) << 16)
+				| (((int)buffer[offset + 3]) << 24);
+		}
+		
+		internal static void WriteInt (int val, byte[] buffer, int offset)
 		{
-			throw new NotImplementedException ();
+			buffer[offset] = (byte)val;
+			buffer[offset + 1] = (byte)(val >> 8);
+			buffer[offset + 2] = (byte)(val >> 16);
+			buffer[offset + 3] = (byte)(val >> 24);
 		}
 
-		[MonoTODO]
-		public static bool operator!= (GenericAce left,
-					       GenericAce right)
+		internal static void WriteUShort (ushort val, byte[] buffer,
+		                                  int offset)
 		{
-			throw new NotImplementedException ();
+			buffer[offset] = (byte)val;
+			buffer[offset + 1] = (byte)(val >> 8);
 		}
 	}
 }
diff --git a/mcs/class/corlib/System.Security.AccessControl/GenericAcl.cs b/mcs/class/corlib/System.Security.AccessControl/GenericAcl.cs
index 658beae..f2ee1a2 100644
--- a/mcs/class/corlib/System.Security.AccessControl/GenericAcl.cs
+++ b/mcs/class/corlib/System.Security.AccessControl/GenericAcl.cs
@@ -93,6 +93,9 @@ namespace System.Security.AccessControl {
 		{
 			return GetEnumerator ();
 		}
+		
+		internal abstract string GetSddlForm(ControlFlags sdFlags,
+		                                     bool isDacl);
 	}
 }
 
diff --git a/mcs/class/corlib/System.Security.AccessControl/GenericSecurityDescriptor.cs b/mcs/class/corlib/System.Security.AccessControl/GenericSecurityDescriptor.cs
index ba75539..83e2170 100644
--- a/mcs/class/corlib/System.Security.AccessControl/GenericSecurityDescriptor.cs
+++ b/mcs/class/corlib/System.Security.AccessControl/GenericSecurityDescriptor.cs
@@ -3,6 +3,7 @@
 //
 // Author:
 //	Dick Porter  <dick at ximian.com>
+//	Kenneth Bell
 //
 // Copyright (C) 2006 Novell, Inc (http://www.novell.com)
 //
@@ -26,68 +27,172 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+using System.Globalization;
 using System.Security.Principal;
+using System.Text;
 
 namespace System.Security.AccessControl {
-	public abstract class GenericSecurityDescriptor
-	{
-//		bool isContainer;
-//		bool isDS;
-//		ControlFlags flags;
-//		SecurityIdentifier owner;
-//		SecurityIdentifier group;
-//		SystemAcl systemAcl;
-//		DiscretionaryAcl discretionaryAcl;
-		
+	public abstract class GenericSecurityDescriptor {
+
 		protected GenericSecurityDescriptor ()
 		{
 		}
 
-		public int BinaryLength
-		{
+		public int BinaryLength {
 			get {
-				throw new NotImplementedException ();
+				int len = 0x14;
+				if (Owner != null)
+					len += Owner.BinaryLength;
+				if (Group != null)
+					len += Group.BinaryLength;
+				if (DaclPresent)
+					len += InternalDacl.BinaryLength;
+				if (SaclPresent)
+					len += InternalSacl.BinaryLength;
+				return len;
 			}
 		}
-		
-		public abstract ControlFlags ControlFlags
-		{
-			get;
+
+		public abstract ControlFlags ControlFlags { get; }
+
+		public abstract SecurityIdentifier Group { get; set; }
+
+		public abstract SecurityIdentifier Owner { get; set; }
+
+		public static byte Revision {
+			get { return 1; }
 		}
-		
-		public abstract SecurityIdentifier Group
-		{
-			get;
-			set;
+
+		internal virtual GenericAcl InternalDacl {
+			get { return null; }
 		}
-		
-		public abstract SecurityIdentifier Owner
+
+		internal virtual GenericAcl InternalSacl {
+			get { return null; }
+		}
+
+		internal virtual byte InternalReservedField {
+			get { return 0; }
+		}
+
+		public void GetBinaryForm (byte[] binaryForm, int offset)
 		{
-			get;
-			set;
+			ControlFlags controlFlags = ControlFlags;
+			binaryForm[offset + 0x00] = Revision;
+			binaryForm[offset + 0x01] = InternalReservedField;
+			WriteUShort ((ushort)controlFlags, binaryForm,
+			             offset + 0x02);
+			
+			// Skip 'offset' fields (will fill later)
+			int pos = 0x14;
+			
+			if (Owner != null) {
+				WriteInt (pos, binaryForm, offset + 0x04);
+				Owner.GetBinaryForm (binaryForm, offset + pos);
+				pos += Owner.BinaryLength;
+			} else {
+				WriteInt (0, binaryForm, offset + 0x04);
+			}
+			
+			if (Group != null) {
+				WriteInt (pos, binaryForm, offset + 0x08);
+				Group.GetBinaryForm (binaryForm, offset + pos);
+				pos += Group.BinaryLength;
+			} else {
+				WriteInt (0, binaryForm, offset + 0x08);
+			}
+			
+			GenericAcl sysAcl = InternalSacl;
+			if (SaclPresent) {
+				WriteInt (pos, binaryForm, offset + 0x0C);
+				sysAcl.GetBinaryForm (binaryForm, offset + pos);
+				pos += InternalSacl.BinaryLength;
+			} else {
+				WriteInt (0, binaryForm, offset + 0x0C);
+			}
+			
+			GenericAcl discAcl = InternalDacl;
+			if (DaclPresent) {
+				WriteInt (pos, binaryForm, offset + 0x10);
+				discAcl.GetBinaryForm (binaryForm, offset + pos);
+				pos += InternalDacl.BinaryLength;
+			} else {
+				WriteInt (0, binaryForm, offset + 0x10);
+			}
 		}
 
-		public static byte Revision
+		public string GetSddlForm (AccessControlSections includeSections)
 		{
-			get {
-				throw new NotImplementedException ();
+			StringBuilder result = new StringBuilder ();
+			
+			if ((includeSections & AccessControlSections.Owner) != 0
+			    && Owner != null) {
+				result.AppendFormat (
+					CultureInfo.InvariantCulture,
+					"O:{0}", Owner.GetSddlForm ());
+			}
+			
+			if ((includeSections & AccessControlSections.Group) != 0
+			    && Group != null) {
+				result.AppendFormat (
+					CultureInfo.InvariantCulture,
+					"G:{0}", Group.GetSddlForm ());
 			}
+			
+			if ((includeSections & AccessControlSections.Access) != 0
+			    && InternalDacl != null) {
+				result.AppendFormat (
+					CultureInfo.InvariantCulture,
+					"D:{0}",
+					InternalDacl.GetSddlForm (ControlFlags,
+				                                  true));
+			}
+			
+			if ((includeSections & AccessControlSections.Audit) != 0
+			    && InternalSacl != null) {
+				result.AppendFormat (
+					CultureInfo.InvariantCulture,
+					"S:{0}",
+					InternalSacl.GetSddlForm (ControlFlags,
+				                                  false));
+			}
+			
+			return result.ToString ();
 		}
 
-		public void GetBinaryForm (byte[] binaryForm, int offset)
+		public static bool IsSddlConversionSupported ()
 		{
-			throw new NotImplementedException ();
+			return true;
 		}
 		
-		public string GetSddlForm (AccessControlSections includeSections)
+		private bool DaclPresent {
+			get {
+				return InternalDacl != null
+				    && (ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0;
+			}
+		}
+
+		private bool SaclPresent {
+			get {
+				return InternalSacl != null
+				    && (ControlFlags & ControlFlags.SystemAclPresent) != 0;
+			}
+		}
+
+		private void WriteUShort (ushort val, byte[] buffer, int offset)
 		{
-			throw new NotImplementedException ();
+			buffer[offset] = (byte)val;
+			buffer[offset + 1] = (byte)(val >> 8);
 		}
 
-		public static bool IsSddlConversionSupported ()
+		private void WriteInt (int val, byte[] buffer, int offset)
 		{
-			throw new NotImplementedException ();
+			buffer[offset] = (byte)val;
+			buffer[offset + 1] = (byte)(val >> 8);
+			buffer[offset + 2] = (byte)(val >> 16);
+			buffer[offset + 3] = (byte)(val >> 24);
 		}
+		
 	}
 }
 
diff --git a/mcs/class/corlib/System.Security.AccessControl/KnownAce.cs b/mcs/class/corlib/System.Security.AccessControl/KnownAce.cs
index 8acc036..5a75f3c 100644
--- a/mcs/class/corlib/System.Security.AccessControl/KnownAce.cs
+++ b/mcs/class/corlib/System.Security.AccessControl/KnownAce.cs
@@ -4,6 +4,7 @@
 // Authors:
 //	Dick Porter  <dick at ximian.com>
 //	Atsushi Enomoto  <atsushi at ximian.com>
+//	Kenneth Bell
 //
 // Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com)
 //
@@ -27,17 +28,24 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+using System.Globalization;
 using System.Security.Principal;
+using System.Text;
 
 namespace System.Security.AccessControl
 {
 	public abstract class KnownAce : GenericAce
 	{
-		int access_mask;
-		SecurityIdentifier identifier;
+		private int access_mask;
+		private SecurityIdentifier identifier;
 
-		internal KnownAce (InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
-			: base (inheritanceFlags, propagationFlags)
+		internal KnownAce (AceType type, AceFlags flags)
+			: base (type, flags)
+		{
+		}
+		
+		internal KnownAce (byte[] binaryForm, int offset)
+			: base (binaryForm, offset)
 		{
 		}
 
@@ -50,6 +58,30 @@ namespace System.Security.AccessControl
 			get { return identifier; }
 			set { identifier = value; }
 		}
+		
+		internal static string GetSddlAccessRights (int accessMask)
+		{
+			string ret = GetSddlAliasRights(accessMask);
+			if (!string.IsNullOrEmpty(ret))
+				return ret;
+			
+			return string.Format (CultureInfo.InvariantCulture,
+			                      "0x{0:x}", accessMask);
+		}
+		
+		private static string GetSddlAliasRights(int accessMask)
+		{
+			SddlAccessRight[] rights = SddlAccessRight.Decompose(accessMask);
+			if (rights == null)
+				return null;
+			
+			StringBuilder ret = new StringBuilder();
+			foreach (var right in rights) {
+				ret.Append(right.Name);
+			}
+			
+			return ret.ToString();
+		}
 	}
 }
 
diff --git a/mcs/class/corlib/System.Security.AccessControl/ObjectAce.cs b/mcs/class/corlib/System.Security.AccessControl/ObjectAce.cs
index 40c802f..cad258a 100644
--- a/mcs/class/corlib/System.Security.AccessControl/ObjectAce.cs
+++ b/mcs/class/corlib/System.Security.AccessControl/ObjectAce.cs
@@ -4,6 +4,7 @@
 // Authors:
 //	Dick Porter  <dick at ximian.com>
 //	Atsushi Enomoto  <atsushi at ximian.com>
+//	Kenneth Bell
 //
 // Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com)
 //
@@ -28,33 +29,70 @@
 //
 
 using System.Security.Principal;
+using System.Globalization;
 
 namespace System.Security.AccessControl
 {
 	public sealed class ObjectAce : QualifiedAce
 	{
+		private Guid object_ace_type;
+		private Guid inherited_object_type;
+		private ObjectAceFlags object_ace_flags;
+
 		public ObjectAce (AceFlags aceFlags, AceQualifier qualifier,
 				  int accessMask, SecurityIdentifier sid,
 				  ObjectAceFlags flags, Guid type,
 				  Guid inheritedType, bool isCallback,
 				  byte[] opaque)
-			: base (InheritanceFlags.None, PropagationFlags.None, qualifier, isCallback, opaque)
+			: base (ConvertType(qualifier, isCallback), aceFlags, opaque)
 		{
-			AceFlags = aceFlags;
+			AccessMask = accessMask;
 			SecurityIdentifier = sid;
 			object_ace_flags = flags;
 			object_ace_type = type;
 			inherited_object_type = inheritedType;
 		}
 
-		Guid object_ace_type, inherited_object_type;
-		ObjectAceFlags object_ace_flags;
+		internal ObjectAce (AceType type, AceFlags flags, int accessMask,
+		                    SecurityIdentifier sid, ObjectAceFlags objFlags,
+		                    Guid objType, Guid inheritedType, byte[] opaque)
+			: base(type, flags, opaque)
+		{
+			AccessMask = accessMask;
+			SecurityIdentifier = sid;
+			object_ace_flags = objFlags;
+			object_ace_type = objType;
+			inherited_object_type = inheritedType;
+		}
+		
+		internal ObjectAce(byte[] binaryForm, int offset)
+			: base(binaryForm, offset)
+		{
+			int len = ReadUShort(binaryForm, offset + 2);
+			if (offset > binaryForm.Length - len)
+				throw new ArgumentException("Invalid ACE - truncated", "binaryForm");
+			if (len < 44 + SecurityIdentifier.MinBinaryLength)
+				throw new ArgumentException("Invalid ACE", "binaryForm");
+			
+			AccessMask = ReadInt(binaryForm, offset + 4);
+			object_ace_flags = (ObjectAceFlags)ReadInt(binaryForm, offset + 8);
+			object_ace_type = ReadGuid(binaryForm, offset + 12);
+			inherited_object_type = ReadGuid(binaryForm, offset + 28);
+			SecurityIdentifier = new SecurityIdentifier(binaryForm, offset + 44);
+			
+			int opaqueLen = len - (44 + SecurityIdentifier.BinaryLength);
+			if (opaqueLen > 0) {
+				byte[] opaque = new byte[opaqueLen];
+				Array.Copy(binaryForm, offset + 44 + SecurityIdentifier.BinaryLength,
+				           opaque, 0, opaqueLen);
+			}
+		}
 
-		[MonoTODO]
 		public override int BinaryLength
 		{
 			get {
-				throw new NotImplementedException ();
+				return 44 + SecurityIdentifier.BinaryLength
+					+ OpaqueLength;
 			}
 		}
 
@@ -73,17 +111,103 @@ namespace System.Security.AccessControl
 			set { object_ace_type = value; }
 		}
 
-		[MonoTODO]
 		public override void GetBinaryForm (byte[] binaryForm,
 						    int offset)
 		{
-			throw new NotImplementedException ();
+			int len = BinaryLength;
+			binaryForm[offset] = (byte)this.AceType;
+			binaryForm[offset + 1] = (byte)this.AceFlags;
+			WriteUShort ((ushort)len, binaryForm, offset + 2);
+			WriteInt (AccessMask, binaryForm, offset + 4);
+			WriteInt ((int)ObjectAceFlags, binaryForm, offset + 8);
+			WriteGuid (ObjectAceType, binaryForm, offset + 12);
+			WriteGuid (InheritedObjectAceType, binaryForm, offset + 28);
+			
+			SecurityIdentifier.GetBinaryForm (binaryForm,
+			                                  offset + 44);
+			
+			byte[] opaque = GetOpaque ();
+			if (opaque != null)
+				Array.Copy (opaque, 0, binaryForm,
+				            offset + 44 + SecurityIdentifier.BinaryLength,
+				            opaque.Length);
 		}
 		
-		[MonoTODO]
 		public static int MaxOpaqueLength (bool isCallback)
 		{
-			throw new NotImplementedException ();
+			// Varies by platform?
+			return 65423;
+		}
+		
+		internal override string GetSddlForm()
+		{
+			if (OpaqueLength != 0)
+				throw new NotImplementedException (
+					"Unable to convert conditional ACEs to SDDL");
+			
+			string objType = "";
+			if ((ObjectAceFlags & ObjectAceFlags.ObjectAceTypePresent) != 0)
+				objType = object_ace_type.ToString("D");
+			
+			string inhObjType = "";
+			if ((ObjectAceFlags & ObjectAceFlags.InheritedObjectAceTypePresent) != 0)
+				inhObjType = inherited_object_type.ToString("D");
+			
+			return string.Format (CultureInfo.InvariantCulture,
+			                      "({0};{1};{2};{3};{4};{5})",
+			                      GetSddlAceType (AceType),
+			                      GetSddlAceFlags (AceFlags),
+			                      GetSddlAccessRights (AccessMask),
+			                      objType,
+			                      inhObjType,
+			                      SecurityIdentifier.GetSddlForm ());
+		}
+		
+		private static AceType ConvertType(AceQualifier qualifier, bool isCallback)
+		{
+			switch(qualifier)
+			{
+			case AceQualifier.AccessAllowed:
+				if (isCallback)
+					return AceType.AccessAllowedCallbackObject;
+				else
+					return AceType.AccessAllowedObject;
+				
+			case AceQualifier.AccessDenied:
+				if (isCallback)
+					return AceType.AccessDeniedCallbackObject;
+				else
+					return AceType.AccessDeniedObject;
+				
+			case AceQualifier.SystemAlarm:
+				if (isCallback)
+					return AceType.SystemAlarmCallbackObject;
+				else
+					return AceType.SystemAlarmObject;
+				
+			case AceQualifier.SystemAudit:
+				if (isCallback)
+					return AceType.SystemAuditCallbackObject;
+				else
+					return AceType.SystemAuditObject;
+				
+			default:
+				throw new ArgumentException("Unrecognized ACE qualifier: " + qualifier, "qualifier");
+			}
+		}
+		
+		private void WriteGuid (Guid val, byte[] buffer,
+		                        int offset)
+		{
+			byte[] guidData = val.ToByteArray();
+			Array.Copy(guidData, 0, buffer, offset, 16);
+		}
+		
+		private Guid ReadGuid(byte[] buffer, int offset)
+		{
+			byte[] temp = new byte[16];
+			Array.Copy(buffer, offset, temp, 0, 16);
+			return new Guid(temp);
 		}
 	}
 }
diff --git a/mcs/class/corlib/System.Security.AccessControl/QualifiedAce.cs b/mcs/class/corlib/System.Security.AccessControl/QualifiedAce.cs
index 95e64e2..343914d 100644
--- a/mcs/class/corlib/System.Security.AccessControl/QualifiedAce.cs
+++ b/mcs/class/corlib/System.Security.AccessControl/QualifiedAce.cs
@@ -4,6 +4,7 @@
 // Authors:
 //	Dick Porter  <dick at ximian.com>
 //	Atsushi Enomoto  <atsushi at ximian.com>
+//	Kenneth Bell
 //
 // Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com)
 //
@@ -30,40 +31,89 @@
 namespace System.Security.AccessControl {
 	public abstract class QualifiedAce : KnownAce
 	{
-		internal QualifiedAce (InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AceQualifier aceQualifier, bool isCallback, byte [] opaque)
-			: base (inheritanceFlags, propagationFlags)
+		private byte [] opaque;
+		
+		internal QualifiedAce (AceType type, AceFlags flags,
+		                       byte[] opaque)
+			: base (type, flags)
 		{
-			ace_qualifier = aceQualifier;
-			is_callback = isCallback;
 			SetOpaque (opaque);
 		}
-
-		AceQualifier ace_qualifier;
-		bool is_callback;
-		byte [] opaque;
+		
+		internal QualifiedAce (byte[] binaryForm, int offset)
+			: base(binaryForm, offset)
+		{
+		}
 
 		public AceQualifier AceQualifier {
-			get { return ace_qualifier; }
+			get {
+				switch(AceType)
+				{
+				case AceType.AccessAllowed:
+				case AceType.AccessAllowedCallback:
+				case AceType.AccessAllowedCallbackObject:
+				case AceType.AccessAllowedCompound:
+				case AceType.AccessAllowedObject:
+					return AceQualifier.AccessAllowed;
+				
+				case AceType.AccessDenied:
+				case AceType.AccessDeniedCallback:
+				case AceType.AccessDeniedCallbackObject:
+				case AceType.AccessDeniedObject:
+					return AceQualifier.AccessDenied;
+					
+				case AceType.SystemAlarm:
+				case AceType.SystemAlarmCallback:
+				case AceType.SystemAlarmCallbackObject:
+				case AceType.SystemAlarmObject:
+					return AceQualifier.SystemAlarm;
+					
+				case AceType.SystemAudit:
+				case AceType.SystemAuditCallback:
+				case AceType.SystemAuditCallbackObject:
+				case AceType.SystemAuditObject:
+					return AceQualifier.SystemAudit;
+					
+				default:
+					throw new ArgumentException("Unrecognised ACE type: " + AceType);
+				}
+			}
 		}
 		
 		public bool IsCallback {
-			get { return is_callback; }
+			get {
+				return AceType == AceType.AccessAllowedCallback
+					|| AceType == AceType.AccessAllowedCallbackObject
+					|| AceType == AceType.AccessDeniedCallback
+					|| AceType == AceType.AccessDeniedCallbackObject
+					|| AceType == AceType.SystemAlarmCallback
+					|| AceType == AceType.SystemAlarmCallbackObject
+					|| AceType == AceType.SystemAuditCallback
+					|| AceType == AceType.SystemAuditCallbackObject;
+			}
 		}
 		
 		public int OpaqueLength {
-			get { return opaque.Length; }
+			get {
+				if (opaque == null)
+					return  0;
+				return opaque.Length;
+			}
 		}
 		
 		public byte[] GetOpaque ()
 		{
-			return (byte []) opaque.Clone ();
+			if (opaque == null)
+				return null;
+			return (byte []) opaque.Clone();
 		}
 		
 		public void SetOpaque (byte[] opaque)
 		{
 			if (opaque == null)
-				throw new ArgumentNullException ("opaque");
-			this.opaque = (byte []) opaque.Clone ();
+				this.opaque = null;
+			else
+				this.opaque = (byte []) opaque.Clone();
 		}
 	}
 }
diff --git a/mcs/class/corlib/System.Security.AccessControl/RawAcl.cs b/mcs/class/corlib/System.Security.AccessControl/RawAcl.cs
index 9188b38..90f0606 100644
--- a/mcs/class/corlib/System.Security.AccessControl/RawAcl.cs
+++ b/mcs/class/corlib/System.Security.AccessControl/RawAcl.cs
@@ -4,6 +4,7 @@
 // Authors:
 //	Dick Porter  <dick at ximian.com>
 //	Atsushi Enomoto  <atsushi at ximian.com>
+//	Kenneth Bell
 //
 // Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com)
 //
@@ -28,10 +29,14 @@
 //
 
 using System.Collections.Generic;
+using System.Text;
 
 namespace System.Security.AccessControl {
 	public sealed class RawAcl : GenericAcl
 	{
+		private byte revision;
+		private List<GenericAce> list;
+
 		public RawAcl (byte revision, int capacity)
 		{
 			this.revision = revision;
@@ -39,18 +44,46 @@ namespace System.Security.AccessControl {
 		}
 		
 		public RawAcl (byte [] binaryForm, int offset)
-			: this (0, 10)
 		{
+			if (binaryForm == null)
+				throw new ArgumentNullException("binaryForm");
+			
+			if (offset < 0 || offset > binaryForm.Length - 8)
+				throw new ArgumentOutOfRangeException("offset", offset, "Offset out of range");
+			
+			revision = binaryForm[offset];
+			if (revision != AclRevision && revision != AclRevisionDS)
+				throw new ArgumentException("Invalid ACL - unknown revision", "binaryForm");
+			
+			int binaryLength = ReadUShort(binaryForm, offset + 2);
+			if (offset > binaryForm.Length - binaryLength)
+				throw new ArgumentException("Invalid ACL - truncated", "binaryForm");
+			
+			int pos = offset + 8;
+			int numAces = ReadUShort(binaryForm, offset + 4);
+			list = new List<GenericAce>(numAces);
+			for (int i = 0; i < numAces; ++i) {
+				GenericAce newAce = GenericAce.CreateFromBinaryForm(binaryForm, pos);
+				list.Add(newAce);
+				pos += newAce.BinaryLength;
+			}
 		}
-
-		byte revision;
-		List<GenericAce> list;
-
-		[MonoTODO]
+		
+		internal RawAcl(byte revision, List<GenericAce> aces)
+		{
+			this.revision = revision;
+			this.list = aces;
+		}
+		
 		public override int BinaryLength
 		{
 			get {
-				throw new NotImplementedException ();
+				int len = 8;
+				foreach(var ace in list)
+				{
+					len += ace.BinaryLength;
+				}
+				return len;
 			}
 		}
 
@@ -68,11 +101,30 @@ namespace System.Security.AccessControl {
 			get { return revision; }
 		}
 
-		[MonoTODO]
 		public override void GetBinaryForm (byte[] binaryForm,
-						    int offset)
+		                                    int offset)
 		{
-			throw new NotImplementedException ();
+			if(binaryForm == null)
+				throw new ArgumentNullException("binaryForm");
+			
+			if(offset < 0
+			   || offset > binaryForm.Length - BinaryLength)
+				throw new ArgumentException("Offset out of range", "offset");
+			
+			binaryForm[offset] = Revision;
+			binaryForm[offset + 1] = 0;
+			WriteUShort((ushort)BinaryLength, binaryForm,
+			            offset + 2);
+			WriteUShort((ushort)list.Count, binaryForm,
+			            offset + 4);
+			WriteUShort(0, binaryForm, offset + 6);
+			
+			int pos = offset + 8;
+			foreach(var ace in list)
+			{
+				ace.GetBinaryForm(binaryForm, pos);
+				pos += ace.BinaryLength;
+			}
 		}
 
 		public void InsertAce (int index, GenericAce ace)
@@ -86,6 +138,105 @@ namespace System.Security.AccessControl {
 		{
 			list.RemoveAt (index);
 		}
+		
+		internal override string GetSddlForm(ControlFlags sdFlags,
+		                                     bool isDacl)
+		{
+			StringBuilder result = new StringBuilder();
+			
+			if(isDacl) {
+				if((sdFlags & ControlFlags.DiscretionaryAclProtected) != 0)
+					result.Append("P");
+				if((sdFlags & ControlFlags.DiscretionaryAclAutoInheritRequired) != 0)
+					result.Append("AR");
+				if((sdFlags & ControlFlags.DiscretionaryAclAutoInherited) != 0)
+					result.Append("AI");
+			} else {
+				if((sdFlags & ControlFlags.SystemAclProtected) != 0)
+					result.Append("P");
+				if((sdFlags & ControlFlags.SystemAclAutoInheritRequired) != 0)
+					result.Append("AR");
+				if((sdFlags & ControlFlags.SystemAclAutoInherited) != 0)
+					result.Append("AI");
+			}
+			
+			foreach(var ace in list)
+			{
+				result.Append(ace.GetSddlForm());
+			}
+			
+			return result.ToString();
+		}
+
+		internal static RawAcl ParseSddlForm(string sddlForm,
+		                                     bool isDacl,
+		                                     ref ControlFlags sdFlags,
+		                                     ref int pos)
+		{
+			ParseFlags(sddlForm, isDacl, ref sdFlags, ref pos);
+			
+			byte revision = GenericAcl.AclRevision;
+			List<GenericAce> aces = new List<GenericAce>();
+			while(pos < sddlForm.Length && sddlForm[pos] == '(') {
+				GenericAce ace = GenericAce.CreateFromSddlForm(
+							sddlForm, ref pos);
+				if ((ace as ObjectAce) != null)
+					revision = GenericAcl.AclRevisionDS;
+				aces.Add(ace);
+			}
+			
+			
+			return new RawAcl(revision, aces);
+		}
+		
+		private static void ParseFlags(string sddlForm,
+		                               bool isDacl,
+		                               ref ControlFlags sdFlags,
+		                               ref int pos)
+		{
+			char ch = Char.ToUpperInvariant(sddlForm[pos]);
+			while(ch == 'P' || ch == 'A') {
+				if(ch == 'P') {
+					if (isDacl)
+						sdFlags |= ControlFlags.DiscretionaryAclProtected;
+					else
+						sdFlags |= ControlFlags.SystemAclProtected;
+					pos++;
+				} else if(sddlForm.Length > pos + 1) {
+					ch = Char.ToUpperInvariant(sddlForm[pos + 1]);
+					if(ch == 'R') {
+						if (isDacl)
+							sdFlags |= ControlFlags.DiscretionaryAclAutoInheritRequired;
+						else
+							sdFlags |= ControlFlags.SystemAclAutoInheritRequired;
+						pos += 2;
+					} else if (ch == 'I') {
+						if (isDacl)
+							sdFlags |= ControlFlags.DiscretionaryAclAutoInherited;
+						else
+							sdFlags |= ControlFlags.SystemAclAutoInherited;
+						pos += 2;
+					} else {
+						throw new ArgumentException("Invalid SDDL string.", "sddlForm");
+					}
+				} else {
+					throw new ArgumentException("Invalid SDDL string.", "sddlForm");
+				}
+			}
+			
+		}
+		
+		private void WriteUShort (ushort val, byte[] buffer, int offset)
+		{
+			buffer[offset] = (byte)val;
+			buffer[offset + 1] = (byte)(val >> 8);
+		}
+		
+		private ushort ReadUShort (byte[] buffer, int offset)
+		{
+			return (ushort)((((int)buffer[offset + 0]) << 0)
+			                | (((int)buffer[offset + 1]) << 8));
+		}
 	}
 }
 
diff --git a/mcs/class/corlib/System.Security.AccessControl/RawSecurityDescriptor.cs b/mcs/class/corlib/System.Security.AccessControl/RawSecurityDescriptor.cs
index ca90f39..c53ec53 100644
--- a/mcs/class/corlib/System.Security.AccessControl/RawSecurityDescriptor.cs
+++ b/mcs/class/corlib/System.Security.AccessControl/RawSecurityDescriptor.cs
@@ -3,6 +3,7 @@
 //
 // Author:
 //	Dick Porter  <dick at ximian.com>
+//	Kenneth Bell
 //
 // Copyright (C) 2006 Novell, Inc (http://www.novell.com)
 //
@@ -30,84 +31,168 @@
 using System.Security.Principal;
 
 namespace System.Security.AccessControl {
-	public sealed class RawSecurityDescriptor : GenericSecurityDescriptor
-	{
+	public sealed class RawSecurityDescriptor : GenericSecurityDescriptor {
+		private ControlFlags control_flags;
+		private SecurityIdentifier owner_sid;
+		private SecurityIdentifier group_sid;
+		private RawAcl system_acl;
+		private RawAcl discretionary_acl;
+		private byte resourcemgr_control;
+
 		public RawSecurityDescriptor (string sddlForm)
 		{
+			if (sddlForm == null)
+				throw new ArgumentNullException ("sddlForm");
+			
+			ParseSddl (sddlForm.Replace (" ", ""));
+			
+			control_flags |= ControlFlags.SelfRelative;
 		}
 
 		public RawSecurityDescriptor (byte[] binaryForm, int offset)
 		{
+			if (binaryForm == null)
+				throw new ArgumentNullException("binaryForm");
+			
+			if (offset < 0 || offset > binaryForm.Length - 0x14)
+				throw new ArgumentOutOfRangeException("offset", offset, "Offset out of range");
+			
+			if (binaryForm[offset] != 1)
+				throw new ArgumentException("Unrecognized Security Descriptor revision.", "binaryForm");
+			
+			resourcemgr_control = binaryForm[offset + 0x01];
+			control_flags = (ControlFlags)ReadUShort(binaryForm, offset + 0x02);
+			
+			int ownerPos = ReadInt(binaryForm, offset + 0x04);
+			int groupPos = ReadInt(binaryForm, offset + 0x08);
+			int saclPos = ReadInt(binaryForm, offset + 0x0C);
+			int daclPos = ReadInt(binaryForm, offset + 0x10);
+			
+			if (ownerPos != 0)
+				owner_sid = new SecurityIdentifier(binaryForm, ownerPos);
+			
+			if (groupPos != 0)
+				group_sid = new SecurityIdentifier(binaryForm, groupPos);
+			
+			if (saclPos != 0)
+				system_acl = new RawAcl(binaryForm, saclPos);
+			
+			if (daclPos != 0)
+				discretionary_acl = new RawAcl(binaryForm, daclPos);
 		}
-		
+
 		public RawSecurityDescriptor (ControlFlags flags,
-					      SecurityIdentifier owner,
-					      SecurityIdentifier group,
-					      RawAcl systemAcl,
-					      RawAcl discretionaryAcl)
+		                              SecurityIdentifier owner,
+		                              SecurityIdentifier @group,
+		                              RawAcl systemAcl,
+		                              RawAcl discretionaryAcl)
 		{
+			control_flags = flags;
+			owner_sid = owner;
+			group_sid = @group;
+			system_acl = systemAcl;
+			discretionary_acl = discretionaryAcl;
 		}
-		
-		public override ControlFlags ControlFlags
-		{
-			get {
-				throw new NotImplementedException ();
-			}
+
+		public override ControlFlags ControlFlags {
+			get { return control_flags; }
 		}
 
-		public RawAcl DiscretionaryAcl
-		{
-			get {
-				throw new NotImplementedException ();
-			}
-			set {
-				throw new NotImplementedException ();
-			}
+		public RawAcl DiscretionaryAcl {
+			get { return discretionary_acl; }
+			set { discretionary_acl = value; }
 		}
-		
-		public override SecurityIdentifier Group
-		{
-			get {
-				throw new NotImplementedException ();
-			}
-			set {
-				throw new NotImplementedException ();
-			}
+
+		public override SecurityIdentifier Group {
+			get { return group_sid; }
+			set { group_sid = value; }
 		}
-		
-		public override SecurityIdentifier Owner
-		{
-			get {
-				throw new NotImplementedException ();
-			}
-			set {
-				throw new NotImplementedException ();
-			}
+
+		public override SecurityIdentifier Owner {
+			get { return owner_sid; }
+			set { owner_sid = value; }
 		}
 
-		public byte ResourceManagerControl
+		public byte ResourceManagerControl {
+			get { return resourcemgr_control; }
+			set { resourcemgr_control = value; }
+		}
+
+		public RawAcl SystemAcl {
+			get { return system_acl; }
+			set { system_acl = value; }
+		}
+
+		public void SetFlags (ControlFlags flags)
 		{
-			get {
-				throw new NotImplementedException ();
-			}
-			set {
-				throw new NotImplementedException ();
-			}
+			control_flags = flags | ControlFlags.SelfRelative;
 		}
 
-		public RawAcl SystemAcl 
+		internal override GenericAcl InternalDacl {
+			get { return this.DiscretionaryAcl; }
+		}
+
+		internal override GenericAcl InternalSacl {
+			get { return this.SystemAcl; }
+		}
+
+		internal override byte InternalReservedField {
+			get { return this.ResourceManagerControl; }
+		}
+
+		private void ParseSddl (string sddlForm)
 		{
-			get {
-				throw new NotImplementedException ();
+			ControlFlags flags = ControlFlags.None;
+			
+			int pos = 0;
+			while (pos < sddlForm.Length - 2) {
+				switch (sddlForm.Substring (pos, 2)) {
+				case "O:":
+					pos += 2;
+					Owner = SecurityIdentifier.ParseSddlForm (sddlForm, ref pos);
+					break;
+				
+				case "G:":
+					pos += 2;
+					Group = SecurityIdentifier.ParseSddlForm (sddlForm, ref pos);
+					break;
+				
+				case "D:":
+					pos += 2;
+					DiscretionaryAcl = RawAcl.ParseSddlForm (sddlForm, true, ref flags, ref pos);
+					flags |= ControlFlags.DiscretionaryAclPresent;
+					break;
+				
+				case "S:":
+					pos += 2;
+					SystemAcl = RawAcl.ParseSddlForm (sddlForm, false, ref flags, ref pos);
+					flags |= ControlFlags.SystemAclPresent;
+					break;
+				default:
+					
+					throw new ArgumentException ("Invalid SDDL.", "sddlForm");
+				}
 			}
-			set {
-				throw new NotImplementedException ();
+			
+			if (pos != sddlForm.Length) {
+				throw new ArgumentException ("Invalid SDDL.", "sddlForm");
 			}
+			
+			SetFlags (flags);
 		}
-
-		public void SetFlags (ControlFlags flags)
+		
+		private ushort ReadUShort (byte[] buffer, int offset)
+		{
+			return (ushort)((((int)buffer[offset + 0]) << 0)
+			                | (((int)buffer[offset + 1]) << 8));
+		}
+		
+		private int ReadInt (byte[] buffer, int offset)
 		{
-			throw new NotImplementedException ();
+			return (((int)buffer[offset + 0]) << 0)
+				| (((int)buffer[offset + 1]) << 8)
+				| (((int)buffer[offset + 2]) << 16)
+				| (((int)buffer[offset + 3]) << 24);
 		}
 	}
 }
diff --git a/mcs/class/corlib/System.Security.AccessControl/SddlAccessRight.cs b/mcs/class/corlib/System.Security.AccessControl/SddlAccessRight.cs
new file mode 100644
index 0000000..218c7f5
--- /dev/null
+++ b/mcs/class/corlib/System.Security.AccessControl/SddlAccessRight.cs
@@ -0,0 +1,98 @@
+//
+// System.Security.AccessControl.SddlAccessRight.cs
+//
+// Author:
+//	Kenneth Bell
+//
+
+using System.Collections.Generic;
+
+namespace System.Security.AccessControl
+{
+	internal class SddlAccessRight
+	{
+		public string Name { get; set; }
+		public int Value { get; set; }
+		public int ObjectType { get; set; }
+
+		public static SddlAccessRight LookupByName(string s)
+		{
+			foreach (var right in rights) {
+				if (right.Name == s)
+					return right;
+			}
+			
+			return null;
+		}
+		
+		public static SddlAccessRight[] Decompose(int mask)
+		{
+			foreach (var right in rights) {
+				if (mask == right.Value)
+					return new SddlAccessRight[] {right};
+			}
+			
+			int foundType = 0;
+			List<SddlAccessRight> found = new List<SddlAccessRight>();
+			int accountedBits = 0;
+			foreach (var right in rights) {
+				if ((mask & right.Value) == right.Value
+				    && (accountedBits | right.Value) != accountedBits) {
+					
+					if (foundType == 0)
+						foundType = right.ObjectType;
+					
+					if(right.ObjectType != 0
+					   && foundType != right.ObjectType)
+						return null;
+
+					found.Add(right);
+					accountedBits |= right.Value;
+				}
+				
+				if (accountedBits == mask)
+				{
+					return found.ToArray();
+				}
+			}
+			
+			return null;
+		}
+
+		private static readonly SddlAccessRight[] rights = new SddlAccessRight[] {
+			new SddlAccessRight { Name = "CC", Value = 0x00000001, ObjectType = 1},
+			new SddlAccessRight { Name = "DC", Value = 0x00000002, ObjectType = 1},
+			new SddlAccessRight { Name = "LC", Value = 0x00000004, ObjectType = 1},
+			new SddlAccessRight { Name = "SW", Value = 0x00000008, ObjectType = 1},
+			new SddlAccessRight { Name = "RP", Value = 0x00000010, ObjectType = 1},
+			new SddlAccessRight { Name = "WP", Value = 0x00000020, ObjectType = 1},
+			new SddlAccessRight { Name = "DT", Value = 0x00000040, ObjectType = 1},
+			new SddlAccessRight { Name = "LO", Value = 0x00000080, ObjectType = 1},
+			new SddlAccessRight { Name = "CR", Value = 0x00000100, ObjectType = 1},
+			
+			new SddlAccessRight { Name = "SD", Value = 0x00010000},
+			new SddlAccessRight { Name = "RC", Value = 0x00020000},
+			new SddlAccessRight { Name = "WD", Value = 0x00040000},
+			new SddlAccessRight { Name = "WO", Value = 0x00080000},
+			
+			new SddlAccessRight { Name = "GA", Value = 0x10000000},
+			new SddlAccessRight { Name = "GX", Value = 0x20000000},
+			new SddlAccessRight { Name = "GW", Value = 0x40000000},
+			new SddlAccessRight { Name = "GR", Value = unchecked((int)0x80000000)},
+
+			new SddlAccessRight { Name = "FA", Value = 0x001F01FF, ObjectType = 2},
+			new SddlAccessRight { Name = "FR", Value = 0x00120089, ObjectType = 2},
+			new SddlAccessRight { Name = "FW", Value = 0x00120116, ObjectType = 2},
+			new SddlAccessRight { Name = "FX", Value = 0x001200A0, ObjectType = 2},
+			
+			new SddlAccessRight { Name = "KA", Value = 0x000F003F, ObjectType = 3},
+			new SddlAccessRight { Name = "KR", Value = 0x00020019, ObjectType = 3},
+			new SddlAccessRight { Name = "KW", Value = 0x00020006, ObjectType = 3},
+			new SddlAccessRight { Name = "KX", Value = 0x00020019, ObjectType = 3},
+
+			new SddlAccessRight { Name = "NW", Value = 0x00000001},
+			new SddlAccessRight { Name = "NR", Value = 0x00000002},
+			new SddlAccessRight { Name = "NX", Value = 0x00000004},
+		};
+	}
+}
diff --git a/mcs/class/corlib/System.Security.AccessControl/SystemAcl.cs b/mcs/class/corlib/System.Security.AccessControl/SystemAcl.cs
index 56ad74b..1970ab9 100644
--- a/mcs/class/corlib/System.Security.AccessControl/SystemAcl.cs
+++ b/mcs/class/corlib/System.Security.AccessControl/SystemAcl.cs
@@ -134,6 +134,11 @@ namespace System.Security.AccessControl {
 		{
 			throw new NotImplementedException ();
 		}
+
+		internal override string GetSddlForm(ControlFlags sdFlags, bool isDacl)
+		{
+			throw new NotImplementedException();
+		}
 	}
 }
 
diff --git a/mcs/class/corlib/System.Security.Cryptography/ChangeLog b/mcs/class/corlib/System.Security.Cryptography/ChangeLog
index 6da7bfe..0825a76 100644
--- a/mcs/class/corlib/System.Security.Cryptography/ChangeLog
+++ b/mcs/class/corlib/System.Security.Cryptography/ChangeLog
@@ -1,3 +1,20 @@
+2011-02-08  Marek Habersack  <grendel at twistedcode.net>
+
+	[crypto] Added missing 4.0 algorithm names
+
+2011-01-25  Marek Habersack  <grendel at twistedcode.net>
+
+	[corlib,crypto] RandomNumberGenerator implements IDisposable in
+	4.0
+
+2011-01-11  Sebastien Pouliot  <sebastien at ximian.com>
+
+	* System.Security.Cryptography/CryptoConfig.cs: Add OID for
+	RIPEMD160 *
+	System.Security.Cryptography/RSACryptoServiceProvider.cs: Update
+	GetHashNameFromOID to include SHA2-family OIDs. Remove historical
+	comments about 1.x FX behavior.
+
 2010-11-11  Sebastien Pouliot  <sebastien at ximian.com>
 
 	* CryptoConfig_2_1.cs: Add fully qualified name (to simple name)
diff --git a/mcs/class/corlib/System.Security.Cryptography/CryptoConfig.cs b/mcs/class/corlib/System.Security.Cryptography/CryptoConfig.cs
index 1d0e78d..8a923c7 100644
--- a/mcs/class/corlib/System.Security.Cryptography/CryptoConfig.cs
+++ b/mcs/class/corlib/System.Security.Cryptography/CryptoConfig.cs
@@ -7,7 +7,7 @@
 //
 // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
 // Copyright (C) Tim Coleman, 2004
-// Copyright (C) 2004-2007 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004-2007,2011 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
@@ -104,6 +104,7 @@ public partial      class CryptoConfig {
 	private const string oidSHA256 = "2.16.840.1.101.3.4.2.1";
 	private const string oidSHA384 = "2.16.840.1.101.3.4.2.2";
 	private const string oidSHA512 = "2.16.840.1.101.3.4.2.3";
+	private const string oidRIPEMD160 = "1.3.36.3.2.1";
 	// new in 2.0
 //	private const string oidRSA = "1.2.840.113549.1.1.1";
 //	private const string oidDSA = "1.2.840.10040.4.1";
@@ -212,7 +213,58 @@ public partial      class CryptoConfig {
 	// new (2.0) X509 Chain
 	private const string nameX509Chain = "X509Chain";
 	private const string defaultX509Chain = defaultNamespace + "X509Certificates.X509Chain, " + Consts.AssemblySystem;
-
+#if NET_4_0
+	// AES
+	const string system_core_assembly = ", System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
+	const string nameAES_1 = "AES";
+	const string nameAES_2 = "System.Security.Cryptography.AesCryptoServiceProvider";
+	const string defaultAES_1 = "System.Security.Cryptography.AesCryptoServiceProvider" + system_core_assembly;
+	
+	const string nameAESManaged_1 = "AesManaged";
+	const string nameAESManaged_2 = "System.Security.Cryptography.AesManaged";
+	const string defaultAESManaged = "System.Security.Cryptography.AesManaged" + system_core_assembly;
+
+	// ECDiffieHellman - not implemented in System.Core at the moment
+	const string nameECDiffieHellman_1 = "ECDH";
+	const string nameECDiffieHellman_2 = "ECDiffieHellman";
+	const string nameECDiffieHellman_3 = "ECDiffieHellmanCng";
+	const string nameECDiffieHellman_4 = "System.Security.Cryptography.ECDiffieHellmanCng";
+	const string defaultECDiffieHellman = "System.Security.Cryptography.ECDiffieHellmanCng" + system_core_assembly;
+
+	// ECDsa - not implemented in System.Core at the moment
+	const string nameECDsa_1 = "ECDsa";
+	const string nameECDsa_2 = "ECDsaCng";
+	const string nameECDsa_3 = "System.Security.Cryptography.ECDsaCng";
+	const string defaultECDsa = "System.Security.Cryptography.ECDsaCng" + system_core_assembly;
+
+	// SHA1Cng
+	const string nameSHA1Cng = "System.Security.Cryptography.SHA1Cng";
+	const string defaultSHA1Cng = "System.Security.Cryptography.SHA1Cng" + system_core_assembly;
+
+	// SHA256Cng
+	const string nameSHA256Cng = "System.Security.Cryptography.SHA256Cng";
+	const string defaultSHA256Cng = "System.Security.Cryptography.SHA256Cng" + system_core_assembly;
+
+	// SHA256 provider
+	const string nameSHA256Provider = "System.Security.Cryptography.SHA256CryptoServiceProvider";
+	const string defaultSHA256Provider = "System.Security.Cryptography.SHA256CryptoServiceProvider" + system_core_assembly;
+
+	// SHA384Cng
+	const string nameSHA384Cng = "System.Security.Cryptography.SHA384Cng";
+	const string defaultSHA384Cng = "System.Security.Cryptography.SHA384Cng" + system_core_assembly;
+
+	// SHA384 provider
+	const string nameSHA384Provider = "System.Security.Cryptography.SHA384CryptoServiceProvider";
+	const string defaultSHA384Provider = "System.Security.Cryptography.SHA384CryptoServiceProvider" + system_core_assembly;
+
+	// SHA512Cng
+	const string nameSHA512Cng = "System.Security.Cryptography.SHA512Cng";
+	const string defaultSHA512Cng = "System.Security.Cryptography.SHA512Cng" + system_core_assembly;
+
+	// SHA512 provider
+	const string nameSHA512Provider = "System.Security.Cryptography.SHA512CryptoServiceProvider";
+	const string defaultSHA512Provider = "System.Security.Cryptography.SHA512CryptoServiceProvider" + system_core_assembly;
+#endif
 	static CryptoConfig () 
 	{
 		// lock(this) is bad
@@ -328,7 +380,29 @@ public partial      class CryptoConfig {
 		algorithms.Add (oidX509EnhancedKeyUsage, nameX509EnhancedKeyUsage);
 		// note: the default X.509Chain can also be created this way
 		algorithms.Add (nameX509Chain, defaultX509Chain);
-
+#if NET_4_0
+		algorithms.Add (nameAES_1, defaultAES_1);
+		algorithms.Add (nameAES_2, defaultAES_1);
+		algorithms.Add (nameAESManaged_1, defaultAESManaged);
+		algorithms.Add (nameAESManaged_2, defaultAESManaged);
+
+		algorithms.Add (nameECDiffieHellman_1, defaultECDiffieHellman);
+		algorithms.Add (nameECDiffieHellman_2, defaultECDiffieHellman);
+		algorithms.Add (nameECDiffieHellman_3, defaultECDiffieHellman);
+		algorithms.Add (nameECDiffieHellman_4, defaultECDiffieHellman);
+
+		algorithms.Add (nameECDsa_1, defaultECDsa);
+		algorithms.Add (nameECDsa_2, defaultECDsa);
+		algorithms.Add (nameECDsa_3, defaultECDsa);
+
+		algorithms.Add (nameSHA1Cng, defaultSHA1Cng);
+		algorithms.Add (nameSHA256Cng, defaultSHA256Cng);
+		algorithms.Add (nameSHA256Provider, defaultSHA256Provider);
+		algorithms.Add (nameSHA384Cng, defaultSHA384Cng);
+		algorithms.Add (nameSHA384Provider, defaultSHA384Provider);
+		algorithms.Add (nameSHA512Cng, defaultSHA512Cng);
+		algorithms.Add (nameSHA512Provider, defaultSHA512Provider);
+#endif
 		Hashtable oid = new Hashtable (new CaseInsensitiveHashCodeProvider (), new CaseInsensitiveComparer ());
 
 		// comments here are to match with MS implementation (but not with doc)
@@ -354,6 +428,10 @@ public partial      class CryptoConfig {
 		oid.Add (nameSHA512a, oidSHA512);
 		oid.Add (nameSHA512c, oidSHA512);
 
+		oid.Add (defaultRIPEMD160, oidRIPEMD160);
+		oid.Add (nameRIPEMD160a, oidRIPEMD160);
+		oid.Add (nameRIPEMD160c, oidRIPEMD160);
+
 		// surprise! documented in ".NET Framework Security" book
 		oid.Add (name3DESKeyWrap, oid3DESKeyWrap);
 
diff --git a/mcs/class/corlib/System.Security.Cryptography/RSACryptoServiceProvider.cs b/mcs/class/corlib/System.Security.Cryptography/RSACryptoServiceProvider.cs
index 822db5b..41bc61d 100644
--- a/mcs/class/corlib/System.Security.Cryptography/RSACryptoServiceProvider.cs
+++ b/mcs/class/corlib/System.Security.Cryptography/RSACryptoServiceProvider.cs
@@ -278,19 +278,21 @@ namespace System.Security.Cryptography {
 		private string GetHashNameFromOID (string oid) 
 		{
 			switch (oid) {
-				case "1.3.14.3.2.26":
-					return "SHA1";
-				case "1.2.840.113549.2.5":
-					return "MD5";
-				default:
-					throw new NotSupportedException (oid + " is an unsupported hash algorithm for RSA signing");
+			case "1.3.14.3.2.26":
+				return "SHA1";
+			case "1.2.840.113549.2.5":
+				return "MD5";
+			case "2.16.840.1.101.3.4.2.1":
+				return "SHA256";
+			case "2.16.840.1.101.3.4.2.2":
+				return "SHA384";
+			case "2.16.840.1.101.3.4.2.3":
+				return "SHA512";
+			default:
+				throw new CryptographicException (oid + " is an unsupported hash algorithm for RSA signing");
 			}
 		}
 
-		// LAMESPEC: str is not the hash name but an OID
-		// NOTE: this method is LIMITED to SHA1 and MD5 like the MS framework 1.0 
-		// and 1.1 because there's no method to get a hash algorithm from an OID. 
-		// However there's no such limit when using the [De]Formatter class.
 		public byte[] SignHash (byte[] rgbHash, string str) 
 		{
 			if (rgbHash == null)
@@ -315,10 +317,6 @@ namespace System.Security.Cryptography {
 			return PKCS1.Verify_v15 (this, hash, toBeVerified, signature);
 		}
 	
-		// LAMESPEC: str is not the hash name but an OID
-		// NOTE: this method is LIMITED to SHA1 and MD5 like the MS framework 1.0 
-		// and 1.1 because there's no method to get a hash algorithm from an OID. 
-		// However there's no such limit when using the [De]Formatter class.
 		public bool VerifyHash (byte[] rgbHash, string str, byte[] rgbSignature) 
 		{
 			if (rgbHash == null) 
diff --git a/mcs/class/corlib/System.Security.Cryptography/RandomNumberGenerator.cs b/mcs/class/corlib/System.Security.Cryptography/RandomNumberGenerator.cs
index 025df7d..80924f9 100644
--- a/mcs/class/corlib/System.Security.Cryptography/RandomNumberGenerator.cs
+++ b/mcs/class/corlib/System.Security.Cryptography/RandomNumberGenerator.cs
@@ -34,7 +34,11 @@ namespace System.Security.Cryptography {
 #if !NET_2_1
 	[ComVisible (true)]
 #endif
-	public abstract class RandomNumberGenerator {
+	public abstract class RandomNumberGenerator
+#if NET_4_0
+	: IDisposable
+#endif
+	{
 
 		protected RandomNumberGenerator ()
 		{
@@ -54,5 +58,14 @@ namespace System.Security.Cryptography {
 		public abstract void GetBytes (byte[] data);
 
 		public abstract void GetNonZeroBytes (byte[] data);
+#if NET_4_0
+		public void Dispose ()
+		{
+			Dispose (true);
+		}
+
+		protected virtual void Dispose (bool disposing)
+		{}
+#endif
 	}
 }
diff --git a/mcs/class/corlib/System.Security.Principal/ChangeLog b/mcs/class/corlib/System.Security.Principal/ChangeLog
index d73b94c..054369a 100644
--- a/mcs/class/corlib/System.Security.Principal/ChangeLog
+++ b/mcs/class/corlib/System.Security.Principal/ChangeLog
@@ -1,3 +1,15 @@
+2010-12-04  Kenneth Bell  <ken.git at chezbell.org.uk>
+
+	Implement SecurityIdentifier and improve NTAccount.
+
+	* Only translates between SecurityIdentifier and NTAccount for
+	well-known accounts.
+
+	* NTAccount changed to not upper-case values to match behaviour
+	observed in Microsoft's .NET (see also unit tests)
+
+	* Add unit tests for both classes
+
 2008-05-30  Sebastien Pouliot  <sebastien at ximian.com> 
 
 	* IdentityReferenceCollection.cs: Remove MonoTODO and throw NIE.
diff --git a/mcs/class/corlib/System.Security.Principal/ChangeLog b/mcs/class/corlib/System.Security.Principal/ChangeLog.old
similarity index 100%
copy from mcs/class/corlib/System.Security.Principal/ChangeLog
copy to mcs/class/corlib/System.Security.Principal/ChangeLog.old
diff --git a/mcs/class/corlib/System.Security.Principal/NTAccount.cs b/mcs/class/corlib/System.Security.Principal/NTAccount.cs
index 1e65ea8..9c0f46b 100644
--- a/mcs/class/corlib/System.Security.Principal/NTAccount.cs
+++ b/mcs/class/corlib/System.Security.Principal/NTAccount.cs
@@ -3,6 +3,7 @@
 //
 // Author:
 //	Sebastien Pouliot  <sebastien at ximian.com>
+//	Kenneth Bell
 //
 // Copyright (C) 2005, 2006 Novell, Inc (http://www.novell.com)
 //
@@ -43,7 +44,7 @@ namespace System.Security.Principal {
 				throw new ArgumentNullException ("name");
 			if (name.Length == 0)
 				throw new ArgumentException (Locale.GetText ("Empty"), "name");
-			_value = name.ToUpper ();
+			_value = name;
 		}
 
 		public NTAccount (string domainName, string accountName)
@@ -53,9 +54,9 @@ namespace System.Security.Principal {
 			if (accountName.Length == 0)
 				throw new ArgumentException (Locale.GetText ("Empty"), "accountName");
 			if (domainName == null)
-				_value = domainName.ToUpper ();
+				_value = accountName;
 			else
-				_value = domainName.ToUpper () + "\\" + domainName.ToUpper ();
+				_value = domainName + "\\" + accountName;
 		}
 
 
@@ -95,7 +96,16 @@ namespace System.Security.Principal {
 		{
 			if (targetType == typeof (NTAccount))
 				return this; // ? copy
-			return null;
+			
+			if(targetType == typeof(SecurityIdentifier)) {
+				WellKnownAccount acct = WellKnownAccount.LookupByName(this.Value);
+				if (acct == null || acct.Sid == null)
+					throw new IdentityNotMappedException("Cannot map account name: " + this.Value);
+
+				return new SecurityIdentifier(acct.Sid);
+			}
+			
+			throw new ArgumentException("Unknown type", "targetType");
 		}
 
 		public static bool operator == (NTAccount left, NTAccount right)
diff --git a/mcs/class/corlib/System.Security.Principal/SecurityIdentifier.cs b/mcs/class/corlib/System.Security.Principal/SecurityIdentifier.cs
index 3664f3d..cd4c47a 100644
--- a/mcs/class/corlib/System.Security.Principal/SecurityIdentifier.cs
+++ b/mcs/class/corlib/System.Security.Principal/SecurityIdentifier.cs
@@ -3,6 +3,7 @@
 //
 // Author:
 //	Sebastien Pouliot  <sebastien at ximian.com>
+//	Kenneth Bell
 //
 // Copyright (C) 2005, 2006 Novell, Inc (http://www.novell.com)
 //
@@ -29,35 +30,42 @@
 
 using System.Globalization;
 using System.Runtime.InteropServices;
+using System.Text;
 
 namespace System.Security.Principal {
 
-	[MonoTODO ("not implemented")]
 	[ComVisible (false)]
 	public sealed class SecurityIdentifier : IdentityReference, IComparable<SecurityIdentifier> {
+		private byte[] buffer;
 
-		private string _value;
-
-		public static readonly int MaxBinaryLength = 0;
-		public static readonly int MinBinaryLength = 0;
+		public static readonly int MaxBinaryLength = 68;
+		public static readonly int MinBinaryLength = 8;
 
 
 		public SecurityIdentifier (string sddlForm)
 		{
 			if (sddlForm == null)
 				throw new ArgumentNullException ("sddlForm");
-
-			_value = sddlForm.ToUpperInvariant ();
+			
+			buffer = ParseSddlForm (sddlForm);
 		}
 
 		public SecurityIdentifier (byte[] binaryForm, int offset)
 		{
 			if (binaryForm == null)
 				throw new ArgumentNullException ("binaryForm");
-			if ((offset < 0) || (offset > binaryForm.Length - 1))
+			if ((offset < 0) || (offset > binaryForm.Length - 2))
 				throw new ArgumentException ("offset");
-
-			throw new NotImplementedException ();
+			
+			int revision = binaryForm[offset];
+			int numSubAuthorities = binaryForm[offset + 1];
+			if (revision != 1 || numSubAuthorities > 15)
+				throw new ArgumentException ("Value was invalid.");
+			if (offset > binaryForm.Length - (8 + (numSubAuthorities * 4)))
+				throw new ArgumentException ("offset");
+			
+			buffer = new byte[8 + (numSubAuthorities * 4)];
+			Array.Copy (binaryForm, offset, buffer, 0, buffer.Length);
 		}
 
 		public SecurityIdentifier (IntPtr binaryForm)
@@ -65,44 +73,68 @@ namespace System.Security.Principal {
 			throw new NotImplementedException ();
 		}
 
-		public SecurityIdentifier (WellKnownSidType sidType, SecurityIdentifier domainSid)
-		{
-			switch (sidType) {
-			case WellKnownSidType.LogonIdsSid:
-				throw new ArgumentException ("sidType");
-			case WellKnownSidType.AccountAdministratorSid:
-			case WellKnownSidType.AccountGuestSid:
-			case WellKnownSidType.AccountKrbtgtSid:
-			case WellKnownSidType.AccountDomainAdminsSid:
-			case WellKnownSidType.AccountDomainUsersSid:
-			case WellKnownSidType.AccountDomainGuestsSid:
-			case WellKnownSidType.AccountComputersSid:
-			case WellKnownSidType.AccountControllersSid:
-			case WellKnownSidType.AccountCertAdminsSid:
-			case WellKnownSidType.AccountSchemaAdminsSid:
-			case WellKnownSidType.AccountEnterpriseAdminsSid:
-			case WellKnownSidType.AccountPolicyAdminsSid:
-			case WellKnownSidType.AccountRasAndIasServersSid:
+		public SecurityIdentifier (WellKnownSidType sidType,
+		                           SecurityIdentifier domainSid)
+		{
+			WellKnownAccount acct = WellKnownAccount.LookupByType (sidType);
+			if (acct == null)
+				throw new ArgumentException ("Unable to convert SID type: " + sidType);
+			
+			if (acct.IsAbsolute) {
+				buffer = ParseSddlForm (acct.Sid);
+			} else {
 				if (domainSid == null)
 					throw new ArgumentNullException ("domainSid");
-				// TODO
-				break;
-			default:
-				// TODO
-				break;
+				
+				buffer = ParseSddlForm (domainSid.Value + "-" + acct.Rid);
 			}
 		}
 
 		public SecurityIdentifier AccountDomainSid {
-			get { throw new ArgumentNullException ("AccountDomainSid"); }
+			get {
+				string strForm = this.Value;
+				
+				// Check prefix, and ensure at least 4 sub authorities
+				if (!strForm.StartsWith ("S-1-5-21") || buffer[1] < 4)
+					return null;
+				
+				// Domain is first four sub-authorities
+				byte[] temp = new byte[8 + (4 * 4)];
+				Array.Copy (buffer, 0, temp, 0, temp.Length);
+				temp[1] = 4;
+				return new SecurityIdentifier (temp, 0);
+			}
 		}
 
 		public int BinaryLength {
-			get { return -1; }
+			get { return buffer.Length; }
 		}
 
-		public override string Value { 
-			get { return _value; }
+		public override string Value {
+			get {
+				StringBuilder s = new StringBuilder ();
+				
+				ulong authority = (((ulong)buffer[2]) << 40) | (((ulong)buffer[3]) << 32)
+					| (((ulong)buffer[4]) << 24) | (((ulong)buffer[5]) << 16)
+					| (((ulong)buffer[6]) << 8) | (((ulong)buffer[7]) << 0);
+				s.AppendFormat (CultureInfo.InvariantCulture, "S-1-{0}", authority);
+				
+				for (int i = 0; i < buffer[1]; ++i) {
+					// Note sub authorities little-endian, authority (above) is big-endian!
+					int offset = 8 + (i * 4);
+					
+					uint subAuthority =
+						(((uint)buffer[offset + 0]) << 0)
+						| (((uint)buffer[offset + 1]) << 8)
+						| (((uint)buffer[offset + 2]) << 16)
+						| (((uint)buffer[offset + 3]) << 24);
+					s.AppendFormat (
+						CultureInfo.InvariantCulture,
+					        "-{0}", subAuthority);
+				}
+				
+				return s.ToString ();
+			}
 		}
 
 		public int CompareTo (SecurityIdentifier sid)
@@ -126,10 +158,10 @@ namespace System.Security.Principal {
 		{
 			if (binaryForm == null)
 				throw new ArgumentNullException ("binaryForm");
-			if ((offset < 0) || (offset > binaryForm.Length - 1 - this.BinaryLength))
+			if ((offset < 0) || (offset > binaryForm.Length - buffer.Length))
 				throw new ArgumentException ("offset");
-
-			// TODO
+			
+			Array.Copy (buffer, 0, binaryForm, offset, buffer.Length);
 		}
 
 		public override int GetHashCode ()
@@ -139,26 +171,40 @@ namespace System.Security.Principal {
 
 		public bool IsAccountSid ()
 		{
-			throw new NotImplementedException ();
+			return AccountDomainSid != null;
 		}
 
 		public bool IsEqualDomainSid (SecurityIdentifier sid)
 		{
-			throw new NotImplementedException ();
+			SecurityIdentifier domSid = AccountDomainSid;
+			if (domSid == null)
+				return false;
+			
+			return domSid.Equals (sid.AccountDomainSid);
 		}
 
 		public override bool IsValidTargetType (Type targetType)
 		{
-			if (targetType == typeof (SecurityIdentifier))
+			if (targetType == typeof(SecurityIdentifier))
 				return true;
-			if (targetType == typeof (NTAccount))
+			if (targetType == typeof(NTAccount))
 				return true;
 			return false;
 		}
 
 		public bool IsWellKnown (WellKnownSidType type)
 		{
-			throw new NotImplementedException ();
+			WellKnownAccount acct = WellKnownAccount.LookupByType (type);
+			if (acct == null)
+				return false;
+			
+			string sid = Value;
+			
+			if (acct.IsAbsolute)
+				return sid == acct.Sid;
+			
+			return sid.StartsWith ("S-1-5-21", StringComparison.OrdinalIgnoreCase)
+				&& sid.EndsWith ("-" + acct.Rid, StringComparison.OrdinalIgnoreCase);
 		}
 
 		public override string ToString ()
@@ -168,9 +214,18 @@ namespace System.Security.Principal {
 
 		public override IdentityReference Translate (Type targetType)
 		{
-			if (targetType == typeof (SecurityIdentifier))
-				return this; // ? copy
-			return null;
+			if (targetType == typeof(SecurityIdentifier))
+				return this;
+			
+			if (targetType == typeof(NTAccount)) {
+				WellKnownAccount acct = WellKnownAccount.LookupBySid (this.Value);
+				if (acct == null || acct.Name == null)
+					throw new IdentityNotMappedException ("Unable to map SID: " + this.Value);
+				
+				return new NTAccount (acct.Name);
+			}
+			
+			throw new ArgumentException ("Unknown type.", "targetType");
 		}
 
 		public static bool operator == (SecurityIdentifier left, SecurityIdentifier right)
@@ -190,6 +245,139 @@ namespace System.Security.Principal {
 				return true;
 			return (left.Value != right.Value);
 		}
+
+		internal string GetSddlForm()
+		{
+			string sidString = Value;
+			
+			WellKnownAccount acct = WellKnownAccount.LookupBySid(sidString);
+			if(acct == null || acct.SddlForm == null)
+				return sidString;
+			
+			return acct.SddlForm;
+		}
+
+		internal static SecurityIdentifier ParseSddlForm(string sddlForm, ref int pos)
+		{
+			if (sddlForm.Length - pos < 2)
+				throw new ArgumentException("Invalid SDDL string.", "sddlForm");
+			
+			string sid;
+			int len;
+			
+			string prefix = sddlForm.Substring(pos, 2).ToUpperInvariant();
+			if (prefix == "S-")
+			{
+				// Looks like a SID, try to parse it.
+				int endPos = pos;
+				
+				char ch = Char.ToUpperInvariant(sddlForm[endPos]);
+				while (ch == 'S' || ch == '-' || ch == 'X'
+				       || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F')) {
+					++endPos;
+					ch = Char.ToUpperInvariant(sddlForm[endPos]);
+				}
+				
+				sid = sddlForm.Substring(pos, endPos - pos);
+				len = endPos - pos;
+			} else {
+				sid = prefix;
+				len = 2;
+			}
+			
+			SecurityIdentifier ret = new SecurityIdentifier(sid);
+			pos += len;
+			return ret;
+		}
+
+		private static byte[] ParseSddlForm (string sddlForm)
+		{
+			string sid = sddlForm;
+			
+			// If only 2 characters long, can't be a full SID string - so assume
+			// it's an attempted alias.  Do that conversion first.
+			if(sddlForm.Length == 2) {
+				WellKnownAccount acct = WellKnownAccount.LookupBySddlForm(sddlForm);
+				if (acct == null)
+					throw new ArgumentException(
+						"Invalid SDDL string - unrecognized account: " + sddlForm,
+					        "sddlForm");
+				if (!acct.IsAbsolute)
+					throw new NotImplementedException(
+					        "Mono unable to convert account to SID: "
+					        + (acct.Name != null ? acct.Name : sddlForm));
+
+				sid = acct.Sid;
+			}
+			
+			string[] elements = sid.ToUpperInvariant ().Split ('-');
+			int numSubAuthorities = elements.Length - 3;
+			
+			if (elements.Length < 3 || elements[0] != "S" || numSubAuthorities > 15)
+				throw new ArgumentException ("Value was invalid.");
+			
+			if (elements[1] != "1")
+				throw new ArgumentException ("Only SIDs with revision 1 are supported");
+			
+			byte[] buffer = new byte[8 + (numSubAuthorities * 4)];
+			buffer[0] = 1;
+			buffer[1] = (byte)numSubAuthorities;
+			
+			ulong authority;
+			if (!TryParseAuthority (elements[2], out authority))
+				throw new ArgumentException ("Value was invalid.");
+			buffer[2] = (byte)((authority >> 40) & 0xFF);
+			buffer[3] = (byte)((authority >> 32) & 0xFF);
+			buffer[4] = (byte)((authority >> 24) & 0xFF);
+			buffer[5] = (byte)((authority >> 16) & 0xFF);
+			buffer[6] = (byte)((authority >> 8) & 0xFF);
+			buffer[7] = (byte)((authority >> 0) & 0xFF);
+			
+			for (int i = 0; i < numSubAuthorities; ++i) {
+				uint subAuthority;
+				
+				if (!TryParseSubAuthority (elements[i + 3],
+				                           out subAuthority))
+					throw new ArgumentException ("Value was invalid.");
+				
+				// Note sub authorities little-endian!
+				int offset = 8 + (i * 4);
+				buffer[offset + 0] = (byte)(subAuthority >> 0);
+				buffer[offset + 1] = (byte)(subAuthority >> 8);
+				buffer[offset + 2] = (byte)(subAuthority >> 16);
+				buffer[offset + 3] = (byte)(subAuthority >> 24);
+			}
+			
+			return buffer;
+		}
+
+		private static bool TryParseAuthority (string s, out ulong result)
+		{
+			if (s.StartsWith ("0X")) {
+				return ulong.TryParse (s.Substring (2),
+				                       NumberStyles.HexNumber,
+				                       CultureInfo.InvariantCulture,
+				                       out result);
+			} else {
+				return ulong.TryParse (s, NumberStyles.Integer,
+				                       CultureInfo.InvariantCulture,
+				                       out result);
+			}
+		}
+
+		private static bool TryParseSubAuthority (string s, out uint result)
+		{
+			if (s.StartsWith ("0X")) {
+				return uint.TryParse (s.Substring (2),
+				                      NumberStyles.HexNumber,
+				                      CultureInfo.InvariantCulture,
+				                      out result);
+			} else {
+				return uint.TryParse (s, NumberStyles.Integer,
+				                      CultureInfo.InvariantCulture,
+				                      out result);
+			}
+		}
 	}
 }
 
diff --git a/mcs/class/corlib/System.Security.Principal/WellKnownAccount.cs b/mcs/class/corlib/System.Security.Principal/WellKnownAccount.cs
new file mode 100644
index 0000000..593fe32
--- /dev/null
+++ b/mcs/class/corlib/System.Security.Principal/WellKnownAccount.cs
@@ -0,0 +1,129 @@
+//
+// System.Security.Policy.WellKnownAccount.cs
+//
+// Author:
+//	Kenneth Bell
+//
+
+
+namespace System.Security.Principal
+{
+	internal class WellKnownAccount
+	{
+		public WellKnownSidType WellKnownValue { get; set; }
+		public bool IsAbsolute { get; set; }
+		public string Sid { get; set; }
+		public string Rid { get; set; }
+		public string Name { get; set; }
+		public string SddlForm { get; set; }
+
+		public static WellKnownAccount LookupByType (WellKnownSidType sidType)
+		{
+			foreach (var acct in accounts) {
+				if (acct.WellKnownValue == sidType)
+					return acct;
+			}
+			
+			return null;
+		}
+
+		public static WellKnownAccount LookupBySid(string s)
+		{
+			foreach (var acct in accounts) {
+				if (acct.Sid == s)
+					return acct;
+			}
+			
+			return null;
+		}
+
+		public static WellKnownAccount LookupByName(string s)
+		{
+			foreach (var acct in accounts) {
+				if (acct.Name == s)
+					return acct;
+			}
+			
+			return null;
+		}
+
+		public static WellKnownAccount LookupBySddlForm(string s)
+		{
+			foreach (var acct in accounts) {
+				if (acct.SddlForm == s)
+					return acct;
+			}
+			
+			return null;
+		}
+
+		private static readonly WellKnownAccount[] accounts = new WellKnownAccount[] {
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.NullSid, IsAbsolute = true, Sid = "S-1-0-0", Name = @"NULL SID"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.WorldSid, IsAbsolute = true, Sid = "S-1-1-0", Name = @"Everyone", SddlForm = "WD"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.LocalSid, IsAbsolute = true, Sid = "S-1-2-0", Name = @"LOCAL"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.CreatorOwnerSid, IsAbsolute = true, Sid = "S-1-3-0", Name = @"CREATOR OWNER", SddlForm = "CO"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.CreatorGroupSid, IsAbsolute = true, Sid = "S-1-3-1", Name = @"CREATOR GROUP", SddlForm = "CG"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.CreatorOwnerServerSid, IsAbsolute = true, Sid = "S-1-3-2", Name = @"CREATOR OWNER SERVER"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.CreatorGroupServerSid, IsAbsolute = true, Sid = "S-1-3-3", Name = @"CREATOR GROUP SERVER"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.NTAuthoritySid, IsAbsolute = true, Sid = "S-1-5", Name = null},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.DialupSid, IsAbsolute = true, Sid = "S-1-5-1", Name = @"NT AUTHORITY\DIALUP"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.NetworkSid, IsAbsolute = true, Sid = "S-1-5-2", Name = @"NT AUTHORITY\NETWORK", SddlForm = "NU"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BatchSid, IsAbsolute = true, Sid = "S-1-5-3", Name = @"NT AUTHORITY\BATCH"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.InteractiveSid, IsAbsolute = true, Sid = "S-1-5-4", Name = @"NT AUTHORITY\INTERACTIVE", SddlForm = "IU"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.ServiceSid, IsAbsolute = true, Sid = "S-1-5-6", Name = @"NT AUTHORITY\SERVICE", SddlForm = "SU"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AnonymousSid, IsAbsolute = true, Sid = "S-1-5-7", Name = @"NT AUTHORITY\ANONYMOUS LOGON", SddlForm = "AN"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.ProxySid, IsAbsolute = true, Sid = "S-1-5-8", Name = @"NT AUTHORITY\PROXY"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.EnterpriseControllersSid, IsAbsolute = true, Sid = "S-1-5-9", Name = @"NT AUTHORITY\ENTERPRISE DOMAIN CONTROLLERS", SddlForm = "ED"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.SelfSid, IsAbsolute = true, Sid = "S-1-5-10", Name = @"NT AUTHORITY\SELF", SddlForm = "PS"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AuthenticatedUserSid, IsAbsolute = true, Sid = "S-1-5-11", Name = @"NT AUTHORITY\Authenticated Users", SddlForm = "AU"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.RestrictedCodeSid, IsAbsolute = true, Sid = "S-1-5-12", Name = @"NT AUTHORITY\RESTRICTED", SddlForm = "RC"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.TerminalServerSid, IsAbsolute = true, Sid = "S-1-5-13", Name = @"NT AUTHORITY\TERMINAL SERVER USER"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.RemoteLogonIdSid, IsAbsolute = true, Sid = "S-1-5-14", Name = @"NT AUTHORITY\REMOTE INTERACTIVE LOGON"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.LocalSystemSid, IsAbsolute = true, Sid = "S-1-5-18", Name = @"NT AUTHORITY\SYSTEM", SddlForm = "SY"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.LocalServiceSid, IsAbsolute = true, Sid = "S-1-5-19", Name = @"NT AUTHORITY\LOCAL SERVICE", SddlForm = "LS"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.NetworkServiceSid, IsAbsolute = true, Sid = "S-1-5-20", Name = @"NT AUTHORITY\NETWORK SERVICE", SddlForm = "NS"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinDomainSid, IsAbsolute = true, Sid = "S-1-5-32", Name = null},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinAdministratorsSid, IsAbsolute = true, Sid = "S-1-5-32-544", Name = @"BUILTIN\Administrators", SddlForm = "BA"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinUsersSid, IsAbsolute = true, Sid = "S-1-5-32-545", Name = @"BUILTIN\Users", SddlForm = "BU"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinGuestsSid, IsAbsolute = true, Sid = "S-1-5-32-546", Name = @"BUILTIN\Guests", SddlForm = "BG"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinPowerUsersSid, IsAbsolute = true, Sid = "S-1-5-32-547", Name = null, SddlForm = "PU"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinAccountOperatorsSid, IsAbsolute = true, Sid = "S-1-5-32-548", Name = null, SddlForm = "AO"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinSystemOperatorsSid, IsAbsolute = true, Sid = "S-1-5-32-549", Name = null, SddlForm = "SO"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinPrintOperatorsSid, IsAbsolute = true, Sid = "S-1-5-32-550", Name = null, SddlForm = "PO"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinBackupOperatorsSid, IsAbsolute = true, Sid = "S-1-5-32-551", Name = null, SddlForm = "BO"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinReplicatorSid, IsAbsolute = true, Sid = "S-1-5-32-552", Name = null, SddlForm = "RE"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinPreWindows2000CompatibleAccessSid, IsAbsolute = true, Sid = "S-1-5-32-554", Name = null, SddlForm = "RU"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinRemoteDesktopUsersSid, IsAbsolute = true, Sid = "S-1-5-32-555", Name = null, SddlForm = "RD"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinNetworkConfigurationOperatorsSid, IsAbsolute = true, Sid = "S-1-5-32-556", Name = null, SddlForm = "NO"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AccountAdministratorSid, IsAbsolute = false, Rid = "500", SddlForm = "LA"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AccountGuestSid, IsAbsolute = false, Rid = "501", SddlForm = "LG"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AccountKrbtgtSid, IsAbsolute = false, Rid = "502"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AccountDomainAdminsSid, IsAbsolute = false, Rid = "512", SddlForm = "DA"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AccountDomainUsersSid, IsAbsolute = false, Rid = "513", SddlForm = "DU"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AccountDomainGuestsSid, IsAbsolute = false, Rid = "514", SddlForm = "DG"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AccountComputersSid, IsAbsolute = false, Rid = "515", SddlForm = "DC"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AccountControllersSid, IsAbsolute = false, Rid = "516", SddlForm = "DD"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AccountCertAdminsSid, IsAbsolute = false, Rid = "517", SddlForm = "CA"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AccountSchemaAdminsSid, IsAbsolute = false, Rid = "518", SddlForm = "SA"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AccountEnterpriseAdminsSid, IsAbsolute = false, Rid = "519", SddlForm = "EA"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AccountPolicyAdminsSid, IsAbsolute = false, Rid = "520", SddlForm = "PA"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.AccountRasAndIasServersSid, IsAbsolute = false, Rid = "553", SddlForm = "RS"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.NtlmAuthenticationSid, IsAbsolute = true, Sid = "S-1-5-64-10", Name = @"NT AUTHORITY\NTLM Authentication"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.DigestAuthenticationSid, IsAbsolute = true, Sid = "S-1-5-64-21", Name = @"NT AUTHORITY\Digest Authentication"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.SChannelAuthenticationSid, IsAbsolute = true, Sid = "S-1-5-64-14", Name = @"NT AUTHORITY\SChannel Authentication"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.ThisOrganizationSid, IsAbsolute = true, Sid = "S-1-5-15", Name = @"NT AUTHORITY\This Organization"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.OtherOrganizationSid, IsAbsolute = true, Sid = "S-1-5-1000", Name = @"NT AUTHORITY\Other Organization"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinIncomingForestTrustBuildersSid, IsAbsolute = true, Sid = "S-1-5-32-557", Name = null},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinPerformanceMonitoringUsersSid, IsAbsolute = true, Sid = "S-1-5-32-558", Name = @"BUILTIN\Performance Monitor Users", SddlForm = "MU"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinPerformanceLoggingUsersSid, IsAbsolute = true, Sid = "S-1-5-32-559", Name = @"BUILTIN\Performance Log Users"},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.BuiltinAuthorizationAccessSid, IsAbsolute = true, Sid = "S-1-5-32-560", Name = null},
+			new WellKnownAccount { WellKnownValue = WellKnownSidType.WinBuiltinTerminalServerLicenseServersSid, IsAbsolute = true, Sid = "S-1-5-32-561", Name = null},
+			new WellKnownAccount { WellKnownValue = (WellKnownSidType)66, IsAbsolute = false, Rid = "4096", SddlForm = "LW"},
+			new WellKnownAccount { WellKnownValue = (WellKnownSidType)67, IsAbsolute = false, Rid = "8192", SddlForm = "ME"},
+			new WellKnownAccount { WellKnownValue = (WellKnownSidType)68, IsAbsolute = false, Rid = "12288", SddlForm = "HI"},
+			new WellKnownAccount { WellKnownValue = (WellKnownSidType)69, IsAbsolute = false, Rid = "16384", SddlForm = "SI"},
+			new WellKnownAccount { WellKnownValue = (WellKnownSidType)74, IsAbsolute = false, Rid = "521", SddlForm = "RO"},
+			new WellKnownAccount { WellKnownValue = (WellKnownSidType)78, IsAbsolute = false, Rid = "574", SddlForm = "CD"},
+		};
+	}
+}
diff --git a/mcs/class/corlib/System.Text/ChangeLog b/mcs/class/corlib/System.Text/ChangeLog
index 0984069..ec42a0f 100644
--- a/mcs/class/corlib/System.Text/ChangeLog
+++ b/mcs/class/corlib/System.Text/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
 2010-08-10  Atsushi Eno  <atsushi at ximian.com>
 
 	EncoderFallback support in UTF8Encoding. Fixed bug #565129 and
diff --git a/mcs/class/corlib/System.Text/StringBuilder.cs b/mcs/class/corlib/System.Text/StringBuilder.cs
index 130bf37..ac10d17 100644
--- a/mcs/class/corlib/System.Text/StringBuilder.cs
+++ b/mcs/class/corlib/System.Text/StringBuilder.cs
@@ -503,7 +503,7 @@ namespace System.Text {
 			return this;
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public StringBuilder Clear ()
 		{
 			_length = 0;
diff --git a/mcs/class/corlib/System.Threading.Tasks/ChangeLog b/mcs/class/corlib/System.Threading.Tasks/ChangeLog
index 34be6f9..33a0016 100644
--- a/mcs/class/corlib/System.Threading.Tasks/ChangeLog
+++ b/mcs/class/corlib/System.Threading.Tasks/ChangeLog
@@ -1,3 +1,12 @@
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Add pfx to the mobile profile
+
+2011-01-24  Jérémie Laval  <jeremie.laval at gmail.com>
+
+	Make sure a synchronous continuation get executed synchronously in
+	all cases
+
 2011-01-13  Jérémie Laval  <jeremie.laval at gmail.com>
 
 	Make use of the wait changes in the internal TaskScheduler ->
diff --git a/mcs/class/corlib/System.Threading.Tasks/CyclicDeque.cs b/mcs/class/corlib/System.Threading.Tasks/CyclicDeque.cs
index bd21edc..6f72bfa 100644
--- a/mcs/class/corlib/System.Threading.Tasks/CyclicDeque.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/CyclicDeque.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 using System.Collections.Generic;
diff --git a/mcs/class/corlib/System.Threading.Tasks/Future.cs b/mcs/class/corlib/System.Threading.Tasks/Future.cs
index 75a2a7c..3ab6a48 100644
--- a/mcs/class/corlib/System.Threading.Tasks/Future.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/Future.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 
 namespace System.Threading.Tasks
diff --git a/mcs/class/corlib/System.Threading.Tasks/IScheduler.cs b/mcs/class/corlib/System.Threading.Tasks/IScheduler.cs
index 9a9aadd..d4c78b4 100644
--- a/mcs/class/corlib/System.Threading.Tasks/IScheduler.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/IScheduler.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Threading;
 using System.Collections.Generic;
diff --git a/mcs/class/corlib/System.Threading.Tasks/Parallel.cs b/mcs/class/corlib/System.Threading.Tasks/Parallel.cs
index 5448dbc..7c4b2db 100644
--- a/mcs/class/corlib/System.Threading.Tasks/Parallel.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/Parallel.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Collections.Generic;
 using System.Collections.Concurrent;
diff --git a/mcs/class/corlib/System.Threading.Tasks/ParallelLoopResult.cs b/mcs/class/corlib/System.Threading.Tasks/ParallelLoopResult.cs
index b432ea5..87801f1 100644
--- a/mcs/class/corlib/System.Threading.Tasks/ParallelLoopResult.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/ParallelLoopResult.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 
 namespace System.Threading.Tasks
diff --git a/mcs/class/corlib/System.Threading.Tasks/ParallelLoopState.cs b/mcs/class/corlib/System.Threading.Tasks/ParallelLoopState.cs
index e5606d5..fa53a80 100644
--- a/mcs/class/corlib/System.Threading.Tasks/ParallelLoopState.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/ParallelLoopState.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Threading;
 
diff --git a/mcs/class/corlib/System.Threading.Tasks/ParallelOptions.cs b/mcs/class/corlib/System.Threading.Tasks/ParallelOptions.cs
index 6bc0b6b..ac9635c 100644
--- a/mcs/class/corlib/System.Threading.Tasks/ParallelOptions.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/ParallelOptions.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Threading;
 
diff --git a/mcs/class/corlib/System.Threading.Tasks/Scheduler.cs b/mcs/class/corlib/System.Threading.Tasks/Scheduler.cs
index b136d12..1179d49 100644
--- a/mcs/class/corlib/System.Threading.Tasks/Scheduler.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/Scheduler.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Collections.Concurrent;
 
diff --git a/mcs/class/corlib/System.Threading.Tasks/SchedulerProxy.cs b/mcs/class/corlib/System.Threading.Tasks/SchedulerProxy.cs
index afe7dc6..72235bc 100644
--- a/mcs/class/corlib/System.Threading.Tasks/SchedulerProxy.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/SchedulerProxy.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 
 namespace System.Threading.Tasks
diff --git a/mcs/class/corlib/System.Threading.Tasks/SimpleConcurrentBag.cs b/mcs/class/corlib/System.Threading.Tasks/SimpleConcurrentBag.cs
index 8309580..22a11e7 100644
--- a/mcs/class/corlib/System.Threading.Tasks/SimpleConcurrentBag.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/SimpleConcurrentBag.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Threading;
 
diff --git a/mcs/class/corlib/System.Threading.Tasks/Task.cs b/mcs/class/corlib/System.Threading.Tasks/Task.cs
index 68f8e17..a40f808 100644
--- a/mcs/class/corlib/System.Threading.Tasks/Task.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/Task.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 using System.Threading;
@@ -329,8 +329,7 @@ namespace System.Threading.Tasks
 		
 		void CheckAndSchedule (Task continuation, TaskContinuationOptions options, TaskScheduler scheduler, bool fromCaller)
 		{
-			if (!fromCaller 
-			    && (options & TaskContinuationOptions.ExecuteSynchronously) > 0)
+			if ((options & TaskContinuationOptions.ExecuteSynchronously) > 0)
 				continuation.ThreadStart ();
 			else
 				continuation.Start (scheduler);
diff --git a/mcs/class/corlib/System.Threading.Tasks/TaskCanceledException.cs b/mcs/class/corlib/System.Threading.Tasks/TaskCanceledException.cs
index 1fc5d1a..5253e54 100644
--- a/mcs/class/corlib/System.Threading.Tasks/TaskCanceledException.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/TaskCanceledException.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Runtime.Serialization;
 
diff --git a/mcs/class/corlib/System.Threading.Tasks/TaskCompletionSource.cs b/mcs/class/corlib/System.Threading.Tasks/TaskCompletionSource.cs
index ecb0bc5..7ecc6a3 100644
--- a/mcs/class/corlib/System.Threading.Tasks/TaskCompletionSource.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/TaskCompletionSource.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Collections.Generic;
 
diff --git a/mcs/class/corlib/System.Threading.Tasks/TaskContinuationOptions.cs b/mcs/class/corlib/System.Threading.Tasks/TaskContinuationOptions.cs
index 0f0ea0d..bbc83bc 100644
--- a/mcs/class/corlib/System.Threading.Tasks/TaskContinuationOptions.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/TaskContinuationOptions.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 
 namespace System.Threading.Tasks
diff --git a/mcs/class/corlib/System.Threading.Tasks/TaskCreationOptions.cs b/mcs/class/corlib/System.Threading.Tasks/TaskCreationOptions.cs
index d8d9c04..cd4553d 100644
--- a/mcs/class/corlib/System.Threading.Tasks/TaskCreationOptions.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/TaskCreationOptions.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 
 namespace System.Threading.Tasks
diff --git a/mcs/class/corlib/System.Threading.Tasks/TaskFactory.cs b/mcs/class/corlib/System.Threading.Tasks/TaskFactory.cs
index e079f1f..a50f74e 100644
--- a/mcs/class/corlib/System.Threading.Tasks/TaskFactory.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/TaskFactory.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 using System.Threading;
diff --git a/mcs/class/corlib/System.Threading.Tasks/TaskScheduler.cs b/mcs/class/corlib/System.Threading.Tasks/TaskScheduler.cs
index b862098..0c473f7 100644
--- a/mcs/class/corlib/System.Threading.Tasks/TaskScheduler.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/TaskScheduler.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Threading;
 using System.Collections.Generic;
diff --git a/mcs/class/corlib/System.Threading.Tasks/TaskSchedulerException.cs b/mcs/class/corlib/System.Threading.Tasks/TaskSchedulerException.cs
index ddcd63b..1d4149c 100644
--- a/mcs/class/corlib/System.Threading.Tasks/TaskSchedulerException.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/TaskSchedulerException.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Runtime.Serialization;
 
diff --git a/mcs/class/corlib/System.Threading.Tasks/TaskStatus.cs b/mcs/class/corlib/System.Threading.Tasks/TaskStatus.cs
index 853afad..7abcd64 100644
--- a/mcs/class/corlib/System.Threading.Tasks/TaskStatus.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/TaskStatus.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 
 namespace System.Threading.Tasks
diff --git a/mcs/class/corlib/System.Threading.Tasks/ThreadWorker.cs b/mcs/class/corlib/System.Threading.Tasks/ThreadWorker.cs
index e0f8a16..c9ff883 100644
--- a/mcs/class/corlib/System.Threading.Tasks/ThreadWorker.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/ThreadWorker.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Threading;
 using System.Collections.Concurrent;
diff --git a/mcs/class/corlib/System.Threading.Tasks/UnobservedTaskExceptionEventArgs.cs b/mcs/class/corlib/System.Threading.Tasks/UnobservedTaskExceptionEventArgs.cs
index aff0675..d3e36f3 100644
--- a/mcs/class/corlib/System.Threading.Tasks/UnobservedTaskExceptionEventArgs.cs
+++ b/mcs/class/corlib/System.Threading.Tasks/UnobservedTaskExceptionEventArgs.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 
 namespace System.Threading.Tasks
@@ -59,4 +59,4 @@ namespace System.Threading.Tasks
 }
 
 #endif
-//
\ No newline at end of file
+//
diff --git a/mcs/class/corlib/System.Threading/AsyncFlowControl.cs b/mcs/class/corlib/System.Threading/AsyncFlowControl.cs
index cdd9373..498afc2 100644
--- a/mcs/class/corlib/System.Threading/AsyncFlowControl.cs
+++ b/mcs/class/corlib/System.Threading/AsyncFlowControl.cs
@@ -65,7 +65,7 @@ namespace System.Threading {
 			_t = null;
 		}
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 		public void Dispose ()
 #else
 		void IDisposable.Dispose ()
diff --git a/mcs/class/corlib/System.Threading/CancellationToken.cs b/mcs/class/corlib/System.Threading/CancellationToken.cs
index 8d97f78..16de213 100644
--- a/mcs/class/corlib/System.Threading/CancellationToken.cs
+++ b/mcs/class/corlib/System.Threading/CancellationToken.cs
@@ -27,7 +27,7 @@
 using System;
 using System.Threading;
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 namespace System.Threading
 {
 	[System.Diagnostics.DebuggerDisplay ("IsCancellationRequested = {IsCancellationRequested}")]
diff --git a/mcs/class/corlib/System.Threading/CancellationTokenRegistration.cs b/mcs/class/corlib/System.Threading/CancellationTokenRegistration.cs
index bd8098a..96f298d 100644
--- a/mcs/class/corlib/System.Threading/CancellationTokenRegistration.cs
+++ b/mcs/class/corlib/System.Threading/CancellationTokenRegistration.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Threading;
 
diff --git a/mcs/class/corlib/System.Threading/CancellationTokenSource.cs b/mcs/class/corlib/System.Threading/CancellationTokenSource.cs
index 9981c57..1d9411f 100644
--- a/mcs/class/corlib/System.Threading/CancellationTokenSource.cs
+++ b/mcs/class/corlib/System.Threading/CancellationTokenSource.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Collections.Generic;
 
diff --git a/mcs/class/corlib/System.Threading/ChangeLog b/mcs/class/corlib/System.Threading/ChangeLog
index 6b38a33..953860a 100644
--- a/mcs/class/corlib/System.Threading/ChangeLog
+++ b/mcs/class/corlib/System.Threading/ChangeLog
@@ -1,3 +1,17 @@
+2011-02-11  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	* Thread.cs (.ctor): Check if maxStackSize is negative and raise
+	and AOORE. Silently use a saner minimum size of 128k as mono can't
+	really run with much less than that.
+
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Add pfx to the mobile profile
+
 2011-01-07  Jérémie Laval  <jeremie.laval at gmail.com>
 
 	Remove now unused internal classes
diff --git a/mcs/class/corlib/System.Threading/CountdownEvent.cs b/mcs/class/corlib/System.Threading/CountdownEvent.cs
index 0046f81..59c282e 100644
--- a/mcs/class/corlib/System.Threading/CountdownEvent.cs
+++ b/mcs/class/corlib/System.Threading/CountdownEvent.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 
diff --git a/mcs/class/corlib/System.Threading/LazyInitializer.cs b/mcs/class/corlib/System.Threading/LazyInitializer.cs
index 487b40e..bf1b1f4 100644
--- a/mcs/class/corlib/System.Threading/LazyInitializer.cs
+++ b/mcs/class/corlib/System.Threading/LazyInitializer.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 
diff --git a/mcs/class/corlib/System.Threading/LazyThreadSafetyMode.cs b/mcs/class/corlib/System.Threading/LazyThreadSafetyMode.cs
index b23ffe7..6ed0f61 100644
--- a/mcs/class/corlib/System.Threading/LazyThreadSafetyMode.cs
+++ b/mcs/class/corlib/System.Threading/LazyThreadSafetyMode.cs
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 using System;
 
diff --git a/mcs/class/corlib/System.Threading/ManualResetEventSlim.cs b/mcs/class/corlib/System.Threading/ManualResetEventSlim.cs
index 30fec4a..3e291a2 100644
--- a/mcs/class/corlib/System.Threading/ManualResetEventSlim.cs
+++ b/mcs/class/corlib/System.Threading/ManualResetEventSlim.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 
 using System;
 
diff --git a/mcs/class/corlib/System.Threading/Monitor.cs b/mcs/class/corlib/System.Threading/Monitor.cs
index 7be943f..4188c0a 100644
--- a/mcs/class/corlib/System.Threading/Monitor.cs
+++ b/mcs/class/corlib/System.Threading/Monitor.cs
@@ -177,7 +177,7 @@ namespace System.Threading
 			}
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		[MethodImplAttribute(MethodImplOptions.InternalCall)]
 		extern static void try_enter_with_atomic_var (object obj, int millisecondsTimeout, ref bool lockTaken);
 
diff --git a/mcs/class/corlib/System.Threading/SemaphoreSlim.cs b/mcs/class/corlib/System.Threading/SemaphoreSlim.cs
index f766933..4f4e6a7 100644
--- a/mcs/class/corlib/System.Threading/SemaphoreSlim.cs
+++ b/mcs/class/corlib/System.Threading/SemaphoreSlim.cs
@@ -25,7 +25,7 @@
 using System;
 using System.Diagnostics;
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 namespace System.Threading
 {
 	[System.Diagnostics.DebuggerDisplayAttribute ("Current Count = {currCount}")]
diff --git a/mcs/class/corlib/System.Threading/SpinWait.cs b/mcs/class/corlib/System.Threading/SpinWait.cs
index 1368367..0cbb85c 100644
--- a/mcs/class/corlib/System.Threading/SpinWait.cs
+++ b/mcs/class/corlib/System.Threading/SpinWait.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 
 namespace System.Threading
diff --git a/mcs/class/corlib/System.Threading/Thread.cs b/mcs/class/corlib/System.Threading/Thread.cs
index 7c4b1c2..8bed10a 100644
--- a/mcs/class/corlib/System.Threading/Thread.cs
+++ b/mcs/class/corlib/System.Threading/Thread.cs
@@ -360,7 +360,7 @@ namespace System.Threading {
 			ResetAbort_internal ();
 		}
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 		[HostProtectionAttribute (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
 		[MethodImplAttribute(MethodImplOptions.InternalCall)]
 		public extern static bool Yield ();
@@ -823,8 +823,10 @@ namespace System.Threading {
 		{
 			if (start == null)
 				throw new ArgumentNullException ("start");
-			if (maxStackSize < 131072)
-				throw new ArgumentException ("< 128 kb", "maxStackSize");
+			if (maxStackSize < 0)
+				throw new ArgumentOutOfRangeException ("less than zero", "maxStackSize");
+			if (maxStackSize < 131072) //make sure stack is at least 128k big
+				maxStackSize = 131072;
 
 			threadstart = start;
 			Internal.stack_size = maxStackSize;
@@ -842,8 +844,10 @@ namespace System.Threading {
 		{
 			if (start == null)
 				throw new ArgumentNullException ("start");
-			if (maxStackSize < 131072)
-				throw new ArgumentException ("< 128 kb", "maxStackSize");
+			if (maxStackSize < 0)
+				throw new ArgumentOutOfRangeException ("less than zero", "maxStackSize");
+			if (maxStackSize < 131072) //make sure stack is at least 128k big
+				maxStackSize = 131072;
 
 			threadstart = start;
 			Internal.stack_size = maxStackSize;
diff --git a/mcs/class/corlib/System.Threading/ThreadLocal.cs b/mcs/class/corlib/System.Threading/ThreadLocal.cs
index d5fcad9..0ee5247 100644
--- a/mcs/class/corlib/System.Threading/ThreadLocal.cs
+++ b/mcs/class/corlib/System.Threading/ThreadLocal.cs
@@ -24,7 +24,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Runtime.Serialization;
 using System.Runtime.InteropServices;
diff --git a/mcs/class/corlib/System.Threading/WaitHandle.cs b/mcs/class/corlib/System.Threading/WaitHandle.cs
index 0c4daaf..0380b5e 100644
--- a/mcs/class/corlib/System.Threading/WaitHandle.cs
+++ b/mcs/class/corlib/System.Threading/WaitHandle.cs
@@ -213,7 +213,7 @@ namespace System.Threading
 			GC.SuppressFinalize (this);
 		}
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 		public void Dispose ()
 #else		
 		void IDisposable.Dispose ()
diff --git a/mcs/class/corlib/System.Threading/Watch.cs b/mcs/class/corlib/System.Threading/Watch.cs
index a158749..c95c90f 100644
--- a/mcs/class/corlib/System.Threading/Watch.cs
+++ b/mcs/class/corlib/System.Threading/Watch.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 
 namespace System.Threading
diff --git a/mcs/class/corlib/System/Action.cs b/mcs/class/corlib/System/Action.cs
index d8bbfa0..4aed9ac 100644
--- a/mcs/class/corlib/System/Action.cs
+++ b/mcs/class/corlib/System/Action.cs
@@ -31,19 +31,35 @@ using System.Runtime.CompilerServices;
 
 namespace System
 {
+#if NET_4_0 || MOBILE
 #if NET_4_0
 	[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
+#elif MOBILE
+	[TypeForwardedFrom (Consts.AssemblySystem_Core)]
+#endif
 	public delegate void Action ();
 	
 	public delegate void Action <in T> (T obj);
 	
+#if NET_4_0
 	[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
+#elif MOBILE
+	[TypeForwardedFrom (Consts.AssemblySystem_Core)]
+#endif
 	public delegate void Action <in T1, in T2> (T1 arg1, T2 arg2);
 	
+#if NET_4_0
 	[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
+#elif MOBILE
+	[TypeForwardedFrom (Consts.AssemblySystem_Core)]
+#endif
 	public delegate void Action <in T1, in T2, in T3> (T1 arg1, T2 arg2, T3 arg3);
 	
+#if NET_4_0
 	[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
+#elif MOBILE
+	[TypeForwardedFrom (Consts.AssemblySystem_Core)]
+#endif
 	public delegate void Action <in T1, in T2, in T3, in T4> (T1 arg1, T2 arg2, T3 arg3, T4 arg4);
 	
 	public delegate void Action <in T1, in T2, in T3, in T4, in T5> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
diff --git a/mcs/class/corlib/System/AggregateException.cs b/mcs/class/corlib/System/AggregateException.cs
index d7d67a0..e75fa60 100644
--- a/mcs/class/corlib/System/AggregateException.cs
+++ b/mcs/class/corlib/System/AggregateException.cs
@@ -22,7 +22,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || MOBILE
 using System;
 using System.Collections.ObjectModel;
 using System.Collections.Generic;
diff --git a/mcs/class/corlib/System/AppDomain.cs b/mcs/class/corlib/System/AppDomain.cs
index 43f144c..22ef293 100644
--- a/mcs/class/corlib/System/AppDomain.cs
+++ b/mcs/class/corlib/System/AppDomain.cs
@@ -1536,7 +1536,7 @@ namespace System {
 		}
 #endif
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		List<string> compatibility_switch;
 
 		public bool? IsCompatibilitySwitchSet (string value)
diff --git a/mcs/class/corlib/System/AppDomainSetup.cs b/mcs/class/corlib/System/AppDomainSetup.cs
index bbf4e66..b0e7131 100644
--- a/mcs/class/corlib/System/AppDomainSetup.cs
+++ b/mcs/class/corlib/System/AppDomainSetup.cs
@@ -386,7 +386,7 @@ namespace System
 			serialized_non_primitives = ms.ToArray ();
 		}
 #endif // !NET_2_1
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		[MonoTODO ("not implemented, does not throw because it's used in testing moonlight")]
 		public void SetCompatibilitySwitches (IEnumerable<string> switches)
 		{
diff --git a/mcs/class/corlib/System/Array.cs b/mcs/class/corlib/System/Array.cs
index 3f44f8c..58b5785 100644
--- a/mcs/class/corlib/System/Array.cs
+++ b/mcs/class/corlib/System/Array.cs
@@ -45,7 +45,7 @@ namespace System
 	[ComVisible (true)]
 	// FIXME: We are doing way to many double/triple exception checks for the overloaded functions"
 	public abstract class Array : ICloneable, ICollection, IList, IEnumerable
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		, IStructuralComparable, IStructuralEquatable
 #endif
 	{
@@ -434,7 +434,7 @@ namespace System
 			return new SimpleEnumerator (this);
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		int IStructuralComparable.CompareTo (object other, IComparer comparer)
 		{
 			if (other == null)
diff --git a/mcs/class/corlib/System/ChangeLog b/mcs/class/corlib/System/ChangeLog
index fd3bb24..e5ea777 100644
--- a/mcs/class/corlib/System/ChangeLog
+++ b/mcs/class/corlib/System/ChangeLog
@@ -1,3 +1,15 @@
+2011-02-08  Miguel de Icaza  <miguel at gnome.org>
+
+	Fix Enum.HasValue, previous version crashed with negative values
+
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Further .NET 4.0 ification of the mobile profile
+
+2011-01-25  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Add pfx to the mobile profile
+
 2011-01-07  Rodrigo Kumpera  <kumpera at gmail.com>
 
 	Properly search overwrites for custom attributes.
diff --git a/mcs/class/corlib/System/Enum.cs b/mcs/class/corlib/System/Enum.cs
index a516be8..798dd47 100644
--- a/mcs/class/corlib/System/Enum.cs
+++ b/mcs/class/corlib/System/Enum.cs
@@ -619,7 +619,7 @@ namespace System
 			return true;
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public static bool TryParse<TEnum> (string value, out TEnum result) where TEnum : struct
 		{
 			return TryParse (value, false, out result);
@@ -1012,11 +1012,12 @@ namespace System
 			}
 			return retVal;
 		}
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public bool HasFlag (Enum flag)
 		{
-			ulong mvalue = Convert.ToUInt64 (get_value (), null);
-			ulong fvalue = Convert.ToUInt64 (flag, null);
+			var val = get_value ();
+			ulong mvalue = GetValue (val, Type.GetTypeCode (val.GetType ()));
+			ulong fvalue = GetValue (flag, Type.GetTypeCode (flag.GetType ()));
 
 			return ((mvalue & fvalue) == fvalue);
 		}
diff --git a/mcs/class/corlib/System/Environment.cs b/mcs/class/corlib/System/Environment.cs
index 32f5388..bc5c4a6 100644
--- a/mcs/class/corlib/System/Environment.cs
+++ b/mcs/class/corlib/System/Environment.cs
@@ -84,7 +84,7 @@ namespace System {
 			ProgramFiles = 0x26,
 			MyPictures = 0x27,
 			CommonProgramFiles = 0x2b,
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			MyVideos = 0x0e,
 #endif
 #if NET_4_0
@@ -609,7 +609,7 @@ namespace System {
 			
 			case SpecialFolder.Templates:
 				return ReadXdgUserDir (config, home, "XDG_TEMPLATES_DIR", "Templates");
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			case SpecialFolder.MyVideos:
 				return ReadXdgUserDir (config, home, "XDG_VIDEOS_DIR", "Videos");
 #endif
@@ -812,7 +812,7 @@ namespace System {
 			throw new NotImplementedException ();
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		[SecurityCritical]
 		public static void FailFast (string message, Exception exception)
 		{
diff --git a/mcs/class/corlib/System/Funcs.cs b/mcs/class/corlib/System/Funcs.cs
index 61fc6bf..d6c3f12 100644
--- a/mcs/class/corlib/System/Funcs.cs
+++ b/mcs/class/corlib/System/Funcs.cs
@@ -29,20 +29,40 @@ using System.Runtime.CompilerServices;
 
 namespace System {
 
+#if NET_4_0 || MOBILE
 #if NET_4_0
 	[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
+#elif MOBILE
+	[TypeForwardedFrom (Consts.AssemblySystem_Core)]
+#endif
 	public delegate TResult Func<out TResult> ();
 	
+#if NET_4_0
 	[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
+#elif MOBILE
+	[TypeForwardedFrom (Consts.AssemblySystem_Core)]
+#endif
 	public delegate TResult Func<in T, out TResult> (T arg);
 	
+#if NET_4_0
 	[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
+#elif MOBILE
+	[TypeForwardedFrom (Consts.AssemblySystem_Core)]
+#endif
 	public delegate TResult Func<in T1, in T2, out TResult> (T1 arg1, T2 arg2);
 	
+#if NET_4_0
 	[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
+#elif MOBILE
+	[TypeForwardedFrom (Consts.AssemblySystem_Core)]
+#endif
 	public delegate TResult Func<in T1, in T2, in T3, out TResult> (T1 arg1, T2 arg2, T3 arg3);
 	
+#if NET_4_0
 	[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
+#elif MOBILE
+	[TypeForwardedFrom (Consts.AssemblySystem_Core)]
+#endif
 	public delegate TResult Func<in T1, in T2, in T3, in T4, out TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4);
 	
 	public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, out TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
@@ -50,6 +70,9 @@ namespace System {
 	public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, out TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
 	public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, out TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
 #elif MOONLIGHT
+	public delegate TResult Func<T1, T2, T3, T4, TResult> (
+		T1 arg1, T2 arg2, T3 arg3, T4 arg4);
+
 	public delegate TResult Func<T1, T2, T3, T4, T5, TResult> (
 		T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
 
diff --git a/mcs/class/corlib/System/GC.cs b/mcs/class/corlib/System/GC.cs
index c4be7b3..4c56588 100644
--- a/mcs/class/corlib/System/GC.cs
+++ b/mcs/class/corlib/System/GC.cs
@@ -145,7 +145,7 @@ namespace System
 		}
 #endif
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		[MethodImplAttribute (MethodImplOptions.InternalCall)]
 		internal extern static void register_ephemeron_array (Ephemeron[] array);
 
@@ -155,4 +155,4 @@ namespace System
 		internal static readonly object EPHEMERON_TOMBSTONE = get_ephemeron_tombstone ();
 #endif
 	}
-}
\ No newline at end of file
+}
diff --git a/mcs/class/corlib/System/Guid.cs b/mcs/class/corlib/System/Guid.cs
index ddd7a47..15562c3 100644
--- a/mcs/class/corlib/System/Guid.cs
+++ b/mcs/class/corlib/System/Guid.cs
@@ -667,7 +667,7 @@ namespace System {
 			return !( a.Equals (b) );
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public static Guid Parse (string input)
 		{
 			Guid guid;
diff --git a/mcs/class/corlib/System/InvalidTimeZoneException.cs b/mcs/class/corlib/System/InvalidTimeZoneException.cs
index f7aaeb7..6554485 100644
--- a/mcs/class/corlib/System/InvalidTimeZoneException.cs
+++ b/mcs/class/corlib/System/InvalidTimeZoneException.cs
@@ -24,7 +24,7 @@
  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 using System.Runtime.CompilerServices;
 
@@ -33,7 +33,7 @@ namespace System
 	[Serializable]
 #if NET_4_0
 	[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
-#elif MOONLIGHT
+#elif MOONLIGHT || MOBILE
 	[TypeForwardedFrom (Consts.AssemblySystem_Core)]
 #endif
 	public class InvalidTimeZoneException : Exception
diff --git a/mcs/class/corlib/System/Lazy.cs b/mcs/class/corlib/System/Lazy.cs
index f9b5c0a..3474fe5 100644
--- a/mcs/class/corlib/System/Lazy.cs
+++ b/mcs/class/corlib/System/Lazy.cs
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 using System;
 using System.Runtime.Serialization;
diff --git a/mcs/class/corlib/System/OperationCanceledException.cs b/mcs/class/corlib/System/OperationCanceledException.cs
index 4107352..90d5df6 100644
--- a/mcs/class/corlib/System/OperationCanceledException.cs
+++ b/mcs/class/corlib/System/OperationCanceledException.cs
@@ -38,7 +38,7 @@ namespace System
 	public class OperationCanceledException : SystemException
 	{
 		const int Result = unchecked ((int)0x8013153b);
-#if NET_4_0
+#if NET_4_0 || MOBILE
 		CancellationToken? token;
 #endif
 
@@ -66,7 +66,7 @@ namespace System
 		{
 		}
 		
-#if NET_4_0
+#if NET_4_0 || MOBILE
 		public OperationCanceledException (CancellationToken token)
 			: this ()
 		{
diff --git a/mcs/class/corlib/System/String.cs b/mcs/class/corlib/System/String.cs
index 0f79656..06cfe22 100644
--- a/mcs/class/corlib/System/String.cs
+++ b/mcs/class/corlib/System/String.cs
@@ -2217,7 +2217,7 @@ namespace System
 			return InternalIsInterned (str);
 		}
 	
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public static string Join (string separator, params string [] value)
 #else
 		public static string Join (string separator, string [] value)
@@ -2525,7 +2525,7 @@ namespace System
 			}
 		}
 
-#if MOONLIGHT || NET_4_0
+#if MOONLIGHT || MOBILE || NET_4_0
 		[ComVisible(false)]
 		public static string Concat (IEnumerable<string> values)
 		{
diff --git a/mcs/class/corlib/System/TimeSpan.cs b/mcs/class/corlib/System/TimeSpan.cs
index 163a7aa..cb627b0 100644
--- a/mcs/class/corlib/System/TimeSpan.cs
+++ b/mcs/class/corlib/System/TimeSpan.cs
@@ -39,7 +39,7 @@ namespace System
 	[Serializable]
 	[System.Runtime.InteropServices.ComVisible (true)]
 	public struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable <TimeSpan>
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 				 , IFormattable
 #endif
 	{
@@ -359,7 +359,7 @@ namespace System
 			return p.Execute (true, out result);
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public static TimeSpan Parse (string input, IFormatProvider formatProvider)
 		{
 			if (input == null)
@@ -526,7 +526,7 @@ namespace System
 			return sb.ToString ();
 		}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		public string ToString (string format)
 		{
 			return ToString (format, null);
@@ -719,7 +719,7 @@ namespace System
 			private int _cur = 0;
 			private int _length;
 			ParseError parse_error;
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			bool parsed_ticks;
 			NumberFormatInfo number_format;
 			int parsed_numbers_count;
@@ -735,12 +735,12 @@ namespace System
 			{
 				_src = src;
 				_length = _src.Length;
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 				number_format = GetNumberFormatInfo (null);
 #endif
 			}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			// Reset state data, so we can execute another parse over the input.
 			void Reset ()
 			{
@@ -806,7 +806,7 @@ namespace System
 				return res;
 			}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			// Used for custom formats parsing, where we may need to declare how
 			// many digits we expect, as well as the maximum allowed.
 			private int ParseIntExact (int digit_count, int max_digit_count)
@@ -855,7 +855,7 @@ namespace System
 
 				if (!optional && (count == 0))
 					SetParseError (ParseError.Format);
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 				if (count > 0)
 					parsed_numbers_count++;
 #endif
@@ -876,7 +876,7 @@ namespace System
 				return false;
 			}	
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			// This behaves pretty much like ParseOptDot, but we need to have it
 			// as a separated routine for both days and decimal separators.
 			private bool ParseOptDaysSeparator ()
@@ -963,7 +963,7 @@ namespace System
 
 				if (!digitseen)
 					SetParseError (ParseError.Format);
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 				else if (!AtEnd && Char.IsDigit (_src, _cur))
 					SetParseError (ParseError.Overflow);
 
@@ -973,7 +973,7 @@ namespace System
 				return res;
 			}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			// Used by custom formats parsing
 			// digits_count = 0 for digits up to max_digits_count (optional), and other value to
 			// force a precise number of digits.
@@ -1007,7 +1007,7 @@ namespace System
 				parse_error = error;
 			}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			bool CheckParseSuccess (bool tryParse)
 #else
 			bool CheckParseSuccess (int hours, int minutes, int seconds, bool tryParse)
@@ -1015,7 +1015,7 @@ namespace System
 			{
 				// We always report the first error, but for 2.0 we need to give a higher
 				// precence to per-element overflow (as opposed to int32 overflow).
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 				if (parse_error == ParseError.Overflow) {
 #else
 				if (parse_error == ParseError.Overflow || hours > 23 || minutes > 59 || seconds > 59) {
@@ -1036,7 +1036,7 @@ namespace System
 				return true;
 			}
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			// We are using a different parse approach in 4.0, due to some changes in the behaviour
 			// of the parse routines.
 			// The input string is documented as:
@@ -1220,7 +1220,7 @@ namespace System
 			}
 #endif
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 			public bool ExecuteWithFormat (string format, TimeSpanStyles style, bool tryParse, out TimeSpan result)
 			{
 				int days, hours, minutes, seconds;
@@ -1327,7 +1327,7 @@ namespace System
 			}
 #endif
 		}
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 		enum FormatElementType 
 		{
 			Days,
diff --git a/mcs/class/corlib/System/TimeZoneNotFoundException.cs b/mcs/class/corlib/System/TimeZoneNotFoundException.cs
index 348d745..a3be93a 100644
--- a/mcs/class/corlib/System/TimeZoneNotFoundException.cs
+++ b/mcs/class/corlib/System/TimeZoneNotFoundException.cs
@@ -24,7 +24,7 @@
  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
 
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 
 using System.Runtime.CompilerServices;
 
@@ -33,7 +33,7 @@ namespace System
 	[Serializable]
 #if NET_4_0
 	[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
-#elif MOONLIGHT
+#elif MOONLIGHT || MOBILE
 	[TypeForwardedFrom (Consts.AssemblySystem_Core)]
 #endif
 	public class TimeZoneNotFoundException : Exception
diff --git a/mcs/class/corlib/System/Tuple.cs b/mcs/class/corlib/System/Tuple.cs
index 0810717..ad07696 100644
--- a/mcs/class/corlib/System/Tuple.cs
+++ b/mcs/class/corlib/System/Tuple.cs
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if MOONLIGHT || NET_4_0
+#if MOONLIGHT || NET_4_0 || MOBILE
 
 using System;
 
diff --git a/mcs/class/corlib/System/Tuples.cs b/mcs/class/corlib/System/Tuples.cs
index 5756fa2..80de292 100644
--- a/mcs/class/corlib/System/Tuples.cs
+++ b/mcs/class/corlib/System/Tuples.cs
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if MOONLIGHT || NET_4_0
+#if MOONLIGHT || NET_4_0 || MOBILE
 
 using System;
 using System.Collections;
diff --git a/mcs/class/corlib/System/TypeAccessException.cs b/mcs/class/corlib/System/TypeAccessException.cs
index fc96e9f..58df33a 100644
--- a/mcs/class/corlib/System/TypeAccessException.cs
+++ b/mcs/class/corlib/System/TypeAccessException.cs
@@ -25,7 +25,7 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-#if NET_4_0 || MOONLIGHT
+#if NET_4_0 || MOONLIGHT || MOBILE
 using System.Runtime.Serialization;
 using System.Runtime.InteropServices;
 
diff --git a/mcs/class/corlib/System/Version.cs b/mcs/class/corlib/System/Version.cs
index 70189f5..9138e8d 100644
--- a/mcs/class/corlib/System/Version.cs
+++ b/mcs/class/corlib/System/Version.cs
@@ -306,7 +306,7 @@ namespace System {
 			return v1.CompareTo (v2) <= 0;
 		}
 
-#if BOOSTRAP_NET_4_0 || NET_4_0 || MOONLIGHT
+#if BOOSTRAP_NET_4_0 || NET_4_0 || MOONLIGHT || MOBILE
 		public static Version Parse (string input)
 		{
 			// Exactly the same as calling Version(string) .ctor
diff --git a/mcs/class/corlib/Test/System.Reflection/BinderTests.cs b/mcs/class/corlib/Test/System.Reflection/BinderTests.cs
index d7905d4..feebedf 100644
--- a/mcs/class/corlib/Test/System.Reflection/BinderTests.cs
+++ b/mcs/class/corlib/Test/System.Reflection/BinderTests.cs
@@ -20,6 +20,12 @@ namespace MonoTests.System.Reflection
 		One,
 		Two
 	}
+
+	class ParamsArrayTest
+	{
+		public ParamsArrayTest (params string[] strings)
+		{}
+	}
 	
 	class SampleClass {
 		public static void SampleMethod (object o) { }
@@ -101,6 +107,14 @@ namespace MonoTests.System.Reflection
 		Binder binder = Type.DefaultBinder;
 
 		[Test]
+		public void ParamsArrayTestCast ()
+		{
+			string[] test_args = { "one", "two", "three" };
+			var o = Activator.CreateInstance (typeof (ParamsArrayTest), new object[] { test_args });
+			Assert.IsNotNull (o, "#A1");
+		}
+		
+		[Test]
 		[ExpectedException (typeof (ArgumentException))]
 		public void SelectPropertyTestNull1 ()
 		{
diff --git a/mcs/class/corlib/Test/System.Reflection/ChangeLog b/mcs/class/corlib/Test/System.Reflection/ChangeLog
index eadfba7..6f61c6d 100644
--- a/mcs/class/corlib/Test/System.Reflection/ChangeLog
+++ b/mcs/class/corlib/Test/System.Reflection/ChangeLog
@@ -1,3 +1,12 @@
+2011-02-03  Marek Habersack  <grendel at twistedcode.net>
+
+	[reflection] Default binder's AdjustArguments method treats
+	ParamArray parameters which are already arrays properly
+
+	Such parameters are not adjusted as it would lead to an
+	InvalidCastException whenever an attempt to set an array index's
+	value would be made.
+
 2011-01-05  Marek Safar  <marek.safar at gmail.com>
 
 	Fix invalid test constraint
diff --git a/mcs/class/corlib/Test/System.Runtime.Serialization.Formatters.Binary/ChangeLog b/mcs/class/corlib/Test/System.Runtime.Serialization.Formatters.Binary/ChangeLog
index dcd003b..e4d588f 100644
--- a/mcs/class/corlib/Test/System.Runtime.Serialization.Formatters.Binary/ChangeLog
+++ b/mcs/class/corlib/Test/System.Runtime.Serialization.Formatters.Binary/ChangeLog
@@ -1,3 +1,17 @@
+2010-09-24  Kyle Ambroff  <kyle at ambroff.com>
+
+	version tolerant serialization fails with missing primitive
+	members
+
+	Modifies ObjectReader so that when it encounters a primitive typed
+	member in an object stream which has no corresponding member in
+	the app domain, it will read the value anyway and throw it away.
+	That way it can read the next block from the stream.
+
+	Added a unit test which passes with the changes to ObjectReader.
+
+	Fixes bug #641821.
+
 2010-09-21  Andrés G. Aragoneses  <knocte at gmail.com>
 
 	[corlib] Prevent BinaryFormatter to throw on missing fields
diff --git a/mcs/class/corlib/Test/System.Runtime.Serialization.Formatters.Binary/VersionTolerantSerialization/BinarySerializationOverVersions.cs b/mcs/class/corlib/Test/System.Runtime.Serialization.Formatters.Binary/VersionTolerantSerialization/BinarySerializationOverVersions.cs
index fb4d9f3..e8b8903 100644
--- a/mcs/class/corlib/Test/System.Runtime.Serialization.Formatters.Binary/VersionTolerantSerialization/BinarySerializationOverVersions.cs
+++ b/mcs/class/corlib/Test/System.Runtime.Serialization.Formatters.Binary/VersionTolerantSerialization/BinarySerializationOverVersions.cs
@@ -124,6 +124,18 @@ namespace MonoTests.System.Runtime.Serialization.Formatters.Binary
 			Deserialize ("4.0", Serialize ("5.0"));
 		}
 
+		[Test]
+		public void TestDroppedPrimitiveTypeField() //eliminate Id (int)
+		{
+			Deserialize ("5.0", Serialize ("6.0"));
+		}
+
+		[Test]
+		public void TestAddedPrimitiveTypeField () //add Id (int)
+		{
+			Deserialize ("6.0", Serialize ("5.0"));
+		}
+
 		private static string Serialize (string assemblyVersion)
 		{
 			return SerializeOOP (SetEnvironment (assemblyVersion)); ;
diff --git a/mcs/class/corlib/Test/System.Security.AccessControl/CommonAceTest.cs b/mcs/class/corlib/Test/System.Security.AccessControl/CommonAceTest.cs
new file mode 100644
index 0000000..74cc8d6
--- /dev/null
+++ b/mcs/class/corlib/Test/System.Security.AccessControl/CommonAceTest.cs
@@ -0,0 +1,39 @@
+//
+// CommonAceTest.cs - NUnit Test Cases for CommonAce
+//
+// Author:
+//	Kenneth Bell
+//
+
+using System.Security.AccessControl;
+using System.Security.Principal;
+using NUnit.Framework;
+
+namespace MonoTests.System.Security.AccessControl {
+	[TestFixture]
+	public class CommonAceTest {
+		[Test]
+		public void GetBinaryForm ()
+		{
+			SecurityIdentifier builtInAdmins = new SecurityIdentifier (WellKnownSidType.BuiltinAdministratorsSid, null);
+			CommonAce ace = new CommonAce (AceFlags.None, AceQualifier.AccessAllowed, 0x7FFFFFFF, builtInAdmins, false, null);
+			
+			byte[] buffer = new byte[ace.BinaryLength];
+			ace.GetBinaryForm (buffer, 0);
+			byte[] aceBinary = new byte[] {
+				0x00, 0x00, 0x18, 0x00, 0xFF, 0xFF, 0xFF, 0x7F, 0x01, 0x02,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00,
+				0x20, 0x02, 0x00, 0x00 };
+			Assert.AreEqual (aceBinary, buffer);
+		}
+
+		[Test]
+		public void MaxOpaqueLength ()
+		{
+			Assert.AreEqual (65459, CommonAce.MaxOpaqueLength (true));
+			Assert.AreEqual (65459, CommonAce.MaxOpaqueLength (false));
+			Assert.AreEqual (65423, ObjectAce.MaxOpaqueLength (true));
+			Assert.AreEqual (65423, ObjectAce.MaxOpaqueLength (false));
+		}
+	}
+}
diff --git a/mcs/class/corlib/Test/System.Security.AccessControl/RawAclTest.cs b/mcs/class/corlib/Test/System.Security.AccessControl/RawAclTest.cs
new file mode 100644
index 0000000..3e3902a
--- /dev/null
+++ b/mcs/class/corlib/Test/System.Security.AccessControl/RawAclTest.cs
@@ -0,0 +1,41 @@
+//
+// RawAclTest.cs - NUnit Test Cases for RawAclTest
+//
+// Author:
+//	Kenneth Bell
+//
+
+using System.Security.AccessControl;
+using System.Security.Principal;
+using NUnit.Framework;
+
+namespace MonoTests.System.Security.AccessControl {
+
+	[TestFixture]
+	public class AclTest {
+
+		[Test]
+		public void GetBinaryForm ()
+		{
+			RawAcl acl = new RawAcl (1, 0);
+			
+			byte[] buffer = new byte[acl.BinaryLength];
+			acl.GetBinaryForm (buffer, 0);
+			byte[] sdBinary = new byte[] { 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 };
+			Assert.AreEqual (sdBinary, buffer);
+			
+			
+			SecurityIdentifier builtInAdmins = new SecurityIdentifier (WellKnownSidType.BuiltinAdministratorsSid, null);
+			CommonAce ace = new CommonAce (AceFlags.None, AceQualifier.AccessAllowed, 0x7FFFFFFF, builtInAdmins, false, null);
+			acl.InsertAce (0, ace);
+			buffer = new byte[acl.BinaryLength];
+			acl.GetBinaryForm (buffer, 0);
+			sdBinary = new byte[] {
+				0x01, 0x00, 0x20, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x18, 0x00, 0xFF, 0xFF, 0xFF, 0x7F, 0x01, 0x02, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
+				0x00, 0x00 };
+			Assert.AreEqual (sdBinary, buffer);
+		}
+	}
+}
diff --git a/mcs/class/corlib/Test/System.Security.AccessControl/RawSecurityDescriptorTest.cs b/mcs/class/corlib/Test/System.Security.AccessControl/RawSecurityDescriptorTest.cs
new file mode 100644
index 0000000..dc9a36c
--- /dev/null
+++ b/mcs/class/corlib/Test/System.Security.AccessControl/RawSecurityDescriptorTest.cs
@@ -0,0 +1,286 @@
+//
+// RawSecurityDescriptorTest.cs - NUnit Test Cases for RawSecurityDescriptor
+//
+// Author:
+//	Kenneth Bell
+//
+
+using System;
+using System.Security.AccessControl;
+using System.Security.Principal;
+using NUnit.Framework;
+
+namespace MonoTests.System.Security.AccessControl {
+
+	[TestFixture]
+	public class RawSecurityDescriptorTest {
+		private void CheckSddlConstructor (string sddl, byte[] expectedBinary)
+		{
+			RawSecurityDescriptor sd = new RawSecurityDescriptor (sddl);
+			
+			Assert.GreaterOrEqual (sd.BinaryLength, 0);
+			byte[] buffer = new byte[sd.BinaryLength];
+			
+			sd.GetBinaryForm (buffer, 0);
+			Assert.AreEqual (expectedBinary, buffer);
+		}
+
+		private void CheckBinaryConstructor (string expectedSddl, byte[] binary)
+		{
+			RawSecurityDescriptor sd = new RawSecurityDescriptor (binary, 0);
+			
+			Assert.AreEqual (sd.BinaryLength, binary.Length);
+			Assert.AreEqual (expectedSddl, sd.GetSddlForm (AccessControlSections.All));
+		}
+
+		private void CheckRoundTrip (string sddl)
+		{
+			RawSecurityDescriptor sd = new RawSecurityDescriptor (sddl);
+			
+			byte[] buffer = new byte[sd.BinaryLength];
+			sd.GetBinaryForm (buffer, 0);
+			
+			sd = new RawSecurityDescriptor (buffer, 0);
+			Assert.AreEqual (sddl, sd.GetSddlForm (AccessControlSections.All));
+		}
+
+		[Test]
+		public void ConstructorEmptyString ()
+		{
+			byte[] sdBinary = new byte[] {
+				0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+			CheckSddlConstructor ("", sdBinary);
+		}
+
+		[Test]
+		public void ConstructorString ()
+		{
+			byte[] sdBinary = new byte[] {
+				0x01, 0x00, 0x04, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
+				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
+				0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
+				0x00, 0x00, 0x02, 0x00, 0x1C, 0x00, 0x01, 0x00, 0x00, 0x00,
+				0x00, 0x00, 0x14, 0x00, 0x3F, 0x00, 0x0E, 0x10, 0x01, 0x01,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+			CheckSddlConstructor ("O:BUG:BAD:(A;;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)", sdBinary);
+			CheckSddlConstructor ("G:BAO:BUD:(A;;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)", sdBinary);
+			CheckSddlConstructor ("G:BAD:(A; ;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)O:BU", sdBinary);
+			CheckSddlConstructor ("O:buG:baD:(a;;rpwpccdclcswrcwdwoga;;;s-1-0-0)", sdBinary);
+			
+			sdBinary = new byte[] {
+				0x01, 0x00, 0x00, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
+				0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
+				0x00, 0x00 };
+			CheckSddlConstructor ("O:BUG:BA", sdBinary);
+			
+			sdBinary = new byte[] {
+				0x01, 0x00, 0x04, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
+				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
+				0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
+				0x00, 0x00, 0x04, 0x00, 0x40, 0x00, 0x01, 0x00, 0x00, 0x00,
+				0x05, 0x00, 0x38, 0x00, 0x3F, 0x00, 0x0E, 0x10, 0x03, 0x00,
+				0x00, 0x00, 0x53, 0x1A, 0x72, 0xAB, 0x2F, 0x1E, 0xD0, 0x11,
+				0x98, 0x19, 0x00, 0xAA, 0x00, 0x40, 0x52, 0x9B, 0x53, 0x1A,
+				0x72, 0xAB, 0x2F, 0x1E, 0xD0, 0x11, 0x98, 0x19, 0x00, 0xAA,
+				0x00, 0x40, 0x52, 0x9B, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+			CheckSddlConstructor ("O:BUG:BAD:(OA;;RPWPCCDCLCSWRCWDWOGA;ab721a53-1e2f-11d0-9819-00aa0040529b;ab721a53-1e2f-11d0-9819-00aa0040529b;S-1-0-0)", sdBinary);
+		}
+
+		[Test]
+		public void ConstructorBinary ()
+		{
+			byte[] sdBinary = new byte[] {
+				0x01, 0x00, 0x04, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
+				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
+				0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
+				0x00, 0x00, 0x02, 0x00, 0x1C, 0x00, 0x01, 0x00, 0x00, 0x00,
+				0x00, 0x00, 0x14, 0x00, 0x3F, 0x00, 0x0E, 0x10, 0x01, 0x01,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+			CheckBinaryConstructor ("O:BUG:BAD:(A;;CCDCLCSWRPWPRCWDWOGA;;;S-1-0-0)", sdBinary);
+			sdBinary = new byte[] {
+				0x01, 0x00, 0x00, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
+				0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
+				0x00, 0x00 };
+			CheckBinaryConstructor ("O:BUG:BA", sdBinary);
+			
+			sdBinary = new byte[] {
+				0x01, 0x00, 0x04, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
+				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
+				0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
+				0x00, 0x00, 0x04, 0x00, 0x40, 0x00, 0x01, 0x00, 0x00, 0x00,
+				0x05, 0x00, 0x38, 0x00, 0x3F, 0x00, 0x0E, 0x10, 0x03, 0x00,
+				0x00, 0x00, 0x53, 0x1A, 0x72, 0xAB, 0x2F, 0x1E, 0xD0, 0x11,
+				0x98, 0x19, 0x00, 0xAA, 0x00, 0x40, 0x52, 0x9B, 0x53, 0x1A,
+				0x72, 0xAB, 0x2F, 0x1E, 0xD0, 0x11, 0x98, 0x19, 0x00, 0xAA,
+				0x00, 0x40, 0x52, 0x9B, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+			CheckBinaryConstructor ("O:BUG:BAD:(OA;;CCDCLCSWRPWPRCWDWOGA;ab721a53-1e2f-11d0-9819-00aa0040529b;ab721a53-1e2f-11d0-9819-00aa0040529b;S-1-0-0)", sdBinary);
+		}
+
+		[Test]
+		public void FlagMismatch ()
+		{
+			// Check setting DACL-present flag on empty SD
+			RawSecurityDescriptor sd = new RawSecurityDescriptor ("");
+			Assert.AreEqual (20, sd.BinaryLength);
+			sd.SetFlags (ControlFlags.DiscretionaryAclPresent);
+			Assert.AreEqual (20, sd.BinaryLength);
+			byte[] buffer = new byte[sd.BinaryLength];
+			sd.GetBinaryForm (buffer, 0);
+			byte[] sdBinary = new byte[] {
+				0x01, 0x00, 0x04, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+			Assert.AreEqual (sdBinary, buffer);
+			
+			// Check unsetting DACL-present flag on SD with DACL
+			sd = new RawSecurityDescriptor ("O:BUG:BAD:(A;;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)");
+			Assert.AreEqual (80, sd.BinaryLength);
+			sd.SetFlags (sd.ControlFlags & ~ControlFlags.DiscretionaryAclPresent);
+			Assert.AreEqual (ControlFlags.SelfRelative, sd.ControlFlags);
+			Assert.AreEqual (52, sd.BinaryLength);
+			buffer = new byte[sd.BinaryLength];
+			sd.GetBinaryForm (buffer, 0);
+			sdBinary = new byte[] {
+				0x01, 0x00, 0x00, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
+				0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
+				0x00, 0x00 };
+			Assert.AreEqual (sdBinary, buffer);
+		}
+
+		[Test]
+		public void GetBinaryForm ()
+		{
+			RawSecurityDescriptor sd = new RawSecurityDescriptor ("");
+			sd.Owner = new SecurityIdentifier (WellKnownSidType.BuiltinUsersSid, null);
+			sd.Group = new SecurityIdentifier (WellKnownSidType.BuiltinAdministratorsSid, null);
+			sd.DiscretionaryAcl = new RawAcl (1, 0);
+			sd.SystemAcl = new RawAcl (1, 0);
+			sd.SetFlags (sd.ControlFlags | ControlFlags.DiscretionaryAclPresent | ControlFlags.SystemAclPresent);
+			
+			// Empty ACL form
+			byte[] buffer = new byte[sd.BinaryLength];
+			sd.GetBinaryForm (buffer, 0);
+			byte[] sdBinary = new byte[] {
+				0x01, 0x00, 0x14, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
+				0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00,
+				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
+				0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
+				0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 };
+			Assert.AreEqual (sdBinary, buffer);
+			
+			// Add an ACE to the DACL
+			SecurityIdentifier builtInAdmins = new SecurityIdentifier (WellKnownSidType.BuiltinAdministratorsSid, null);
+			CommonAce ace = new CommonAce (AceFlags.None, AceQualifier.AccessAllowed, 0x7FFFFFFF, builtInAdmins, false, null);
+			sd.DiscretionaryAcl.InsertAce (0, ace);
+			buffer = new byte[sd.BinaryLength];
+			sd.GetBinaryForm (buffer, 0);
+			sdBinary = new byte[] {
+				0x01, 0x00, 0x14, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
+				0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00,
+				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
+				0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
+				0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x01, 0x00, 0x20, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x18, 0x00, 0xFF, 0xFF, 0xFF, 0x7F, 0x01, 0x02, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
+				0x00, 0x00 };
+			Assert.AreEqual (sdBinary, buffer);
+			
+			// This time with an Object ACE
+			ObjectAce objectAce = new ObjectAce (AceFlags.Inherited, AceQualifier.AccessAllowed, 0x12345678, builtInAdmins, ObjectAceFlags.ObjectAceTypePresent | ObjectAceFlags.InheritedObjectAceTypePresent, new Guid ("189c0dc7-b849-4dea-93a5-6d4cb8857a5c"), new Guid ("53b4a3d4-fe39-468b-bc60-b4fcba772fa5"), false, null);
+			sd.DiscretionaryAcl = new RawAcl (2, 0);
+			sd.DiscretionaryAcl.InsertAce (0, objectAce);
+			buffer = new byte[sd.BinaryLength];
+			sd.GetBinaryForm (buffer, 0);
+			sdBinary = new byte[] {
+				0x01, 0x00, 0x14, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
+				0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00,
+				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
+				0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
+				0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x02, 0x00, 0x44, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x10,
+				0x3C, 0x00, 0x78, 0x56, 0x34, 0x12, 0x03, 0x00, 0x00, 0x00,
+				0xC7, 0x0D, 0x9C, 0x18, 0x49, 0xB8, 0xEA, 0x4D, 0x93, 0xA5,
+				0x6D, 0x4C, 0xB8, 0x85, 0x7A, 0x5C, 0xD4, 0xA3, 0xB4, 0x53,
+				0x39, 0xFE, 0x8B, 0x46, 0xBC, 0x60, 0xB4, 0xFC, 0xBA, 0x77,
+				0x2F, 0xA5, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05,
+				0x20, 0x00, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00 };
+			Assert.AreEqual (sdBinary, buffer);
+		}
+
+		[Test]
+		public void GetSddlForm ()
+		{
+			RawSecurityDescriptor sd = new RawSecurityDescriptor ("");
+			Assert.AreEqual ("", sd.GetSddlForm (AccessControlSections.All));
+			
+			// Ask for part of SD that isn't represented
+			sd.Owner = new SecurityIdentifier (WellKnownSidType.BuiltinUsersSid, null);
+			sd.Group = new SecurityIdentifier (WellKnownSidType.BuiltinAdministratorsSid, null);
+			Assert.AreEqual ("", sd.GetSddlForm (AccessControlSections.Access));
+			
+			// Empty ACL form
+			sd.DiscretionaryAcl = new RawAcl (2, 0);
+			sd.SystemAcl = new RawAcl (1, 0);
+			sd.SetFlags (sd.ControlFlags | ControlFlags.DiscretionaryAclPresent | ControlFlags.SystemAclPresent);
+			Assert.AreEqual ("O:BUG:BAD:S:", sd.GetSddlForm (AccessControlSections.All));
+			
+			// Add an ACE to the DACL
+			SecurityIdentifier builtInAdmins = new SecurityIdentifier (WellKnownSidType.BuiltinAdministratorsSid, null);
+			CommonAce ace = new CommonAce (AceFlags.None, AceQualifier.AccessAllowed, 0x7FFFFFFF, builtInAdmins, false, null);
+			sd.DiscretionaryAcl.InsertAce (0, ace);
+			Assert.AreEqual ("O:BUG:BAD:(A;;0x7fffffff;;;BA)S:", sd.GetSddlForm (AccessControlSections.All));
+			
+			// Add second ACE to the DACL
+			SecurityIdentifier randomUser = new SecurityIdentifier ("S-1-5-21-324-23423-234-334");
+			ace = new CommonAce (AceFlags.Inherited | AceFlags.ContainerInherit, AceQualifier.AccessDenied, 0x12345678, randomUser, true, null);
+			sd.DiscretionaryAcl.InsertAce (0, ace);
+			Assert.AreEqual ("O:BUD:(XD;CIID;0x12345678;;;S-1-5-21-324-23423-234-334)(A;;0x7fffffff;;;BA)", sd.GetSddlForm (AccessControlSections.Owner | AccessControlSections.Access));
+			
+			// DACL & SACL flags
+			sd.SetFlags (sd.ControlFlags | ControlFlags.DiscretionaryAclProtected | ControlFlags.DiscretionaryAclAutoInherited | ControlFlags.DiscretionaryAclAutoInheritRequired | ControlFlags.SystemAclAutoInherited);
+			sd.DiscretionaryAcl = new RawAcl (1, 0);
+			ace = new CommonAce (AceFlags.None, AceQualifier.AccessAllowed, 0x7FFFFFFF, builtInAdmins, false, null);
+			sd.DiscretionaryAcl.InsertAce (0, ace);
+			Assert.AreEqual ("O:BUG:BAD:PARAI(A;;0x7fffffff;;;BA)S:AI", sd.GetSddlForm (AccessControlSections.All));
+			
+			sd.SetFlags (sd.ControlFlags | ControlFlags.ServerSecurity | ControlFlags.DiscretionaryAclDefaulted);
+			Assert.AreEqual ("O:BUG:BAD:PARAI(A;;0x7fffffff;;;BA)S:AI", sd.GetSddlForm (AccessControlSections.All));
+		}
+
+		[Test]
+		public void RoundTrip ()
+		{
+			CheckRoundTrip ("O:BUG:BAD:(A;;CCDCLCSWRPWPRCWDWOGA;;;S-1-0-0)");
+			CheckRoundTrip ("O:BUG:BAD:(A;;KR;;;S-1-0-0)");
+			CheckRoundTrip ("O:BUG:BAD:(OA;;CCDCLCSWRPWPRCWDWOGA;ab721a53-1e2f-11d0-9819-00aa0040529b;ab721a53-1e2f-11d0-9819-00aa0040529b;S-1-0-0)");
+			CheckRoundTrip ("O:BUG:BAD:(A;;CCDCLCSWRPRC;;;S-1-0-0)");
+			CheckRoundTrip ("O:SYG:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)");
+			CheckRoundTrip ("O:SYG:BAD:(A;OICINPIOID;0x12019f;;;SY)");
+			CheckRoundTrip ("O:SYG:BAS:(AU;SAFA;0x12019f;;;SY)");
+		}
+	}
+}
diff --git a/mcs/class/corlib/Test/System.Security.Cryptography/ChangeLog b/mcs/class/corlib/Test/System.Security.Cryptography/ChangeLog
index 702c9aa..cf24615 100644
--- a/mcs/class/corlib/Test/System.Security.Cryptography/ChangeLog
+++ b/mcs/class/corlib/Test/System.Security.Cryptography/ChangeLog
@@ -1,3 +1,15 @@
+2011-01-11  Sebastien Pouliot  <sebastien at ximian.com>
+
+	* Test/System.Security.Cryptography/CryptoConfigTest.cs: Add test
+	cases wrt RIPEMD160 OID *
+	Test/System.Security.Cryptography/RSACryptoServiceProviderTest.cs:
+	Add test case for SignHash with all FX-provided hash
+	implementations (all working except RIPEMD160). Remove some
+	NET_2_0/NET_1_1 defines. *
+	Test/System.Security.Cryptography/RSAPKCS1SignatureFormatterTest.cs:
+	Remove hacks that were needed for running the tests under FX 1.x.
+	Remove some NET_2_0/NET_1_1 defines.
+
 2010-10-07  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
 
 	Buffer sizes
diff --git a/mcs/class/corlib/Test/System.Security.Cryptography/CryptoConfigTest.cs b/mcs/class/corlib/Test/System.Security.Cryptography/CryptoConfigTest.cs
index 4f4edc1..db368d0 100644
--- a/mcs/class/corlib/Test/System.Security.Cryptography/CryptoConfigTest.cs
+++ b/mcs/class/corlib/Test/System.Security.Cryptography/CryptoConfigTest.cs
@@ -5,7 +5,7 @@
 //	Sebastien Pouliot  <sebastien at ximian.com>
 //
 // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
-// Copyright (C) 2004-2007 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004-2007,2011 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
@@ -337,6 +337,9 @@ public class CryptoConfigTest {
 		MapNameToOID ("SHA512", "2.16.840.1.101.3.4.2.3");
 		MapNameToOID ("System.Security.Cryptography.SHA512", "2.16.840.1.101.3.4.2.3");
 		MapNameToOID ("System.Security.Cryptography.SHA512Managed", "2.16.840.1.101.3.4.2.3");
+		MapNameToOID ("RIPEMD160", "1.3.36.3.2.1");
+		MapNameToOID ("System.Security.Cryptography.RIPEMD160", "1.3.36.3.2.1");
+		MapNameToOID ("System.Security.Cryptography.RIPEMD160Managed", "1.3.36.3.2.1");
 #else
 		MapNameToOID ("SHA256", "2.16.840.1.101.3.4.1");
 //		MapNameToOID ("SHA-256", "2.16.840.1.101.3.4.1");
diff --git a/mcs/class/corlib/Test/System.Security.Cryptography/RSACryptoServiceProviderTest.cs b/mcs/class/corlib/Test/System.Security.Cryptography/RSACryptoServiceProviderTest.cs
index 0d567b4..e702751 100644
--- a/mcs/class/corlib/Test/System.Security.Cryptography/RSACryptoServiceProviderTest.cs
+++ b/mcs/class/corlib/Test/System.Security.Cryptography/RSACryptoServiceProviderTest.cs
@@ -5,7 +5,7 @@
 //	Sebastien Pouliot <sebastien at ximian.com>
 //
 // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
-// Copyright (C) 2004,2006 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004,2006,2011 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
@@ -51,9 +51,6 @@ public class RSACryptoServiceProviderTest : Assertion {
 		sha1OID = CryptoConfig.MapNameToOID ("SHA1");
 		disposed = new RSACryptoServiceProvider (minKeySize);
 		disposed.FromXmlString ("<RSAKeyValue><Modulus>vtXAf62+o50prNCTiVGTMzdhm4sMjK0QVDkKQLFGu2fJQCULt9NZBab14PiWfG1t</Modulus><Exponent>AQAB</Exponent><P>5y2AHOzIhTChIFzLsgZQAGfy3U8OPwFh</P><Q>01NUVJJv+hhIsnbFiSi24FLRrfr/qYuN</Q><DP>HKLAOdUCyazKaK3V9Yleo448wTkntJpB</DP><DQ>AH5MTxo8arAN02TVlzliG+n1lVtlp2at</DQ><InverseQ>ZpgJwTxSYpT81sQCuVUvX0AYrvSziNIw</InverseQ><D>CStiJYBmsZvincAj5qw5w3M8yGmE/9ls4yv7wenozzC4kZshpI2MuON0d2Z8f4aB</D></RSAKeyValue>");
-		// FX 2.0 beta 1 bug - we must use the key before clearing it
-		// http://lab.msdn.microsoft.com/ProductFeedback/viewfeedback.aspx?feedbackid=1bc807eb-c4ca-4c2d-8499-9f0470b71a29
-		int ks = disposed.KeySize;
 		disposed.Clear ();
 	}
 
@@ -213,11 +210,7 @@ public class RSACryptoServiceProviderTest : Assertion {
 
 	[Test]
 	// LAMESPEC/BUG: Disposed object can still be used (but original keypair seems lost)
-#if NET_1_1
 	[ExpectedException (typeof (ObjectDisposedException))]	// in MS.NET v.1.1
-#else
-	[ExpectedException (typeof (CryptographicException))]	// in MS.NET v.1.0
-#endif
 	public void DecryptDisposed () 
 	{
 		byte[] encdata = { 0x4C, 0xBF, 0xFD, 0xD9, 0xAD, 0xDB, 0x65, 0x15, 0xB3, 0xE8, 0xE6, 0xD3, 0x22, 0x99, 0x69, 0x56, 0xD3, 0x1F, 0x1D, 0x2A, 0x66, 0x07, 0x00, 0xBB, 0x77, 0x47, 0xB6, 0x6F, 0x8E, 0x3A, 0xBA, 0x37, 0xA3, 0x0F, 0x0A, 0xC8, 0x8D, 0x1F, 0x8D, 0xAB, 0xAC, 0xFD, 0x82, 0x6F, 0x7F, 0x88, 0x3B, 0xA1, 0x0F, 0x9B, 0x4B, 0x8A, 0x27, 0x3B, 0xEC, 0xFF, 0x69, 0x20, 0x57, 0x64, 0xE1, 0xD8, 0x9E, 0x96, 0x7A, 0x53, 0x6A, 0x80, 0x63, 0xB0, 0xEE, 0x84, 0xA7, 0x67, 0x38, 0xA5, 0x30, 0x06, 0xA8, 0xBB, 0x16, 0x77, 0x49, 0x67, 0x0F, 0x90, 0x67, 0xD5, 0xC5, 0x12, 0x92, 0x5A, 0xDA, 0xC3, 0xFD, 0xC4, 0x8A, 0x89, 0x77, 0x79, 0x11, 0xEC, 0x95, 0xF6, 0x6A, 0x3B, 0xAD, 0xA8, 0xDF, 0xA1, 0xB0, 0x51, 0x34, 0xE8, 0xC1, 0x05, 0xB9, 0x09, 0x23, 0x33, 0x2A, 0x3E, 0xE7, 0x6A, 0x77, 0x6F, 0xBD, 0x21 };
@@ -252,11 +245,7 @@ public class RSACryptoServiceProviderTest : Assertion {
 	}
 
 	[Test]
-#if NET_1_1
 	[ExpectedException (typeof (ArgumentNullException))]
-#else
-	[ExpectedException (typeof (NullReferenceException))]
-#endif
 	public void SignDataByteArrayNull () 
 	{
 		rsa = new RSACryptoServiceProvider (minKeySize);
@@ -282,7 +271,6 @@ public class RSACryptoServiceProviderTest : Assertion {
 		rsa.SignHash (null, "1.3.14.3.2.26"); // SHA-1
 	}
 
-#if NET_2_0
 	[Test]
 	public void SignHashNullOID ()
 	{
@@ -292,26 +280,58 @@ public class RSACryptoServiceProviderTest : Assertion {
 		Assert ("Null OID == SHA1", rsa.VerifyHash (hash, "1.3.14.3.2.26", signature));
 		Assert ("Null OID", rsa.VerifyHash (hash, null, signature));
 	}
-#else
+
+	void SignHash (string name, int size)
+	{
+		string oid = CryptoConfig.MapNameToOID (name);
+		byte [] hash = new byte [size];
+		rsa = new RSACryptoServiceProvider (1024);
+		byte [] signature = rsa.SignHash (hash, oid);
+		Assert (name, rsa.VerifyHash (hash, oid, signature));
+		Assert ("OID", rsa.VerifyHash (hash, oid, signature));
+	}
+
 	[Test]
-	[ExpectedException (typeof (CryptographicException))]
-	public void SignHashNullOID () 
+	public void SignHashMD5 ()
 	{
-		byte[] hash = new byte [20];
-		rsa = new RSACryptoServiceProvider (minKeySize);
-		rsa.SignHash (hash, null);
+		SignHash ("MD5", 16);
+	}
+
+	[Test]
+	public void SignHashSHA1 ()
+	{
+		SignHash ("SHA1", 20);
 	}
 
 	[Test]
+	public void SignHashSHA256 ()
+	{
+		SignHash ("SHA256", 32);
+	}
+
+	[Test]
+	public void SignHashSHA384 ()
+	{
+		SignHash ("SHA384", 48);
+	}
+
+	[Test]
+	public void SignHashSHA512 ()
+	{
+		SignHash ("SHA512", 64);
+	}
+	
+	[Test]
 	[ExpectedException (typeof (CryptographicException))]
-	public void VerifyHashNullOID () 
+	public void SignHashRIPEMD160 ()
 	{
-		byte[] sign = new byte [(minKeySize << 3)];
-		byte[] hash = new byte [20];
+		string oid = CryptoConfig.MapNameToOID ("RIPEMD160");
+		AssertNotNull (oid);
+		byte [] hash = new byte [20];
 		rsa = new RSACryptoServiceProvider (minKeySize);
-		rsa.VerifyHash (hash, null, sign);
+		// OID not supported
+		rsa.SignHash (hash, oid);
 	}
-#endif
 
 	[Test]
 	[ExpectedException (typeof (ObjectDisposedException))]
@@ -340,11 +360,7 @@ public class RSACryptoServiceProviderTest : Assertion {
 	}
 
 	[Test]
-#if NET_1_1
 	[ExpectedException (typeof (ArgumentNullException))]
-#else
-	[ExpectedException (typeof (NullReferenceException))]
-#endif
 	public void VerifyDataNullData () 
 	{
 		byte[] sign = new byte [(minKeySize << 3)];
@@ -1149,8 +1165,6 @@ public class RSACryptoServiceProviderTest : Assertion {
 		AssertEquals ("KeyNumber", KeyNumber.Exchange, info.KeyNumber);
 		Assert ("MachineKeyStore", !info.MachineKeyStore);
 		Assert ("Protected", !info.Protected);
-		AssertNotNull ("ProviderName", info.ProviderName);
-		AssertEquals ("ProviderType", 1, info.ProviderType);
 		Assert ("RandomlyGenerated", info.RandomlyGenerated);
 		Assert ("Removable", !info.Removable);
 		AssertNotNull ("UniqueKeyContainerName", info.UniqueKeyContainerName);
@@ -1172,8 +1186,6 @@ public class RSACryptoServiceProviderTest : Assertion {
 		AssertEquals ("KeyNumber", KeyNumber.Exchange, info.KeyNumber);
 		Assert ("MachineKeyStore", !info.MachineKeyStore);
 		Assert ("Protected", !info.Protected);
-		AssertNotNull ("ProviderName", info.ProviderName);
-		AssertEquals ("ProviderType", 1, info.ProviderType);
 		Assert ("RandomlyGenerated", info.RandomlyGenerated);
 		Assert ("Removable", !info.Removable);
 		AssertNotNull ("UniqueKeyContainerName", info.UniqueKeyContainerName);
@@ -1196,8 +1208,6 @@ public class RSACryptoServiceProviderTest : Assertion {
 		AssertEquals ("KeyNumber", KeyNumber.Exchange, info.KeyNumber);
 		Assert ("MachineKeyStore", !info.MachineKeyStore);
 		// info.Protected throws a CryptographicException at this stage
-		AssertNotNull ("ProviderName", info.ProviderName);
-		AssertEquals ("ProviderType", 1, info.ProviderType);
 		Assert ("RandomlyGenerated", info.RandomlyGenerated);
 		Assert ("Removable", !info.Removable);
 		// info.UniqueKeyContainerName throws a CryptographicException at this stage
diff --git a/mcs/class/corlib/Test/System.Security.Cryptography/RSAPKCS1SignatureFormatterTest.cs b/mcs/class/corlib/Test/System.Security.Cryptography/RSAPKCS1SignatureFormatterTest.cs
index 4082d4f..faf67ee 100644
--- a/mcs/class/corlib/Test/System.Security.Cryptography/RSAPKCS1SignatureFormatterTest.cs
+++ b/mcs/class/corlib/Test/System.Security.Cryptography/RSAPKCS1SignatureFormatterTest.cs
@@ -5,7 +5,7 @@
 //	Sebastien Pouliot (sebastien at ximian.com)
 //
 // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
-// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004-2005, 2011 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
@@ -34,18 +34,12 @@ using System.Security.Cryptography;
 namespace MonoTests.System.Security.Cryptography {
 
 	[TestFixture]
-	public class RSAPKCS1SignatureFormatterTest : Assertion {
+	public class RSAPKCS1SignatureFormatterTest {
 
-#if NET_2_0
-		// FX 2.0 changed the OID values for SHA256, SHA384 and SHA512 - so the signature values are different
 		private static byte[] signatureRSASHA256 = { 0xAD, 0x6E, 0x29, 0xC8, 0x7D, 0xFE, 0x5F, 0xB3, 0x92, 0x07, 0x4C, 0x51, 0x08, 0xC5, 0x91, 0xA2, 0xCF, 0x7E, 0xA6, 0x05, 0x66, 0x85, 0xA3, 0x8E, 0x7C, 0xB0, 0xCA, 0x93, 0x4F, 0x4E, 0xF5, 0x45, 0x0F, 0xED, 0x46, 0xFB, 0x34, 0xBC, 0x8A, 0x6A, 0x48, 0xD9, 0x76, 0x28, 0xE1, 0x68, 0xA0, 0x1F, 0x7F, 0x3E, 0xCC, 0x0A, 0x5F, 0x06, 0x8E, 0xEB, 0xB7, 0xA7, 0x48, 0x6B, 0x92, 0x1A, 0x7A, 0x66, 0x42, 0x4F, 0x0B, 0xC1, 0x19, 0x96, 0xAC, 0x67, 0xA0, 0x6C, 0x3E, 0x39, 0xD2, 0xEB, 0xCA, 0xD7, 0x12, 0x29, 0x46, 0x0A, 0x60, 0x70, 0xA9, 0x2B, 0x80, 0x9F, 0xCD, 0x08, 0x02, 0xEB, 0xA5, 0x62, 0xEC, 0xAB, 0xBB, 0x64, 0x8B, 0x2D, 0xB9, 0x55, 0x0A, 0xE3, 0x5A, 0x2C, 0xDA, 0x54, 0xD4, 0x79, 0x0A, 0x8D, 0xB6, 0x57, 0x05, 0xF7, 0x6C, 0x6D, 0xB7, 0xD8, 0xB4, 0x07, 0xC4, 0xCD, 0x79, 0xD4 };
 		private static byte[] signatureRSASHA384 = { 0x53, 0x80, 0xFD, 0x26, 0x8F, 0xCF, 0xE5, 0x44, 0x55, 0x4A, 0xC5, 0xB2, 0x46, 0x78, 0x89, 0x42, 0xF8, 0x51, 0xB8, 0x4D, 0x3B, 0xCA, 0x48, 0x5A, 0x36, 0x9F, 0x62, 0x01, 0x72, 0x1E, 0xD8, 0x2D, 0xC2, 0x2D, 0x3E, 0x67, 0x1C, 0x5D, 0x89, 0xAB, 0x39, 0x8D, 0x07, 0xC8, 0xD4, 0x47, 0x97, 0xA4, 0x68, 0x7A, 0x87, 0xA4, 0xCF, 0x7B, 0x32, 0x4F, 0xD3, 0xD1, 0x90, 0xDC, 0x76, 0x23, 0x51, 0xA7, 0xEE, 0xFC, 0x7F, 0xDF, 0x3C, 0xB0, 0x05, 0xF3, 0xE3, 0xAA, 0x96, 0x30, 0xE0, 0xE4, 0x8B, 0x09, 0xB1, 0x78, 0xAC, 0x99, 0xDB, 0xC5, 0x0E, 0xFA, 0xAB, 0x4F, 0xA1, 0x02, 0xCA, 0x77, 0x93, 0x74, 0x5A, 0xB8, 0x71, 0x9C, 0x3E, 0x2E, 0xAE, 0x62, 0xC7, 0xE5, 0xBF, 0xDA, 0xFE, 0x31, 0xA7, 0x91, 0xC0, 0x04, 0xE3, 0x95, 0xCB, 0x3F, 0x54, 0xA8, 0x09, 0x25, 0xF7, 0x09, 0x78, 0xE6, 0x09, 0x84 };
 		private static byte[] signatureRSASHA512 = { 0xA8, 0xD0, 0x24, 0xCB, 0xA2, 0x4B, 0x5E, 0x0D, 0xBC, 0x3F, 0x6F, 0x0F, 0x8D, 0xE4, 0x31, 0x9E, 0x37, 0x84, 0xE0, 0x31, 0x5B, 0x63, 0x24, 0xC5, 0xA9, 0x05, 0x41, 0xAA, 0x69, 0x02, 0x8F, 0xC1, 0x57, 0x06, 0x1F, 0xBF, 0x3B, 0x8B, 0xC8, 0x86, 0xB3, 0x02, 0xEA, 0xF1, 0x75, 0xE4, 0x70, 0x21, 0x1E, 0x16, 0x4C, 0x37, 0xB2, 0x31, 0x78, 0xD0, 0xA0, 0x88, 0xA5, 0x1D, 0x5D, 0x8F, 0xBC, 0xC3, 0x87, 0x94, 0x4B, 0x8F, 0x4E, 0x92, 0xBC, 0x80, 0xF8, 0xA5, 0x90, 0xF7, 0xA0, 0x6D, 0x96, 0x61, 0x65, 0x0D, 0xD5, 0x3F, 0xD7, 0x4F, 0x07, 0x58, 0x40, 0xB8, 0xA4, 0x14, 0x14, 0x55, 0x39, 0x4F, 0xF0, 0xB5, 0x56, 0x99, 0xC8, 0x52, 0x0C, 0xDD, 0xBA, 0x8D, 0xFB, 0x06, 0x83, 0x6E, 0x79, 0x25, 0x75, 0xEF, 0x0D, 0x26, 0x14, 0x3A, 0xBB, 0x62, 0x29, 0x21, 0xF6, 0x4B, 0x9E, 0x87, 0x28, 0x57 };
-#else
-		private static byte[] signatureRSASHA256 = { 0x0F, 0xE3, 0x15, 0x5B, 0x4D, 0xA1, 0xB4, 0x13, 0x93, 0x91, 0x1E, 0x17, 0xF9, 0x36, 0xB3, 0x2C, 0xAC, 0x51, 0x77, 0xBC, 0x86, 0x21, 0xB0, 0x69, 0x75, 0x57, 0xAF, 0xB0, 0xAD, 0xF9, 0x42, 0xF5, 0x58, 0xBC, 0xD5, 0x61, 0xD5, 0x14, 0x8E, 0xC6, 0xE0, 0xB3, 0xB5, 0x51, 0xCD, 0x17, 0x68, 0x58, 0x27, 0x74, 0x8A, 0xA7, 0x88, 0xB9, 0x24, 0xD6, 0xE4, 0xC4, 0x93, 0x82, 0x95, 0xB4, 0x36, 0x14, 0x48, 0xA7, 0xF6, 0x27, 0x87, 0xEB, 0xD8, 0xB9, 0x75, 0x14, 0x75, 0xFB, 0x6E, 0xA1, 0xF7, 0xAB, 0xA6, 0x78, 0x32, 0xEF, 0x1A, 0x23, 0x60, 0xD3, 0x0C, 0x8D, 0xFE, 0x89, 0x72, 0xB7, 0x93, 0x6D, 0x00, 0x25, 0xED, 0xF5, 0x55, 0x66, 0xA8, 0x52, 0x7F, 0x20, 0xFD, 0x77, 0xDA, 0x10, 0x77, 0xE9, 0xF0, 0x58, 0x8D, 0xE6, 0x3A, 0x5A, 0x00, 0x83, 0x64, 0x42, 0xA5, 0x15, 0x79, 0x3C, 0xB0, 0x8F };
-		private static byte[] signatureRSASHA384 = { 0x86, 0x20, 0x2A, 0xB6, 0xA8, 0x0F, 0x59, 0x42, 0xCA, 0x83, 0xC3, 0x46, 0x2C, 0xA9, 0x2E, 0x62, 0x73, 0x2C, 0xEE, 0x52, 0xA5, 0xAE, 0x4F, 0xFD, 0xB1, 0x1F, 0xFA, 0x0C, 0x71, 0x4A, 0xFD, 0xE2, 0xAC, 0x64, 0x1C, 0x63, 0x41, 0xB8, 0x43, 0x3F, 0x8A, 0xF3, 0x7E, 0x1C, 0x25, 0xBE, 0xEE, 0xFC, 0x7C, 0xCB, 0x33, 0x72, 0x3B, 0x91, 0x1F, 0xF3, 0x78, 0xC2, 0xD0, 0xEA, 0xDF, 0x69, 0xE9, 0x31, 0x2F, 0x39, 0x32, 0x5F, 0x4A, 0x51, 0xAE, 0x24, 0x9E, 0x96, 0x77, 0xFB, 0x16, 0xC4, 0xDD, 0x98, 0xDA, 0xA9, 0x9D, 0xA0, 0x7C, 0x2C, 0x95, 0x12, 0x53, 0x1F, 0x7B, 0x23, 0xEE, 0x78, 0x95, 0x57, 0xFF, 0x02, 0x57, 0x2B, 0x4A, 0x3E, 0x62, 0x6A, 0xC0, 0x99, 0xDF, 0x4B, 0x7E, 0xBF, 0x86, 0xC4, 0xFB, 0x8E, 0xF3, 0x70, 0xA2, 0xEE, 0x7B, 0xCA, 0x8B, 0x22, 0xA4, 0x07, 0xBA, 0xBD, 0x16, 0xA9 };
-		private static byte[] signatureRSASHA512 = { 0xB7, 0x7E, 0x7E, 0xEF, 0x95, 0xCE, 0xE8, 0x9D, 0x0F, 0x40, 0x35, 0x50, 0x88, 0xFE, 0x8B, 0xA3, 0x26, 0xD3, 0x9E, 0xA7, 0x82, 0x23, 0x1A, 0x46, 0x13, 0x46, 0x81, 0x59, 0xD1, 0x24, 0x45, 0xAC, 0x53, 0xEF, 0x5A, 0x06, 0x31, 0xA7, 0xC2, 0x76, 0xDC, 0x2B, 0x60, 0x69, 0xB1, 0x36, 0x1D, 0xE1, 0xFC, 0xD5, 0x9A, 0x01, 0x71, 0x08, 0xE9, 0x0C, 0xAE, 0xF4, 0x29, 0xCF, 0xC4, 0xB0, 0x60, 0xA4, 0xBE, 0x1C, 0x9B, 0x05, 0x2A, 0xA9, 0x6A, 0x12, 0xFF, 0x73, 0x84, 0x5C, 0xA8, 0x74, 0x5B, 0x9C, 0xA2, 0x07, 0x9D, 0x73, 0xB8, 0xE3, 0x20, 0x16, 0x3C, 0x47, 0x8F, 0x27, 0x7A, 0x48, 0xAF, 0x01, 0x07, 0xA0, 0x6A, 0x2D, 0x71, 0xAD, 0xDD, 0x8B, 0x68, 0xC8, 0x32, 0x61, 0x95, 0x68, 0x22, 0x1B, 0x8B, 0xD9, 0x86, 0xA7, 0xBE, 0x60, 0x06, 0x70, 0x7C, 0xED, 0x51, 0x28, 0x66, 0x28, 0xF0, 0x65 };
-#endif
+
 		private static RSA rsa;
 		private static DSA dsa;
 
@@ -64,31 +58,28 @@ namespace MonoTests.System.Security.Cryptography {
 
 		public void AssertEquals (string msg, byte[] array1, byte[] array2) 
 		{
-			AllTests.AssertEquals (msg, array1, array2);
+			Assert.AreEqual (array1, array2, msg);
 		}
 
 		[Test]
 		public void ConstructorEmpty () 
 		{
 			fmt = new RSAPKCS1SignatureFormatter ();
-			AssertNotNull ("RSAPKCS1SignatureFormatter()", fmt);
+			Assert.IsNotNull (fmt);
 		}
 
 		[Test]
-#if NET_2_0
 		[ExpectedException (typeof (ArgumentNullException))]
-#endif
 		public void ConstructorNull () 
 		{
-			fmt = new RSAPKCS1SignatureFormatter (null);
-			AssertNotNull ("RSAPKCS1SignatureFormatter(null)", fmt);
+			new RSAPKCS1SignatureFormatter (null);
 		}
 
 		[Test]
 		public void ConstructorRSA () 
 		{
 			fmt = new RSAPKCS1SignatureFormatter (rsa);
-			AssertNotNull ("RSAPKCS1SignatureFormatter(rsa)", fmt);
+			Assert.IsNotNull (fmt);
 		}
 
 		[Test]
@@ -114,9 +105,7 @@ namespace MonoTests.System.Security.Cryptography {
 		}
 
 		[Test]
-#if NET_2_0
 		[ExpectedException (typeof (ArgumentNullException))]
-#endif
 		public void SetKeyNull ()
 		{
 			fmt = new RSAPKCS1SignatureFormatter ();
@@ -209,7 +198,7 @@ namespace MonoTests.System.Security.Cryptography {
 			fmt.SetHashAlgorithm ("SHA1");
 			byte[] hash = new byte [20];
 			byte[] signature = fmt.CreateSignature (hash);
-			AssertNotNull ("CreateSignature(SHA1)", signature);
+			Assert.IsNotNull (fmt);
 		}
 
 		[Test]
@@ -235,72 +224,55 @@ namespace MonoTests.System.Security.Cryptography {
 			fmt.SetHashAlgorithm ("MD5");
 			byte[] hash = new byte [16];
 			byte[] signature = fmt.CreateSignature (hash);
-			AssertNotNull ("CreateSignature(MD5)", signature);
+			Assert.IsNotNull (fmt);
 		}
 
 		private byte[] CreateSignature (string hashName, int hashSize) 
 		{
-			byte[] signature = null;
 			fmt = new RSAPKCS1SignatureFormatter ();
-			bool ms = false;
+
 			// we need the private key 
 			RSA rsa = RSA.Create ("Mono.Security.Cryptography.RSAManaged");	// only available with Mono::
 			if (rsa == null) {
-				ms = true;
 				rsa = RSA.Create ();
 			}
 			rsa.ImportParameters (AllTests.GetRsaKey (true));
 			fmt.SetKey (rsa);
-			try {
-				HashAlgorithm ha = HashAlgorithm.Create (hashName);
-				byte[] data = new byte [ha.HashSize >> 3];
-				// this way we get the same results as CreateSignatureHash
-				data = ha.ComputeHash (data);
-
-				fmt.SetHashAlgorithm (hashName);
-				signature = fmt.CreateSignature (data);
-				if (ms)
-					Fail ("CreateSignature(" + hashName + ") Expected CryptographicException but got none");
-			}
-			catch (CryptographicException) {
-				if (!ms)
-					throw;
-			}
-			catch (Exception e) {
-				if (ms)
-					Fail ("CreateSignatureHash(" + hashName + ") Expected CryptographicException but got " + e.ToString ());
-			}
-			return signature;
+
+			HashAlgorithm ha = HashAlgorithm.Create (hashName);
+			byte[] data = new byte [ha.HashSize >> 3];
+			// this way we get the same results as CreateSignatureHash
+			data = ha.ComputeHash (data);
+
+			fmt.SetHashAlgorithm (hashName);
+			return fmt.CreateSignature (data);
 		}
 
-		// not supported using MS framework 1.0 and 1.1 (CryptographicException)
-		// supported by Mono::
+		// historical note: this was not supported using MS framework 1.0 and 1.1 (CryptographicException)
+		// but was supported by Mono:: - it's also supported on 2.0+ (at least on Win XP+)
 		[Test]
 		public void CreateSignatureRSASHA256 () 
 		{
 			byte[] signature = CreateSignature ("SHA256", 32);
-			if (signature != null)
-				AssertEquals ("CreateSignature(SHA256)", signatureRSASHA256, signature);
+			AssertEquals ("CreateSignature(SHA256)", signatureRSASHA256, signature);
 		}
 
-		// not supported using MS framework 1.0 and 1.1 (CryptographicException)
-		// supported by Mono::
+		// historical note: this was not supported using MS framework 1.0 and 1.1 (CryptographicException)
+		// but was supported by Mono:: - it's also supported on 2.0+ (at least on Win XP+)
 		[Test]
 		public void CreateSignatureRSASHA384 () 
 		{
 			byte[] signature = CreateSignature ("SHA384", 48);
-			if (signature != null)
-				AssertEquals ("CreateSignature(SHA384)", signatureRSASHA384, signature);
+			AssertEquals ("CreateSignature(SHA384)", signatureRSASHA384, signature);
 		}
 
-		// not supported using MS framework 1.0 and 1.1 (CryptographicException)
-		// supported by Mono::
+		// historical note: this was not supported using MS framework 1.0 and 1.1 (CryptographicException)
+		// but was supported by Mono:: - it's also supported on 2.0+ (at least on Win XP+)
 		[Test]
 		public void CreateSignatureRSASHA512 () 
 		{
 			byte[] signature = CreateSignature ("SHA512", 64);
-			if (signature != null)
-				AssertEquals ("CreateSignature(SHA512)", signatureRSASHA512, signature);
+			AssertEquals ("CreateSignature(SHA512)", signatureRSASHA512, signature);
 		}
 
 		[Test]
@@ -349,7 +321,7 @@ namespace MonoTests.System.Security.Cryptography {
 			HashAlgorithm hash = SHA1.Create ();
 			hash.ComputeHash (data);
 			byte[] signature = fmt.CreateSignature (hash);
-			AssertNotNull ("CreateSignature(SHA1)", signature);
+			Assert.IsNotNull (signature);
 		}
 
 		[Test]
@@ -363,69 +335,52 @@ namespace MonoTests.System.Security.Cryptography {
 			HashAlgorithm hash = MD5.Create ();
 			hash.ComputeHash (data);
 			byte[] signature = fmt.CreateSignature (hash);
-			AssertNotNull ("CreateSignature(MD5)", signature);
+			Assert.IsNotNull (signature);
 		}
 
 		private byte[] CreateSignatureHash (string hashName) 
 		{
-			byte[] signature = null;
 			fmt = new RSAPKCS1SignatureFormatter ();
-			bool ms = false;
+
 			// we need the private key 
 			RSA rsa = RSA.Create ("Mono.Security.Cryptography.RSAManaged");	// only available with Mono::
 			if (rsa == null) {
-				ms = true;
 				rsa = RSA.Create ();
 			}
 			rsa.ImportParameters (AllTests.GetRsaKey (true));
 			fmt.SetKey (rsa);
-			try {
-				HashAlgorithm hash = HashAlgorithm.Create (hashName);
-				byte[] data = new byte [(hash.HashSize >> 3)];
-				hash.ComputeHash (data);
-				signature = fmt.CreateSignature (hash);
-				if (ms)
-					Fail ("CreateSignatureHash(" + hashName + ") Expected CryptographicException but got none");
-			}
-			catch (CryptographicException) {
-				if (!ms)
-					throw;
-			}
-			catch (Exception e) {
-				if (ms)
-					Fail ("CreateSignatureHash(" + hashName + ") Expected CryptographicException but got " + e.ToString ());
-			}
-			return signature;																																																																																																      
+
+			HashAlgorithm hash = HashAlgorithm.Create (hashName);
+			byte[] data = new byte [(hash.HashSize >> 3)];
+			hash.ComputeHash (data);
+			return fmt.CreateSignature (hash);
 		}
 
-		// not supported using MS framework 1.0 and 1.1 (CryptographicException)
-		// supported by Mono::
+		// historical note: this was not supported using MS framework 1.0 and 1.1 (CryptographicException)
+		// but was supported by Mono:: - it's also supported on 2.0+ (at least on Win XP+)
 		[Test]
 		public void CreateSignatureHashSHA256 () 
 		{
 			byte[] signature = CreateSignatureHash ("SHA256");
-			if (signature != null)
-				AssertEquals ("CreateSignatureHash(SHA256)", signatureRSASHA256, signature);
+			AssertEquals ("CreateSignatureHash(SHA256)", signatureRSASHA256, signature);
 		}
 
-		// not supported using MS framework 1.0 and 1.1 (CryptographicException)
-		// supported by Mono::
+		// historical note: this was not supported using MS framework 1.0 and 1.1 (CryptographicException)
+		// but was supported by Mono:: - it's also supported on 2.0+ (at least on Win XP+)
 		[Test]
 		public void CreateSignatureHashSHA384 () 
 		{
 			byte[] signature = CreateSignatureHash ("SHA384");
-			if (signature != null)
-				AssertEquals ("CreateSignatureHash(SHA384)", signatureRSASHA384, signature);
+			AssertEquals ("CreateSignatureHash(SHA384)", signatureRSASHA384, signature);
 		}
 
-		// not supported using MS framework 1.0 and 1.1 (CryptographicException)
-		// supported by Mono::
+		// historical note: this was not supported using MS framework 1.0 and 1.1 (CryptographicException)
+		// but was supported by Mono:: - it's also supported on 2.0+ (at least on Win XP+)
 		[Test]
 		public void CreateSignatureHashSHA512 () 
 		{
 			byte[] signature = CreateSignatureHash ("SHA512");
-			if (signature != null)
-				AssertEquals ("CreateSignatureHash(SHA512)", signatureRSASHA512, signature);
+			AssertEquals ("CreateSignatureHash(SHA512)", signatureRSASHA512, signature);
 		}
 	}
 }
diff --git a/mcs/class/corlib/Test/System.Security.Principal/ChangeLog b/mcs/class/corlib/Test/System.Security.Principal/ChangeLog
index 6105ee0..b38dd60 100644
--- a/mcs/class/corlib/Test/System.Security.Principal/ChangeLog
+++ b/mcs/class/corlib/Test/System.Security.Principal/ChangeLog
@@ -1,3 +1,15 @@
+2010-12-04  Kenneth Bell  <ken.git at chezbell.org.uk>
+
+	Implement SecurityIdentifier and improve NTAccount.
+
+	* Only translates between SecurityIdentifier and NTAccount for
+	well-known accounts.
+
+	* NTAccount changed to not upper-case values to match behaviour
+	observed in Microsoft's .NET (see also unit tests)
+
+	* Add unit tests for both classes
+
 2009-06-24  Zoltan Varga  <vargaz at gmail.com>
 
 	* *.cs: Convert all tests to new-style nunit classes/methods.
diff --git a/mcs/class/corlib/Test/System.Security.Principal/ChangeLog b/mcs/class/corlib/Test/System.Security.Principal/ChangeLog.old
similarity index 100%
copy from mcs/class/corlib/Test/System.Security.Principal/ChangeLog
copy to mcs/class/corlib/Test/System.Security.Principal/ChangeLog.old
diff --git a/mcs/class/corlib/Test/System.Security.Principal/NTAccountTest.cs b/mcs/class/corlib/Test/System.Security.Principal/NTAccountTest.cs
new file mode 100644
index 0000000..4a4cf71
--- /dev/null
+++ b/mcs/class/corlib/Test/System.Security.Principal/NTAccountTest.cs
@@ -0,0 +1,49 @@
+//
+// NTAccountTest.cs - NUnit Test Cases for NTAccount
+//
+// Author:
+//	Kenneth Bell
+//
+
+using System;
+using System.Security.Principal;
+using System.Text;
+using NUnit.Framework;
+
+namespace MonoTests.System.Security.Principal
+{
+    [TestFixture]
+    public class NTAccountTest : Assert
+    {
+        [Test]
+        public void ConstructorOneString()
+        {
+            Assert.AreEqual(@"Everyone", new NTAccount("Everyone").Value);
+            Assert.AreEqual(@"EVERYONE", new NTAccount("EVERYONE").Value);
+            Assert.AreEqual(@"DoMaIn\uSeR", new NTAccount(@"DoMaIn\uSeR").Value);
+        }
+
+        [Test]
+        public void ConstructorTwoString()
+        {
+            Assert.AreEqual(@"DoMaIn\uSeR", new NTAccount("DoMaIn", "uSeR").Value);
+            Assert.AreEqual(@"uSeR", new NTAccount(null, "uSeR").Value);
+        }
+
+        [Test]
+        public void Translate()
+        {
+            NTAccount acct = new NTAccount("Everyone");
+            SecurityIdentifier sid = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier));
+            Assert.AreEqual("S-1-1-0", sid.Value);
+        }
+
+        [Test]
+        [ExpectedException(typeof(IdentityNotMappedException))]
+        public void TranslateUnknown()
+        {
+            NTAccount acct = new NTAccount(@"UnknownDomain\UnknownUser");
+            acct.Translate(typeof(SecurityIdentifier));
+        }
+    }
+}
diff --git a/mcs/class/corlib/Test/System.Security.Principal/SecurityIdentifierTest.cs b/mcs/class/corlib/Test/System.Security.Principal/SecurityIdentifierTest.cs
new file mode 100644
index 0000000..b94470f
--- /dev/null
+++ b/mcs/class/corlib/Test/System.Security.Principal/SecurityIdentifierTest.cs
@@ -0,0 +1,306 @@
+//
+// SecurityIdentifierTest.cs - NUnit Test Cases for SecurityIdentifier
+//
+// Author:
+//	Kenneth Bell
+//
+
+using System;
+using System.Security.Principal;
+using System.Text;
+using NUnit.Framework;
+
+namespace MonoTests.System.Security.Principal {
+	[TestFixture]
+	public class SecurityIdentifierTest : Assert {
+		[Test]
+		[ExpectedException(typeof(ArgumentNullException))]
+		public void ConstructorNull ()
+		{
+			new SecurityIdentifier (null);
+		}
+
+		private void CheckStringCtor (string strValue, byte[] expectedBinary)
+		{
+			SecurityIdentifier sid = new SecurityIdentifier (strValue);
+			byte[] buffer = new byte[sid.BinaryLength];
+			sid.GetBinaryForm (buffer, 0);
+			
+			Assert.AreEqual (expectedBinary.Length, buffer.Length, "SID length mismatch");
+			Assert.AreEqual (expectedBinary, buffer, "SIDs different in binary form");
+		}
+
+		private void CheckUnqualifiedWellKnownSid (WellKnownSidType type, string sddl)
+		{
+			SecurityIdentifier sid = new SecurityIdentifier (type, null);
+			Assert.AreEqual (sddl, sid.Value, "Bad SID for type: " + type);
+		}
+
+		private void CheckQualifiedWellKnownSid (WellKnownSidType type, SecurityIdentifier domain, string sddl)
+		{
+			SecurityIdentifier sid = new SecurityIdentifier (type, domain);
+			Assert.AreEqual (sddl, sid.Value, "Bad SID for type: " + type);
+		}
+
+		private void CheckWellKnownSidLookup (WellKnownSidType wellKnownSidType, string name)
+		{
+			Assert.AreEqual (name, ((NTAccount)new SecurityIdentifier (wellKnownSidType, null).Translate (typeof(NTAccount))).Value);
+		}
+
+		[Test]
+		public void ConstructorString ()
+		{
+			CheckStringCtor ("S-1-0-0",
+			                 new byte[] {
+				0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x00, 0x00 });
+			CheckStringCtor ("S-1-5-33",
+			                 new byte[] {
+				0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x21, 0x00,
+				0x00, 0x00 });
+			CheckStringCtor ("s-1-5-334-234",
+			                 new byte[] {
+				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x4E, 0x01,
+				0x00, 0x00, 0xEA, 0x00, 0x00, 0x00 });
+			CheckStringCtor ("S-1-5-0x3432",
+			                 new byte[] {
+				0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x32, 0x34,
+				0x00, 0x00 });
+			CheckStringCtor ("S-1-0xCBA987654321-0",
+			                 new byte[] {
+				0x01, 0x01, 0xCB, 0xA9, 0x87, 0x65, 0x43, 0x21, 0x00, 0x00,
+				0x00, 0x00 });
+		}
+
+		[Test]
+		public void ConstructorStringSddl ()
+		{
+			Assert.AreEqual ("S-1-5-32-545",
+			                 new SecurityIdentifier ("BU").Value);
+		}
+
+		[Test]
+		[ExpectedException(typeof(ArgumentException))]
+		public void ConstructorStringBadRevision ()
+		{
+			CheckStringCtor ("S-2-0-0",
+			                 new byte[] {
+				0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x00, 0x00 });
+		}
+
+		[Test]
+		[ExpectedException(typeof(ArgumentException))]
+		public void ConstructorInvalidString ()
+		{
+			new SecurityIdentifier ("M");
+		}
+
+		[Test]
+		public void ConstructorBinary ()
+		{
+			byte[] inForm = new byte[] {
+				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x4E, 0x01,
+				0x00, 0x00, 0xEA, 0x00, 0x00, 0x00 };
+			SecurityIdentifier sid = new SecurityIdentifier (inForm, 0);
+			
+			byte[] outForm = new byte[inForm.Length];
+			sid.GetBinaryForm (outForm, 0);
+			Assert.AreEqual (inForm, outForm);
+		}
+
+		[Test]
+		public void ConstructorWellKnownSids ()
+		{
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.NullSid, "S-1-0-0");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.WorldSid, "S-1-1-0");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.LocalSid, "S-1-2-0");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.CreatorOwnerSid, "S-1-3-0");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.CreatorGroupSid, "S-1-3-1");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.CreatorOwnerServerSid, "S-1-3-2");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.CreatorGroupServerSid, "S-1-3-3");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.NTAuthoritySid, "S-1-5");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.DialupSid, "S-1-5-1");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.NetworkSid, "S-1-5-2");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BatchSid, "S-1-5-3");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.InteractiveSid, "S-1-5-4");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.ServiceSid, "S-1-5-6");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.AnonymousSid, "S-1-5-7");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.ProxySid, "S-1-5-8");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.EnterpriseControllersSid, "S-1-5-9");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.SelfSid, "S-1-5-10");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.AuthenticatedUserSid, "S-1-5-11");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.RestrictedCodeSid, "S-1-5-12");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.TerminalServerSid, "S-1-5-13");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.RemoteLogonIdSid, "S-1-5-14");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.LocalSystemSid, "S-1-5-18");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.LocalServiceSid, "S-1-5-19");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.NetworkServiceSid, "S-1-5-20");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinDomainSid, "S-1-5-32");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinAdministratorsSid, "S-1-5-32-544");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinUsersSid, "S-1-5-32-545");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinGuestsSid, "S-1-5-32-546");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinPowerUsersSid, "S-1-5-32-547");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinAccountOperatorsSid, "S-1-5-32-548");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinSystemOperatorsSid, "S-1-5-32-549");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinPrintOperatorsSid, "S-1-5-32-550");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinBackupOperatorsSid, "S-1-5-32-551");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinReplicatorSid, "S-1-5-32-552");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinPreWindows2000CompatibleAccessSid, "S-1-5-32-554");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinRemoteDesktopUsersSid, "S-1-5-32-555");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinNetworkConfigurationOperatorsSid, "S-1-5-32-556");
+			CheckQualifiedWellKnownSid (WellKnownSidType.AccountAdministratorSid, new SecurityIdentifier ("S-1-5-21-125-3215-342"), "S-1-5-21-125-3215-342-500");
+			CheckQualifiedWellKnownSid (WellKnownSidType.AccountGuestSid, new SecurityIdentifier ("S-1-5-21-125-3215-342"), "S-1-5-21-125-3215-342-501");
+			CheckQualifiedWellKnownSid (WellKnownSidType.AccountKrbtgtSid, new SecurityIdentifier ("S-1-5-21-125-3215-342"), "S-1-5-21-125-3215-342-502");
+			CheckQualifiedWellKnownSid (WellKnownSidType.AccountDomainAdminsSid, new SecurityIdentifier ("S-1-5-21-125-3215-342"), "S-1-5-21-125-3215-342-512");
+			CheckQualifiedWellKnownSid (WellKnownSidType.AccountDomainUsersSid, new SecurityIdentifier ("S-1-5-21-125-3215-342"), "S-1-5-21-125-3215-342-513");
+			CheckQualifiedWellKnownSid (WellKnownSidType.AccountDomainGuestsSid, new SecurityIdentifier ("S-1-5-21-125-3215-342"), "S-1-5-21-125-3215-342-514");
+			CheckQualifiedWellKnownSid (WellKnownSidType.AccountComputersSid, new SecurityIdentifier ("S-1-5-21-125-3215-342"), "S-1-5-21-125-3215-342-515");
+			CheckQualifiedWellKnownSid (WellKnownSidType.AccountControllersSid, new SecurityIdentifier ("S-1-5-21-125-3215-342"), "S-1-5-21-125-3215-342-516");
+			CheckQualifiedWellKnownSid (WellKnownSidType.AccountCertAdminsSid, new SecurityIdentifier ("S-1-5-21-125-3215-342"), "S-1-5-21-125-3215-342-517");
+			CheckQualifiedWellKnownSid (WellKnownSidType.AccountSchemaAdminsSid, new SecurityIdentifier ("S-1-5-21-125-3215-342"), "S-1-5-21-125-3215-342-518");
+			CheckQualifiedWellKnownSid (WellKnownSidType.AccountEnterpriseAdminsSid, new SecurityIdentifier ("S-1-5-21-125-3215-342"), "S-1-5-21-125-3215-342-519");
+			CheckQualifiedWellKnownSid (WellKnownSidType.AccountPolicyAdminsSid, new SecurityIdentifier ("S-1-5-21-125-3215-342"), "S-1-5-21-125-3215-342-520");
+			CheckQualifiedWellKnownSid (WellKnownSidType.AccountRasAndIasServersSid, new SecurityIdentifier ("S-1-5-21-125-3215-342"), "S-1-5-21-125-3215-342-553");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.NtlmAuthenticationSid, "S-1-5-64-10");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.DigestAuthenticationSid, "S-1-5-64-21");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.SChannelAuthenticationSid, "S-1-5-64-14");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.ThisOrganizationSid, "S-1-5-15");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.OtherOrganizationSid, "S-1-5-1000");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinIncomingForestTrustBuildersSid, "S-1-5-32-557");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinPerformanceMonitoringUsersSid, "S-1-5-32-558");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinPerformanceLoggingUsersSid, "S-1-5-32-559");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.BuiltinAuthorizationAccessSid, "S-1-5-32-560");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.WinBuiltinTerminalServerLicenseServersSid, "S-1-5-32-561");
+			CheckUnqualifiedWellKnownSid (WellKnownSidType.MaxDefined, "S-1-5-32-561");
+		}
+
+		[Test]
+		[ExpectedException(typeof(ArgumentException))]
+		public void ConstructorWellKnownSidLogonIds ()
+		{
+			CheckQualifiedWellKnownSid (WellKnownSidType.LogonIdsSid,
+			                            new SecurityIdentifier ("S-1-5-21-125-3215-342"),
+			                            "S-1-5-21-125-3215-342-3");
+		}
+
+		[Test]
+		public void AccountDomainSid ()
+		{
+			Assert.AreEqual ("S-1-5-21-125-3215-342", new SecurityIdentifier ("S-1-5-21-125-3215-342-324-1000").AccountDomainSid.Value);
+			Assert.AreEqual ("S-1-5-21-125-3215-342", new SecurityIdentifier ("S-1-5-21-125-3215-342-1000").AccountDomainSid.Value);
+			Assert.AreEqual ("S-1-5-21-125-3215-1", new SecurityIdentifier ("S-1-5-21-125-3215-1").AccountDomainSid.Value);
+			Assert.IsNull (new SecurityIdentifier ("S-1-5-21-125-1").AccountDomainSid);
+			Assert.IsNull (new SecurityIdentifier ("S-1-0-0").AccountDomainSid);
+			Assert.IsNull (new SecurityIdentifier ("S-1-5-44-125-3215-1").AccountDomainSid);
+		}
+
+		[Test]
+		public void BinaryLength ()
+		{
+			Assert.AreEqual (12, new SecurityIdentifier ("S-1-0-0").BinaryLength);
+		}
+
+		[Test]
+		public void Value ()
+		{
+			Assert.AreEqual ("S-1-5-13362", new SecurityIdentifier ("s-1-5-0x3432").Value);
+		}
+
+		[Test]
+		public void Equals ()
+		{
+			Assert.IsTrue (new SecurityIdentifier ("S-1-5-13362").Equals (new SecurityIdentifier ("s-1-5-0x3432")));
+		}
+
+		[Test]
+		public void IsAccountSid ()
+		{
+			Assert.IsTrue (new SecurityIdentifier ("S-1-5-21-125-3215-342-324-1000").IsAccountSid ());
+			Assert.IsTrue (new SecurityIdentifier ("S-1-5-21-125-3215-342-1000").IsAccountSid ());
+			Assert.IsTrue (new SecurityIdentifier ("S-1-5-21-125-3215-1").IsAccountSid ());
+			Assert.IsFalse (new SecurityIdentifier ("S-1-5-21-125-1").IsAccountSid ());
+			Assert.IsFalse (new SecurityIdentifier ("S-1-0-0").IsAccountSid ());
+		}
+
+		[Test]
+		public void IsEqualDomainSid ()
+		{
+			Assert.IsTrue (new SecurityIdentifier ("S-1-5-21-125-3215-342-1000").IsEqualDomainSid (new SecurityIdentifier ("S-1-5-21-125-3215-342-333")));
+			Assert.IsTrue (new SecurityIdentifier ("S-1-5-21-125-3215-342-1000").IsEqualDomainSid (new SecurityIdentifier ("S-1-5-21-125-3215-342-324-333")));
+			Assert.IsFalse (new SecurityIdentifier ("S-1-5-21-125-1").IsEqualDomainSid (new SecurityIdentifier ("S-1-5-21-125-2")));
+			Assert.IsFalse (new SecurityIdentifier ("S-1-0-0").IsEqualDomainSid (new SecurityIdentifier ("S-1-0-0")));
+		}
+
+		[Test]
+		public void IsValidTargetType ()
+		{
+			Assert.IsTrue (new SecurityIdentifier ("S-1-0-0").IsValidTargetType (typeof(SecurityIdentifier)));
+			Assert.IsTrue (new SecurityIdentifier ("S-1-0-0").IsValidTargetType (typeof(NTAccount)));
+			Assert.IsFalse (new SecurityIdentifier ("S-1-0-0").IsValidTargetType (typeof(WindowsPrincipal)));
+			Assert.IsFalse (new SecurityIdentifier ("S-1-0-0").IsValidTargetType (typeof(WindowsIdentity)));
+		}
+
+		[Test]
+		public void IsWellKnown ()
+		{
+			Assert.IsTrue (new SecurityIdentifier ("S-1-0-0").IsWellKnown (WellKnownSidType.NullSid));
+			Assert.IsTrue (new SecurityIdentifier ("S-1-5-21-125-3215-342-500").IsWellKnown (WellKnownSidType.AccountAdministratorSid));
+			Assert.IsTrue (new SecurityIdentifier ("S-1-5-21-125-3215-342-513").IsWellKnown (WellKnownSidType.AccountDomainUsersSid));
+			Assert.IsFalse (new SecurityIdentifier ("S-1-6-21-125-3215-342-513").IsWellKnown (WellKnownSidType.AccountDomainUsersSid));
+			Assert.IsFalse (new SecurityIdentifier ("S-1-5-22-125-3215-342-513").IsWellKnown (WellKnownSidType.AccountDomainUsersSid));
+		}
+
+		[Test]
+		public void Translate ()
+		{
+			CheckWellKnownSidLookup (WellKnownSidType.NullSid, @"NULL SID");
+			CheckWellKnownSidLookup (WellKnownSidType.WorldSid, @"Everyone");
+			CheckWellKnownSidLookup (WellKnownSidType.LocalSid, @"LOCAL");
+			CheckWellKnownSidLookup (WellKnownSidType.CreatorOwnerSid, @"CREATOR OWNER");
+			CheckWellKnownSidLookup (WellKnownSidType.CreatorGroupSid, @"CREATOR GROUP");
+			CheckWellKnownSidLookup (WellKnownSidType.CreatorOwnerServerSid, @"CREATOR OWNER SERVER");
+			CheckWellKnownSidLookup (WellKnownSidType.CreatorGroupServerSid, @"CREATOR GROUP SERVER");
+			CheckWellKnownSidLookup (WellKnownSidType.DialupSid, @"NT AUTHORITY\DIALUP");
+			CheckWellKnownSidLookup (WellKnownSidType.NetworkSid, @"NT AUTHORITY\NETWORK");
+			CheckWellKnownSidLookup (WellKnownSidType.BatchSid, @"NT AUTHORITY\BATCH");
+			CheckWellKnownSidLookup (WellKnownSidType.InteractiveSid, @"NT AUTHORITY\INTERACTIVE");
+			CheckWellKnownSidLookup (WellKnownSidType.ServiceSid, @"NT AUTHORITY\SERVICE");
+			CheckWellKnownSidLookup (WellKnownSidType.AnonymousSid, @"NT AUTHORITY\ANONYMOUS LOGON");
+			CheckWellKnownSidLookup (WellKnownSidType.ProxySid, @"NT AUTHORITY\PROXY");
+			CheckWellKnownSidLookup (WellKnownSidType.EnterpriseControllersSid, @"NT AUTHORITY\ENTERPRISE DOMAIN CONTROLLERS");
+			CheckWellKnownSidLookup (WellKnownSidType.SelfSid, @"NT AUTHORITY\SELF");
+			CheckWellKnownSidLookup (WellKnownSidType.AuthenticatedUserSid, @"NT AUTHORITY\Authenticated Users");
+			CheckWellKnownSidLookup (WellKnownSidType.RestrictedCodeSid, @"NT AUTHORITY\RESTRICTED");
+			CheckWellKnownSidLookup (WellKnownSidType.TerminalServerSid, @"NT AUTHORITY\TERMINAL SERVER USER");
+			CheckWellKnownSidLookup (WellKnownSidType.RemoteLogonIdSid, @"NT AUTHORITY\REMOTE INTERACTIVE LOGON");
+			CheckWellKnownSidLookup (WellKnownSidType.LocalSystemSid, @"NT AUTHORITY\SYSTEM");
+			CheckWellKnownSidLookup (WellKnownSidType.LocalServiceSid, @"NT AUTHORITY\LOCAL SERVICE");
+			CheckWellKnownSidLookup (WellKnownSidType.NetworkServiceSid, @"NT AUTHORITY\NETWORK SERVICE");
+			CheckWellKnownSidLookup (WellKnownSidType.BuiltinAdministratorsSid, @"BUILTIN\Administrators");
+			CheckWellKnownSidLookup (WellKnownSidType.BuiltinUsersSid, @"BUILTIN\Users");
+			CheckWellKnownSidLookup (WellKnownSidType.BuiltinGuestsSid, @"BUILTIN\Guests");
+			CheckWellKnownSidLookup (WellKnownSidType.NtlmAuthenticationSid, @"NT AUTHORITY\NTLM Authentication");
+			CheckWellKnownSidLookup (WellKnownSidType.DigestAuthenticationSid, @"NT AUTHORITY\Digest Authentication");
+			CheckWellKnownSidLookup (WellKnownSidType.SChannelAuthenticationSid, @"NT AUTHORITY\SChannel Authentication");
+			CheckWellKnownSidLookup (WellKnownSidType.ThisOrganizationSid, @"NT AUTHORITY\This Organization");
+			CheckWellKnownSidLookup (WellKnownSidType.OtherOrganizationSid, @"NT AUTHORITY\Other Organization");
+			CheckWellKnownSidLookup (WellKnownSidType.BuiltinPerformanceMonitoringUsersSid, @"BUILTIN\Performance Monitor Users");
+			CheckWellKnownSidLookup (WellKnownSidType.BuiltinPerformanceLoggingUsersSid, @"BUILTIN\Performance Log Users");
+		}
+
+		[Test]
+		[ExpectedException(typeof(IdentityNotMappedException))]
+		public void TranslateUnknown ()
+		{
+			new SecurityIdentifier ("S-1-5-21-125-3215-342-513").Translate (typeof(NTAccount));
+		}
+
+		[Test]
+		public void LengthLimits ()
+		{
+			Assert.AreEqual (8, SecurityIdentifier.MinBinaryLength);
+			Assert.AreEqual (68, SecurityIdentifier.MaxBinaryLength);
+		}
+	}
+}
diff --git a/mcs/class/corlib/corlib.dll.sources b/mcs/class/corlib/corlib.dll.sources
index 3f0eda8..6a0321e 100644
--- a/mcs/class/corlib/corlib.dll.sources
+++ b/mcs/class/corlib/corlib.dll.sources
@@ -251,6 +251,7 @@ System/TimeSpan.cs
 System/TimeZone.cs
 ../System.Core/System/TimeZoneInfo.cs
 ../System.Core/System/TimeZoneInfo.AdjustmentRule.cs
+../System.Core/System/TimeZoneInfo.Android.cs
 ../System.Core/System/TimeZoneInfo.TransitionTime.cs
 System/TimeZoneNotFoundException.cs
 System/TimeoutException.cs
@@ -1219,6 +1220,7 @@ System.Security.AccessControl/RegistryAuditRule.cs
 System.Security.AccessControl/RegistryRights.cs
 System.Security.AccessControl/RegistrySecurity.cs
 System.Security.AccessControl/ResourceType.cs
+System.Security.AccessControl/SddlAccessRight.cs
 System.Security.AccessControl/SecurityInfos.cs
 System.Security.AccessControl/SystemAcl.cs
 ../System.Core/System.Security.Cryptography/Aes.cs
@@ -1422,6 +1424,7 @@ System.Security.Principal/PrincipalPolicy.cs
 System.Security.Principal/SecurityIdentifier.cs
 System.Security.Principal/TokenAccessLevels.cs
 System.Security.Principal/TokenImpersonationLevel.cs
+System.Security.Principal/WellKnownAccount.cs
 System.Security.Principal/WellKnownSidType.cs
 System.Security.Principal/WindowsAccountType.cs
 System.Security.Principal/WindowsBuiltInRole.cs
diff --git a/mcs/class/corlib/corlib_test.dll.sources b/mcs/class/corlib/corlib_test.dll.sources
index e6cdea6..e59eebd 100644
--- a/mcs/class/corlib/corlib_test.dll.sources
+++ b/mcs/class/corlib/corlib_test.dll.sources
@@ -198,6 +198,9 @@ System.Runtime.Versioning/TargetFrameworkAttributeTest.cs
 System.Runtime.Versioning/VersioningHelperTest.cs
 System/SByteTest.cs
 System.Security/CodeAccessPermissionTest.cs
+System.Security.AccessControl/CommonAceTest.cs
+System.Security.AccessControl/RawAclTest.cs
+System.Security.AccessControl/RawSecurityDescriptorTest.cs
 System.Security.Cryptography/AllTests2.cs
 System.Security.Cryptography/AsymmetricAlgorithmTest.cs
 System.Security.Cryptography/CipherModeTest.cs
@@ -331,6 +334,8 @@ System.Security.Policy/ZoneTest.cs
 System.Security.Policy/ZoneMembershipConditionTest.cs
 System.Security.Principal/GenericIdentityTest.cs
 System.Security.Principal/GenericPrincipalTest.cs
+System.Security.Principal/NTAccountTest.cs
+System.Security.Principal/SecurityIdentifierTest.cs
 System.Security.Principal/WindowsIdentityTest.cs
 System.Security.Principal/WindowsPrincipalTest.cs
 System.Security/SecureStringTest.cs
diff --git a/mcs/class/lib/monolite/Mono.Security.dll b/mcs/class/lib/monolite/Mono.Security.dll
index 52409ec..4091588 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 6fae056..67831af 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 2d48238..29fbbf2 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 e738bdd..887c341 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/mcs.exe b/mcs/class/lib/monolite/mcs.exe
index 98b9a72..3be4ac8 100755
Binary files a/mcs/class/lib/monolite/mcs.exe and b/mcs/class/lib/monolite/mcs.exe differ
diff --git a/mcs/class/lib/monolite/mscorlib.dll b/mcs/class/lib/monolite/mscorlib.dll
index eb39dc7..f9c6f2a 100755
Binary files a/mcs/class/lib/monolite/mscorlib.dll and b/mcs/class/lib/monolite/mscorlib.dll differ
diff --git a/mcs/errors/ChangeLog b/mcs/errors/ChangeLog
index 30cfa9e..692d4c8 100644
--- a/mcs/errors/ChangeLog
+++ b/mcs/errors/ChangeLog
@@ -1,3 +1,8 @@
+2011-01-24  Marek Safar  <marek.safar at gmail.com>
+
+	[666476] Use correct parameter count when checking ambiguous
+	params methods
+
 2011-01-11  Marek Safar  <marek.safar at gmail.com>
 
 	Use base type parameters to extract params modifier of virtual
diff --git a/mcs/errors/cs0121-20.cs b/mcs/errors/cs0121-20.cs
new file mode 100644
index 0000000..48af521
--- /dev/null
+++ b/mcs/errors/cs0121-20.cs
@@ -0,0 +1,18 @@
+// CS0121: The call is ambiguous between the following methods or properties: `Test.Foo(string, params object[])' and `Test.Foo(string, params int[])'
+// Line: 16
+
+public class Test
+{
+	static void Foo (string s, params object[] args)
+	{
+	}
+	
+	static void Foo (string s, params int[] args)
+	{
+	}
+	
+	public static void Main ()
+	{
+		Foo ("a");
+	}
+}
diff --git a/mcs/mcs/ChangeLog b/mcs/mcs/ChangeLog
index abc4e11..0e9999c 100644
--- a/mcs/mcs/ChangeLog
+++ b/mcs/mcs/ChangeLog
@@ -1,3 +1,115 @@
+2011-02-14  Marek Safar  <marek.safar at gmail.com>
+
+	[671552] Use correct emit method for stobj type
+
+2011-02-08  Marek Safar  <marek.safar at gmail.com>
+
+	[657099] Fix cloning of remapped blocks
+
+2011-02-08  Marek Safar  <marek.safar at gmail.com>
+
+	Fix remapping of cloned block parent when already in cloned
+	context
+
+2011-02-03  Marek Safar  <marek.safar at gmail.com>
+
+	Fix importing of private types under dynamic context
+
+2011-02-03  Marek Safar  <marek.safar at gmail.com>
+
+	Allow any expression to be used in where clause. Some custom linq
+	implementations use non-predicate version of where
+
+2011-02-02  Miguel de Icaza  <miguel at gnome.org>
+
+	[csharp] Change the signature for print
+
+2011-02-02  Marek Safar  <marek.safar at gmail.com>
+
+	Implement support for implicit user conversion for
+	DefaultParameterValue (very odd)
+
+2011-02-01  Marek Safar  <marek.safar at gmail.com>
+
+	Fix empty cast conversion from dynamic type object type argument
+
+2011-01-30  Miguel de Icaza  <miguel at gnome.org>
+
+	[repl] Fix running specified scripts from command line, allow #!
+	syntax, add print command
+
+	We were calling the Reset () method after we had initialized the
+	driver with the new command line arguments, clearing the list of
+	files to execute before we executed them.
+
+	Added support for #! in the csharp repl, and added the print()
+	command to the InteractiveBase
+
+	Add a better way of dealing with -e, without adding hacks to the
+	core that wont work in the future
+
+2011-01-30  Miguel de Icaza  <miguel at gnome.org>
+
+	[repl] Add support for -e EXPRESSION to the csharp command
+
+2011-01-30  Miguel de Icaza  <miguel at gnome.org>
+
+	[repl] Fix running specified scripts from command line, allow #!
+	syntax, add print command
+
+	We were calling the Reset () method after we had initialized the
+	driver with the new command line arguments, clearing the list of
+	files to execute before we executed them.
+
+	Added support for #! in the csharp repl, and added the print()
+	command to the InteractiveBase
+
+2011-01-27  Marek Safar  <marek.safar at gmail.com>
+
+	[667261] Fixes overload resolution of an optional parameter
+	followed by a params parameter of the same type
+
+2011-01-26  Marek Safar  <marek.safar at gmail.com>
+
+	Optimized constructor readonly access has to be inside same
+	declarting type
+
+2011-01-25  Marek Safar  <marek.safar at gmail.com>
+
+	Degrade wrong override member to virtual instead of non-virtual
+
+2011-01-24  Tomasz Kubacki  <tomasz.kubacki at gmail.com>
+
+	[Mono.CSharp] Improve error reporting
+
+2011-01-24  Marek Safar  <marek.safar at gmail.com>
+
+	[666476] Use correct parameter count when checking ambiguous
+	params methods
+
+2011-01-21  Marek Safar  <marek.safar at gmail.com>
+
+	Use byte array as underlying storage for AttributeEncoder
+
+2011-01-21  Miguel de Icaza  <miguel at gnome.org>
+
+	[Mono.CSharp] Fix bug where overwriting variables cleared the
+	wrong value
+
+	This fixes #641910
+
+2011-01-21  Miguel de Icaza  <miguel at gnome.org>
+
+	[csharp] repl using statement fix + support for --fatal
+
+	Fixes #638585 which kept reporting the same error on the using
+	statements over and over Added support for the --fatal flag to the
+	REPL
+
+2011-01-19  Marek Safar  <marek.safar at gmail.com>
+
+	[665333] Encode Length of Public Key correctly
+
 2011-01-18  Marek Safar  <marek.safar at gmail.com>
 
 	Checking skd path for is not enough, add check for mscorlib as
diff --git a/mcs/mcs/assembly.cs b/mcs/mcs/assembly.cs
index 6430c51..fc6abcb 100644
--- a/mcs/mcs/assembly.cs
+++ b/mcs/mcs/assembly.cs
@@ -448,7 +448,7 @@ namespace Mono.CSharp
 				if (pa.IsDefined && pa.ResolveBuilder ()) {
 					var prop = pa.GetProperty ("WrapNonExceptionThrows", TypeManager.bool_type, Location.Null);
 					if (prop != null) {
-						AttributeEncoder encoder = new AttributeEncoder (false);
+						AttributeEncoder encoder = new AttributeEncoder ();
 						encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (true, Location.Null));
 						SetCustomAttribute (pa.Constructor, encoder.ToArray ());
 					}
@@ -549,11 +549,11 @@ namespace Mono.CSharp
 					Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length);
 
 					// Length of Public Key (in bytes)
-					byte[] lastPart = BitConverter.GetBytes (public_key.Length - 12);
-					public_key[8] = lastPart[0];
-					public_key[9] = lastPart[1];
-					public_key[10] = lastPart[2];
-					public_key[11] = lastPart[3];
+					int lastPart = public_key.Length - 12;
+					public_key[8] = (byte) (lastPart & 0xFF);
+					public_key[9] = (byte) ((lastPart >> 8) & 0xFF);
+					public_key[10] = (byte) ((lastPart >> 16) & 0xFF);
+					public_key[11] = (byte) ((lastPart >> 24) & 0xFF);
 
 					Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length);
 				} catch {
diff --git a/mcs/mcs/attribute.cs b/mcs/mcs/attribute.cs
index e0f5a13..e19147f 100644
--- a/mcs/mcs/attribute.cs
+++ b/mcs/mcs/attribute.cs
@@ -191,6 +191,11 @@ namespace Mono.CSharp {
 			target.OptAttributes = null;
 		}
 
+		public ResolveContext CreateResolveContext ()
+		{
+			return new ResolveContext (context, ResolveContext.Options.ConstantScope);
+		}
+
 		static void Error_InvalidNamedArgument (ResolveContext rc, NamedArgument name)
 		{
 			rc.Report.Error (617, name.Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
@@ -400,7 +405,7 @@ namespace Mono.CSharp {
 				}
 			}
 
-			ResolveContext rc = new ResolveContext (context, ResolveContext.Options.ConstantScope);
+			ResolveContext rc = CreateResolveContext ();
 			ctor = ResolveConstructor (rc);
 			if (ctor == null) {
 				return null;
@@ -956,22 +961,19 @@ namespace Mono.CSharp {
 		// 
 		public bool IsExplicitLayoutKind ()
 		{
-			if (PosArguments.Count != 1)
+			if (PosArguments == null || PosArguments.Count != 1)
 				return false;
 
 			var value = (LayoutKind) System.Enum.Parse (typeof (LayoutKind), ((Constant) PosArguments[0].Expr).GetValue ().ToString ());
 			return value == LayoutKind.Explicit;
 		}
 
-		public Constant GetParameterDefaultValue (out TypeSpec type)
+		public Expression GetParameterDefaultValue ()
 		{
-			var expr = PosArguments[0].Expr;
-
-			if (expr is TypeCast)
-				expr = ((TypeCast) expr).Child;
+			if (PosArguments == null)
+				return null;
 
-			type = expr.Type;
-			return expr as Constant;
+			return PosArguments[0].Expr;
 		}
 
 		public override bool Equals (object obj)
@@ -1007,75 +1009,80 @@ namespace Mono.CSharp {
 				return;
 			}
 
-			AttributeEncoder encoder = new AttributeEncoder (false);
-
-			if (PosArguments != null) {
-				var param_types = ctor.Parameters.Types;
-				for (int j = 0; j < PosArguments.Count; ++j) {
-					var pt = param_types[j];
-					var arg_expr = PosArguments[j].Expr;
-					if (j == 0) {
-						if (Type == predefined.IndexerName || Type == predefined.Conditional) {
-							string v = ((StringConstant) arg_expr).Value;
-							if (!Tokenizer.IsValidIdentifier (v) || Tokenizer.IsKeyword (v)) {
-								context.Compiler.Report.Error (633, arg_expr.Location,
-									"The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
-							}
-						} else if (Type == predefined.Guid) {
-							try {
+			byte[] cdata;
+			if (PosArguments == null && named_values == null) {
+				cdata = AttributeEncoder.Empty;
+			} else {
+				AttributeEncoder encoder = new AttributeEncoder ();
+
+				if (PosArguments != null) {
+					var param_types = ctor.Parameters.Types;
+					for (int j = 0; j < PosArguments.Count; ++j) {
+						var pt = param_types[j];
+						var arg_expr = PosArguments[j].Expr;
+						if (j == 0) {
+							if (Type == predefined.IndexerName || Type == predefined.Conditional) {
 								string v = ((StringConstant) arg_expr).Value;
-								new Guid (v);
-							} catch (Exception e) {
-								Error_AttributeEmitError (e.Message);
-								return;
-							}
-						} else if (Type == predefined.AttributeUsage) {
-							int v = ((IntConstant)((EnumConstant) arg_expr).Child).Value;
-							if (v == 0) {
-								context.Compiler.Report.Error (591, Location, "Invalid value for argument to `{0}' attribute",
-									"System.AttributeUsage");
-							}
-						} else if (Type == predefined.MarshalAs) {
-							if (PosArguments.Count == 1) {
-								var u_type = (UnmanagedType) System.Enum.Parse (typeof (UnmanagedType), ((Constant) PosArguments[0].Expr).GetValue ().ToString ());
-								if (u_type == UnmanagedType.ByValArray && !(Owner is FieldBase)) {
-									Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
+								if (!Tokenizer.IsValidIdentifier (v) || Tokenizer.IsKeyword (v)) {
+									context.Compiler.Report.Error (633, arg_expr.Location,
+										"The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
 								}
+							} else if (Type == predefined.Guid) {
+								try {
+									string v = ((StringConstant) arg_expr).Value;
+									new Guid (v);
+								} catch (Exception e) {
+									Error_AttributeEmitError (e.Message);
+									return;
+								}
+							} else if (Type == predefined.AttributeUsage) {
+								int v = ((IntConstant) ((EnumConstant) arg_expr).Child).Value;
+								if (v == 0) {
+									context.Compiler.Report.Error (591, Location, "Invalid value for argument to `{0}' attribute",
+										"System.AttributeUsage");
+								}
+							} else if (Type == predefined.MarshalAs) {
+								if (PosArguments.Count == 1) {
+									var u_type = (UnmanagedType) System.Enum.Parse (typeof (UnmanagedType), ((Constant) PosArguments[0].Expr).GetValue ().ToString ());
+									if (u_type == UnmanagedType.ByValArray && !(Owner is FieldBase)) {
+										Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
+									}
+								}
+							} else if (Type == predefined.DllImport) {
+								if (PosArguments.Count == 1) {
+									var value = ((Constant) PosArguments[0].Expr).GetValue () as string;
+									if (string.IsNullOrEmpty (value))
+										Error_AttributeEmitError ("DllName cannot be empty");
+								}
+							} else if (Type == predefined.MethodImpl && pt == TypeManager.short_type &&
+								!System.Enum.IsDefined (typeof (MethodImplOptions), ((Constant) arg_expr).GetValue ().ToString ())) {
+								Error_AttributeEmitError ("Incorrect argument value.");
+								return;
 							}
-						} else if (Type == predefined.DllImport) {
-							if (PosArguments.Count == 1) {
-								var value = ((Constant) PosArguments[0].Expr).GetValue () as string;
-								if (string.IsNullOrEmpty (value))
-									Error_AttributeEmitError ("DllName cannot be empty");
-							}
-						} else if (Type == predefined.MethodImpl && pt == TypeManager.short_type &&
-							!System.Enum.IsDefined (typeof (MethodImplOptions), ((Constant) arg_expr).GetValue ().ToString ())) {
-							Error_AttributeEmitError ("Incorrect argument value.");
-							return;
 						}
-					}
 
-					arg_expr.EncodeAttributeValue (context, encoder, pt);
+						arg_expr.EncodeAttributeValue (context, encoder, pt);
+					}
 				}
-			}
 
-			if (named_values != null) {
-				encoder.Stream.Write ((ushort) named_values.Count);
-				foreach (var na in named_values) {
-					if (na.Key is FieldExpr)
-						encoder.Stream.Write ((byte) 0x53);
-					else
-						encoder.Stream.Write ((byte) 0x54);
-
-					encoder.Encode (na.Key.Type);
-					encoder.Encode (na.Value.Name);
-					na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type);
+				if (named_values != null) {
+					encoder.Encode ((ushort) named_values.Count);
+					foreach (var na in named_values) {
+						if (na.Key is FieldExpr)
+							encoder.Encode ((byte) 0x53);
+						else
+							encoder.Encode ((byte) 0x54);
+
+						encoder.Encode (na.Key.Type);
+						encoder.Encode (na.Value.Name);
+						na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type);
+					}
+				} else {
+					encoder.EncodeEmptyNamedArguments ();
 				}
-			} else {
-				encoder.EncodeEmptyNamedArguments ();
-			}
 
-			byte[] cdata = encoder.ToArray ();
+				cdata = encoder.ToArray ();
+			}
 
 			try {
 				foreach (Attributable target in targets)
@@ -1349,7 +1356,7 @@ namespace Mono.CSharp {
 		}
 	}
 
-	public struct AttributeEncoder
+	public sealed class AttributeEncoder
 	{
 		[Flags]
 		public enum EncodedTypeProperties
@@ -1359,101 +1366,159 @@ namespace Mono.CSharp {
 			TypeParameter = 1 << 1
 		}
 
-		const ushort Version = 1;
-
 		public static readonly byte[] Empty;
 
-		public readonly BinaryWriter Stream;
+		byte[] buffer;
+		int pos;
+		const ushort Version = 1;
 
 		static AttributeEncoder ()
 		{
 			Empty = new byte[4];
-			Array.Copy (BitConverter.GetBytes (Version), Empty, 2);
+			Empty[0] = (byte) Version;
 		}
 
-		public AttributeEncoder (bool empty)
+		public AttributeEncoder ()
 		{
-			if (empty) {
-				Stream = null;
-				return;
-			}
+			buffer = new byte[32];
+			Encode (Version);
+		}
 
-			Stream = new BinaryWriter (new MemoryStream ());
-			Stream.Write (Version);
+		public void Encode (bool value)
+		{
+			Encode (value ? (byte) 1 : (byte) 0);
 		}
 
 		public void Encode (byte value)
 		{
-			Stream.Write (value);
+			if (pos == buffer.Length)
+				Grow (1);
+
+			buffer [pos++] = value;
+		}
+
+		public void Encode (sbyte value)
+		{
+			Encode ((byte) value);
 		}
 
 		public void Encode (short value)
 		{
-			Stream.Write (value);
+			if (pos + 2 > buffer.Length)
+				Grow (2);
+
+			buffer[pos++] = (byte) value;
+			buffer[pos++] = (byte) (value >> 8);
+		}
+
+		public void Encode (ushort value)
+		{
+			Encode ((short) value);
 		}
 
 		public void Encode (int value)
 		{
-			Stream.Write (value);
+			if (pos + 4 > buffer.Length)
+				Grow (4);
+
+			buffer[pos++] = (byte) value;
+			buffer[pos++] = (byte) (value >> 8);
+			buffer[pos++] = (byte) (value >> 16);
+			buffer[pos++] = (byte) (value >> 24);
 		}
 
 		public void Encode (uint value)
 		{
-			Stream.Write (value);
+			Encode ((int) value);
+		}
+
+		public void Encode (long value)
+		{
+			if (pos + 8 > buffer.Length)
+				Grow (8);
+
+			buffer[pos++] = (byte) value;
+			buffer[pos++] = (byte) (value >> 8);
+			buffer[pos++] = (byte) (value >> 16);
+			buffer[pos++] = (byte) (value >> 24);
+			buffer[pos++] = (byte) (value >> 32);
+			buffer[pos++] = (byte) (value >> 40);
+			buffer[pos++] = (byte) (value >> 48);
+			buffer[pos++] = (byte) (value >> 56);
+		}
+
+		public void Encode (ulong value)
+		{
+			Encode ((long) value);
+		}
+
+		public void Encode (float value)
+		{
+			Encode (SingleConverter.SingleToInt32Bits (value));
+		}
+
+		public void Encode (double value)
+		{
+			Encode (BitConverter.DoubleToInt64Bits (value));
 		}
 
 		public void Encode (string value)
 		{
 			if (value == null) {
-				Stream.Write ((byte) 0xFF);
+				Encode ((byte) 0xFF);
 				return;
 			}
 
 			var buf = Encoding.UTF8.GetBytes(value);
 			WriteCompressedValue (buf.Length);
-			Stream.Write (buf);
+
+			if (pos + buf.Length > buffer.Length)
+				Grow (buf.Length);
+
+			Buffer.BlockCopy (buf, 0, buffer, pos, buf.Length);
+			pos += buf.Length;
 		}
 
 		public EncodedTypeProperties Encode (TypeSpec type)
 		{
 			if (type == TypeManager.bool_type) {
-				Stream.Write ((byte) 0x02);
+				Encode ((byte) 0x02);
 			} else if (type == TypeManager.char_type) {
-				Stream.Write ((byte) 0x03);
+				Encode ((byte) 0x03);
 			} else if (type == TypeManager.sbyte_type) {
-				Stream.Write ((byte) 0x04);
+				Encode ((byte) 0x04);
 			} else if (type == TypeManager.byte_type) {
-				Stream.Write ((byte) 0x05);
+				Encode ((byte) 0x05);
 			} else if (type == TypeManager.short_type) {
-				Stream.Write ((byte) 0x06);
+				Encode ((byte) 0x06);
 			} else if (type == TypeManager.ushort_type) {
-				Stream.Write ((byte) 0x07);
+				Encode ((byte) 0x07);
 			} else if (type == TypeManager.int32_type) {
-				Stream.Write ((byte) 0x08);
+				Encode ((byte) 0x08);
 			} else if (type == TypeManager.uint32_type) {
-				Stream.Write ((byte) 0x09);
+				Encode ((byte) 0x09);
 			} else if (type == TypeManager.int64_type) {
-				Stream.Write ((byte) 0x0A);
+				Encode ((byte) 0x0A);
 			} else if (type == TypeManager.uint64_type) {
-				Stream.Write ((byte) 0x0B);
+				Encode ((byte) 0x0B);
 			} else if (type == TypeManager.float_type) {
-				Stream.Write ((byte) 0x0C);
+				Encode ((byte) 0x0C);
 			} else if (type == TypeManager.double_type) {
-				Stream.Write ((byte) 0x0D);
+				Encode ((byte) 0x0D);
 			} else if (type == TypeManager.string_type) {
-				Stream.Write ((byte) 0x0E);
+				Encode ((byte) 0x0E);
 			} else if (type == TypeManager.type_type) {
-				Stream.Write ((byte) 0x50);
+				Encode ((byte) 0x50);
 			} else if (type == TypeManager.object_type) {
-				Stream.Write ((byte) 0x51);
+				Encode ((byte) 0x51);
 			} else if (TypeManager.IsEnumType (type)) {
-				Stream.Write ((byte) 0x55);
+				Encode ((byte) 0x55);
 				EncodeTypeName (type);
 			} else if (type.IsArray) {
-				Stream.Write ((byte) 0x1D);
+				Encode ((byte) 0x1D);
 				return Encode (TypeManager.GetElementType (type));
 			} else if (type == InternalType.Dynamic) {
-				Stream.Write ((byte) 0x51);
+				Encode ((byte) 0x51);
 				return EncodedTypeProperties.DynamicType;
 			}
 
@@ -1471,8 +1536,8 @@ namespace Mono.CSharp {
 		//
 		public void EncodeNamedPropertyArgument (PropertySpec property, Constant value)
 		{
-			Stream.Write ((ushort) 1);	// length
-			Stream.Write ((byte) 0x54); // property
+			Encode ((ushort) 1);	// length
+			Encode ((byte) 0x54); // property
 			Encode (property.MemberType);
 			Encode (property.Name);
 			value.EncodeAttributeValue (null, this, property.MemberType);
@@ -1483,8 +1548,8 @@ namespace Mono.CSharp {
 		//
 		public void EncodeNamedFieldArgument (FieldSpec field, Constant value)
 		{
-			Stream.Write ((ushort) 1);	// length
-			Stream.Write ((byte) 0x53); // field
+			Encode ((ushort) 1);	// length
+			Encode ((byte) 0x53); // field
 			Encode (field.MemberType);
 			Encode (field.Name);
 			value.EncodeAttributeValue (null, this, field.MemberType);
@@ -1492,16 +1557,16 @@ namespace Mono.CSharp {
 
 		public void EncodeNamedArguments<T> (T[] members, Constant[] values) where T : MemberSpec, IInterfaceMemberSpec
 		{
-			Stream.Write ((ushort) members.Length);
+			Encode ((ushort) members.Length);
 
 			for (int i = 0; i < members.Length; ++i)
 			{
 				var member = members[i];
 
 				if (member.Kind == MemberKind.Field)
-					Stream.Write ((byte) 0x53);
+					Encode ((byte) 0x53);
 				else if (member.Kind == MemberKind.Property)
-					Stream.Write ((byte) 0x54);
+					Encode ((byte) 0x54);
 				else
 					throw new NotImplementedException (member.Kind.ToString ());
 
@@ -1513,28 +1578,36 @@ namespace Mono.CSharp {
 
 		public void EncodeEmptyNamedArguments ()
 		{
-			Stream.Write ((ushort) 0);
+			Encode ((ushort) 0);
+		}
+
+		void Grow (int inc)
+		{
+			int size = System.Math.Max (pos * 4, pos + inc + 2);
+			Array.Resize (ref buffer, size);
 		}
 
 		void WriteCompressedValue (int value)
 		{
 			if (value < 0x80) {
-				Stream.Write ((byte) value);
+				Encode ((byte) value);
 				return;
 			}
 
 			if (value < 0x4000) {
-				Stream.Write ((byte) (0x80 | (value >> 8)));
-				Stream.Write ((byte) value);
+				Encode ((byte) (0x80 | (value >> 8)));
+				Encode ((byte) value);
 				return;
 			}
 
-			Stream.Write (value);
+			Encode (value);
 		}
 
 		public byte[] ToArray ()
 		{
-			return ((MemoryStream) Stream.BaseStream).ToArray ();
+			byte[] buf = new byte[pos];
+			Array.Copy (buffer, buf, pos);
+			return buf;
 		}
 	}
 
@@ -1904,7 +1977,7 @@ namespace Mono.CSharp {
 				return;
 
 			int[] bits = decimal.GetBits (value);
-			AttributeEncoder encoder = new AttributeEncoder (false);
+			AttributeEncoder encoder = new AttributeEncoder ();
 			encoder.Encode ((byte) (bits[3] >> 16));
 			encoder.Encode ((byte) (bits[3] >> 31));
 			encoder.Encode ((uint) bits[2]);
@@ -1924,7 +1997,7 @@ namespace Mono.CSharp {
 				return;
 
 			int[] bits = decimal.GetBits (value);
-			AttributeEncoder encoder = new AttributeEncoder (false);
+			AttributeEncoder encoder = new AttributeEncoder ();
 			encoder.Encode ((byte) (bits[3] >> 16));
 			encoder.Encode ((byte) (bits[3] >> 31));
 			encoder.Encode ((uint) bits[2]);
diff --git a/mcs/mcs/class.cs b/mcs/mcs/class.cs
index ca5e9ba..7c8a05e 100644
--- a/mcs/mcs/class.cs
+++ b/mcs/mcs/class.cs
@@ -1632,7 +1632,7 @@ namespace Mono.CSharp {
 				!pa.ResolveConstructor (Location, TypeManager.string_type))
 				return;
 
-			var encoder = new AttributeEncoder (false);
+			var encoder = new AttributeEncoder ();
 			encoder.Encode (GetAttributeDefaultMember ());
 			encoder.EncodeEmptyNamedArguments ();
 
diff --git a/mcs/mcs/codegen.cs b/mcs/mcs/codegen.cs
index 662c07e..8b15c9c 100644
--- a/mcs/mcs/codegen.cs
+++ b/mcs/mcs/codegen.cs
@@ -563,7 +563,7 @@ namespace Mono.CSharp
 			else if (type == TypeManager.intptr_type)
 				ig.Emit (OpCodes.Stind_I);
 			else if (TypeManager.IsStruct (type) || TypeManager.IsGenericParameter (type))
-				ig.Emit (OpCodes.Stobj, type.GetMetaInfo ());
+				Emit (OpCodes.Stobj, type);
 			else
 				ig.Emit (OpCodes.Stind_Ref);
 		}
diff --git a/mcs/mcs/constant.cs b/mcs/mcs/constant.cs
index d9fdbfc..7d6fe94 100644
--- a/mcs/mcs/constant.cs
+++ b/mcs/mcs/constant.cs
@@ -352,7 +352,7 @@ namespace Mono.CSharp {
 
 		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 		{
-			enc.Stream.Write (Value);
+			enc.Encode (Value);
 		}
 		
 		public override void Emit (EmitContext ec)
@@ -397,7 +397,7 @@ namespace Mono.CSharp {
 
 		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 		{
-			enc.Stream.Write (Value);
+			enc.Encode (Value);
 		}
 
 		public override void Emit (EmitContext ec)
@@ -502,7 +502,7 @@ namespace Mono.CSharp {
 
 		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 		{
-			enc.Stream.Write ((ushort) Value);
+			enc.Encode ((ushort) Value);
 		}
 
 		public override void Emit (EmitContext ec)
@@ -626,7 +626,7 @@ namespace Mono.CSharp {
 
 		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 		{
-			enc.Stream.Write (Value);
+			enc.Encode (Value);
 		}
 
 		public override void Emit (EmitContext ec)
@@ -732,7 +732,7 @@ namespace Mono.CSharp {
 
 		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 		{
-			enc.Stream.Write (Value);
+			enc.Encode (Value);
 		}
 
 		public override void Emit (EmitContext ec)
@@ -850,7 +850,7 @@ namespace Mono.CSharp {
 
 		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 		{
-			enc.Stream.Write (Value);
+			enc.Encode (Value);
 		}
 
 		public override void Emit (EmitContext ec)
@@ -962,7 +962,7 @@ namespace Mono.CSharp {
 
 		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 		{
-			enc.Stream.Write (Value);
+			enc.Encode (Value);
 		}
 
 		public override void Emit (EmitContext ec)
@@ -1143,7 +1143,7 @@ namespace Mono.CSharp {
 
 		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 		{
-			enc.Stream.Write (Value);
+			enc.Encode (Value);
 		}
 
 		public override void Emit (EmitContext ec)
@@ -1266,7 +1266,7 @@ namespace Mono.CSharp {
 
 		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 		{
-			enc.Stream.Write (Value);
+			enc.Encode (Value);
 		}
 
 		public override void Emit (EmitContext ec)
@@ -1405,7 +1405,7 @@ namespace Mono.CSharp {
 
 		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 		{
-			enc.Stream.Write (Value);
+			enc.Encode (Value);
 		}
 
 		public override void Emit (EmitContext ec)
@@ -1522,7 +1522,7 @@ namespace Mono.CSharp {
 
 		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 		{
-			enc.Stream.Write (Value);
+			enc.Encode (Value);
 		}
 
 		public override void Emit (EmitContext ec)
@@ -1645,7 +1645,7 @@ namespace Mono.CSharp {
 
 		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 		{
-			enc.Stream.Write (Value);
+			enc.Encode (Value);
 		}
 
 		public override void Emit (EmitContext ec)
@@ -2004,9 +2004,9 @@ namespace Mono.CSharp {
 				if (ac.Rank != 1 || ac.Element.IsArray)
 					base.EncodeAttributeValue (rc, enc, targetType);
 				else
-					enc.Stream.Write (uint.MaxValue);
+					enc.Encode (uint.MaxValue);
 			} else {
-				enc.Stream.Write (byte.MaxValue);
+				enc.Encode (byte.MaxValue);
 			}
 		}
 
diff --git a/mcs/mcs/convert.cs b/mcs/mcs/convert.cs
index eeedfd2..9e49dcd 100644
--- a/mcs/mcs/convert.cs
+++ b/mcs/mcs/convert.cs
@@ -1370,8 +1370,12 @@ namespace Mono.CSharp {
 			if (expr_type == InternalType.Arglist && target_type == TypeManager.arg_iterator_type)
 				return expr;
 
-			if (TypeSpecComparer.IsEqual (expr_type, target_type))
-				return expr;
+			if (TypeSpecComparer.IsEqual (expr_type, target_type)) {
+				if (expr_type == target_type)
+					return expr;
+
+				return EmptyCast.Create (expr, target_type);
+			}
 
 			return null;
 		}
diff --git a/mcs/mcs/cs-parser.jay b/mcs/mcs/cs-parser.jay
index 3cb0479..4a1267b 100644
--- a/mcs/mcs/cs-parser.jay
+++ b/mcs/mcs/cs-parser.jay
@@ -1552,7 +1552,7 @@ fixed_parameter
 		lbag.AddLocation ($$, GetLocation ($5));
 		
 		if ($7 != null)
-			((Parameter) $$).DefaultValue = (Expression) $7;
+			((Parameter) $$).DefaultValue = new DefaultParameterValueExpression ((Expression) $7);
 	  }
 	;
 
@@ -5661,9 +5661,9 @@ where_clause
 	  {
 	  	current_block = new Linq.QueryBlock (compiler, current_block, lexer.Location);
 	  }
-	  boolean_expression
+	  expression
 	  {
-		$$ = new Linq.Where ((Linq.QueryBlock)current_block, (BooleanExpression)$3, GetLocation ($1));
+		$$ = new Linq.Where ((Linq.QueryBlock)current_block, (Expression)$3, GetLocation ($1));
 
 		current_block.SetEndLocation (lexer.Location);
 		current_block = current_block.Parent;
diff --git a/mcs/mcs/driver.cs b/mcs/mcs/driver.cs
index 47b075e..c76e066 100644
--- a/mcs/mcs/driver.cs
+++ b/mcs/mcs/driver.cs
@@ -47,11 +47,11 @@ namespace Mono.CSharp
 			this.ctx = ctx;
 		}
 
-		public static Driver Create (string[] args, bool require_files, ReportPrinter printer)
+		public static Driver Create (string[] args, bool require_files, Func<string [], int, int> unknown_option_parser, ReportPrinter printer)
 		{
 			Driver d = new Driver (new CompilerContext (new Report (printer)));
 
-			if (!d.ParseArguments (args, require_files))
+			if (!d.ParseArguments (args, require_files, unknown_option_parser))
 				return null;
 
 			return d;
@@ -234,7 +234,7 @@ namespace Mono.CSharp
 		{
 			Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
 			var crp = new ConsoleReportPrinter ();
-			Driver d = Driver.Create (args, true, crp);
+			Driver d = Driver.Create (args, true, null, crp);
 			if (d == null)
 				return 1;
 
@@ -341,7 +341,7 @@ namespace Mono.CSharp
 			Location.AddFile (Report, f);
 		}
 
-		bool ParseArguments (string[] args, bool require_files)
+		bool ParseArguments (string[] args, bool require_files, Func<string [], int, int> unknown_option_parser)
 		{
 			List<string> response_file_list = null;
 			bool parsing_options = true;
@@ -393,6 +393,14 @@ namespace Mono.CSharp
 						if (CSCParseOption (csc_opt, ref args))
 							continue;
 
+						if (unknown_option_parser != null){
+							var ret = unknown_option_parser (args, i);
+							if (ret != -1){
+								i = ret;
+								return true;
+							}
+						}
+						
 						Error_WrongOption (arg);
 						return false;
 					}
@@ -1619,7 +1627,7 @@ namespace Mono.CSharp
 		{
 			try {
 				StreamReportPrinter srp = new StreamReportPrinter (error);
-				Driver d = Driver.Create (args, true, srp);
+				Driver d = Driver.Create (args, true, null, srp);
 				if (d == null)
 					return false;
 
@@ -1649,7 +1657,7 @@ namespace Mono.CSharp
 		{
 			CSharpParser.yacc_verbose_flag = 0;
 			Location.Reset ();
-
+			
 			if (!full_flag)
 				return;
 
diff --git a/mcs/mcs/ecore.cs b/mcs/mcs/ecore.cs
index 8a94833..1fc2efa 100644
--- a/mcs/mcs/ecore.cs
+++ b/mcs/mcs/ecore.cs
@@ -1986,7 +1986,7 @@ namespace Mono.CSharp {
 	//
 	public abstract class CompositeExpression : Expression
 	{
-		Expression expr;
+		protected Expression expr;
 
 		protected CompositeExpression (Expression expr)
 		{
@@ -3688,7 +3688,7 @@ namespace Mono.CSharp {
 			var best_def_pd = ((IParametersMember) best.MemberDefinition).Parameters;
 
 			bool specific_at_least_once = false;
-			for (j = 0; j < candidate_param_count; ++j) {
+			for (j = 0; j < args_count; ++j) {
 				NamedArgument na = args_count == 0 ? null : args [j] as NamedArgument;
 				if (na != null) {
 					ct = candidate_def_pd.Types[cparam.GetParameterIndexByName (na.Name)];
@@ -3750,20 +3750,18 @@ namespace Mono.CSharp {
 					}
 				}
 
-				int args_gap = System.Math.Abs (arg_count - param_count);
 				if (optional_count != 0) {
-					if (args_gap > optional_count)
-						return int.MaxValue - 10000 + args_gap - optional_count;
-
 					// Readjust expected number when params used
 					if (cpd.HasParams) {
 						optional_count--;
 						if (arg_count < param_count)
 							param_count--;
 					} else if (arg_count > param_count) {
+						int args_gap = System.Math.Abs (arg_count - param_count);
 						return int.MaxValue - 10000 + args_gap;
 					}
 				} else if (arg_count != param_count) {
+					int args_gap = System.Math.Abs (arg_count - param_count);
 					if (!cpd.HasParams)
 						return int.MaxValue - 10000 + args_gap;
 					if (arg_count < param_count - 1)
@@ -5156,7 +5154,7 @@ namespace Mono.CSharp {
 			bool need_copy;
 			if (spec.IsReadOnly){
 				need_copy = true;
-				if (ec.HasSet (EmitContext.Options.ConstructorScope)){
+				if (ec.HasSet (EmitContext.Options.ConstructorScope) && spec.DeclaringType == ec.CurrentType) {
 					if (IsStatic){
 						if (ec.IsStatic)
 							need_copy = false;
diff --git a/mcs/mcs/eval.cs b/mcs/mcs/eval.cs
index 6a69761..3ca4723 100644
--- a/mcs/mcs/eval.cs
+++ b/mcs/mcs/eval.cs
@@ -92,6 +92,11 @@ namespace Mono.CSharp
 			return ctx.Report.SetPrinter (report_printer);
 		}				
 
+		public static string [] InitAndGetStartupFiles (string [] args)
+		{
+			return InitAndGetStartupFiles (args, null);
+		}
+
 		/// <summary>
 		///   Optional initialization for the Evaluator.
 		/// </summary>
@@ -108,20 +113,27 @@ namespace Mono.CSharp
 		///
 		///  This method return an array of strings that contains any
 		///  files that were specified in `args'.
+		///
+		///  If the unknownOptionParser is not null, this function is invoked
+		///  with the current args array and the index of the option that is not
+		///  known.  A value of true means that the value was processed, otherwise
+		///  it will be reported as an error
 		/// </remarks>
-		public static string [] InitAndGetStartupFiles (string [] args)
+		public static string [] InitAndGetStartupFiles (string [] args, Func<string [], int, int> unknownOptionParser)
 		{
 			lock (evaluator_lock){
 				if (inited)
 					return new string [0];
-				
-				driver = Driver.Create (args, false, new ConsoleReportPrinter ());
+
+				CompilerCallableEntryPoint.Reset ();
+				var crp = new ConsoleReportPrinter ();
+				driver = Driver.Create (args, false, unknownOptionParser, crp);
 				if (driver == null)
 					throw new Exception ("Failed to create compiler driver with the given arguments");
 
+				crp.Fatal = driver.fatal_errors;
 				ctx = driver.ctx;
 
-				CompilerCallableEntryPoint.Reset ();
 				RootContext.ToplevelTypes = new ModuleContainer (ctx);
 				
 				var startup_files = new List<string> ();
@@ -189,6 +201,9 @@ namespace Mono.CSharp
 			if (type == null)
 				throw new ArgumentNullException ();
 
+			if (!inited)
+				throw new Exception ("Evaluator has to be initiated before seting custom InteractiveBase class");
+
 			lock (evaluator_lock)
 				interactive_base_class = loader.Importer.ImportType (type);
 		}
@@ -240,7 +255,7 @@ namespace Mono.CSharp
 				compiled = null;
 				return null;
 			}
-			
+
 			lock (evaluator_lock){
 				if (!inited)
 					Init ();
@@ -264,10 +279,12 @@ namespace Mono.CSharp
 				
 				if (!(parser_result is Class)){
 					int errors = ctx.Report.Errors;
-					
+
 					NamespaceEntry.VerifyAllUsing ();
 					if (errors == ctx.Report.Errors)
 						parser.CurrentNamespace.Extract (using_alias_list, using_list);
+					else
+						NamespaceEntry.Reset ();
 				}
 
 #if STATIC
@@ -768,7 +785,7 @@ namespace Mono.CSharp
 						}
 					}
 
-					fields [field.Name] = Tuple.Create (old.Item1, fi);
+					fields [field.Name] = Tuple.Create (field.Spec, fi);
 				} else {
 					fields.Add (field.Name, Tuple.Create (field.Spec, fi));
 				}
@@ -1037,6 +1054,16 @@ namespace Mono.CSharp
 		{
 			Evaluator.LoadAssembly (assembly);
 		}
+
+		static public void print (string obj)
+		{
+			Output.WriteLine (obj);
+		}
+
+		static public void print (string fmt, params object [] args)
+		{
+			Output.WriteLine (fmt, args);
+		}
 #endif
 		
 		/// <summary>
@@ -1053,6 +1080,7 @@ namespace Mono.CSharp
 					"  Prompt                  - The prompt used by the C# shell\n" +
 					"  ContinuationPrompt      - The prompt for partial input\n" +
 					"  Time(() -> { })         - Times the specified code\n" +
+					"  print (obj)             - Shorthand for Console.WriteLine\n" +
 					"  quit;                   - You'll never believe it - this quits the repl!\n" +
 					"  help;                   - This help text\n";
 			}
diff --git a/mcs/mcs/expression.cs b/mcs/mcs/expression.cs
index e115f8c..b6296a2 100644
--- a/mcs/mcs/expression.cs
+++ b/mcs/mcs/expression.cs
@@ -6609,13 +6609,13 @@ namespace Mono.CSharp
 				if (ic == null || !ic.IsDefaultValue) {
 					base.EncodeAttributeValue (rc, enc, targetType);
 				} else {
-					enc.Stream.Write (0);
+					enc.Encode (0);
 				}
 
 				return;
 			}
 
-			enc.Stream.Write ((int) array_data.Count);
+			enc.Encode (array_data.Count);
 			foreach (var element in array_data) {
 				element.EncodeAttributeValue (rc, enc, array_element_type);
 			}
diff --git a/mcs/mcs/field.cs b/mcs/mcs/field.cs
index 4026d96..27cbc4a 100644
--- a/mcs/mcs/field.cs
+++ b/mcs/mcs/field.cs
@@ -477,7 +477,7 @@ namespace Mono.CSharp
 
 			var char_set = CharSet ?? Module.DefaultCharSet;
 
-			encoder = new AttributeEncoder (false);
+			encoder = new AttributeEncoder ();
 			encoder.Encode ((short)LayoutKind.Sequential);
 			encoder.EncodeNamedArguments (
 				new [] { field_size, field_charset },
@@ -496,7 +496,7 @@ namespace Mono.CSharp
 			if (pa.Constructor == null && !pa.ResolveConstructor (Location, TypeManager.type_type, TypeManager.int32_type))
 				return;
 
-			encoder = new AttributeEncoder (false);
+			encoder = new AttributeEncoder ();
 			encoder.EncodeTypeName (MemberType);
 			encoder.Encode (buffer_size);
 			encoder.EncodeEmptyNamedArguments ();
diff --git a/mcs/mcs/import.cs b/mcs/mcs/import.cs
index 84276a6..9f44f12 100644
--- a/mcs/mcs/import.cs
+++ b/mcs/mcs/import.cs
@@ -394,6 +394,7 @@ namespace Mono.CSharp
 					const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
 					if (candidate == null || (candidate.Modifiers & conflict_mask) != (mod & conflict_mask) || candidate.IsStatic) {
 						mod &= ~Modifiers.OVERRIDE;
+						mod |= Modifiers.VIRTUAL;
 					}
 				}
 			}
@@ -1789,7 +1790,7 @@ namespace Mono.CSharp
 					var t = (MetaType) member;
 
 					// Ignore compiler generated types, mostly lambda containers
-					if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate)
+					if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
 						continue;
 
 					imported = importer.CreateNestedType (t, declaringType);
@@ -1802,7 +1803,7 @@ namespace Mono.CSharp
 
 					var t = (MetaType) member;
 
-					if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate)
+					if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
 						continue;
 
 					importer.ImportTypeBase (t);
diff --git a/mcs/mcs/linq.cs b/mcs/mcs/linq.cs
index afda915..8d3f05b 100644
--- a/mcs/mcs/linq.cs
+++ b/mcs/mcs/linq.cs
@@ -349,8 +349,6 @@ namespace Mono.CSharp.Linq
 
 		public Expression CreateReferenceExpression (ResolveContext rc, Location loc)
 		{
-			Expression expr = null;
-
 			// 
 			// We know the variable name is somewhere in the scope. This generates
 			// an access expression from current block
@@ -363,6 +361,7 @@ namespace Mono.CSharp.Linq
 						if (p.Name == Name)
 							return pb.GetParameterReference (i, loc);
 
+						Expression expr = null;
 						var tp = p as QueryBlock.TransparentParameter;
 						while (tp != null) {
 							if (expr == null)
@@ -379,8 +378,6 @@ namespace Mono.CSharp.Linq
 							tp = tp.Parent as QueryBlock.TransparentParameter;
 						}
 					}
-
-					expr = null;
 				}
 
 				if (pb == block)
@@ -644,7 +641,7 @@ namespace Mono.CSharp.Linq
 
 	public class Where : AQueryClause
 	{
-		public Where (QueryBlock block, BooleanExpression expr, Location loc)
+		public Where (QueryBlock block, Expression expr, Location loc)
 			: base (block, expr, loc)
 		{
 		}
diff --git a/mcs/mcs/parameter.cs b/mcs/mcs/parameter.cs
index 7ccda1d..2485974 100644
--- a/mcs/mcs/parameter.cs
+++ b/mcs/mcs/parameter.cs
@@ -247,15 +247,28 @@ namespace Mono.CSharp {
 
 		#region Properties
 
-		public Expression DefaultValue {
+		public DefaultParameterValueExpression DefaultValue {
 			get {
-				return default_expr;
+				return default_expr as DefaultParameterValueExpression;
 			}
 			set {
 				default_expr = value;
 			}
 		}
 
+		Expression IParameterData.DefaultValue {
+			get {
+				var expr = default_expr as DefaultParameterValueExpression;
+				return expr == null ? default_expr : expr.Child;
+			}
+		}
+
+		bool HasOptionalExpression {
+			get {
+				return default_expr is DefaultParameterValueExpression;
+			}
+		}
+
 		public Location Location {
 			get {
 				return loc;
@@ -305,35 +318,15 @@ namespace Mono.CSharp {
 				a.Report.Warning (3022, 1, a.Location, "CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead");
 			}
 
-			if (HasDefaultValue && (a.Type == pa.DefaultParameterValue || a.Type == pa.OptionalParameter)) {
-				a.Report.Error (1745, a.Location,
-					"Cannot specify `{0}' attribute on optional parameter `{1}'",
-					TypeManager.CSharpName (a.Type).Replace ("Attribute", ""), Name);
-				return;
-			}
-
-			if (a.Type == pa.DefaultParameterValue) {
-				TypeSpec arg_type;
-				var c = a.GetParameterDefaultValue (out arg_type);
-				if (c == null) {
-					if (parameter_type == TypeManager.object_type) {
-						a.Report.Error (1910, a.Location, "Argument of type `{0}' is not applicable for the DefaultParameterValue attribute",
-							arg_type.GetSignatureForError ());
-					} else {
-						a.Report.Error (1909, a.Location, "The DefaultParameterValue attribute is not applicable on parameters of type `{0}'",
-							parameter_type.GetSignatureForError ()); ;
-					}
-
-					return;
+			if (a.Type == pa.DefaultParameterValue || a.Type == pa.OptionalParameter) {
+				if (HasOptionalExpression) {
+					a.Report.Error (1745, a.Location,
+						"Cannot specify `{0}' attribute on optional parameter `{1}'",
+						TypeManager.CSharpName (a.Type).Replace ("Attribute", ""), Name);
 				}
 
-				if (arg_type == parameter_type || parameter_type == TypeManager.object_type || 
-					(c.IsNull && TypeManager.IsReferenceType (parameter_type) && !TypeManager.IsGenericParameter (parameter_type)))
-					builder.SetConstant (c.GetValue ());
-				else
-					a.Report.Error (1908, a.Location, "The type of the default value should match the type of the parameter");
-
-				return;
+				if (a.Type == pa.DefaultParameterValue)
+					return;
 			}
 
 			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
@@ -402,87 +395,72 @@ namespace Mono.CSharp {
 			// Default value was specified using an expression
 			//
 			if (default_expr != null) {
-				default_expr = ResolveDefaultExpression (rc);
+				((DefaultParameterValueExpression)default_expr).Resolve (rc, this);
 				return;
 			}
 
 			if (attributes == null)
 				return;
 			
-			var pa = attributes.Search (rc.Module.PredefinedAttributes.OptionalParameter);
-			if (pa == null)
-				return;
-
-			//
-			// Default value was specified using an attribute
-			//
-			attributes.Attrs.Remove (pa);
-
-			TypeSpec expr_type = null;
-			pa = attributes.Search (rc.Module.PredefinedAttributes.DefaultParameterValue);
-			if (pa != null) {
-				attributes.Attrs.Remove (pa);
-				default_expr = pa.GetParameterDefaultValue (out expr_type);
-			} else {
-				default_expr = EmptyExpression.MissingValue;
-			}
-
-			if (default_expr == null) {
-				if (expr_type == null)
-					expr_type = parameter_type;
-
-				default_expr = new DefaultValueExpression (new TypeExpression (expr_type, Location), Location);
-			}
-
-			default_expr = default_expr.Resolve (rc);
-		}
-
-		Expression ResolveDefaultExpression (ResolveContext rc)
-		{
-			default_expr = default_expr.Resolve (rc);
-			if (default_expr == null)
-				return null;
+			var opt_attr = attributes.Search (rc.Module.PredefinedAttributes.OptionalParameter);
+			var def_attr = attributes.Search (rc.Module.PredefinedAttributes.DefaultParameterValue);
+			if (def_attr != null) {
+				if (def_attr.Resolve () == null)
+					return;
 
-			if (!(default_expr is Constant || default_expr is DefaultValueExpression || (default_expr is New && ((New)default_expr).IsDefaultStruct))) {
-				rc.Compiler.Report.Error (1736, default_expr.Location,
-					"The expression being assigned to optional parameter `{0}' must be a constant or default value",
-					Name);
+				var default_expr_attr = def_attr.GetParameterDefaultValue ();
+				if (default_expr_attr == null)
+					return;
 
-				return null;
-			}
+				var dpa_rc = def_attr.CreateResolveContext ();
+				default_expr = default_expr_attr.Resolve (dpa_rc);
 
-			if (default_expr.Type == parameter_type)
-				return default_expr;
+				if (default_expr is BoxedCast)
+					default_expr = ((BoxedCast) default_expr).Child;
 
-			var res = Convert.ImplicitConversionStandard (rc, default_expr, parameter_type, default_expr.Location);
-			if (res != null) {
-				if (TypeManager.IsNullableType (parameter_type) && res is Nullable.Wrap) {
-					Nullable.Wrap wrap = (Nullable.Wrap) res;
-					res = wrap.Child;
-					if (!(res is Constant)) {
-						rc.Compiler.Report.Error (1770, default_expr.Location,
-							"The expression being assigned to nullable optional parameter `{0}' must be default value",
-							Name);
-						return null;
+				Constant c = default_expr as Constant;
+				if (c == null) {
+					if (parameter_type == TypeManager.object_type) {
+						rc.Compiler.Report.Error (1910, default_expr.Location,
+							"Argument of type `{0}' is not applicable for the DefaultParameterValue attribute",
+							default_expr.Type.GetSignatureForError ());
+					} else {
+						rc.Compiler.Report.Error (1909, default_expr.Location,
+							"The DefaultParameterValue attribute is not applicable on parameters of type `{0}'",
+							default_expr.Type.GetSignatureForError ()); ;
 					}
-				}
 
-				if (!default_expr.IsNull && TypeManager.IsReferenceType (parameter_type) && parameter_type != TypeManager.string_type) {
-					rc.Compiler.Report.Error (1763, default_expr.Location,
-						"Optional parameter `{0}' of type `{1}' can only be initialized with `null'",
-						Name, GetSignatureForError ());
+					default_expr = null;
+					return;
+				}
 
-					return null;
+				if (TypeSpecComparer.IsEqual (default_expr.Type, parameter_type) ||
+					(default_expr is NullConstant && TypeManager.IsReferenceType (parameter_type) && !parameter_type.IsGenericParameter) ||
+					TypeSpecComparer.IsEqual (parameter_type, TypeManager.object_type)) {
+					return;
 				}
 
-				return res;
+				//
+				// LAMESPEC: Some really weird csc behaviour which we have to mimic
+				// User operators returning same type as parameter type are considered
+				// valid for this attribute only
+				//
+				// struct S { public static implicit operator S (int i) {} }
+				//
+				// void M ([DefaultParameterValue (3)]S s)
+				//
+				var expr = Convert.ImplicitUserConversion (dpa_rc, default_expr, parameter_type, loc);
+				if (expr != null && TypeSpecComparer.IsEqual (expr.Type, parameter_type)) {
+					return;
+				}
+				
+				rc.Compiler.Report.Error (1908, default_expr.Location, "The type of the default value should match the type of the parameter");
+				return;
 			}
 
-			rc.Compiler.Report.Error (1750, Location,
-				"Optional parameter expression of type `{0}' cannot be converted to parameter type `{1}'",
-				TypeManager.CSharpName (default_expr.Type), GetSignatureForError ());
-
-			return null;
+			if (opt_attr != null) {
+				default_expr = EmptyExpression.MissingValue;
+			}
 		}
 
 		public bool HasDefaultValue {
@@ -514,11 +492,6 @@ namespace Mono.CSharp {
 			set { name = value; }
 		}
 
-		ParameterAttributes Attributes {
-			get { return ParametersCompiled.GetParameterAttribute (modFlags) |
-				(HasDefaultValue ? ParameterAttributes.Optional : ParameterAttributes.None); }
-		}
-
 		public override AttributeTargets AttributeTargets {
 			get {
 				return AttributeTargets.Parameter;
@@ -570,10 +543,14 @@ namespace Mono.CSharp {
 			if (builder != null)
 				throw new InternalErrorException ("builder already exists");
 
+			var pattrs = ParametersCompiled.GetParameterAttribute (modFlags);
+			if (HasOptionalExpression)
+				pattrs |= ParameterAttributes.Optional;
+
 			if (mb == null)
-				builder = cb.DefineParameter (index, Attributes, Name);
+				builder = cb.DefineParameter (index, pattrs, Name);
 			else
-				builder = mb.DefineParameter (index, Attributes, Name);
+				builder = mb.DefineParameter (index, pattrs, Name);
 
 			if (OptAttributes != null)
 				OptAttributes.Emit ();
@@ -583,7 +560,8 @@ namespace Mono.CSharp {
 				// Emit constant values for true constants only, the other
 				// constant-like expressions will rely on default value expression
 				//
-				Constant c = default_expr as Constant;
+				var def_value = DefaultValue;
+				Constant c = def_value != null ? def_value.Child as Constant : default_expr as Constant;
 				if (c != null) {
 					if (default_expr.Type == TypeManager.decimal_type) {
 						pa.DecimalConstant.EmitAttribute (builder, (decimal) c.GetValue (), c.Location);
@@ -1209,4 +1187,74 @@ namespace Mono.CSharp {
 			return p;
 		}
 	}
+
+	//
+	// Default parameter value expression. We need this wrapper to handle
+	// default parameter values of folded constants when for indexer parameters
+	// The expression is resolved only once but applied to two methods which
+	// both share reference to this expression and we ensure that resolving
+	// this expression always returns same instance
+	//
+	public class DefaultParameterValueExpression : CompositeExpression
+	{
+		public DefaultParameterValueExpression (Expression expr)
+			: base (expr)
+		{
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			return base.DoResolve (rc);
+		}
+
+		public void Resolve (ResolveContext rc, Parameter p)
+		{
+			var expr = Resolve (rc);
+			if (expr == null)
+				return;
+
+			expr = Child;
+
+			if (!(expr is Constant || expr is DefaultValueExpression || (expr is New && ((New) expr).IsDefaultStruct))) {
+				rc.Compiler.Report.Error (1736, Location,
+					"The expression being assigned to optional parameter `{0}' must be a constant or default value",
+					p.Name);
+
+				return;
+			}
+
+			var parameter_type = p.Type;
+			if (type == parameter_type)
+				return;
+
+			var res = Convert.ImplicitConversionStandard (rc, expr, parameter_type, Location);
+			if (res != null) {
+				if (TypeManager.IsNullableType (parameter_type) && res is Nullable.Wrap) {
+					Nullable.Wrap wrap = (Nullable.Wrap) res;
+					res = wrap.Child;
+					if (!(res is Constant)) {
+						rc.Compiler.Report.Error (1770, Location,
+							"The expression being assigned to nullable optional parameter `{0}' must be default value",
+							p.Name);
+						return;
+					}
+				}
+
+				if (!expr.IsNull && TypeManager.IsReferenceType (parameter_type) && parameter_type != TypeManager.string_type) {
+					rc.Compiler.Report.Error (1763, Location,
+						"Optional parameter `{0}' of type `{1}' can only be initialized with `null'",
+						p.Name, parameter_type.GetSignatureForError ());
+
+					return;
+				}
+
+				this.expr = res;
+				return;
+			}
+
+			rc.Compiler.Report.Error (1750, Location,
+				"Optional parameter expression of type `{0}' cannot be converted to parameter type `{1}'",
+				type.GetSignatureForError (), parameter_type.GetSignatureForError ());
+		}
+	}
 }
diff --git a/mcs/mcs/reflection.cs b/mcs/mcs/reflection.cs
index a34b9d7..e7158b6 100644
--- a/mcs/mcs/reflection.cs
+++ b/mcs/mcs/reflection.cs
@@ -184,6 +184,22 @@ namespace Mono.CSharp
 		}
 	}
 
+	[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Explicit)]
+	struct SingleConverter
+	{
+		[System.Runtime.InteropServices.FieldOffset (0)]
+		int i;
+		[System.Runtime.InteropServices.FieldOffset (0)]
+		float f;
+
+		public static int SingleToInt32Bits (float v)
+		{
+			SingleConverter c = new SingleConverter ();
+			c.f = v;
+			return c.i;
+		}
+	}
+
 #endif
 
 	public class AssemblyDefinitionDynamic : AssemblyDefinition
diff --git a/mcs/mcs/roottypes.cs b/mcs/mcs/roottypes.cs
index 245a6d7..d8dd1a8 100644
--- a/mcs/mcs/roottypes.cs
+++ b/mcs/mcs/roottypes.cs
@@ -73,7 +73,7 @@ namespace Mono.CSharp
 
 					var pa = Module.PredefinedAttributes.StructLayout;
 					if (pa.Constructor != null || pa.ResolveConstructor (Location, TypeManager.short_type)) {
-						var argsEncoded = new AttributeEncoder (false);
+						var argsEncoded = new AttributeEncoder ();
 						argsEncoded.Encode ((short) LayoutKind.Explicit);
 
 						var field_size = pa.GetField ("Size", TypeManager.int32_type, Location);
diff --git a/mcs/mcs/statement.cs b/mcs/mcs/statement.cs
index a639157..5488cd9 100644
--- a/mcs/mcs/statement.cs
+++ b/mcs/mcs/statement.cs
@@ -87,13 +87,6 @@ namespace Mono.CSharp {
 			ec.Report.Error (834, loc, "A lambda expression with statement body cannot be converted to an expresion tree");
 			return null;
 		}
-
-		public Statement PerformClone ()
-		{
-			CloneContext clonectx = new CloneContext ();
-
-			return Clone (clonectx);
-		}
 	}
 
 	public sealed class EmptyStatement : Statement
@@ -2111,6 +2104,8 @@ namespace Mono.CSharp {
 #endif
 
 			clonectx.AddBlockMap (this, target);
+			if (original != this)
+				clonectx.AddBlockMap (original, target);
 
 			target.ParametersBlock = (ParametersBlock) (ParametersBlock == this ? target : clonectx.RemapBlockCopy (ParametersBlock));
 			target.Explicit = (ExplicitBlock) (Explicit == this ? target : clonectx.LookupBlock (Explicit));
@@ -2512,6 +2507,12 @@ namespace Mono.CSharp {
 			return new ParameterReference (parameter_info[index], loc);
 		}
 
+		public Statement PerformClone ()
+		{
+			CloneContext clonectx = new CloneContext ();
+			return Clone (clonectx);
+		}
+
 		protected void ProcessParameters ()
 		{
 			if (parameters.Count == 0)
diff --git a/mcs/tests/ChangeLog b/mcs/tests/ChangeLog
index b4bb440..708e6c6 100644
--- a/mcs/tests/ChangeLog
+++ b/mcs/tests/ChangeLog
@@ -1,3 +1,8 @@
+2011-01-26  Marek Safar  <marek.safar at gmail.com>
+
+	Optimized constructor readonly access has to be inside same
+	declarting type
+
 2011-01-08  Marek Safar  <marek.safar at gmail.com>
 
 	Test update
diff --git a/mcs/tests/gtest-551.cs b/mcs/tests/gtest-551.cs
new file mode 100644
index 0000000..694398e
--- /dev/null
+++ b/mcs/tests/gtest-551.cs
@@ -0,0 +1,27 @@
+using System;
+
+class Base<T> where T : new ()
+{
+	protected readonly T field = new T ();
+}
+
+class Derived<T> : Base<T> where T : ICloneable, new ()
+{
+	public Derived()
+	{
+		field.Clone();
+	}
+}
+
+class C : ICloneable
+{
+	public object Clone ()
+	{
+		return null;
+	}
+	
+	public static void Main ()
+	{
+		var a = new Derived<C> ();
+	}
+}
\ No newline at end of file
diff --git a/mcs/tools/csharp/ChangeLog b/mcs/tools/csharp/ChangeLog
index d0d1050..f425397 100644
--- a/mcs/tools/csharp/ChangeLog
+++ b/mcs/tools/csharp/ChangeLog
@@ -1,3 +1,38 @@
+2011-01-30  Miguel de Icaza  <miguel at gnome.org>
+
+	[repl] Fix running specified scripts from command line, allow #!
+	syntax, add print command
+
+	We were calling the Reset () method after we had initialized the
+	driver with the new command line arguments, clearing the list of
+	files to execute before we executed them.
+
+	Added support for #! in the csharp repl, and added the print()
+	command to the InteractiveBase
+
+	Add a better way of dealing with -e, without adding hacks to the
+	core that wont work in the future
+
+2011-01-30  Miguel de Icaza  <miguel at gnome.org>
+
+	[repl] Add support for -e EXPRESSION to the csharp command
+
+2011-01-30  Miguel de Icaza  <miguel at gnome.org>
+
+	[repl] Fix running specified scripts from command line, allow #!
+	syntax, add print command
+
+	We were calling the Reset () method after we had initialized the
+	driver with the new command line arguments, clearing the list of
+	files to execute before we executed them.
+
+	Added support for #! in the csharp repl, and added the print()
+	command to the InteractiveBase
+
+2011-01-21  Miguel de Icaza  <miguel at gnome.org>
+
+	[getline] Fix history search in the cmdline editor
+
 2010-05-08  Daniel Nauck <dna at mono-project.de>
 
 	* csharp.sln: enable build for jay project in Debug|Win32 configuration.
diff --git a/mcs/tools/csharp/ChangeLog b/mcs/tools/csharp/ChangeLog.old
similarity index 100%
copy from mcs/tools/csharp/ChangeLog
copy to mcs/tools/csharp/ChangeLog.old
diff --git a/mcs/tools/csharp/getline.cs b/mcs/tools/csharp/getline.cs
index 63ff480..f259f73 100644
--- a/mcs/tools/csharp/getline.cs
+++ b/mcs/tools/csharp/getline.cs
@@ -1033,7 +1033,7 @@ namespace Mono.Terminal {
 
 			public void Dump ()
 			{
-				Console.WriteLine ("Head={0} Tail={1} Cursor={2}", head, tail, cursor);
+				Console.WriteLine ("Head={0} Tail={1} Cursor={2} count={3}", head, tail, cursor, count);
 				for (int i = 0; i < history.Length;i++){
 					Console.WriteLine (" {0} {1}: {2}", i == cursor ? "==>" : "   ", i, history[i]);
 				}
@@ -1042,21 +1042,16 @@ namespace Mono.Terminal {
 
 			public string SearchBackward (string term)
 			{
-				for (int i = 1; i < count; i++){
-					int slot = cursor-i;
+				for (int i = 0; i < count; i++){
+					int slot = cursor-i-1;
 					if (slot < 0)
-						slot = history.Length-1;
+						slot = history.Length+slot;
+					if (slot >= history.Length)
+						slot = 0;
 					if (history [slot] != null && history [slot].IndexOf (term) != -1){
 						cursor = slot;
 						return history [slot];
 					}
-
-					// Will the next hit tail?
-					slot--;
-					if (slot < 0)
-						slot = history.Length-1;
-					if (slot == tail)
-						break;
 				}
 
 				return null;
@@ -1069,7 +1064,7 @@ namespace Mono.Terminal {
 	class Demo {
 		static void Main ()
 		{
-			LineEditor le = new LineEditor (null);
+			LineEditor le = new LineEditor ("foo");
 			string s;
 			
 			while ((s = le.Edit ("shell> ", "")) != null){
diff --git a/mcs/tools/csharp/repl.cs b/mcs/tools/csharp/repl.cs
index 5137fcb..3796410 100644
--- a/mcs/tools/csharp/repl.cs
+++ b/mcs/tools/csharp/repl.cs
@@ -32,6 +32,7 @@ using Mono.CSharp;
 namespace Mono {
 
 	public class Driver {
+		public static string StartupEvalExpression;
 		
 		static int Main (string [] args)
 		{
@@ -53,15 +54,24 @@ namespace Mono {
 		{
 			string[] startup_files;
 			try {
-				startup_files = Evaluator.InitAndGetStartupFiles (args);
+				startup_files = Evaluator.InitAndGetStartupFiles (args, HandleExtraArguments);
 				Evaluator.DescribeTypeExpressions = true;
 				Evaluator.SetInteractiveBaseClass (typeof (InteractiveBaseShell));
 			} catch {
 				return 1;
 			}
-
 			return new CSharpShell ().Run (startup_files);
 		}
+
+		static int HandleExtraArguments (string [] args, int pos)
+		{
+			if (args [pos] == "-e" && pos+1 < args.Length){
+				StartupEvalExpression = args [pos+1];
+				return pos+1;
+			}
+			return -1;
+		}
+		
 	}
 
 	public class InteractiveBaseShell : InteractiveBase {
@@ -173,7 +183,7 @@ namespace Mono {
 			Evaluate ("using System; using System.Linq; using System.Collections.Generic; using System.Collections;");
 		}
 
-		void InitTerminal ()
+		void InitTerminal (bool show_banner)
 		{
 #if ON_DOTNET
 			is_unix = false;
@@ -195,7 +205,7 @@ namespace Mono {
 //			Report.Stderr = Console.Out;
 			SetupConsole ();
 
-			if (isatty)
+			if (isatty && show_banner)
 				Console.WriteLine ("Mono C# Shell, type \"help;\" for help\n\nEnter statements below.");
 
 		}
@@ -205,8 +215,17 @@ namespace Mono {
 			foreach (string file in sources){
 				try {
 					try {
+						bool first = true;
+			
 						using (System.IO.StreamReader r = System.IO.File.OpenText (file)){
-							ReadEvalPrintLoopWith (p => r.ReadLine ());
+							ReadEvalPrintLoopWith (p => {
+								var line = r.ReadLine ();
+								if (first && line.StartsWith ("#!")){
+									line = r.ReadLine ();
+									first = false;
+								}
+								return line;
+							});
 						}
 					} catch (FileNotFoundException){
 						Console.Error.WriteLine ("cs2001: Source file `{0}' not found", file);
@@ -265,18 +284,21 @@ namespace Mono {
 		public int ReadEvalPrintLoop ()
 		{
 			if (startup_files != null && startup_files.Length == 0)
-				InitTerminal ();
+				InitTerminal (startup_files.Length == 0 && Driver.StartupEvalExpression == null);
 
 			InitializeUsing ();
 
 			LoadStartupFiles ();
 
-			//
-			// Interactive or startup files provided?
-			//
 			if (startup_files.Length != 0)
 				ExecuteSources (startup_files, false);
-			else
+			else if (Driver.StartupEvalExpression != null){
+				ReadEvalPrintLoopWith (p => {
+					var ret = Driver.StartupEvalExpression;
+					Driver.StartupEvalExpression = null;
+					return ret;
+					});
+			} else
 				ReadEvalPrintLoopWith (GetLine);
 
 			return 0;
diff --git a/mcs/tools/mono-service/ChangeLog b/mcs/tools/mono-service/ChangeLog
index c22a1ee..1ddc884 100644
--- a/mcs/tools/mono-service/ChangeLog
+++ b/mcs/tools/mono-service/ChangeLog
@@ -1,3 +1,9 @@
+2011-01-31  Bit Diff  <lists at bitdiff.com>
+
+	Fixes #527447 whereby it was not possible to pass additional
+	arguments to mono-service2 (if your executable required
+	command-line arguments of it's own).
+
 2008-02-08  Jonathan Pryor  <pryorj at novell.com>
 
 	* mono-service.cs: The return value of UnixSignal.WaitAny() changed; cope.
diff --git a/mcs/tools/mono-service/ChangeLog b/mcs/tools/mono-service/ChangeLog.old
similarity index 100%
copy from mcs/tools/mono-service/ChangeLog
copy to mcs/tools/mono-service/ChangeLog.old
diff --git a/mcs/tools/mono-service/mono-service.cs b/mcs/tools/mono-service/mono-service.cs
index a59e4d7..35c9da0 100644
--- a/mcs/tools/mono-service/mono-service.cs
+++ b/mcs/tools/mono-service/mono-service.cs
@@ -9,6 +9,7 @@
  * (C) 2005 Novell Inc
  */
 using System;
+using System.Collections.Generic;
 using System.IO;
 using System.Reflection;
 using Mono.Unix;
@@ -20,6 +21,7 @@ using System.Runtime.InteropServices;
 class MonoServiceRunner : MarshalByRefObject
 {
 	string assembly, name, logname;
+	string[] args;
 	
 	static void info (string prefix, string format, params object [] args)
 	{
@@ -55,6 +57,7 @@ class MonoServiceRunner : MarshalByRefObject
 		string lockfile = null;
 		string name = null;
 		string logname = null;
+		var assebmlyArgs = new List<string>();
 
 		foreach (string s in args){
 			if (s.Length > 3 && s [0] == '-' && s [2] == ':'){
@@ -69,9 +72,13 @@ class MonoServiceRunner : MarshalByRefObject
 				}
 			} else {
 				if (assembly != null)
-					Usage ();
-				
-				assembly = s;
+				{
+					assebmlyArgs.Add(s);
+				}
+				else
+				{
+					assembly = s;
+				}
 			}
 		}
 
@@ -131,7 +138,7 @@ class MonoServiceRunner : MarshalByRefObject
 				true,
 				BindingFlags.Default,
 				null,
-				new object [] {assembly, name, logname},
+				new object [] {assembly, name, logname, assebmlyArgs.ToArray()},
 				null, null, null) as MonoServiceRunner;
 				
 			if (rnr == null) {
@@ -147,11 +154,12 @@ class MonoServiceRunner : MarshalByRefObject
 		}
 	}
 	
-	public MonoServiceRunner (string assembly, string name, string logname)
+	public MonoServiceRunner (string assembly, string name, string logname, string[] args)
 	{
 		this.assembly = assembly;
 		this.name = name;
 		this.logname = logname;
+		this.args = args;
 	}
 	
 	public int StartService ()
@@ -196,7 +204,7 @@ class MonoServiceRunner : MarshalByRefObject
 			
 			// And run its Main. Our RunService handler is invoked from 
 			// ServiceBase.Run.
-			return AppDomain.CurrentDomain.ExecuteAssembly (assembly, AppDomain.CurrentDomain.Evidence);
+			return AppDomain.CurrentDomain.ExecuteAssembly (assembly, AppDomain.CurrentDomain.Evidence, args);
 			
 		} catch ( Exception ex ) {
 			for (Exception e = ex; e != null; e = e.InnerException) {
diff --git a/mcs/tools/xbuild/ChangeLog b/mcs/tools/xbuild/ChangeLog
index dde8f5c..8bdd2fa 100644
--- a/mcs/tools/xbuild/ChangeLog
+++ b/mcs/tools/xbuild/ChangeLog
@@ -1,3 +1,26 @@
+2011-01-21  Ankit Jain  <radical at corewars.org>
+
+	* tools/xbuild/xbuild/Microsoft.CSharp.targets: $(CscToolExe) is
+	set depending on the value of $(TargetFrameworkVersion). Since,
+	$(TargetFrameworkVersion)'s default value is set by
+	MS.Common.targets, set $(CscToolExe) *after* importing
+	MS.Common.targets .
+
+2011-01-20  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Fix bug #665637.
+
+	Pass $(WarningsNotAsErrors) to Csc task.
+
+2011-01-19  Ankit Jain  <radical at corewars.org>
+
+	* tools/xbuild/Parameters.cs (DisplayVersion): Remove, not
+	required.
+
+2011-01-14  Ankit Jain  <radical at corewars.org>
+
+	[xbuild] Update Novell copyright.
+
 2011-01-14  Ankit Jain  <radical at corewars.org>
 
 	[xbuild] Add $(TargetDir) property.
diff --git a/mcs/tools/xbuild/ErrorUtilities.cs b/mcs/tools/xbuild/ErrorUtilities.cs
index 78c078b..06ca453 100644
--- a/mcs/tools/xbuild/ErrorUtilities.cs
+++ b/mcs/tools/xbuild/ErrorUtilities.cs
@@ -35,7 +35,7 @@ namespace Mono.XBuild.CommandLine {
 		static string[] version = {
 			String.Format ("XBuild Engine Version {0}", Consts.MonoVersion),
 			String.Format ("Mono, Version {0}", Consts.MonoVersion),
-			"Copyright (C) Marek Sieradzki 2005-2008, Novell 2008-2009.",
+			"Copyright (C) Marek Sieradzki 2005-2008, Novell 2008-2011.",
 		};
 
 		
diff --git a/mcs/tools/xbuild/Main.cs b/mcs/tools/xbuild/Main.cs
index 88fc1b7..0038477 100644
--- a/mcs/tools/xbuild/Main.cs
+++ b/mcs/tools/xbuild/Main.cs
@@ -76,7 +76,7 @@ namespace Mono.XBuild.CommandLine {
 				show_stacktrace = (parameters.LoggerVerbosity == LoggerVerbosity.Detailed ||
 					parameters.LoggerVerbosity == LoggerVerbosity.Diagnostic);
 				
-				if (parameters.DisplayVersion)
+				if (!parameters.NoLogo)
 					ErrorUtilities.ShowVersion (false);
 				
 				engine  = Engine.GlobalEngine;
diff --git a/mcs/tools/xbuild/Parameters.cs b/mcs/tools/xbuild/Parameters.cs
index beabc9f..6932907 100644
--- a/mcs/tools/xbuild/Parameters.cs
+++ b/mcs/tools/xbuild/Parameters.cs
@@ -43,7 +43,6 @@ namespace Mono.XBuild.CommandLine {
 	
 		string			consoleLoggerParameters;
 		bool			displayHelp;
-		bool			displayVersion;
 		IList			flatArguments;
 		IList			loggers;
 		LoggerVerbosity		loggerVerbosity;
@@ -64,7 +63,6 @@ namespace Mono.XBuild.CommandLine {
 		{
 			consoleLoggerParameters = "";
 			displayHelp = false;
-			displayVersion = true;
 			loggers = new ArrayList ();
 			loggerVerbosity = LoggerVerbosity.Normal;
 			noConsoleLogger = false;
@@ -354,10 +352,6 @@ namespace Mono.XBuild.CommandLine {
 			get { return noLogo; }
 		}
 		
-		public bool DisplayVersion {
-			get { return displayVersion; }
-		}
-		
 		public string ProjectFile {
 			get { return projectFile; }
 		}
diff --git a/mcs/tools/xbuild/xbuild/Microsoft.CSharp.targets b/mcs/tools/xbuild/xbuild/Microsoft.CSharp.targets
index 9840130..1580106 100644
--- a/mcs/tools/xbuild/xbuild/Microsoft.CSharp.targets
+++ b/mcs/tools/xbuild/xbuild/Microsoft.CSharp.targets
@@ -14,12 +14,6 @@
 		<CreateManifestResourceNamesDependsOn></CreateManifestResourceNamesDependsOn>
 		<CoreCompileDependsOn></CoreCompileDependsOn>
 
-		<CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(OS)' != 'Windows_NT'">gmcs</CscToolExe>
-		<CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(OS)' == 'Windows_NT'">gmcs.bat</CscToolExe>
-
-		<CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.0' and '$(OS)' != 'Windows_NT'">dmcs</CscToolExe>
-		<CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.0' and '$(OS)' == 'Windows_NT'">dmcs.bat</CscToolExe>
-
 		<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildToolsPath)\Microsoft.CSharp.targets</MSBuildAllProjects>
 	</PropertyGroup>
 
@@ -71,6 +65,7 @@
 			Utf8Output="$(Utf8Output)"
 			WarningLevel="$(WarningLevel)"
 			WarningsAsErrors="$(WarningsAsErrors)"
+			WarningsNotAsErrors="$(WarningsNotAsErrors)"
 			Win32Icon="$(Win32Icon)"
 			Win32Resource="$(Win32Resource)"
 			Resources="@(ManifestResourceWithNoCulture);@(ManifestNonResxWithNoCultureOnDisk);@(CompiledLicenseFile)"
@@ -102,4 +97,13 @@
 	</Target>
 
 	<Import Project="Microsoft.Common.targets" />
+
+	<PropertyGroup>
+		<CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(OS)' != 'Windows_NT'">gmcs</CscToolExe>
+		<CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(OS)' == 'Windows_NT'">gmcs.bat</CscToolExe>
+
+		<CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.0' and '$(OS)' != 'Windows_NT'">dmcs</CscToolExe>
+		<CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.0' and '$(OS)' == 'Windows_NT'">dmcs.bat</CscToolExe>
+	</PropertyGroup>
+
 </Project>
diff --git a/mono-core.spec.in b/mono-core.spec.in
index 77716f5..c79ee34 100644
--- a/mono-core.spec.in
+++ b/mono-core.spec.in
@@ -350,6 +350,7 @@ A Library for embedding Mono in your Application (sgen version).
 %files -n libmonosgen-2_0-0
 %defattr(-, root, root)
 %_libdir/libmonosgen-2.0.so.0*
+%_libdir/pkgconfig/monosgen-2.pc
 
 %post -n libmonosgen-2_0-0 -p /sbin/ldconfig
 
@@ -483,6 +484,7 @@ Database connectivity for Mono.
 %_prefix/lib/mono/4.0/System.EnterpriseServices.dll
 %_prefix/lib/mono/4.0/System.Runtime.Serialization.dll
 %_prefix/lib/mono/4.0/System.Transactions.dll
+%_prefix/lib/mono/4.0/WebMatrix.Data.dll
 %_prefix/lib/mono/4.0/sqlmetal.exe*
 %_prefix/lib/mono/4.0/sqlsharp.exe*
 %_prefix/lib/mono/gac/Mono.Data.Tds
@@ -494,6 +496,7 @@ Database connectivity for Mono.
 %_prefix/lib/mono/gac/System.EnterpriseServices
 %_prefix/lib/mono/gac/System.Runtime.Serialization
 %_prefix/lib/mono/gac/System.Transactions
+%_prefix/lib/mono/gac/WebMatrix.Data
 
 %package -n mono-winforms
 License:        LGPL v2.1 only
@@ -702,7 +705,9 @@ Mono implementation of core WinFX APIs
 
 %files -n mono-winfxcore
 %defattr(-, root, root)
+%_prefix/lib/mono/2.0/System.Data.Services.Client.dll*
 %_prefix/lib/mono/2.0/WindowsBase.dll*
+%_prefix/lib/mono/4.0/System.Data.Services.Client.dll*
 %_prefix/lib/mono/4.0/WindowsBase.dll*
 %_prefix/lib/mono/gac/System.Data.Services.Client
 %_prefix/lib/mono/gac/WindowsBase
@@ -766,6 +771,7 @@ Mono implementation of ASP.NET, Remoting and Web Services.
 %_prefix/lib/mono/2.0/System.Web.dll
 %_prefix/lib/mono/2.0/wsdl.exe*
 %_prefix/lib/mono/2.0/xsd.exe*
+%_prefix/lib/mono/4.0/Microsoft.Web.Infrastructure.dll
 %_prefix/lib/mono/4.0/Mono.Http.dll
 %_prefix/lib/mono/4.0/Mono.Web.dll
 %_prefix/lib/mono/4.0/System.ComponentModel.Composition.dll
@@ -782,6 +788,7 @@ Mono implementation of ASP.NET, Remoting and Web Services.
 %_prefix/lib/mono/4.0/soapsuds.exe*
 %_prefix/lib/mono/4.0/wsdl.exe*
 %_prefix/lib/mono/4.0/xsd.exe*
+%_prefix/lib/mono/gac/Microsoft.Web.Infrastructure
 %_prefix/lib/mono/gac/Mono.Http
 %_prefix/lib/mono/gac/Mono.Web
 %_prefix/lib/mono/gac/System.ComponentModel.Composition
@@ -1080,6 +1087,7 @@ Mono development tools.
 %_prefix/lib/mono/4.0/Microsoft.Common.tasks
 %_prefix/lib/mono/4.0/Microsoft.VisualBasic.targets
 %_prefix/lib/mono/4.0/Mono.CodeContracts.dll
+%_prefix/lib/mono/4.0/Mono.Debugger.Soft.dll
 %_prefix/lib/mono/4.0/PEAPI.dll
 %_prefix/lib/mono/4.0/caspol.exe*
 %_prefix/lib/mono/4.0/ccrewrite.exe*
diff --git a/mono/io-layer/ChangeLog b/mono/io-layer/ChangeLog
index f442535..4296c36 100644
--- a/mono/io-layer/ChangeLog
+++ b/mono/io-layer/ChangeLog
@@ -1,3 +1,16 @@
+2011-02-07  Hib Eris  <hib at hiberis.nl>
+
+	Remove implementation details from public header io-layer.h
+
+	The macro HAVE_GETPROCESSID is defined in config.h and should not
+	be exposed in public headers.
+
+2011-01-26  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Prevent abort
+
+	When cleaning up the sockets we no longer have access to Tls.
+
 2011-01-05  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
 
 	[sockets] Fixed reading blocking flag
diff --git a/mono/io-layer/io-layer.h b/mono/io-layer/io-layer.h
index e6af1c6..57ef8db 100644
--- a/mono/io-layer/io-layer.h
+++ b/mono/io-layer/io-layer.h
@@ -31,17 +31,6 @@
 #if (_WIN32_WINNT < 0x0502)
 #undef GetProcessId
 #endif
-#ifndef HAVE_GETPROCESSID
-#ifdef _MSC_VER
-#include <winternl.h>
-#ifndef NT_SUCCESS
-#define NT_SUCCESS(status) ((NTSTATUS) (status) >= 0)
-#endif /* !NT_SUCCESS */
-#else /* !_MSC_VER */
-#include <ddk/ntddk.h>
-#include <ddk/ntapi.h>
-#endif /* _MSC_VER */
-#endif /* !HAVE_GETPROCESSID */
 #else	/* EVERYONE ELSE */
 #include "mono/io-layer/wapi.h"
 #include "mono/io-layer/uglify.h"
diff --git a/mono/io-layer/sockets.c b/mono/io-layer/sockets.c
index c068f06..28601fc 100644
--- a/mono/io-layer/sockets.c
+++ b/mono/io-layer/sockets.c
@@ -54,6 +54,7 @@
 #undef DEBUG
 
 static guint32 startup_count=0;
+static guint32 in_cleanup = 0;
 
 static void socket_close (gpointer handle, gpointer data);
 
@@ -82,7 +83,7 @@ static void socket_close (gpointer handle, gpointer data)
 	g_message ("%s: closing socket handle %p", __func__, handle);
 #endif
 
-	if (startup_count == 0) {
+	if (startup_count == 0 && !in_cleanup) {
 		WSASetLastError (WSANOTINITIALISED);
 		return;
 	}
@@ -103,10 +104,12 @@ static void socket_close (gpointer handle, gpointer data)
 		g_message ("%s: close error: %s", __func__, strerror (errno));
 #endif
 		errnum = errno_to_WSA (errnum, __func__);
-		WSASetLastError (errnum);
+		if (!in_cleanup)
+			WSASetLastError (errnum);
 	}
 
-	socket_handle->saved_error = 0;
+	if (!in_cleanup)
+		socket_handle->saved_error = 0;
 }
 
 int WSAStartup(guint32 requested, WapiWSAData *data)
@@ -156,7 +159,9 @@ int WSACleanup(void)
 		return(0);
 	}
 
+	in_cleanup = 1;
 	_wapi_handle_foreach (WAPI_HANDLE_SOCKET, cleanup_close, NULL);
+	in_cleanup = 0;
 	return(0);
 }
 
diff --git a/mono/metadata/ChangeLog b/mono/metadata/ChangeLog
index 7c438f2..d84c31a 100644
--- a/mono/metadata/ChangeLog
+++ b/mono/metadata/ChangeLog
@@ -1,3 +1,229 @@
+2011-02-13  Mark Probst  <mark.probst at gmail.com>
+
+	[sgen] Register the main_thread as a GC root. Fixes shutdown
+	crashes.
+
+2011-02-13  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix reading of cattr arguments of type Type[]. Fixes #670331.
+
+2011-02-12  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix token generation for TypeBuilder's in another assembly. Fixes
+	#671245.
+
+2011-02-09  Hib Eris  <hib at hiberis.nl>
+
+	Earlier undefine HAVE_GETPROCESSID when cross compiling
+
+2011-02-11  Zoltan Varga  <vargaz at gmail.com>
+
+	Make the wait in the finalizer thread alertable to fix sdb on
+	windows. Fixes #670619.
+
+2011-02-09  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	Handle assignment check of variant type and its gtd.
+
+2011-02-09  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	* gc.c (finalize_domain_objects): Clear reference queues on domain
+	unload after running all finalizers.
+
+2011-02-08  Miguel de Icaza  <miguel at gnome.org>
+
+	Update docs
+
+2011-02-03  Miguel de Icaza  <miguel at gnome.org>
+
+	Add prototype to .h file
+
+2011-01-31  Lucas Meijer  <lucas at unity3d.com>
+
+	implement mono_set_assemblies_path for platforms that cannot set
+	MONO_PATH environment variable.
+
+2011-02-08  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	* gc.c (finalizer_thread): Clean reference queues after finalizers
+	are called to give boehm a chance to resurrect it.
+
+2011-02-07  Hib Eris  <hib at hiberis.nl>
+
+	Use winternl.h instead of ddk (when available)
+
+	These changes are nescessary for compiling with a mingw-w64
+	compiler.
+
+2011-02-07  Hib Eris  <hib at hiberis.nl>
+
+	Remove implementation details from public header io-layer.h
+
+	The macro HAVE_GETPROCESSID is defined in config.h and should not
+	be exposed in public headers.
+
+2011-02-07  Zoltan Varga  <vargaz at gmail.com>
+
+	Use mono_method_get_vtable_slot () instead of accessing
+	method->slot directly. Fixes #669808.
+
+2011-02-03  Zoltan Varga  <vargaz at gmail.com>
+
+	Add support for --debug=casts to Array:SetValue (). Fixes #668851.
+
+2011-02-03  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix a warning.
+
+2011-02-02  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	* gc.c (mono_gc_cleanup): Cleanup all reference queues after
+	regular finalization.
+
+	* reflection.c: The dynamic method ref queue is finalized by the
+	runtime itself.
+
+	* runtime.c: Ditto.
+
+2011-02-01  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	* reflection.c: Use a reference queue to cleanup dynamic methods
+	instead of finalization.
+
+	* runtime.c: Shutdown the dynamic method queue before runtime
+	cleanup begins.
+
+	* icall-def.h: Remove unused dynamic method icall.
+
+	Fixes #660422
+
+2011-02-01  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	* gc.c: A reference queue allows one to queue callbcks for when
+	objects are collected. It allows for safe cleanup of objects that
+	can only be done when it is effectively collected. The major
+	difference with regular finalization is that the collector makes
+	sure the object was collected - and can't be resurrected.
+
+	* gc-internal.h: Export entrypoints for the new API.
+
+2011-02-01  Zoltan Varga  <vargaz at gmail.com>
+
+	Make caching in mono_marshal_get_virtual_stelemref () thread-safe.
+	Fixes #668489.
+
+2011-01-31  Marek Habersack  <grendel at twistedcode.net>
+
+	[runtime] AddWatcher icall must look up the path in an IOMAP-aware
+	way
+
+2011-01-29  Marek Habersack  <grendel at twistedcode.net>
+
+	[runtime] Use IOAMP-aware method of looking for domain
+	configuration file
+
+2011-01-30  Jo Shields  <directhex at apebox.org>
+
+	Really fix sgen on PowerPC Linux. Assembler on Linux requires that
+	register names are just bare numbers, unlike OSX, i.e. "r0" must
+	be "0" on Linux.
+
+2011-01-29  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Typo
+
+2011-01-28  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Avoid a crash when shutting down jit attached threads
+
+2011-01-28  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Ensure we setup the vtable before accessing it
+
+2011-01-27  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix AOT support for types in the EXPORTEDTYPE table.
+
+2011-01-27  Zoltan Varga  <vargaz at gmail.com>
+
+	Applied patch from Burkhard Linke
+	<blinke at cebitec.uni-bielefeld.de>. Add support for newer boehm-gc
+	versions.
+
+2011-01-26  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	* marshal.c (mono_marshal_get_delegate_invoke): If the target is a
+	static method with first arg bound and it belongs to a different
+	assembly than the delegate we might end up with a freed signature
+	in the hashtable.
+
+	Fix a moonlight crash.
+
+2011-01-24  Mark Probst  <mark.probst at gmail.com>
+
+	[sgen] Don't assert when on Android.
+
+2011-01-20  Mark Probst  <mark.probst at gmail.com>
+
+	[sgen] Make the second bridge DFS pass use an implicit stack to
+	avoid stack overflow.
+
+2011-01-19  Mark Probst  <mark.probst at gmail.com>
+
+	[sgen] Use an explicit stack instead of recursion for the first
+	DFS pass in the bridge code.
+
+2011-01-19  Mark Probst  <mark.probst at gmail.com>
+
+	[build] pkg-config support for libmonosgen.
+
+2011-01-16  Mark Probst  <mark.probst at gmail.com>
+
+	[sgen] Bridge cross references pass.
+
+	This is an extension for the benefit of the Mono/Java bridge on
+	MonoDroid. We go through all finalizable objects and report the
+	strongly connected components of bridge objects and their
+	connections between each other.
+
+2011-01-24  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Avoid leaking the vmmap allocated by the kernel for the
+	thread_act_array_t
+
+2011-01-24  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Fix a mach port leak
+
+2011-01-21  Bassam Tabbara  <bassam at symform.com>
+
+	Fix for 666225
+
+2011-01-21  Zoltan Varga  <vargaz at gmail.com>
+
+	Transition non perf-critical users of klass->has_finalize over to
+	mono_class_has_finalizer ().
+
+2011-01-21  Zoltan Varga  <vargaz at gmail.com>
+
+	Initialize klass->has_finalizer lazily. This allows us to remove
+	the find_method_in_metadata () optimization without a perf cost
+	which is broken in the presence of overrides. Fixes #665769.
+
+2011-01-20  Jb Evain  <jbevain at gmail.com>
+
+	[bug] Prevent a GetMethodBody call on a dynamic method. Fixes
+	665788
+
+2011-01-19  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	* sgen-gc.c (finish_gray_stack): We must clear weak refs that
+	don't track resurrection before processing finalizable objects
+	otherwise we'll copy/mark them and the weak ref won't be cleared
+	until after finalization.
+
+	Fixes #657408
+
 2011-01-18  Zoltan Varga  <vargaz at gmail.com>
 
 	Disable some of the FastCopy fast paths since they are racy.
diff --git a/mono/metadata/Makefile.am b/mono/metadata/Makefile.am
index 0b767a4..83c50ca 100644
--- a/mono/metadata/Makefile.am
+++ b/mono/metadata/Makefile.am
@@ -191,6 +191,8 @@ libmonoruntime_la_SOURCES = \
 	sgen-major-copying.c	\
 	sgen-los.c		\
 	sgen-protocol.c \
+	sgen-bridge.c		\
+	sgen-bridge.h		\
 	sgen-gc.h		\
 	sgen-archdep.h		\
 	sgen-cardtable.h	\
@@ -253,6 +255,7 @@ libmonoruntimeinclude_HEADERS = \
 	mono-config.h		\
 	mono-debug.h		\
 	mono-gc.h		\
+	sgen-bridge.h		\
 	object.h		\
 	opcodes.h		\
 	profiler.h		\
diff --git a/mono/metadata/Makefile.in b/mono/metadata/Makefile.in
index 6e0f53a..a0b4cac 100644
--- a/mono/metadata/Makefile.in
+++ b/mono/metadata/Makefile.in
@@ -80,13 +80,14 @@ am__libmonoruntime_static_la_SOURCES_DIST = console-unix.c \
 	security-manager.h sgen-os-posix.c sgen-os-mach.c sgen-gc.c \
 	sgen-internal.c sgen-marksweep.c sgen-marksweep-fixed.c \
 	sgen-marksweep-par.c sgen-marksweep-fixed-par.c \
-	sgen-major-copying.c sgen-los.c sgen-protocol.c sgen-gc.h \
-	sgen-archdep.h sgen-cardtable.h sgen-major-copy-object.h \
-	sgen-major-scan-object.h sgen-protocol.h sgen-scan-object.h \
-	string-icalls.c string-icalls.h sysmath.h sysmath.c \
-	tabledefs.h threads.c threads-types.h threadpool.c \
-	threadpool.h threadpool-internals.h verify.c \
-	verify-internals.h wrapper-types.h
+	sgen-major-copying.c sgen-los.c sgen-protocol.c sgen-bridge.c \
+	sgen-bridge.h sgen-gc.h sgen-archdep.h sgen-cardtable.h \
+	sgen-major-copy-object.h sgen-major-scan-object.h \
+	sgen-protocol.h sgen-scan-object.h string-icalls.c \
+	string-icalls.h sysmath.h sysmath.c tabledefs.h threads.c \
+	threads-types.h threadpool.c threadpool.h \
+	threadpool-internals.h verify.c verify-internals.h \
+	wrapper-types.h
 @HOST_WIN32_FALSE at am__objects_1 =  \
 @HOST_WIN32_FALSE@	libmonoruntime_static_la-console-unix.lo
 @HOST_WIN32_TRUE at am__objects_2 =  \
@@ -153,6 +154,7 @@ am__objects_4 = $(am__objects_3) libmonoruntime_static_la-appdomain.lo \
 	libmonoruntime_static_la-sgen-major-copying.lo \
 	libmonoruntime_static_la-sgen-los.lo \
 	libmonoruntime_static_la-sgen-protocol.lo \
+	libmonoruntime_static_la-sgen-bridge.lo \
 	libmonoruntime_static_la-string-icalls.lo \
 	libmonoruntime_static_la-sysmath.lo \
 	libmonoruntime_static_la-threads.lo \
@@ -193,13 +195,13 @@ am__libmonoruntime_la_SOURCES_DIST = console-unix.c console-win32.c \
 	sgen-os-posix.c sgen-os-mach.c sgen-gc.c sgen-internal.c \
 	sgen-marksweep.c sgen-marksweep-fixed.c sgen-marksweep-par.c \
 	sgen-marksweep-fixed-par.c sgen-major-copying.c sgen-los.c \
-	sgen-protocol.c sgen-gc.h sgen-archdep.h sgen-cardtable.h \
-	sgen-major-copy-object.h sgen-major-scan-object.h \
-	sgen-protocol.h sgen-scan-object.h string-icalls.c \
-	string-icalls.h sysmath.h sysmath.c tabledefs.h threads.c \
-	threads-types.h threadpool.c threadpool.h \
-	threadpool-internals.h verify.c verify-internals.h \
-	wrapper-types.h
+	sgen-protocol.c sgen-bridge.c sgen-bridge.h sgen-gc.h \
+	sgen-archdep.h sgen-cardtable.h sgen-major-copy-object.h \
+	sgen-major-scan-object.h sgen-protocol.h sgen-scan-object.h \
+	string-icalls.c string-icalls.h sysmath.h sysmath.c \
+	tabledefs.h threads.c threads-types.h threadpool.c \
+	threadpool.h threadpool-internals.h verify.c \
+	verify-internals.h wrapper-types.h
 @HOST_WIN32_FALSE at am__objects_5 = libmonoruntime_la-console-unix.lo
 @HOST_WIN32_TRUE at am__objects_6 = libmonoruntime_la-console-win32.lo
 @HOST_WIN32_FALSE at am__objects_7 = $(am__objects_5)
@@ -246,6 +248,7 @@ am_libmonoruntime_la_OBJECTS = $(am__objects_7) \
 	libmonoruntime_la-sgen-major-copying.lo \
 	libmonoruntime_la-sgen-los.lo \
 	libmonoruntime_la-sgen-protocol.lo \
+	libmonoruntime_la-sgen-bridge.lo \
 	libmonoruntime_la-string-icalls.lo \
 	libmonoruntime_la-sysmath.lo libmonoruntime_la-threads.lo \
 	libmonoruntime_la-threadpool.lo libmonoruntime_la-verify.lo
@@ -283,13 +286,14 @@ am__libmonoruntimemoon_la_SOURCES_DIST = console-unix.c \
 	security-manager.h sgen-os-posix.c sgen-os-mach.c sgen-gc.c \
 	sgen-internal.c sgen-marksweep.c sgen-marksweep-fixed.c \
 	sgen-marksweep-par.c sgen-marksweep-fixed-par.c \
-	sgen-major-copying.c sgen-los.c sgen-protocol.c sgen-gc.h \
-	sgen-archdep.h sgen-cardtable.h sgen-major-copy-object.h \
-	sgen-major-scan-object.h sgen-protocol.h sgen-scan-object.h \
-	string-icalls.c string-icalls.h sysmath.h sysmath.c \
-	tabledefs.h threads.c threads-types.h threadpool.c \
-	threadpool.h threadpool-internals.h verify.c \
-	verify-internals.h wrapper-types.h
+	sgen-major-copying.c sgen-los.c sgen-protocol.c sgen-bridge.c \
+	sgen-bridge.h sgen-gc.h sgen-archdep.h sgen-cardtable.h \
+	sgen-major-copy-object.h sgen-major-scan-object.h \
+	sgen-protocol.h sgen-scan-object.h string-icalls.c \
+	string-icalls.h sysmath.h sysmath.c tabledefs.h threads.c \
+	threads-types.h threadpool.c threadpool.h \
+	threadpool-internals.h verify.c verify-internals.h \
+	wrapper-types.h
 @HOST_WIN32_FALSE at am__objects_8 =  \
 @HOST_WIN32_FALSE@	libmonoruntimemoon_la-console-unix.lo
 @HOST_WIN32_TRUE at am__objects_9 =  \
@@ -353,6 +357,7 @@ am__objects_11 = $(am__objects_10) libmonoruntimemoon_la-appdomain.lo \
 	libmonoruntimemoon_la-sgen-major-copying.lo \
 	libmonoruntimemoon_la-sgen-los.lo \
 	libmonoruntimemoon_la-sgen-protocol.lo \
+	libmonoruntimemoon_la-sgen-bridge.lo \
 	libmonoruntimemoon_la-string-icalls.lo \
 	libmonoruntimemoon_la-sysmath.lo \
 	libmonoruntimemoon_la-threads.lo \
@@ -393,13 +398,14 @@ am__libmonoruntimesgen_static_la_SOURCES_DIST = console-unix.c \
 	security-manager.h sgen-os-posix.c sgen-os-mach.c sgen-gc.c \
 	sgen-internal.c sgen-marksweep.c sgen-marksweep-fixed.c \
 	sgen-marksweep-par.c sgen-marksweep-fixed-par.c \
-	sgen-major-copying.c sgen-los.c sgen-protocol.c sgen-gc.h \
-	sgen-archdep.h sgen-cardtable.h sgen-major-copy-object.h \
-	sgen-major-scan-object.h sgen-protocol.h sgen-scan-object.h \
-	string-icalls.c string-icalls.h sysmath.h sysmath.c \
-	tabledefs.h threads.c threads-types.h threadpool.c \
-	threadpool.h threadpool-internals.h verify.c \
-	verify-internals.h wrapper-types.h
+	sgen-major-copying.c sgen-los.c sgen-protocol.c sgen-bridge.c \
+	sgen-bridge.h sgen-gc.h sgen-archdep.h sgen-cardtable.h \
+	sgen-major-copy-object.h sgen-major-scan-object.h \
+	sgen-protocol.h sgen-scan-object.h string-icalls.c \
+	string-icalls.h sysmath.h sysmath.c tabledefs.h threads.c \
+	threads-types.h threadpool.c threadpool.h \
+	threadpool-internals.h verify.c verify-internals.h \
+	wrapper-types.h
 @HOST_WIN32_FALSE at am__objects_12 = libmonoruntimesgen_static_la-console-unix.lo
 @HOST_WIN32_TRUE at am__objects_13 = libmonoruntimesgen_static_la-console-win32.lo
 @HOST_WIN32_FALSE at am__objects_14 = $(am__objects_12)
@@ -465,6 +471,7 @@ am__objects_15 = $(am__objects_14) \
 	libmonoruntimesgen_static_la-sgen-major-copying.lo \
 	libmonoruntimesgen_static_la-sgen-los.lo \
 	libmonoruntimesgen_static_la-sgen-protocol.lo \
+	libmonoruntimesgen_static_la-sgen-bridge.lo \
 	libmonoruntimesgen_static_la-string-icalls.lo \
 	libmonoruntimesgen_static_la-sysmath.lo \
 	libmonoruntimesgen_static_la-threads.lo \
@@ -506,13 +513,14 @@ am__libmonoruntimesgen_la_SOURCES_DIST = console-unix.c \
 	security-manager.h sgen-os-posix.c sgen-os-mach.c sgen-gc.c \
 	sgen-internal.c sgen-marksweep.c sgen-marksweep-fixed.c \
 	sgen-marksweep-par.c sgen-marksweep-fixed-par.c \
-	sgen-major-copying.c sgen-los.c sgen-protocol.c sgen-gc.h \
-	sgen-archdep.h sgen-cardtable.h sgen-major-copy-object.h \
-	sgen-major-scan-object.h sgen-protocol.h sgen-scan-object.h \
-	string-icalls.c string-icalls.h sysmath.h sysmath.c \
-	tabledefs.h threads.c threads-types.h threadpool.c \
-	threadpool.h threadpool-internals.h verify.c \
-	verify-internals.h wrapper-types.h
+	sgen-major-copying.c sgen-los.c sgen-protocol.c sgen-bridge.c \
+	sgen-bridge.h sgen-gc.h sgen-archdep.h sgen-cardtable.h \
+	sgen-major-copy-object.h sgen-major-scan-object.h \
+	sgen-protocol.h sgen-scan-object.h string-icalls.c \
+	string-icalls.h sysmath.h sysmath.c tabledefs.h threads.c \
+	threads-types.h threadpool.c threadpool.h \
+	threadpool-internals.h verify.c verify-internals.h \
+	wrapper-types.h
 @HOST_WIN32_FALSE at am__objects_16 =  \
 @HOST_WIN32_FALSE@	libmonoruntimesgen_la-console-unix.lo
 @HOST_WIN32_TRUE at am__objects_17 =  \
@@ -576,6 +584,7 @@ am__objects_19 = $(am__objects_18) libmonoruntimesgen_la-appdomain.lo \
 	libmonoruntimesgen_la-sgen-major-copying.lo \
 	libmonoruntimesgen_la-sgen-los.lo \
 	libmonoruntimesgen_la-sgen-protocol.lo \
+	libmonoruntimesgen_la-sgen-bridge.lo \
 	libmonoruntimesgen_la-string-icalls.lo \
 	libmonoruntimesgen_la-sysmath.lo \
 	libmonoruntimesgen_la-threads.lo \
@@ -980,6 +989,8 @@ libmonoruntime_la_SOURCES = \
 	sgen-major-copying.c	\
 	sgen-los.c		\
 	sgen-protocol.c \
+	sgen-bridge.c		\
+	sgen-bridge.h		\
 	sgen-gc.h		\
 	sgen-archdep.h		\
 	sgen-cardtable.h	\
@@ -1031,6 +1042,7 @@ libmonoruntimeinclude_HEADERS = \
 	mono-config.h		\
 	mono-debug.h		\
 	mono-gc.h		\
+	sgen-bridge.h		\
 	object.h		\
 	opcodes.h		\
 	profiler.h		\
@@ -1189,6 +1201,7 @@ distclean-compile:
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntime_la-security-core-clr.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntime_la-security-manager.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntime_la-security.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntime_la-sgen-bridge.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntime_la-sgen-gc.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntime_la-sgen-internal.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntime_la-sgen-los.Plo at am__quote@
@@ -1256,6 +1269,7 @@ distclean-compile:
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntime_static_la-security-core-clr.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntime_static_la-security-manager.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntime_static_la-security.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntime_static_la-sgen-bridge.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntime_static_la-sgen-gc.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntime_static_la-sgen-internal.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntime_static_la-sgen-los.Plo at am__quote@
@@ -1323,6 +1337,7 @@ distclean-compile:
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimemoon_la-security-core-clr.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimemoon_la-security-manager.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimemoon_la-security.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimemoon_la-sgen-bridge.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimemoon_la-sgen-gc.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimemoon_la-sgen-internal.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimemoon_la-sgen-los.Plo at am__quote@
@@ -1390,6 +1405,7 @@ distclean-compile:
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimesgen_la-security-core-clr.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimesgen_la-security-manager.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimesgen_la-security.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimesgen_la-sgen-bridge.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimesgen_la-sgen-gc.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimesgen_la-sgen-internal.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimesgen_la-sgen-los.Plo at am__quote@
@@ -1457,6 +1473,7 @@ distclean-compile:
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimesgen_static_la-security-core-clr.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimesgen_static_la-security-manager.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimesgen_static_la-security.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimesgen_static_la-sgen-bridge.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimesgen_static_la-sgen-gc.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimesgen_static_la-sgen-internal.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmonoruntimesgen_static_la-sgen-los.Plo at am__quote@
@@ -1931,6 +1948,13 @@ libmonoruntime_static_la-sgen-protocol.lo: sgen-protocol.c
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
 @am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntime_static_la_CFLAGS) $(CFLAGS) -c -o libmonoruntime_static_la-sgen-protocol.lo `test -f 'sgen-protocol.c' || echo '$(srcdir)/'`sgen-protocol.c
 
+libmonoruntime_static_la-sgen-bridge.lo: sgen-bridge.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntime_static_la_CFLAGS) $(CFLAGS) -MT libmonoruntime_static_la-sgen-bridge.lo -MD -MP -MF $(DEPDIR)/libmonoruntime_static_la-sgen-bridge.Tpo -c -o libmonoruntime_static_la-sgen-bridge.lo `test -f 'sgen-bridge.c' || echo '$(srcdir)/'`sgen-bridge.c
+ at am__fastdepCC_TRUE@	mv -f $(DEPDIR)/libmonoruntime_static_la-sgen-bridge.Tpo $(DEPDIR)/libmonoruntime_static_la-sgen-bridge.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source='sgen-bridge.c' object='libmonoruntime_static_la-sgen-bridge.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntime_static_la_CFLAGS) $(CFLAGS) -c -o libmonoruntime_static_la-sgen-bridge.lo `test -f 'sgen-bridge.c' || echo '$(srcdir)/'`sgen-bridge.c
+
 libmonoruntime_static_la-string-icalls.lo: string-icalls.c
 @am__fastdepCC_TRUE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntime_static_la_CFLAGS) $(CFLAGS) -MT libmonoruntime_static_la-string-icalls.lo -MD -MP -MF $(DEPDIR)/libmonoruntime_static_la-string-icalls.Tpo -c -o libmonoruntime_static_la-string-icalls.lo `test -f 'string-icalls.c' || echo '$(srcdir)/'`string-icalls.c
 @am__fastdepCC_TRUE@	mv -f $(DEPDIR)/libmonoruntime_static_la-string-icalls.Tpo $(DEPDIR)/libmonoruntime_static_la-string-icalls.Plo
@@ -2400,6 +2424,13 @@ libmonoruntime_la-sgen-protocol.lo: sgen-protocol.c
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
 @am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntime_la_CFLAGS) $(CFLAGS) -c -o libmonoruntime_la-sgen-protocol.lo `test -f 'sgen-protocol.c' || echo '$(srcdir)/'`sgen-protocol.c
 
+libmonoruntime_la-sgen-bridge.lo: sgen-bridge.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntime_la_CFLAGS) $(CFLAGS) -MT libmonoruntime_la-sgen-bridge.lo -MD -MP -MF $(DEPDIR)/libmonoruntime_la-sgen-bridge.Tpo -c -o libmonoruntime_la-sgen-bridge.lo `test -f 'sgen-bridge.c' || echo '$(srcdir)/'`sgen-bridge.c
+ at am__fastdepCC_TRUE@	mv -f $(DEPDIR)/libmonoruntime_la-sgen-bridge.Tpo $(DEPDIR)/libmonoruntime_la-sgen-bridge.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source='sgen-bridge.c' object='libmonoruntime_la-sgen-bridge.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntime_la_CFLAGS) $(CFLAGS) -c -o libmonoruntime_la-sgen-bridge.lo `test -f 'sgen-bridge.c' || echo '$(srcdir)/'`sgen-bridge.c
+
 libmonoruntime_la-string-icalls.lo: string-icalls.c
 @am__fastdepCC_TRUE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntime_la_CFLAGS) $(CFLAGS) -MT libmonoruntime_la-string-icalls.lo -MD -MP -MF $(DEPDIR)/libmonoruntime_la-string-icalls.Tpo -c -o libmonoruntime_la-string-icalls.lo `test -f 'string-icalls.c' || echo '$(srcdir)/'`string-icalls.c
 @am__fastdepCC_TRUE@	mv -f $(DEPDIR)/libmonoruntime_la-string-icalls.Tpo $(DEPDIR)/libmonoruntime_la-string-icalls.Plo
@@ -2869,6 +2900,13 @@ libmonoruntimemoon_la-sgen-protocol.lo: sgen-protocol.c
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
 @am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntimemoon_la_CFLAGS) $(CFLAGS) -c -o libmonoruntimemoon_la-sgen-protocol.lo `test -f 'sgen-protocol.c' || echo '$(srcdir)/'`sgen-protocol.c
 
+libmonoruntimemoon_la-sgen-bridge.lo: sgen-bridge.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntimemoon_la_CFLAGS) $(CFLAGS) -MT libmonoruntimemoon_la-sgen-bridge.lo -MD -MP -MF $(DEPDIR)/libmonoruntimemoon_la-sgen-bridge.Tpo -c -o libmonoruntimemoon_la-sgen-bridge.lo `test -f 'sgen-bridge.c' || echo '$(srcdir)/'`sgen-bridge.c
+ at am__fastdepCC_TRUE@	mv -f $(DEPDIR)/libmonoruntimemoon_la-sgen-bridge.Tpo $(DEPDIR)/libmonoruntimemoon_la-sgen-bridge.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source='sgen-bridge.c' object='libmonoruntimemoon_la-sgen-bridge.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntimemoon_la_CFLAGS) $(CFLAGS) -c -o libmonoruntimemoon_la-sgen-bridge.lo `test -f 'sgen-bridge.c' || echo '$(srcdir)/'`sgen-bridge.c
+
 libmonoruntimemoon_la-string-icalls.lo: string-icalls.c
 @am__fastdepCC_TRUE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntimemoon_la_CFLAGS) $(CFLAGS) -MT libmonoruntimemoon_la-string-icalls.lo -MD -MP -MF $(DEPDIR)/libmonoruntimemoon_la-string-icalls.Tpo -c -o libmonoruntimemoon_la-string-icalls.lo `test -f 'string-icalls.c' || echo '$(srcdir)/'`string-icalls.c
 @am__fastdepCC_TRUE@	mv -f $(DEPDIR)/libmonoruntimemoon_la-string-icalls.Tpo $(DEPDIR)/libmonoruntimemoon_la-string-icalls.Plo
@@ -3338,6 +3376,13 @@ libmonoruntimesgen_static_la-sgen-protocol.lo: sgen-protocol.c
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
 @am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntimesgen_static_la_CFLAGS) $(CFLAGS) -c -o libmonoruntimesgen_static_la-sgen-protocol.lo `test -f 'sgen-protocol.c' || echo '$(srcdir)/'`sgen-protocol.c
 
+libmonoruntimesgen_static_la-sgen-bridge.lo: sgen-bridge.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntimesgen_static_la_CFLAGS) $(CFLAGS) -MT libmonoruntimesgen_static_la-sgen-bridge.lo -MD -MP -MF $(DEPDIR)/libmonoruntimesgen_static_la-sgen-bridge.Tpo -c -o libmonoruntimesgen_static_la-sgen-bridge.lo `test -f 'sgen-bridge.c' || echo '$(srcdir)/'`sgen-bridge.c
+ at am__fastdepCC_TRUE@	mv -f $(DEPDIR)/libmonoruntimesgen_static_la-sgen-bridge.Tpo $(DEPDIR)/libmonoruntimesgen_static_la-sgen-bridge.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source='sgen-bridge.c' object='libmonoruntimesgen_static_la-sgen-bridge.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntimesgen_static_la_CFLAGS) $(CFLAGS) -c -o libmonoruntimesgen_static_la-sgen-bridge.lo `test -f 'sgen-bridge.c' || echo '$(srcdir)/'`sgen-bridge.c
+
 libmonoruntimesgen_static_la-string-icalls.lo: string-icalls.c
 @am__fastdepCC_TRUE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntimesgen_static_la_CFLAGS) $(CFLAGS) -MT libmonoruntimesgen_static_la-string-icalls.lo -MD -MP -MF $(DEPDIR)/libmonoruntimesgen_static_la-string-icalls.Tpo -c -o libmonoruntimesgen_static_la-string-icalls.lo `test -f 'string-icalls.c' || echo '$(srcdir)/'`string-icalls.c
 @am__fastdepCC_TRUE@	mv -f $(DEPDIR)/libmonoruntimesgen_static_la-string-icalls.Tpo $(DEPDIR)/libmonoruntimesgen_static_la-string-icalls.Plo
@@ -3807,6 +3852,13 @@ libmonoruntimesgen_la-sgen-protocol.lo: sgen-protocol.c
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
 @am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntimesgen_la_CFLAGS) $(CFLAGS) -c -o libmonoruntimesgen_la-sgen-protocol.lo `test -f 'sgen-protocol.c' || echo '$(srcdir)/'`sgen-protocol.c
 
+libmonoruntimesgen_la-sgen-bridge.lo: sgen-bridge.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntimesgen_la_CFLAGS) $(CFLAGS) -MT libmonoruntimesgen_la-sgen-bridge.lo -MD -MP -MF $(DEPDIR)/libmonoruntimesgen_la-sgen-bridge.Tpo -c -o libmonoruntimesgen_la-sgen-bridge.lo `test -f 'sgen-bridge.c' || echo '$(srcdir)/'`sgen-bridge.c
+ at am__fastdepCC_TRUE@	mv -f $(DEPDIR)/libmonoruntimesgen_la-sgen-bridge.Tpo $(DEPDIR)/libmonoruntimesgen_la-sgen-bridge.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source='sgen-bridge.c' object='libmonoruntimesgen_la-sgen-bridge.lo' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntimesgen_la_CFLAGS) $(CFLAGS) -c -o libmonoruntimesgen_la-sgen-bridge.lo `test -f 'sgen-bridge.c' || echo '$(srcdir)/'`sgen-bridge.c
+
 libmonoruntimesgen_la-string-icalls.lo: string-icalls.c
 @am__fastdepCC_TRUE@	$(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libmonoruntimesgen_la_CFLAGS) $(CFLAGS) -MT libmonoruntimesgen_la-string-icalls.lo -MD -MP -MF $(DEPDIR)/libmonoruntimesgen_la-string-icalls.Tpo -c -o libmonoruntimesgen_la-string-icalls.lo `test -f 'string-icalls.c' || echo '$(srcdir)/'`string-icalls.c
 @am__fastdepCC_TRUE@	mv -f $(DEPDIR)/libmonoruntimesgen_la-string-icalls.Tpo $(DEPDIR)/libmonoruntimesgen_la-string-icalls.Plo
diff --git a/mono/metadata/appdomain.c b/mono/metadata/appdomain.c
index ab1fc10..1b53294 100644
--- a/mono/metadata/appdomain.c
+++ b/mono/metadata/appdomain.c
@@ -816,7 +816,7 @@ void
 mono_set_private_bin_path_from_config (MonoDomain *domain)
 {
 	MonoError error;
-	gchar *config_file, *text;
+	gchar *config_file_name = NULL, *text = NULL, *config_file_path = NULL;
 	gsize len;
 	GMarkupParseContext *context;
 	RuntimeConfig runtime_config;
@@ -825,21 +825,23 @@ mono_set_private_bin_path_from_config (MonoDomain *domain)
 	if (!domain || !domain->setup || !domain->setup->configuration_file)
 		return;
 
-	config_file = mono_string_to_utf8_checked (domain->setup->configuration_file, &error); 
+	config_file_name = mono_string_to_utf8_checked (domain->setup->configuration_file, &error);
 	if (!mono_error_ok (&error)) {
 		mono_error_cleanup (&error);
-		return;
+		goto free_and_out;
 	}
 
-	if (!g_file_get_contents (config_file, &text, &len, NULL)) {
-		g_free (config_file);
-		return;
-	}
+	config_file_path = mono_portability_find_file (config_file_name, TRUE);
+	if (!config_file_path)
+		config_file_path = config_file_name;
+
+	if (!g_file_get_contents (config_file_path, &text, &len, NULL))
+		goto free_and_out;
 
 	runtime_config.runtime_count = 0;
 	runtime_config.assemblybinding_count = 0;
 	runtime_config.domain = domain;
-	runtime_config.filename = config_file;
+	runtime_config.filename = config_file_path;
 	
 	offset = 0;
 	if (len > 3 && text [0] == '\xef' && text [1] == (gchar) '\xbb' && text [2] == '\xbf')
@@ -849,8 +851,12 @@ mono_set_private_bin_path_from_config (MonoDomain *domain)
 	if (g_markup_parse_context_parse (context, text + offset, len - offset, NULL))
 		g_markup_parse_context_end_parse (context, NULL);
 	g_markup_parse_context_free (context);
+
+  free_and_out:
 	g_free (text);
-	g_free (config_file);
+	if (config_file_name != config_file_path)
+		g_free (config_file_name);
+	g_free (config_file_path);
 }
 
 MonoAppDomain *
diff --git a/mono/metadata/assembly.c b/mono/metadata/assembly.c
index 1d2bf75..f5e98c8 100644
--- a/mono/metadata/assembly.c
+++ b/mono/metadata/assembly.c
@@ -32,6 +32,7 @@
 #include <mono/utils/mono-path.h>
 #include <mono/metadata/reflection.h>
 #include <mono/metadata/coree.h>
+#include <mono/utils/mono-io-portability.h>
 
 #ifndef HOST_WIN32
 #include <sys/types.h>
@@ -197,26 +198,24 @@ mono_public_tokens_are_equal (const unsigned char *pubt1, const unsigned char *p
 	return memcmp (pubt1, pubt2, 16) == 0;
 }
 
-/* Native Client can't get this info from an environment variable so */
-/* it's passed in to the runtime, or set manually by embedding code. */
-#ifdef __native_client__
-char* nacl_mono_path = NULL;
-#endif
-
-static void
-check_path_env (void)
+/**
+ * mono_set_assemblies_path:
+ * @path: list of paths that contain directories where Mono will look for assemblies
+ *
+ * Use this method to override the standard assembly lookup system and
+ * override any assemblies coming from the GAC.  This is the method
+ * that supports the MONO_PATH variable.
+ *
+ * Notice that MONO_PATH and this method are really a very bad idea as
+ * it prevents the GAC from working and it prevents the standard
+ * resolution mechanisms from working.  Nonetheless, for some debugging
+ * situations and bootstrapping setups, this is useful to have. 
+ */
+void
+mono_set_assemblies_path (const char* path)
 {
-	const char *path;
 	char **splitted, **dest;
 	
-#ifdef __native_client__
-	path = nacl_mono_path;
-#else
-	path = g_getenv ("MONO_PATH");
-#endif
-	if (!path)
-		return;
-
 	splitted = g_strsplit (path, G_SEARCHPATH_SEPARATOR_S, 1000);
 	if (assemblies_path)
 		g_strfreev (assemblies_path);
@@ -240,6 +239,27 @@ check_path_env (void)
 	}
 }
 
+/* Native Client can't get this info from an environment variable so */
+/* it's passed in to the runtime, or set manually by embedding code. */
+#ifdef __native_client__
+char* nacl_mono_path = NULL;
+#endif
+
+static void
+check_path_env (void)
+{
+	const char* path;
+#ifdef __native_client__
+	path = nacl_mono_path;
+#else
+	path = g_getenv ("MONO_PATH");
+#endif
+	if (!path || assemblies_path != NULL)
+		return;
+
+	mono_set_assemblies_path(path);
+}
+
 static void
 check_extra_gac_path_env (void) {
 	const char *path;
@@ -2454,11 +2474,17 @@ mono_assembly_apply_binding (MonoAssemblyName *aname, MonoAssemblyName *dest_nam
 	if (domain && domain->setup && domain->setup->configuration_file) {
 		mono_domain_lock (domain);
 		if (!domain->assembly_bindings_parsed) {
-			gchar *domain_config_file = mono_string_to_utf8 (domain->setup->configuration_file);
+			gchar *domain_config_file_name = mono_string_to_utf8 (domain->setup->configuration_file);
+			gchar *domain_config_file_path = mono_portability_find_file (domain_config_file_name, TRUE);
 
-			mono_config_parse_assembly_bindings (domain_config_file, aname->major, aname->minor, domain, assembly_binding_info_parsed);
+			if (!domain_config_file_path)
+				domain_config_file_path = domain_config_file_name;
+			
+			mono_config_parse_assembly_bindings (domain_config_file_path, aname->major, aname->minor, domain, assembly_binding_info_parsed);
 			domain->assembly_bindings_parsed = TRUE;
-			g_free (domain_config_file);
+			if (domain_config_file_name != domain_config_file_path)
+				g_free (domain_config_file_name);
+			g_free (domain_config_file_path);
 		}
 		mono_domain_unlock (domain);
 
diff --git a/mono/metadata/assembly.h b/mono/metadata/assembly.h
index 0b8fd8d..be01cf9 100644
--- a/mono/metadata/assembly.h
+++ b/mono/metadata/assembly.h
@@ -104,7 +104,7 @@ void	      mono_register_machine_config (const char *config_xml);
 
 void          mono_set_rootdir (void);
 void          mono_set_dirs (const char *assembly_dir, const char *config_dir);
-
+void          mono_set_assemblies_path (const char* path);
 MONO_END_DECLS
 
 #endif
diff --git a/mono/metadata/boehm-gc.c b/mono/metadata/boehm-gc.c
index 050cb32..fa5846d 100644
--- a/mono/metadata/boehm-gc.c
+++ b/mono/metadata/boehm-gc.c
@@ -132,6 +132,10 @@ mono_gc_base_init (void)
 	GC_init_gcj_malloc (5, NULL);
 #endif
 
+#ifdef HAVE_GC_ALLOW_REGISTER_THREADS
+	GC_allow_register_threads();
+#endif
+
 	if ((env = getenv ("MONO_GC_PARAMS"))) {
 		char **ptr, **opts = g_strsplit (env, ",", -1);
 		for (ptr = opts; *ptr; ++ptr) {
@@ -961,7 +965,7 @@ mono_gc_get_managed_allocator (MonoVTable *vtable, gboolean for_box)
 		return NULL;
 	if (!SMALL_ENOUGH (klass->instance_size))
 		return NULL;
-	if (klass->has_finalize || klass->marshalbyref || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
+	if (mono_class_has_finalizer (klass) || klass->marshalbyref || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
 		return NULL;
 	if (klass->rank)
 		return NULL;
diff --git a/mono/metadata/class-internals.h b/mono/metadata/class-internals.h
index 710891c..d9e5bcf 100644
--- a/mono/metadata/class-internals.h
+++ b/mono/metadata/class-internals.h
@@ -350,6 +350,8 @@ struct _MonoClass {
 	guint simd_type : 1; /* class is a simd intrinsic type */
 	guint is_generic : 1; /* class is a generic type definition */
 	guint is_inflated : 1; /* class is a generic instance */
+	/* next byte */
+	guint has_finalize_inited    : 1; /* has_finalize is initialized */
 
 	guint8     exception_type;	/* MONO_EXCEPTION_* */
 
@@ -1297,4 +1299,7 @@ mono_class_get_fields_lazy (MonoClass* klass, gpointer *iter) MONO_INTERNAL;
 gboolean
 mono_class_check_vtable_constraints (MonoClass *class, GList *in_setup) MONO_INTERNAL;
 
+gboolean
+mono_class_has_finalizer (MonoClass *klass) MONO_INTERNAL;
+
 #endif /* __MONO_METADATA_CLASS_INTERBALS_H__ */
diff --git a/mono/metadata/class.c b/mono/metadata/class.c
index 999bcb0..7d8fb45 100644
--- a/mono/metadata/class.c
+++ b/mono/metadata/class.c
@@ -4718,6 +4718,7 @@ mono_class_init (MonoClass *class)
 		/* AOT case */
 		class->vtable_size = cached_info.vtable_size;
 		class->has_finalize = cached_info.has_finalize;
+		class->has_finalize_inited = TRUE;
 		class->ghcimpl = cached_info.ghcimpl;
 		class->has_cctor = cached_info.has_cctor;
 	} else if (class->rank == 1 && class->byval_arg.type == MONO_TYPE_SZARRAY) {
@@ -4735,12 +4736,14 @@ mono_class_init (MonoClass *class)
 		} else {
 			class->vtable_size = szarray_vtable_size[slot];
 		}
+		class->has_finalize_inited = TRUE;
 	} else if (class->generic_class && !MONO_CLASS_IS_INTERFACE (class)) {
 		MonoClass *gklass = class->generic_class->container_class;
 
 		/* Generic instance case */
 		class->ghcimpl = gklass->ghcimpl;
-		class->has_finalize = gklass->has_finalize;
+		class->has_finalize = mono_class_has_finalizer (gklass);
+		class->has_finalize_inited = TRUE;
 		class->has_cctor = gklass->has_cctor;
 
 		mono_class_setup_vtable (gklass);
@@ -4765,45 +4768,6 @@ mono_class_init (MonoClass *class)
 		}
 		*/
 
-		/* Interfaces and valuetypes are not supposed to have finalizers */
-		if (!(MONO_CLASS_IS_INTERFACE (class) || class->valuetype)) {
-			MonoMethod *cmethod = NULL;
-
-			if (class->parent && class->parent->has_finalize) {
-				class->has_finalize = 1;
-			} else {
-				if (class->type_token) {
-					cmethod = find_method_in_metadata (class, "Finalize", 0, METHOD_ATTRIBUTE_VIRTUAL);
-				} else if (class->parent) {
-					/* FIXME: Optimize this */
-					mono_class_setup_vtable (class);
-					if (class->exception_type || mono_loader_get_last_error ())
-						goto leave;
-					cmethod = class->vtable [finalize_slot];
-				}
-
-				if (cmethod) {
-					/* Check that this is really the finalizer method */
-					mono_class_setup_vtable (class);
-					if (class->exception_type || mono_loader_get_last_error ())
-						goto leave;
-
-					g_assert (class->vtable_size > finalize_slot);
-
-					class->has_finalize = 0;
-					if (class->parent) { 
-						cmethod = class->vtable [finalize_slot];
-						g_assert (cmethod);
-						if (cmethod->is_inflated)
-							cmethod = ((MonoMethodInflated*)cmethod)->declaring;
-						if (cmethod != default_finalize) {
-							class->has_finalize = 1;
-						}
-					}
-				}
-			}
-		}
-
 		/* C# doesn't allow interfaces to have cctors */
 		if (!MONO_CLASS_IS_INTERFACE (class) || class->image != mono_defaults.corlib) {
 			MonoMethod *cmethod = NULL;
@@ -4887,6 +4851,66 @@ mono_class_init (MonoClass *class)
 	return class->exception_type == MONO_EXCEPTION_NONE;
 }
 
+/*
+ * mono_class_has_finalizer:
+ *
+ *   Return whenever KLASS has a finalizer, initializing klass->has_finalizer in the
+ * process.
+ */
+gboolean
+mono_class_has_finalizer (MonoClass *klass)
+{
+	if (!klass->has_finalize_inited) {
+		MonoClass *class = klass;
+
+		mono_loader_lock ();
+
+		/* Interfaces and valuetypes are not supposed to have finalizers */
+		if (!(MONO_CLASS_IS_INTERFACE (class) || class->valuetype)) {
+			MonoMethod *cmethod = NULL;
+
+			if (class->parent && class->parent->has_finalize) {
+				class->has_finalize = 1;
+			} else {
+				if (class->parent) {
+					/*
+					 * Can't search in metadata for a method named Finalize, because that
+					 * ignores overrides.
+					 */
+					mono_class_setup_vtable (class);
+					if (class->exception_type || mono_loader_get_last_error ())
+						goto leave;
+					cmethod = class->vtable [finalize_slot];
+				}
+
+				if (cmethod) {
+					g_assert (class->vtable_size > finalize_slot);
+
+					class->has_finalize = 0;
+					if (class->parent) { 
+						if (cmethod->is_inflated)
+							cmethod = ((MonoMethodInflated*)cmethod)->declaring;
+						if (cmethod != default_finalize) {
+							class->has_finalize = 1;
+						}
+					}
+				}
+			}
+		}
+
+		mono_memory_barrier ();
+		klass->has_finalize_inited = TRUE;
+
+		mono_loader_unlock ();
+	}
+
+	return klass->has_finalize;
+
+ leave:
+	mono_loader_unlock ();
+	return FALSE;
+}
+
 gboolean
 mono_is_corlib_image (MonoImage *image)
 {
@@ -7020,7 +7044,8 @@ mono_class_from_name (MonoImage *image, const char* name_space, const char *name
 		name = buf;
 	}
 
-	if (get_class_from_name) {
+	/* FIXME: get_class_from_name () can't handle types in the EXPORTEDTYPE table */
+	if (get_class_from_name && image->tables [MONO_TABLE_EXPORTEDTYPE].rows == 0) {
 		gboolean res = get_class_from_name (image, name_space, name, &class);
 		if (res) {
 			if (!class)
@@ -7171,10 +7196,11 @@ mono_class_is_variant_compatible (MonoClass *klass, MonoClass *oklass)
 	int j;
 	MonoType **klass_argv, **oklass_argv;
 	MonoClass *klass_gtd = mono_class_get_generic_type_definition (klass);
+	MonoClass *oklass_gtd = mono_class_get_generic_type_definition (oklass);
 	MonoGenericContainer *container = klass_gtd->generic_container;
 
 	/*Viable candidates are instances of the same generic interface*/
-	if (mono_class_get_generic_type_definition (oklass) != klass_gtd)
+	if (mono_class_get_generic_type_definition (oklass) != klass_gtd || oklass == klass_gtd)
 		return FALSE;
 
 	klass_argv = &klass->generic_class->context.class_inst->type_argv [0];
@@ -7314,7 +7340,7 @@ mono_class_is_variant_compatible_slow (MonoClass *klass, MonoClass *oklass)
 	MonoGenericContainer *container = klass_gtd->generic_container;
 
 	/*Viable candidates are instances of the same generic interface*/
-	if (mono_class_get_generic_type_definition (oklass) != klass_gtd)
+	if (mono_class_get_generic_type_definition (oklass) != klass_gtd || oklass == klass_gtd)
 		return FALSE;
 
 	klass_argv = &klass->generic_class->context.class_inst->type_argv [0];
@@ -7482,7 +7508,7 @@ mono_class_get_finalizer (MonoClass *klass)
 
 	if (!klass->inited)
 		mono_class_init (klass);
-	if (!klass->has_finalize)
+	if (!mono_class_has_finalizer (klass))
 		return NULL;
 
 	if (mono_class_get_cached_class_info (klass, &cached_info))
diff --git a/mono/metadata/file-io.c b/mono/metadata/file-io.c
index 9997086..c52cbfa 100644
--- a/mono/metadata/file-io.c
+++ b/mono/metadata/file-io.c
@@ -343,7 +343,7 @@ ves_icall_System_IO_MonoIO_GetFileSystemEntries (MonoString *path,
 	if (find_handle == INVALID_HANDLE_VALUE) {
 		gint32 find_error = GetLastError ();
 		
-		if (find_error == ERROR_FILE_NOT_FOUND) {
+		if (find_error == ERROR_FILE_NOT_FOUND || find_error == ERROR_NO_MORE_FILES) {
 			/* No files, so just return an empty array */
 			result = mono_array_new (domain,
 						 mono_defaults.string_class,
diff --git a/mono/metadata/filewatcher.c b/mono/metadata/filewatcher.c
index b16ccc8..c0c37bc 100644
--- a/mono/metadata/filewatcher.c
+++ b/mono/metadata/filewatcher.c
@@ -16,6 +16,7 @@
 #include <mono/metadata/filewatcher.h>
 #include <mono/metadata/marshal.h>
 #include <mono/utils/mono-dl.h>
+#include <mono/utils/mono-io-portability.h>
 #ifdef HOST_WIN32
 
 /*
@@ -171,7 +172,7 @@ ves_icall_System_IO_InotifyWatcher_GetInotifyInstance ()
 int
 ves_icall_System_IO_InotifyWatcher_AddWatch (int fd, MonoString *name, gint32 mask)
 {
-	char *str;
+	char *str, *path;
 	int retval;
 
 	MONO_ARCH_SAVE_REGS;
@@ -180,7 +181,11 @@ ves_icall_System_IO_InotifyWatcher_AddWatch (int fd, MonoString *name, gint32 ma
 		return -1;
 
 	str = mono_string_to_utf8 (name);
-	retval = syscall (__NR_inotify_add_watch, fd, str, mask);
+	path = mono_portability_find_file (str, TRUE);
+	if (!path)
+		path = str;
+
+	retval = syscall (__NR_inotify_add_watch, fd, path, mask);
 	if (retval < 0) {
 		switch (errno) {
 		case EACCES:
@@ -207,6 +212,8 @@ ves_icall_System_IO_InotifyWatcher_AddWatch (int fd, MonoString *name, gint32 ma
 		}
 		mono_marshal_set_last_error ();
 	}
+	if (path != str)
+		g_free (path);
 	g_free (str);
 	return retval;
 }
diff --git a/mono/metadata/gc-internal.h b/mono/metadata/gc-internal.h
index 4ec41b9..dcb89a8 100644
--- a/mono/metadata/gc-internal.h
+++ b/mono/metadata/gc-internal.h
@@ -331,5 +331,36 @@ pthread_t mono_gc_get_mach_exception_thread (void) MONO_INTERNAL;
 
 gboolean mono_gc_parse_environment_string_extract_number (const char *str, glong *out) MONO_INTERNAL;
 
+gboolean mono_gc_precise_stack_mark_enabled (void) MONO_INTERNAL;
+
+FILE *mono_gc_get_logfile (void) MONO_INTERNAL;
+
+typedef void (*mono_reference_queue_callback) (void *user_data);
+
+typedef struct _MonoReferenceQueue MonoReferenceQueue;
+typedef struct _RefQueueEntry RefQueueEntry;
+
+struct _RefQueueEntry {
+#ifdef HAVE_SGEN_GC
+	void *dis_link;
+#else
+	guint32 gchandle;
+#endif
+	void *user_data;
+	RefQueueEntry *next;
+};
+
+struct _MonoReferenceQueue {
+	RefQueueEntry *queue;
+	mono_reference_queue_callback callback;
+	MonoReferenceQueue *next;
+	gboolean should_be_deleted;
+};
+
+MonoReferenceQueue* mono_gc_reference_queue_new (mono_reference_queue_callback callback) MONO_INTERNAL;
+void mono_gc_reference_queue_free (MonoReferenceQueue *queue) MONO_INTERNAL;
+gboolean mono_gc_reference_queue_add (MonoReferenceQueue *queue, MonoObject *obj, void *user_data) MONO_INTERNAL;
+
+
 #endif /* __MONO_METADATA_GC_INTERNAL_H__ */
 
diff --git a/mono/metadata/gc.c b/mono/metadata/gc.c
index 53e07e3..7b3ecf6 100644
--- a/mono/metadata/gc.c
+++ b/mono/metadata/gc.c
@@ -54,6 +54,7 @@ static gboolean finalizing_root_domain = FALSE;
 #define mono_finalizer_lock() EnterCriticalSection (&finalizer_mutex)
 #define mono_finalizer_unlock() LeaveCriticalSection (&finalizer_mutex)
 static CRITICAL_SECTION finalizer_mutex;
+static CRITICAL_SECTION reference_queue_mutex;
 
 static GSList *domains_to_finalize= NULL;
 static MonoMList *threads_to_finalize = NULL;
@@ -64,6 +65,9 @@ static void object_register_finalizer (MonoObject *obj, void (*callback)(void *,
 
 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
 
+static void reference_queue_proccess_all (void);
+static void mono_reference_queue_cleanup (void);
+static void reference_queue_clear_for_domain (MonoDomain *domain);
 #ifndef HAVE_NULL_GC
 static HANDLE pending_done_event;
 static HANDLE shutdown_event;
@@ -1029,6 +1033,9 @@ finalize_domain_objects (DomainFinalizationReq *req)
 	/* Process finalizers which are already in the queue */
 	mono_gc_invoke_finalizers ();
 
+	/* cleanup the reference queue */
+	reference_queue_clear_for_domain (domain);
+	
 	/* printf ("DONE.\n"); */
 	SetEvent (req->done_event);
 
@@ -1046,11 +1053,11 @@ finalizer_thread (gpointer unused)
 
 		g_assert (mono_domain_get () == mono_get_root_domain ());
 
+		/* An alertable wait is required so this thread can be suspended on windows */
 #ifdef MONO_HAS_SEMAPHORES
-		MONO_SEM_WAIT (&finalizer_sem);
+		MONO_SEM_WAIT_ALERTABLE (&finalizer_sem, TRUE);
 #else
-		/* Use alertable=FALSE since we will be asked to exit using the event too */
-		WaitForSingleObjectEx (finalizer_event, INFINITE, FALSE);
+		WaitForSingleObjectEx (finalizer_event, INFINITE, TRUE);
 #endif
 
 		mono_console_handle_async_ops ();
@@ -1077,6 +1084,8 @@ finalizer_thread (gpointer unused)
 		 */
 		mono_gc_invoke_finalizers ();
 
+		reference_queue_proccess_all ();
+
 		SetEvent (pending_done_event);
 	}
 
@@ -1091,6 +1100,7 @@ mono_gc_init (void)
 	InitializeCriticalSection (&allocator_section);
 
 	InitializeCriticalSection (&finalizer_mutex);
+	InitializeCriticalSection (&reference_queue_mutex);
 
 	MONO_GC_REGISTER_ROOT_FIXED (gc_handles [HANDLE_NORMAL].entries);
 	MONO_GC_REGISTER_ROOT_FIXED (gc_handles [HANDLE_PINNED].entries);
@@ -1165,9 +1175,12 @@ mono_gc_cleanup (void)
 #endif
 	}
 
+	mono_reference_queue_cleanup ();
+
 	DeleteCriticalSection (&handle_section);
 	DeleteCriticalSection (&allocator_section);
 	DeleteCriticalSection (&finalizer_mutex);
+	DeleteCriticalSection (&reference_queue_mutex);
 }
 
 #else
@@ -1286,3 +1299,184 @@ mono_gc_alloc_mature (MonoVTable *vtable)
 	return mono_object_new_specific (vtable);
 }
 #endif
+
+
+static MonoReferenceQueue *ref_queues;
+
+static void
+ref_list_remove_element (RefQueueEntry **prev, RefQueueEntry *element)
+{
+	do {
+		/* Guard if head is changed concurrently. */
+		while (*prev != element)
+			prev = &(*prev)->next;
+	} while (prev && InterlockedCompareExchangePointer ((void*)prev, element->next, element) != element);
+}
+
+static void
+ref_list_push (RefQueueEntry **head, RefQueueEntry *value)
+{
+	RefQueueEntry *current;
+	do {
+		current = *head;
+		value->next = current;
+	} while (InterlockedCompareExchangePointer ((void*)head, value, current) != current);
+}
+
+static void
+reference_queue_proccess (MonoReferenceQueue *queue)
+{
+	RefQueueEntry **iter = &queue->queue;
+	RefQueueEntry *entry;
+	while ((entry = *iter)) {
+#ifdef HAVE_SGEN_GC
+		if (queue->should_be_deleted || !mono_gc_weak_link_get (&entry->dis_link)) {
+			mono_gc_weak_link_remove (&entry->dis_link);
+#else
+		if (queue->should_be_deleted || !mono_gchandle_get_target (entry->gchandle)) {
+			mono_gchandle_free ((guint32)entry->gchandle);
+#endif
+			ref_list_remove_element (iter, entry);
+			queue->callback (entry->user_data);
+			g_free (entry);
+		} else {
+			iter = &entry->next;
+		}
+	}
+}
+
+static void
+reference_queue_proccess_all (void)
+{
+	MonoReferenceQueue **iter;
+	MonoReferenceQueue *queue = ref_queues;
+	for (; queue; queue = queue->next)
+		reference_queue_proccess (queue);
+
+restart:
+	EnterCriticalSection (&reference_queue_mutex);
+	for (iter = &ref_queues; *iter;) {
+		queue = *iter;
+		if (!queue->should_be_deleted) {
+			iter = &queue->next;
+			continue;
+		}
+		if (queue->queue) {
+			LeaveCriticalSection (&reference_queue_mutex);
+			reference_queue_proccess (queue);
+			goto restart;
+		}
+		*iter = queue->next;
+		g_free (queue);
+	}
+	LeaveCriticalSection (&reference_queue_mutex);
+}
+
+static void
+mono_reference_queue_cleanup (void)
+{
+	MonoReferenceQueue *queue = ref_queues;
+	for (; queue; queue = queue->next)
+		queue->should_be_deleted = TRUE;
+	reference_queue_proccess_all ();
+}
+
+static void
+reference_queue_clear_for_domain (MonoDomain *domain)
+{
+	MonoReferenceQueue *queue = ref_queues;
+	for (; queue; queue = queue->next) {
+		RefQueueEntry **iter = &queue->queue;
+		RefQueueEntry *entry;
+		while ((entry = *iter)) {
+			MonoObject *obj;
+#ifdef HAVE_SGEN_GC
+			obj = mono_gc_weak_link_get (&entry->dis_link);
+			if (obj && mono_object_domain (obj) == domain) {
+				mono_gc_weak_link_remove (&entry->dis_link);
+#else
+			obj = mono_gchandle_get_target (entry->gchandle);
+			if (obj && mono_object_domain (obj) == domain) {
+				mono_gchandle_free ((guint32)entry->gchandle);
+#endif
+				ref_list_remove_element (iter, entry);
+				queue->callback (entry->user_data);
+				g_free (entry);
+			} else {
+				iter = &entry->next;
+			}
+		}
+	}
+}
+/**
+ * mono_gc_reference_queue_new:
+ * @callback callback used when processing dead entries.
+ *
+ * Create a new reference queue used to process collected objects.
+ * A reference queue let you queue the pair (managed object, user data).
+ * Once the managed object is collected @callback will be called
+ * in the finalizer thread with 'user data' as argument.
+ *
+ * The callback is called without any locks held.
+ */
+MonoReferenceQueue*
+mono_gc_reference_queue_new (mono_reference_queue_callback callback)
+{
+	MonoReferenceQueue *res = g_new0 (MonoReferenceQueue, 1);
+	res->callback = callback;
+
+	EnterCriticalSection (&reference_queue_mutex);
+	res->next = ref_queues;
+	ref_queues = res;
+	LeaveCriticalSection (&reference_queue_mutex);
+
+	return res;
+}
+
+/**
+ * mono_gc_reference_queue_add:
+ * @queue the queue to add the reference to.
+ * @obj the object to be watched for collection
+ * @user_data parameter to be passed to the queue callback
+ *
+ * Queue an object to be watched for collection.
+ *
+ * @returns false if the queue is scheduled to be freed.
+ */
+gboolean
+mono_gc_reference_queue_add (MonoReferenceQueue *queue, MonoObject *obj, void *user_data)
+{
+	RefQueueEntry *entry;
+	if (queue->should_be_deleted)
+		return FALSE;
+
+	entry = g_new0 (RefQueueEntry, 1);
+	entry->user_data = user_data;
+
+#ifdef HAVE_SGEN_GC
+	mono_gc_weak_link_add (&entry->dis_link, obj, TRUE);
+#else
+	entry->gchandle = mono_gchandle_new_weakref (obj, TRUE);
+	mono_object_register_finalizer (obj);
+#endif
+
+	ref_list_push (&queue->queue, entry);
+	return TRUE;
+}
+
+/**
+ * mono_gc_reference_queue_free:
+ * @queue the queue that should be deleted.
+ *
+ * This operation signals that @queue should be deleted. This operation is deferred
+ * as it happens on the finalizer thread.
+ *
+ * After this call, no further objects can be queued. It's the responsibility of the
+ * caller to make sure that no further attempt to access queue will be made.
+ */
+void
+mono_gc_reference_queue_free (MonoReferenceQueue *queue)
+{
+	queue->should_be_deleted = TRUE;
+}
+
diff --git a/mono/metadata/icall-def.h b/mono/metadata/icall-def.h
index 26614eb..9b894cb 100644
--- a/mono/metadata/icall-def.h
+++ b/mono/metadata/icall-def.h
@@ -524,7 +524,6 @@ ICALL(DERIVEDTYPE_1, "create_unmanaged_type", mono_reflection_create_unmanaged_t
 
 ICALL_TYPE(DYNM, "System.Reflection.Emit.DynamicMethod", DYNM_1)
 ICALL(DYNM_1, "create_dynamic_method", mono_reflection_create_dynamic_method)
-ICALL(DYNM_2, "destroy_dynamic_method", mono_reflection_destroy_dynamic_method)
 
 ICALL_TYPE(ENUMB, "System.Reflection.Emit.EnumBuilder", ENUMB_1)
 ICALL(ENUMB_1, "setup_enum_type", ves_icall_EnumBuilder_setup_enum_type)
diff --git a/mono/metadata/icall.c b/mono/metadata/icall.c
index a8d0edc..beb055f 100644
--- a/mono/metadata/icall.c
+++ b/mono/metadata/icall.c
@@ -77,6 +77,7 @@
 #include <mono/utils/mono-string.h>
 #include <mono/utils/mono-error-internals.h>
 #include <mono/utils/mono-mmap.h>
+#include <mono/utils/mono-io-portability.h>
 
 #if defined (HOST_WIN32)
 #include <windows.h>
@@ -245,7 +246,8 @@ ves_icall_System_Array_SetValueImpl (MonoArray *this, MonoObject *value, guint32
 			"value", "not a widening conversion")); \
 }G_STMT_END
 
-#define INVALID_CAST G_STMT_START{\
+#define INVALID_CAST G_STMT_START{ \
+		mono_get_runtime_callbacks ()->set_cast_details (vc, ec); \
 	mono_raise_exception (mono_get_exception_invalid_cast ()); \
 }G_STMT_END
 
@@ -6920,7 +6922,7 @@ get_bundled_app_config (void)
 	const gchar *app_config;
 	MonoDomain *domain;
 	MonoString *file;
-	gchar *config_file;
+	gchar *config_file_name, *config_file_path;
 	gsize len;
 	gchar *module;
 
@@ -6932,15 +6934,20 @@ get_bundled_app_config (void)
 		return NULL;
 
 	// Retrieve config file and remove the extension
-	config_file = mono_string_to_utf8 (file);
-	len = strlen (config_file) - strlen (".config");
+	config_file_name = mono_string_to_utf8 (file);
+	config_file_path = mono_portability_find_file (config_file_name, TRUE);
+	if (!config_file_path)
+		config_file_path = config_file_name;
+	len = strlen (config_file_path) - strlen (".config");
 	module = g_malloc0 (len + 1);
-	memcpy (module, config_file, len);
+	memcpy (module, config_file_path, len);
 	// Get the config file from the module name
 	app_config = mono_config_string_for_assembly_file (module);
 	// Clean-up
 	g_free (module);
-	g_free (config_file);
+	if (config_file_name != config_file_path)
+		g_free (config_file_name);
+	g_free (config_file_path);
 
 	if (!app_config)
 		return NULL;
@@ -7058,6 +7065,7 @@ ves_icall_MonoMethod_get_base_method (MonoReflectionMethod *m, gboolean definiti
 	MonoClass *klass, *parent;
 	MonoMethod *method = m->method;
 	MonoMethod *result = NULL;
+	int slot;
 
 	MONO_ARCH_SAVE_REGS;
 
@@ -7069,6 +7077,10 @@ ves_icall_MonoMethod_get_base_method (MonoReflectionMethod *m, gboolean definiti
 	    method->flags & METHOD_ATTRIBUTE_NEW_SLOT)
 		return m;
 
+	slot = mono_method_get_vtable_slot (method);
+	if (slot == -1)
+		return m;
+
 	klass = method->klass;
 	if (klass->generic_class)
 		klass = klass->generic_class->container_class;
@@ -7077,7 +7089,7 @@ ves_icall_MonoMethod_get_base_method (MonoReflectionMethod *m, gboolean definiti
 		/* At the end of the loop, klass points to the eldest class that has this virtual function slot. */
 		for (parent = klass->parent; parent != NULL; parent = parent->parent) {
 			mono_class_setup_vtable (parent);
-			if (parent->vtable_size <= method->slot)
+			if (parent->vtable_size <= slot)
 				break;
 			klass = parent;
 		}
@@ -7093,15 +7105,17 @@ ves_icall_MonoMethod_get_base_method (MonoReflectionMethod *m, gboolean definiti
 	/*This is possible if definition == FALSE.
 	 * Do it here to be really sure we don't read invalid memory.
 	 */
-	if (method->slot >= klass->vtable_size)
+	if (slot >= klass->vtable_size)
 		return m;
 
-	result = klass->vtable [method->slot];
+	mono_class_setup_vtable (klass);
+
+	result = klass->vtable [slot];
 	if (result == NULL) {
 		/* It is an abstract method */
 		gpointer iter = NULL;
 		while ((result = mono_class_get_methods (klass, &iter)))
-			if (result->slot == method->slot)
+			if (result->slot == slot)
 				break;
 	}
 
diff --git a/mono/metadata/marshal.c b/mono/metadata/marshal.c
index fc725e7..ad0a4f9 100644
--- a/mono/metadata/marshal.c
+++ b/mono/metadata/marshal.c
@@ -4023,6 +4023,8 @@ mono_marshal_get_delegate_invoke (MonoMethod *method, MonoDelegate *del)
 			res = newm;
 			new_key = g_new0 (SignatureMethodPair, 1);
 			*new_key = key;
+			if (static_method_with_first_arg_bound)
+				new_key->sig = signature_dup (del->method->klass->image, key.sig);
 			g_hash_table_insert (cache, new_key, res);
 			mono_marshal_set_wrapper_info (res, new_key);
 			mono_marshal_unlock ();
@@ -10132,10 +10134,18 @@ mono_marshal_get_virtual_stelemref (MonoClass *array_class)
 	res = mono_mb_create_method (mb, signature, 4);
 	res->flags |= METHOD_ATTRIBUTE_VIRTUAL;
 	mono_marshal_set_wrapper_info (res, GUINT_TO_POINTER (kind + 1));
-	cached_methods [kind] = res;
+
+	mono_marshal_lock ();
+	if (!cached_methods [kind]) {
+		cached_methods [kind] = res;
+		mono_marshal_unlock ();
+	} else {
+		mono_marshal_unlock ();
+		mono_free_method (res);
+	}
 
 	mono_mb_free (mb);
-	return res;
+	return cached_methods [kind];
 }
 
 MonoMethod*
diff --git a/mono/metadata/object-internals.h b/mono/metadata/object-internals.h
index 7928048..7348edc 100644
--- a/mono/metadata/object-internals.h
+++ b/mono/metadata/object-internals.h
@@ -568,6 +568,7 @@ typedef struct {
 	char*    (*get_runtime_build_info) (void);
 	gpointer (*get_vtable_trampoline) (int slot_index);
 	gpointer (*get_imt_trampoline) (int imt_slot_index);
+	void (*set_cast_details) (MonoClass *from, MonoClass *to);
 } MonoRuntimeCallbacks;
 
 /* used to free a dynamic method */
diff --git a/mono/metadata/object.c b/mono/metadata/object.c
index 565285f..61367e9 100644
--- a/mono/metadata/object.c
+++ b/mono/metadata/object.c
@@ -162,6 +162,13 @@ static MonoRuntimeCallbacks callbacks;
 void
 mono_thread_set_main (MonoThread *thread)
 {
+	static gboolean registered = FALSE;
+
+	if (!registered) {
+		MONO_GC_REGISTER_ROOT_SINGLE (main_thread);
+		registered = TRUE;
+	}
+
 	main_thread = thread;
 }
 
@@ -1851,6 +1858,9 @@ mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *class, gboolean
 	if (class->generic_class && !class->vtable)
 		mono_class_check_vtable_constraints (class, NULL);
 
+	/* Initialize klass->has_finalize */
+	mono_class_has_finalizer (class);
+
 	if (class->exception_type) {
 		mono_domain_unlock (domain);
 		mono_loader_unlock ();
@@ -4368,7 +4378,7 @@ mono_class_get_allocation_ftn (MonoVTable *vtable, gboolean for_box, gboolean *p
 	if (!(mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
 		profile_allocs = FALSE;
 
-	if (vtable->klass->has_finalize || vtable->klass->marshalbyref || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
+	if (mono_class_has_finalizer (vtable->klass) || vtable->klass->marshalbyref || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
 		return mono_object_new_specific;
 
 	if (!vtable->klass->has_references) {
diff --git a/mono/metadata/process.c b/mono/metadata/process.c
index f970878..83cb671 100644
--- a/mono/metadata/process.c
+++ b/mono/metadata/process.c
@@ -23,6 +23,20 @@
 #include <mono/utils/strenc.h>
 #include <mono/utils/mono-proclib.h>
 #include <mono/io-layer/io-layer.h>
+#if defined (MINGW_CROSS_COMPILE) && defined (HAVE_GETPROCESSID)
+#undef HAVE_GETPROCESSID
+#endif
+#ifndef HAVE_GETPROCESSID
+#if defined(_MSC_VER) || defined(HAVE_WINTERNL_H)
+#include <winternl.h>
+#ifndef NT_SUCCESS
+#define NT_SUCCESS(status) ((NTSTATUS) (status) >= 0)
+#endif /* !NT_SUCCESS */
+#else /* ! (defined(_MSC_VER) || defined(HAVE_WINTERNL_H)) */
+#include <ddk/ntddk.h>
+#include <ddk/ntapi.h>
+#endif /* (defined(_MSC_VER) || defined(HAVE_WINTERNL_H)) */
+#endif /* !HAVE_GETPROCESSID */
 /* FIXME: fix this code to not depend so much on the inetrnals */
 #include <mono/metadata/class-internals.h>
 
@@ -514,10 +528,6 @@ complete_path (const gunichar2 *appname, gchar **completed)
 	return TRUE;
 }
 
-#if defined (MINGW_CROSS_COMPILE) && defined (HAVE_GETPROCESSID)
-#undef HAVE_GETPROCESSID
-#endif
-
 #ifndef HAVE_GETPROCESSID
 /* Run-time GetProcessId detection for Windows */
 #ifdef TARGET_WIN32
diff --git a/mono/metadata/reflection.c b/mono/metadata/reflection.c
index 29a05d3..20e8791 100644
--- a/mono/metadata/reflection.c
+++ b/mono/metadata/reflection.c
@@ -4941,8 +4941,12 @@ mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
 			type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
 			token = mono_image_typedef_or_ref_full (assembly, type, TRUE);
 			token = mono_metadata_token_from_dor (token);
-		} else {
+		} else if (tb->module->dynamic_image == assembly) {
 			token = tb->table_idx | MONO_TOKEN_TYPE_DEF;
+		} else {
+			MonoType *type;
+			type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
+			token = mono_metadata_token_from_dor (mono_image_typedef_or_ref (assembly, type));
 		}
 	} else if (strcmp (klass->name, "MonoType") == 0) {
 		MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
@@ -6861,6 +6865,10 @@ mono_method_body_get_object (MonoDomain *domain, MonoMethod *method)
 	unsigned char format, flags;
 	int i;
 
+	/* for compatibility with .net */
+    if (method->dynamic)
+        mono_raise_exception (mono_get_exception_invalid_operation (NULL));
+
 	if (!System_Reflection_MethodBody)
 		System_Reflection_MethodBody = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MethodBody");
 	if (!System_Reflection_LocalVariableInfo)
@@ -7854,12 +7862,16 @@ handle_type:
 			int etype = *p;
 			p ++;
 
-			if (etype == 0x51)
-				/* See Partition II, Appendix B3 */
-				etype = MONO_TYPE_OBJECT;
 			type = MONO_TYPE_SZARRAY;
-			simple_type.type = etype;
-			tklass = mono_class_from_mono_type (&simple_type);
+			if (etype == 0x50) {
+				tklass = mono_defaults.systemtype_class;
+			} else {
+				if (etype == 0x51)
+					/* See Partition II, Appendix B3 */
+					etype = MONO_TYPE_OBJECT;
+				simple_type.type = etype;
+				tklass = mono_class_from_mono_type (&simple_type);
+			}
 			goto handle_enum;
 		} else if (subt == 0x55) {
 			char *n;
@@ -11234,6 +11246,7 @@ mono_reflection_create_runtime_class (MonoReflectionTypeBuilder *tb)
 	klass->flags = tb->attrs;
 	klass->has_cctor = 1;
 	klass->has_finalize = 1;
+	klass->has_finalize_inited = 1;
 
 	/* fool mono_class_setup_parent */
 	klass->supertypes = NULL;
@@ -11436,15 +11449,47 @@ mono_reflection_sighelper_get_signature_field (MonoReflectionSigHelper *sig)
 	return result;
 }
 
+typedef struct {
+	MonoMethod *handle;
+	MonoDomain *domain;
+} DynamicMethodReleaseData;
+
+/*
+ * The runtime automatically clean up those after finalization.
+*/	
+static MonoReferenceQueue *dynamic_method_queue;
+
+static void
+free_dynamic_method (void *dynamic_method)
+{
+	DynamicMethodReleaseData *data = dynamic_method;
+
+	mono_runtime_free_method (data->domain, data->handle);
+	g_free (data);
+}
+
 void 
 mono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb)
 {
+	MonoReferenceQueue *queue;
+	MonoMethod *handle;
+	DynamicMethodReleaseData *release_data;
 	ReflectionMethodBuilder rmb;
 	MonoMethodSignature *sig;
 	MonoClass *klass;
 	GSList *l;
 	int i;
 
+	if (mono_runtime_is_shutting_down ())
+		mono_raise_exception (mono_get_exception_invalid_operation (""));
+
+	if (!(queue = dynamic_method_queue)) {
+		mono_loader_lock ();
+		if (!(queue = dynamic_method_queue))
+			queue = dynamic_method_queue = mono_gc_reference_queue_new (free_dynamic_method);
+		mono_loader_unlock ();
+	}
+
 	sig = dynamic_method_to_signature (mb);
 
 	reflection_methodbuilder_from_dynamic_method (&rmb, mb);
@@ -11502,7 +11547,12 @@ mono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb)
 
 	klass = mb->owner ? mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)mb->owner)) : mono_defaults.object_class;
 
-	mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
+	mb->mhandle = handle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
+	release_data = g_new (DynamicMethodReleaseData, 1);
+	release_data->handle = handle;
+	release_data->domain = mono_object_get_domain ((MonoObject*)mb);
+	if (!mono_gc_reference_queue_add (queue, (MonoObject*)mb, release_data))
+		g_free (release_data);
 
 	/* Fix up refs entries pointing at us */
 	for (l = mb->referenced_by; l; l = l->next) {
@@ -11528,16 +11578,6 @@ mono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb)
 
 #endif /* DISABLE_REFLECTION_EMIT */
 
-void
-mono_reflection_destroy_dynamic_method (MonoReflectionDynamicMethod *mb)
-{
-	g_assert (mb);
-
-	if (mb->mhandle)
-		mono_runtime_free_method (
-			mono_object_get_domain ((MonoObject*)mb), mb->mhandle);
-}
-
 /**
  * 
  * mono_reflection_is_valid_dynamic_token:
diff --git a/mono/metadata/sgen-archdep.h b/mono/metadata/sgen-archdep.h
index 79514e9..bfb47b4 100644
--- a/mono/metadata/sgen-archdep.h
+++ b/mono/metadata/sgen-archdep.h
@@ -107,12 +107,21 @@
 #define REDZONE_SIZE	224
 
 #define ARCH_NUM_REGS 32
+#ifdef __APPLE__
 #define ARCH_STORE_REGS(ptr)	\
 	__asm__ __volatile__(	\
 		"stmw r0, 0(%0)\n"	\
 		:			\
 		: "b" (ptr)		\
 	)
+#else
+#define ARCH_STORE_REGS(ptr)	\
+	__asm__ __volatile__(	\
+		"stmw 0, 0(%0)\n"	\
+		:			\
+		: "b" (ptr)		\
+	)
+#endif
 #define ARCH_SIGCTX_SP(ctx)	(UCONTEXT_REG_Rn((ctx), 1))
 #define ARCH_SIGCTX_IP(ctx)	(UCONTEXT_REG_NIP((ctx)))
 #define ARCH_COPY_SIGCTX_REGS(a,ctx) do {	\
diff --git a/mono/metadata/sgen-bridge.c b/mono/metadata/sgen-bridge.c
new file mode 100644
index 0000000..21d13e1
--- /dev/null
+++ b/mono/metadata/sgen-bridge.c
@@ -0,0 +1,706 @@
+/*
+ * sgen-bridge.c: Simple generational GC.
+ *
+ * Copyright 2011 Novell, Inc (http://www.novell.com)
+ *
+ * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
+ * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
+ *
+ * Permission is hereby granted to use or copy this program
+ * for any purpose,  provided the above notices are retained on all copies.
+ * Permission to modify the code and to distribute modified code is granted,
+ * provided the above notices are retained, and a notice that the code was
+ * modified is included with the above copyright notice.
+ *
+ *
+ * Copyright 2001-2003 Ximian, Inc
+ * Copyright 2003-2010 Novell, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifdef HAVE_SGEN_GC
+
+#include <stdlib.h>
+
+#include "sgen-gc.h"
+#include "sgen-bridge.h"
+
+typedef struct {
+	int size;
+	int elem_size;
+	int capacity;
+	char *data;
+} DynArray;
+
+#define DYN_ARRAY_REF(da,i)	((void*)((da)->data + (i) * (da)->elem_size))
+#define DYN_ARRAY_PTR_REF(da,i)	(((void**)(da)->data) [(i)])
+#define DYN_ARRAY_INT_REF(da,i)	(((int*)(da)->data) [(i)])
+
+static void
+dyn_array_init (DynArray *da, int elem_size)
+{
+	da->size = 0;
+	da->elem_size = elem_size;
+	da->capacity = 0;
+	da->data = NULL;
+}
+
+static void
+dyn_array_ptr_init (DynArray *da)
+{
+	dyn_array_init (da, sizeof (void*));
+}
+
+static void
+dyn_array_int_init (DynArray *da)
+{
+	dyn_array_init (da, sizeof (int));
+}
+
+static void
+dyn_array_uninit (DynArray *da)
+{
+	if (da->capacity <= 0)
+		return;
+
+	mono_sgen_free_internal_dynamic (da->data, da->elem_size * da->capacity, INTERNAL_MEM_BRIDGE_DATA);
+	da->data = NULL;
+}
+
+static void
+dyn_array_ensure_capacity (DynArray *da, int capacity)
+{
+	char *new_data;
+
+	if (capacity <= da->capacity)
+		return;
+
+	if (da->capacity == 0)
+		da->capacity = 2;
+	while (capacity > da->capacity)
+		da->capacity *= 2;
+
+	new_data = mono_sgen_alloc_internal_dynamic (da->elem_size * da->capacity, INTERNAL_MEM_BRIDGE_DATA);
+	memcpy (new_data, da->data, da->elem_size * da->size);
+	mono_sgen_free_internal_dynamic (da->data, da->elem_size * da->size, INTERNAL_MEM_BRIDGE_DATA);
+	da->data = new_data;
+}
+
+static void*
+dyn_array_add (DynArray *da)
+{
+	void *p;
+
+	dyn_array_ensure_capacity (da, da->size + 1);
+
+	p = DYN_ARRAY_REF (da, da->size);
+	++da->size;
+	return p;
+}
+
+static void
+dyn_array_ptr_add (DynArray *da, void *ptr)
+{
+	void **p = dyn_array_add (da);
+	*p = ptr;
+}
+
+#define dyn_array_ptr_push dyn_array_ptr_add
+
+static void*
+dyn_array_ptr_pop (DynArray *da)
+{
+	void *p;
+	g_assert (da->size > 0);
+	p = DYN_ARRAY_PTR_REF (da, da->size - 1);
+	--da->size;
+	return p;
+}
+
+static void
+dyn_array_int_add (DynArray *da, int x)
+{
+	int *p = dyn_array_add (da);
+	*p = x;
+}
+
+/*
+static gboolean
+dyn_array_ptr_contains (DynArray *da, void *ptr)
+{
+	int i;
+	for (i = 0; i < da->size; ++i)
+		if (DYN_ARRAY_PTR_REF (da, i) == ptr)
+			return TRUE;
+	return FALSE;
+}
+*/
+
+static gboolean
+dyn_array_int_contains (DynArray *da, int x)
+{
+	int i;
+	for (i = 0; i < da->size; ++i)
+		if (DYN_ARRAY_INT_REF (da, i) == x)
+			return TRUE;
+	return FALSE;
+}
+
+static void
+dyn_array_append (DynArray *dst, DynArray *src)
+{
+	g_assert (dst->elem_size == src->elem_size);
+
+	dyn_array_ensure_capacity (dst, dst->size + src->size);
+	memcpy (DYN_ARRAY_REF (dst, dst->size), DYN_ARRAY_REF (src, 0), src->size * src->elem_size);
+	dst->size += src->size;
+}
+
+/*
+ * FIXME: Optimizations:
+ *
+ * Don't allocate a scrs array for just one source.  Most objects have
+ * just one source, so use the srcs pointer itself.
+ */
+typedef struct _HashEntry {
+	MonoObject *obj;
+	gboolean is_bridge;
+	gboolean is_visited;
+
+	int finishing_time;
+
+	DynArray srcs;
+
+	int scc_index;
+
+	struct _HashEntry *next;
+} HashEntry;
+
+typedef struct _SCC {
+	int index;
+	int api_index;
+	int num_bridge_entries;
+	DynArray xrefs;		/* these are incoming, not outgoing */
+} SCC;
+
+static int num_hash_entries = 0;
+static int hash_size = 0;
+static HashEntry **hash_table = NULL;
+
+static MonoGCBridgeCallbacks bridge_callbacks;
+
+static int current_time;
+
+void
+mono_gc_register_bridge_callbacks (MonoGCBridgeCallbacks *callbacks)
+{
+	bridge_callbacks = *callbacks;
+}
+
+gboolean
+mono_sgen_need_bridge_processing (void)
+{
+	return bridge_callbacks.cross_references != NULL;
+}
+
+static HashEntry**
+alloc_hash_table (int size)
+{
+	HashEntry **table;
+	table = mono_sgen_alloc_internal_dynamic (sizeof (HashEntry*) * size, INTERNAL_MEM_BRIDGE_DATA);
+	memset (table, 0, sizeof (HashEntry*) * size);
+	return table;
+}
+
+static void
+rehash (void)
+{
+	HashEntry **new_table;
+	int new_size = hash_size << 1;
+	int i;
+
+	new_table = alloc_hash_table (new_size);
+	for (i = 0; i < hash_size; ++i) {
+		HashEntry *entry = hash_table [i];
+		while (entry != NULL) {
+			HashEntry *next = entry->next;
+			int hash = ((mword)entry->obj >> 4) & (new_size - 1);
+			entry->next = new_table [hash];
+			new_table [hash] = entry;
+			entry = next;
+		}
+	}
+
+	mono_sgen_free_internal_dynamic (hash_table, sizeof (HashEntry*) * hash_size, INTERNAL_MEM_BRIDGE_DATA);
+
+	hash_table = new_table;
+	hash_size = new_size;
+}
+
+static HashEntry*
+lookup_hash_entry (MonoObject *obj)
+{
+	int hash = (mword)obj >> 4;
+	HashEntry *entry;
+
+	if (!hash_table) {
+		g_assert (hash_size == 0 && num_hash_entries == 0);
+		hash_size = 32;
+		hash_table = alloc_hash_table (hash_size);
+	}
+
+	hash &= hash_size - 1;
+	for (entry = hash_table [hash]; entry != NULL; entry = entry->next) {
+		if (entry->obj == obj)
+			return entry;
+	}
+
+	return NULL;
+}
+
+static HashEntry*
+get_hash_entry (MonoObject *obj)
+{
+	HashEntry *entry = lookup_hash_entry (obj);
+	int hash;
+
+	if (entry)
+		return entry;
+
+	entry = mono_sgen_alloc_internal_dynamic (sizeof (HashEntry), INTERNAL_MEM_BRIDGE_DATA);
+	memset (entry, 0, sizeof (HashEntry));
+
+	entry->obj = obj;
+	dyn_array_ptr_init (&entry->srcs);
+	entry->finishing_time = -1;
+	entry->scc_index = -1;
+
+	hash = ((mword)obj >> 4) & (hash_size - 1);
+	entry->next = hash_table [hash];
+	hash_table [hash] = entry;
+
+	++num_hash_entries;
+
+	if (num_hash_entries > hash_size >> 1)
+		rehash ();
+
+	return entry;
+}
+
+static void
+add_source (HashEntry *entry, HashEntry *src)
+{
+	dyn_array_ptr_add (&entry->srcs, src);
+}
+
+static void
+free_data (void)
+{
+	int i;
+	int total_srcs = 0;
+	int max_srcs = 0;
+
+	if (hash_table == NULL)
+		return;
+
+	for (i = 0; i < hash_size; ++i) {
+		HashEntry *entry = hash_table [i];
+		while (entry != NULL) {
+			HashEntry *next = entry->next;
+			total_srcs += entry->srcs.size;
+			if (entry->srcs.size > max_srcs)
+				max_srcs = entry->srcs.size;
+			dyn_array_uninit (&entry->srcs);
+			mono_sgen_free_internal_dynamic (entry, sizeof (HashEntry), INTERNAL_MEM_BRIDGE_DATA);
+			entry = next;
+		}
+	}
+
+	mono_sgen_free_internal_dynamic (hash_table, sizeof (HashEntry*) * hash_size, INTERNAL_MEM_BRIDGE_DATA);
+
+	hash_size = 0;
+	num_hash_entries = 0;
+	hash_table = NULL;
+
+	//g_print ("total srcs %d - max %d\n", total_srcs, max_srcs);
+}
+
+static void
+register_bridge_object (MonoObject *obj)
+{
+	HashEntry *entry = get_hash_entry (obj);
+	g_assert (!entry->is_bridge);
+	entry->is_bridge = TRUE;
+}
+
+static void
+register_finishing_time (HashEntry *entry, int t)
+{
+	g_assert (entry->finishing_time < 0);
+	entry->finishing_time = t;
+}
+
+static gboolean
+object_is_live (MonoObject **objp)
+{
+	MonoObject *obj = *objp;
+	MonoObject *fwd = SGEN_OBJECT_IS_FORWARDED (obj);
+	if (fwd) {
+		*objp = fwd;
+		return lookup_hash_entry (fwd) == NULL;
+	}
+	if (!mono_sgen_object_is_live (obj))
+		return FALSE;
+	return lookup_hash_entry (obj) == NULL;
+}
+
+static DynArray dfs_stack;
+
+#undef HANDLE_PTR
+#define HANDLE_PTR(ptr,obj)	do {					\
+		MonoObject *dst = (MonoObject*)*(ptr);			\
+		if (dst && !object_is_live (&dst)) {			\
+			dyn_array_ptr_push (&dfs_stack, obj_entry);	\
+			dyn_array_ptr_push (&dfs_stack, get_hash_entry (dst)); \
+		}							\
+	} while (0)
+
+static void
+dfs1 (HashEntry *obj_entry, HashEntry *src)
+{
+	g_assert (dfs_stack.size == 0);
+
+	dyn_array_ptr_push (&dfs_stack, src);
+	dyn_array_ptr_push (&dfs_stack, obj_entry);
+
+	do {
+		MonoObject *obj;
+		char *start;
+
+		obj_entry = dyn_array_ptr_pop (&dfs_stack);
+		if (obj_entry) {
+			src = dyn_array_ptr_pop (&dfs_stack);
+
+			obj = obj_entry->obj;
+			start = (char*)obj;
+
+			if (src) {
+				//g_print ("link %s -> %s\n", mono_sgen_safe_name (src->obj), mono_sgen_safe_name (obj));
+				add_source (obj_entry, src);
+			} else {
+				//g_print ("starting with %s\n", mono_sgen_safe_name (obj));
+			}
+
+			if (obj_entry->is_visited)
+				continue;
+
+			obj_entry->is_visited = TRUE;
+
+			dyn_array_ptr_push (&dfs_stack, obj_entry);
+			/* NULL marks that the next entry is to be finished */
+			dyn_array_ptr_push (&dfs_stack, NULL);
+
+#include "sgen-scan-object.h"
+		} else {
+			obj_entry = dyn_array_ptr_pop (&dfs_stack);
+
+			//g_print ("finish %s\n", mono_sgen_safe_name (obj_entry->obj));
+			register_finishing_time (obj_entry, current_time++);
+		}
+	} while (dfs_stack.size > 0);
+}
+
+static void
+scc_add_xref (SCC *src, SCC *dst)
+{
+	g_assert (src != dst);
+	g_assert (src->index != dst->index);
+
+	if (dyn_array_int_contains (&dst->xrefs, src->index))
+		return;
+	if (src->num_bridge_entries) {
+		dyn_array_int_add (&dst->xrefs, src->index);
+	} else {
+		int i;
+		// FIXME: uniq here
+		dyn_array_append (&dst->xrefs, &src->xrefs);
+		for (i = 0; i < dst->xrefs.size; ++i)
+			g_assert (DYN_ARRAY_INT_REF (&dst->xrefs, i) != dst->index);
+	}
+}
+
+static void
+scc_add_entry (SCC *scc, HashEntry *entry)
+{
+	g_assert (entry->scc_index < 0);
+	entry->scc_index = scc->index;
+	if (entry->is_bridge)
+		++scc->num_bridge_entries;
+}
+
+static DynArray sccs;
+static SCC *current_scc;
+
+static void
+dfs2 (HashEntry *entry)
+{
+	int i;
+
+	g_assert (dfs_stack.size == 0);
+
+	dyn_array_ptr_push (&dfs_stack, entry);
+
+	do {
+		entry = dyn_array_ptr_pop (&dfs_stack);
+
+		if (entry->scc_index >= 0) {
+			if (entry->scc_index != current_scc->index)
+				scc_add_xref (DYN_ARRAY_REF (&sccs, entry->scc_index), current_scc);
+			continue;
+		}
+
+		scc_add_entry (current_scc, entry);
+
+		for (i = 0; i < entry->srcs.size; ++i)
+			dyn_array_ptr_push (&dfs_stack, DYN_ARRAY_PTR_REF (&entry->srcs, i));
+	} while (dfs_stack.size > 0);
+}
+
+static int
+compare_hash_entries (const void *ep1, const void *ep2)
+{
+	HashEntry *e1 = *(HashEntry**)ep1;
+	HashEntry *e2 = *(HashEntry**)ep2;
+	return e2->finishing_time - e1->finishing_time;
+}
+
+void
+mono_sgen_bridge_processing (int num_objs, MonoObject **objs)
+{
+	HashEntry **all_entries;
+	int j = 0;
+	int num_sccs, num_xrefs;
+	int max_entries, max_xrefs;
+	int i;
+	MonoGCBridgeSCC **api_sccs;
+	MonoGCBridgeXRef *api_xrefs;
+
+	g_assert (mono_sgen_need_bridge_processing ());
+
+	//g_print ("%d finalized objects\n", num_objs);
+
+	/* remove objects that are not bridge objects */
+
+	for (i = 0; i < num_objs; ++i) {
+		MonoObject *obj = objs [i];
+		//g_assert (!mono_sgen_object_is_live (obj));
+		if (bridge_callbacks.is_bridge_object (obj)) {
+			register_bridge_object (obj);
+			objs [j++] = obj;
+		}
+	}
+	num_objs = j;
+
+	//g_print ("%d bridge objects\n", num_objs);
+
+	/* first DFS pass */
+
+	dyn_array_ptr_init (&dfs_stack);
+
+	current_time = 0;
+	for (i = 0; i < num_objs; ++i)
+		dfs1 (get_hash_entry (objs [i]), NULL);
+
+	//g_print ("%d entries - hash size %d\n", num_hash_entries, hash_size);
+
+	/* alloc and fill array of all entries */
+
+	all_entries = mono_sgen_alloc_internal_dynamic (sizeof (HashEntry*) * num_hash_entries, INTERNAL_MEM_BRIDGE_DATA);
+
+	j = 0;
+	max_entries = 0;
+	for (i = 0; i < hash_size; ++i) {
+		HashEntry *entry;
+		int length = 0;
+		for (entry = hash_table [i]; entry != NULL; entry = entry->next) {
+			g_assert (entry->finishing_time >= 0);
+			all_entries [j++] = entry;
+			++length;
+		}
+		if (length > max_entries)
+			max_entries = length;
+	}
+	g_assert (j == num_hash_entries);
+
+	//g_print ("max hash bucket length %d\n", max_entries);
+
+	/* sort array according to decreasing finishing time */
+
+	qsort (all_entries, num_hash_entries, sizeof (HashEntry*), compare_hash_entries);
+
+	/* second DFS pass */
+
+	dyn_array_init (&sccs, sizeof (SCC));
+	for (i = 0; i < num_hash_entries; ++i) {
+		HashEntry *entry = all_entries [i];
+		if (entry->scc_index < 0) {
+			int index = sccs.size;
+			current_scc = dyn_array_add (&sccs);
+			current_scc->index = index;
+			current_scc->num_bridge_entries = 0;
+			current_scc->api_index = -1;
+			dyn_array_int_init (&current_scc->xrefs);
+
+			dfs2 (entry);
+		}
+	}
+
+	//g_print ("%d sccs\n", sccs.size);
+
+	dyn_array_uninit (&dfs_stack);
+
+	/* init data for callback */
+
+	num_sccs = 0;
+	for (i = 0; i < sccs.size; ++i) {
+		SCC *scc = DYN_ARRAY_REF (&sccs, i);
+		g_assert (scc->index == i);
+		if (scc->num_bridge_entries)
+			++num_sccs;
+	}
+
+	api_sccs = mono_sgen_alloc_internal_dynamic (sizeof (MonoGCBridgeSCC*) * num_sccs, INTERNAL_MEM_BRIDGE_DATA);
+	num_xrefs = 0;
+	j = 0;
+	for (i = 0; i < sccs.size; ++i) {
+		SCC *scc = DYN_ARRAY_REF (&sccs, i);
+		if (!scc->num_bridge_entries)
+			continue;
+
+		api_sccs [j] = mono_sgen_alloc_internal_dynamic (sizeof (MonoGCBridgeSCC) + sizeof (MonoObject*) * scc->num_bridge_entries, INTERNAL_MEM_BRIDGE_DATA);
+		api_sccs [j]->num_objs = scc->num_bridge_entries;
+		scc->num_bridge_entries = 0;
+		scc->api_index = j++;
+
+		num_xrefs += scc->xrefs.size;
+	}
+
+	for (i = 0; i < hash_size; ++i) {
+		HashEntry *entry;
+		for (entry = hash_table [i]; entry != NULL; entry = entry->next) {
+			SCC *scc;
+			if (!entry->is_bridge)
+				continue;
+			scc = DYN_ARRAY_REF (&sccs, entry->scc_index);
+			api_sccs [scc->api_index]->objs [scc->num_bridge_entries++] = entry->obj;
+		}
+	}
+
+	api_xrefs = mono_sgen_alloc_internal_dynamic (sizeof (MonoGCBridgeXRef) * num_xrefs, INTERNAL_MEM_BRIDGE_DATA);
+	j = 0;
+	for (i = 0; i < sccs.size; ++i) {
+		int k;
+		SCC *scc = DYN_ARRAY_REF (&sccs, i);
+		if (!scc->num_bridge_entries)
+			continue;
+		for (k = 0; k < scc->xrefs.size; ++k) {
+			SCC *src_scc = DYN_ARRAY_REF (&sccs, DYN_ARRAY_INT_REF (&scc->xrefs, k));
+			if (!src_scc->num_bridge_entries)
+				continue;
+			api_xrefs [j].src_scc_index = src_scc->api_index;
+			api_xrefs [j].dst_scc_index = scc->api_index;
+			++j;
+		}
+	}
+
+	/* free data */
+
+	j = 0;
+	max_entries = max_xrefs = 0;
+	for (i = 0; i < sccs.size; ++i) {
+		SCC *scc = DYN_ARRAY_REF (&sccs, i);
+		if (scc->num_bridge_entries)
+			++j;
+		if (scc->num_bridge_entries > max_entries)
+			max_entries = scc->num_bridge_entries;
+		if (scc->xrefs.size > max_xrefs)
+			max_xrefs = scc->xrefs.size;
+		dyn_array_uninit (&scc->xrefs);
+
+	}
+	dyn_array_uninit (&sccs);
+
+	mono_sgen_free_internal_dynamic (all_entries, sizeof (HashEntry*) * num_hash_entries, INTERNAL_MEM_BRIDGE_DATA);
+
+	free_data ();
+
+	//g_print ("%d sccs containing bridges - %d max bridge objects - %d max xrefs\n", j, max_entries, max_xrefs);
+
+	/* callback */
+
+	bridge_callbacks.cross_references (num_sccs, api_sccs, num_xrefs, api_xrefs);
+
+	/* free callback data */
+
+	for (i = 0; i < num_sccs; ++i) {
+		mono_sgen_free_internal_dynamic (api_sccs [i],
+				sizeof (MonoGCBridgeSCC) + sizeof (MonoObject*) * api_sccs [i]->num_objs,
+				INTERNAL_MEM_BRIDGE_DATA);
+	}
+	mono_sgen_free_internal_dynamic (api_sccs, sizeof (MonoGCBridgeSCC*) * num_sccs, INTERNAL_MEM_BRIDGE_DATA);
+
+	mono_sgen_free_internal_dynamic (api_xrefs, sizeof (MonoGCBridgeXRef) * num_xrefs, INTERNAL_MEM_BRIDGE_DATA);
+}
+
+static gboolean
+bridge_test_is_bridge_object (MonoObject *obj)
+{
+	return TRUE;
+}
+
+static void
+bridge_test_cross_reference (int num_sccs, MonoGCBridgeSCC **sccs, int num_xrefs, MonoGCBridgeXRef *xrefs)
+{
+	int i;
+	for (i = 0; i < num_sccs; ++i) {
+		int j;
+		g_print ("--- SCC %d\n", i);
+		for (j = 0; j < sccs [i]->num_objs; ++j)
+			g_print ("  %s\n", mono_sgen_safe_name (sccs [i]->objs [j]));
+	}
+	for (i = 0; i < num_xrefs; ++i) {
+		g_assert (xrefs [i].src_scc_index >= 0 && xrefs [i].src_scc_index < num_sccs);
+		g_assert (xrefs [i].dst_scc_index >= 0 && xrefs [i].dst_scc_index < num_sccs);
+		g_print ("%d -> %d\n", xrefs [i].src_scc_index, xrefs [i].dst_scc_index);
+	}
+}
+
+
+void
+mono_sgen_register_test_bridge_callbacks (void)
+{
+	MonoGCBridgeCallbacks callbacks;
+	callbacks.is_bridge_object = bridge_test_is_bridge_object;
+	callbacks.cross_references = bridge_test_cross_reference;
+	mono_gc_register_bridge_callbacks (&callbacks);
+}
+
+#endif
diff --git a/mono/metadata/sgen-bridge.h b/mono/metadata/sgen-bridge.h
new file mode 100644
index 0000000..98bdfe6
--- /dev/null
+++ b/mono/metadata/sgen-bridge.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2011 Novell, Inc.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef _MONO_SGEN_BRIDGE_H_
+#define _MONO_SGEN_BRIDGE_H_
+
+#include <mono/utils/mono-publib.h>
+
+MONO_BEGIN_DECLS
+
+typedef struct {
+	int num_objs;
+	MonoObject *objs [MONO_ZERO_LEN_ARRAY];
+} MonoGCBridgeSCC;
+
+typedef struct {
+	int src_scc_index;
+	int dst_scc_index;
+} MonoGCBridgeXRef;
+
+typedef struct {
+	mono_bool (*is_bridge_object) (MonoObject *obj);
+	void (*cross_references) (int num_sccs, MonoGCBridgeSCC **sccs, int num_xrefs, MonoGCBridgeXRef *xrefs);
+} MonoGCBridgeCallbacks;
+
+void mono_gc_register_bridge_callbacks (MonoGCBridgeCallbacks *callbacks);
+
+MONO_END_DECLS
+
+#endif
diff --git a/mono/metadata/sgen-gc.c b/mono/metadata/sgen-gc.c
index d5c3f3c..6dc796f 100644
--- a/mono/metadata/sgen-gc.c
+++ b/mono/metadata/sgen-gc.c
@@ -202,6 +202,7 @@
 #include "metadata/sgen-cardtable.h"
 #include "metadata/sgen-protocol.h"
 #include "metadata/sgen-archdep.h"
+#include "metadata/sgen-bridge.h"
 #include "metadata/mono-gc.h"
 #include "metadata/method-builder.h"
 #include "metadata/profiler-private.h"
@@ -825,7 +826,7 @@ static void find_pinning_ref_from_thread (char *obj, size_t size);
 static void update_current_thread_stack (void *start);
 static void finalize_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation, GrayQueue *queue);
 static void add_or_remove_disappearing_link (MonoObject *obj, void **link, gboolean track, int generation);
-static void null_link_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation, GrayQueue *queue);
+static void null_link_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation, gboolean before_finalization, GrayQueue *queue);
 static void null_links_for_domain (MonoDomain *domain, int generation);
 static gboolean search_fragment_for_size (size_t size);
 static int search_fragment_for_size_range (size_t desired_size, size_t minimum_size);
@@ -2443,6 +2444,28 @@ get_finalize_entry_hash_table (int generation)
 	}
 }
 
+static MonoObject **finalized_array = NULL;
+static int finalized_array_capacity = 0;
+static int finalized_array_entries = 0;
+
+static void
+bridge_register_finalized_object (MonoObject *object)
+{
+	if (!finalized_array)
+		return;
+
+	if (finalized_array_entries >= finalized_array_capacity) {
+		MonoObject **new_array;
+		g_assert (finalized_array_entries == finalized_array_capacity);
+		finalized_array_capacity *= 2;
+		new_array = mono_sgen_alloc_internal_dynamic (sizeof (MonoObject*) * finalized_array_capacity, INTERNAL_MEM_BRIDGE_DATA);
+		memcpy (new_array, finalized_array, sizeof (MonoObject*) * finalized_array_entries);
+		mono_sgen_free_internal_dynamic (finalized_array, sizeof (MonoObject*) * finalized_array_entries, INTERNAL_MEM_BRIDGE_DATA);
+		finalized_array = new_array;
+	}
+	finalized_array [finalized_array_entries++] = object;
+}
+
 static void
 finish_gray_stack (char *start_addr, char *end_addr, int generation, GrayQueue *queue)
 {
@@ -2450,6 +2473,7 @@ finish_gray_stack (char *start_addr, char *end_addr, int generation, GrayQueue *
 	TV_DECLARE (btv);
 	int fin_ready;
 	int ephemeron_rounds = 0;
+	int num_loops;
 	CopyOrMarkObjectFunc copy_func = current_collection_generation == GENERATION_NURSERY ? major_collector.copy_object : major_collector.copy_or_mark_object;
 
 	/*
@@ -2468,6 +2492,21 @@ finish_gray_stack (char *start_addr, char *end_addr, int generation, GrayQueue *
 	drain_gray_stack (queue);
 	TV_GETTIME (atv);
 	DEBUG (2, fprintf (gc_debug_file, "%s generation done\n", generation_name (generation)));
+
+	/*
+	We must clear weak links that don't track resurrection before processing object ready for
+	finalization so they can be cleared before that.
+	*/
+	null_link_in_range (copy_func, start_addr, end_addr, generation, TRUE, queue);
+	if (generation == GENERATION_OLD)
+		null_link_in_range (copy_func, start_addr, end_addr, GENERATION_NURSERY, TRUE, queue);
+
+	if (finalized_array == NULL && mono_sgen_need_bridge_processing ()) {
+		finalized_array_capacity = 32;
+		finalized_array = mono_sgen_alloc_internal_dynamic (sizeof (MonoObject*) * finalized_array_capacity, INTERNAL_MEM_BRIDGE_DATA);
+	}
+	finalized_array_entries = 0;
+
 	/* walk the finalization queue and move also the objects that need to be
 	 * finalized: use the finalized objects as new roots so the objects they depend
 	 * on are also not reclaimed. As with the roots above, only objects in the nursery
@@ -2475,6 +2514,7 @@ finish_gray_stack (char *start_addr, char *end_addr, int generation, GrayQueue *
 	 * We need a loop here, since objects ready for finalizers may reference other objects
 	 * that are fin-ready. Speedup with a flag?
 	 */
+	num_loops = 0;
 	do {
 		/*
 		 * Walk the ephemeron tables marking all values with reachable keys. This must be completely done
@@ -2495,11 +2535,20 @@ finish_gray_stack (char *start_addr, char *end_addr, int generation, GrayQueue *
 		if (generation == GENERATION_OLD)
 			finalize_in_range (copy_func, nursery_start, nursery_real_end, GENERATION_NURSERY, queue);
 
+		if (fin_ready != num_ready_finalizers) {
+			++num_loops;
+			if (finalized_array != NULL)
+				mono_sgen_bridge_processing (finalized_array_entries, finalized_array);
+		}
+
 		/* drain the new stack that might have been created */
 		DEBUG (6, fprintf (gc_debug_file, "Precise scan of gray area post fin\n"));
 		drain_gray_stack (queue);
 	} while (fin_ready != num_ready_finalizers);
 
+	if (mono_sgen_need_bridge_processing ())
+		g_assert (num_loops <= 1);
+
 	/*
 	 * Clear ephemeron pairs with unreachable keys.
 	 * We pass the copy func so we can figure out if an array was promoted or not.
@@ -2519,9 +2568,9 @@ finish_gray_stack (char *start_addr, char *end_addr, int generation, GrayQueue *
 	 */
 	g_assert (gray_object_queue_is_empty (queue));
 	for (;;) {
-		null_link_in_range (copy_func, start_addr, end_addr, generation, queue);
+		null_link_in_range (copy_func, start_addr, end_addr, generation, FALSE, queue);
 		if (generation == GENERATION_OLD)
-			null_link_in_range (copy_func, start_addr, end_addr, GENERATION_NURSERY, queue);
+			null_link_in_range (copy_func, start_addr, end_addr, GENERATION_NURSERY, FALSE, queue);
 		if (gray_object_queue_is_empty (queue))
 			break;
 		drain_gray_stack (queue);
@@ -4061,6 +4110,7 @@ finalize_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int g
 					num_ready_finalizers++;
 					hash_table->num_registered--;
 					queue_finalization_entry (entry);
+					bridge_register_finalized_object ((MonoObject*)copy);
 					/* Make it survive */
 					from = entry->object;
 					entry->object = copy;
@@ -4115,6 +4165,16 @@ object_is_reachable (char *object, char *start, char *end)
 	return !object_is_fin_ready (object) || major_collector.is_object_live (object);
 }
 
+gboolean
+mono_sgen_object_is_live (void *obj)
+{
+	if (ptr_in_nursery (obj))
+		return object_is_pinned (obj);
+	if (current_collection_generation == GENERATION_NURSERY)
+		return FALSE;
+	return major_collector.is_object_live (obj);
+}
+
 /* LOCKING: requires that the GC lock is held */
 static void
 null_ephemerons_for_domain (MonoDomain *domain)
@@ -4276,7 +4336,7 @@ mark_ephemerons_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end
 
 /* LOCKING: requires that the GC lock is held */
 static void
-null_link_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation, GrayQueue *queue)
+null_link_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation, gboolean before_finalization, GrayQueue *queue)
 {
 	DisappearingLinkHashTable *hash = get_dislink_hash_table (generation);
 	DisappearingLink **disappearing_link_hash = hash->table;
@@ -4288,9 +4348,17 @@ null_link_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int
 	for (i = 0; i < disappearing_link_hash_size; ++i) {
 		prev = NULL;
 		for (entry = disappearing_link_hash [i]; entry;) {
-			char *object = DISLINK_OBJECT (entry);
+			char *object;
+			gboolean track = DISLINK_TRACK (entry);
+			if (track == before_finalization) {
+				prev = entry;
+				entry = entry->next;
+				continue;
+			}
+
+			object = DISLINK_OBJECT (entry);
+
 			if (object >= start && object < end && !major_collector.is_object_live (object)) {
-				gboolean track = DISLINK_TRACK (entry);
 				if (!track && object_is_fin_ready (object)) {
 					void **p = entry->link;
 					DisappearingLink *old;
@@ -5768,7 +5836,15 @@ unregister_current_thread (void)
 static void
 unregister_thread (void *k)
 {
-	g_assert (!mono_domain_get ());
+	/* If a delegate is passed to native code and invoked on a thread we dont
+	 * know about, the jit will register it with mono_jit_thead_attach, but
+	 * we have no way of knowing when that thread goes away.  SGen has a TSD
+	 * so we assume that if the domain is still registered, we can detach
+	 * the thread
+	 */
+	if (mono_domain_get ())
+		mono_thread_detach (mono_thread_current ());
+
 	LOCK_GC;
 	unregister_current_thread ();
 	UNLOCK_GC;
@@ -6909,10 +6985,6 @@ mono_gc_base_init (void)
 	struct sigaction sinfo;
 	glong max_heap = 0;
 
-#ifdef PLATFORM_ANDROID
-	g_assert_not_reached ();
-#endif
-
 	/* the gc_initialized guard seems to imply this method is
 	   idempotent, but LOCK_INIT(gc_mutex) might not be.  It's
 	   defined in sgen-gc.h as nothing, so there's no danger at
@@ -7531,7 +7603,7 @@ mono_gc_get_managed_array_allocator (MonoVTable *vtable, int rank)
 		return NULL;
 	if (collect_before_allocs)
 		return NULL;
-	g_assert (!klass->has_finalize && !klass->marshalbyref);
+	g_assert (!mono_class_has_finalizer (klass) && !klass->marshalbyref);
 
 	return mono_gc_get_managed_allocator_by_type (ATYPE_VECTOR);
 #else
diff --git a/mono/metadata/sgen-gc.h b/mono/metadata/sgen-gc.h
index af37843..1282118 100644
--- a/mono/metadata/sgen-gc.h
+++ b/mono/metadata/sgen-gc.h
@@ -612,6 +612,7 @@ enum {
 	INTERNAL_MEM_MS_BLOCK_INFO,
 	INTERNAL_MEM_EPHEMERON_LINK,
 	INTERNAL_MEM_WORKER_DATA,
+	INTERNAL_MEM_BRIDGE_DATA,
 	INTERNAL_MEM_MAX
 };
 
@@ -768,6 +769,11 @@ mono_sgen_par_object_get_size (MonoVTable *vtable, MonoObject* o)
 
 const char* mono_sgen_safe_name (void* obj) MONO_INTERNAL;
 
+gboolean mono_sgen_object_is_live (void *obj) MONO_INTERNAL;
+
+gboolean mono_sgen_need_bridge_processing (void) MONO_INTERNAL;
+void mono_sgen_bridge_processing (int num_objs, MonoObject **objs) MONO_INTERNAL;
+
 enum {
 	SPACE_MAJOR,
 	SPACE_LOS
diff --git a/mono/metadata/sgen-internal.c b/mono/metadata/sgen-internal.c
index e42cce4..2f7b7ce 100644
--- a/mono/metadata/sgen-internal.c
+++ b/mono/metadata/sgen-internal.c
@@ -494,7 +494,8 @@ mono_sgen_dump_internal_mem_usage (FILE *heap_dump_file)
 						     "fin-table", "finalize-entry", "dislink-table",
 						     "dislink", "roots-table", "root-record", "statistics",
 						     "remset", "gray-queue", "store-remset", "marksweep-tables",
-						     "marksweep-block-info", "ephemeron-link" };
+						     "marksweep-block-info", "ephemeron-link", "worker-data",
+						     "bridge-data" };
 
 	int i;
 
diff --git a/mono/metadata/sgen-os-mach.c b/mono/metadata/sgen-os-mach.c
index ea74a4d..8d51620 100644
--- a/mono/metadata/sgen-os-mach.c
+++ b/mono/metadata/sgen-os-mach.c
@@ -118,9 +118,13 @@ mono_sgen_thread_handshake (int signum)
 			count ++;
 
 			mach_port_deallocate (task, t);
+		} else {
+			mach_port_deallocate (task, t);
 		}
 	}
 
+	mono_mach_free_threads (thread_list, num_threads);
+
 	mach_port_deallocate (task, cur_thread);
 
 	return count;
diff --git a/mono/mini/ChangeLog b/mono/mini/ChangeLog
index fa5148b..3bb21ca 100644
--- a/mono/mini/ChangeLog
+++ b/mono/mini/ChangeLog
@@ -1,3 +1,181 @@
+2011-02-13  Alexandre Mutel  <alexandre_mutel at yahoo.fr>
+
+	Fix sizeof(T) in non-gshared code. Fixes #580189.
+
+2011-02-11  Zoltan Varga  <vargaz at gmail.com>
+
+	Change some Sleep(0)'s to Sleep(1) in the soft-debugger code to
+	avoid 100% cpu utilization on windows.
+
+2011-02-09  Zoltan Varga  <vargaz at gmail.com>
+
+	Disable OP_INEG cfolding on 32 bit arches, as it breaks the LNEG
+	decomposition. The previous special casing didn't work as the
+	spill pass could insert a store between the ineg and the adc_imm.
+	Fixes #670479.
+
+2011-02-07  Zoltan Varga  <vargaz at gmail.com>
+
+	Cast the result of MONO_CONTEXT_GET_SP () to an int to fix the
+	windows build.
+
+2011-02-07  Zoltan Varga  <vargaz at gmail.com>
+
+	Include sys/types.h for pid_t on mingw. Fixes #670076.
+
+2011-02-06  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix the ia64 build.
+
+2011-02-05  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	* mini-trampolines.c (mono_delegate_trampoline): The ldftn to
+	ldvtftn conversion must check if the method is abstract, otherwise
+	it breaks delegate to base classes.
+
+	Fixes #666008
+
+2011-02-04  Zoltan Varga  <vargaz at gmail.com>
+
+	Print a normal stack trace even if a hard stack overflow happens
+	in unmanaged code.
+
+2011-02-03  Zoltan Varga  <vargaz at gmail.com>
+
+	Print a normal stack trace on a hard stack overflow.
+
+2011-02-03  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix the handling of CompareExchange icalls in AOT, we were using
+	the 'object' versions for everything, which broke with 64 bit
+	types on 32 bit platforms.
+
+2011-02-03  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix the passing of vtype arguments for methods which return floats
+	in soft-float mode. Fixes #668905.
+
+2011-02-03  Zoltan Varga  <vargaz at gmail.com>
+
+	Add support for --debug=casts to Array:SetValue (). Fixes #668851.
+
+2011-02-02  Rodrigo Kumpera  <kumpera at gmail.com>
+
+	* mini-x86.c (emit_call): Align call instructions on 3 mod 4 so
+	the address is 4 bytes aligned and can't span two cache lines.
+	This is required for proper SMP support as CAS is not atomic
+	across cache lines.
+
+	Fixes one of the crashes due to #667921.
+
+2010-10-26  Lucas Meijer  <lucas at unity3d.com>
+
+	make mono_print_thread_dump output to the visualstudio debugger
+	window, for better debugger experience
+
+2011-01-31  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix stack walks on sparc.
+
+2011-01-31  Zoltan Varga  <vargaz at gmail.com>
+
+	When using xdebug, allocate all code from the code manager of the
+	root domain. Hopefully fixes #666152.
+
+2011-01-30  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix some quadratic behavior in the AOT compiler.
+
+2011-01-30  Zoltan Varga  <vargaz at gmail.com>
+
+	Improve hashing of MONO_PATCH_INFO_TYPE_FROM_HANDLE.
+
+2011-01-30  Zoltan Varga  <vargaz at gmail.com>
+
+	Mark a newly added test as !FULLAOT.
+
+2011-01-30  Zoltan Varga  <vargaz at gmail.com>
+
+	Don't crash when inlining static methods called using callvirt.
+	Fixes #668170.
+
+2011-01-29  Zoltan Varga  <vargaz at gmail.com>
+
+	Clear the 'need_rgctx_tramp' flag when creating a synchronized
+	wrapper. Fixes
+
+2011-01-28  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Bump SDB protocol so MonoDevelop can guard IL inspection of
+	dynamic methods
+
+2011-01-27  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Dont leak loader errors in the aot compiler, as it could cause
+	later methods to not get compiled erroneously
+
+2011-01-27  Zoltan Varga  <vargaz at gmail.com>
+
+	Increase an aot buffer size again.
+
+2011-01-27  Zoltan Varga  <vargaz at gmail.com>
+
+	Add AOT support for castclass_with_cache wrappers.
+
+2011-01-26  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Ensure we properly align the stack before resuming from breakpoint
+	signal handlers
+
+2011-01-26  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Dynamic methods are classes already here
+
+2011-01-26  Zoltan Varga  <vargaz at gmail.com>
+
+	Add a 'suspend-on-unhandled' MONO_DEBUG option to help track down
+	the random build failures on ia64.
+
+2011-01-22  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix an assert which happens when a call is made to Nullable.Unbox
+	from gshared code in AOT.
+
+2011-01-21  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix the previous aot fix.
+
+2011-01-21  Zoltan Varga  <vargaz at gmail.com>
+
+	Add a test for infinite generic recursion + AOT.
+
+2011-01-21  Zoltan Varga  <vargaz at gmail.com>
+
+	Only add imt items whose is_equal flag is set to the array passed
+	to the full-aot imt thunk.
+
+2011-01-21  Zoltan Varga  <vargaz at gmail.com>
+
+	Avoid emitting .note.GNU-stack on arm.
+
+2011-01-21  Zoltan Varga  <vargaz at gmail.com>
+
+	Detect inifinite generic recursion differently in the AOT
+	compiler.
+
+2011-01-20  Zoltan Varga  <vargaz at gmail.com>
+
+	Properly align the stack in the arm generic trampoline.
+
+2011-01-20  Zoltan Varga  <vargaz at gmail.com>
+
+	Add a TID field to ThreadMirror which returns the system thread
+	id.
+
+2011-01-18  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	Happy new year.
+
 2011-01-18  Zoltan Varga  <vargaz at gmail.com>
 
 	Make the stacks of aot image non-executable.
diff --git a/mono/mini/aot-compiler.c b/mono/mini/aot-compiler.c
index 0525e85..0749c25 100644
--- a/mono/mini/aot-compiler.c
+++ b/mono/mini/aot-compiler.c
@@ -144,7 +144,7 @@ typedef struct MonoAotCompile {
 	GPtrArray *extra_methods;
 	GPtrArray *image_table;
 	GPtrArray *globals;
-	GList *method_order;
+	GPtrArray *method_order;
 	guint32 *plt_got_info_offsets;
 	guint32 got_offset, plt_offset, plt_got_offset_base;
 	guint32 final_got_size;
@@ -526,7 +526,7 @@ arch_init (MonoAotCompile *acfg)
 	acfg->need_no_dead_strip = TRUE;
 #endif
 
-#if defined(__linux__)
+#if defined(__linux__) && !defined(TARGET_ARM)
 	acfg->need_pt_gnu_stack = TRUE;
 #endif
 }
@@ -2036,6 +2036,13 @@ encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8
 				g_assert_not_reached ();
 			}
 			break;
+		case MONO_WRAPPER_CASTCLASS:
+			if (!strcmp (method->name, "__castclass_with_cache")) {
+				encode_value (MONO_AOT_WRAPPER_CASTCLASS_WITH_CACHE, p, &p);
+			} else {
+				g_assert_not_reached ();
+			}
+			break;
 		default:
 			g_assert_not_reached ();
 		}
@@ -2317,8 +2324,7 @@ add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int d
 	index = acfg->method_index;
 	add_method_with_index (acfg, method, index, extra);
 
-	/* FIXME: Fix quadratic behavior */
-	acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
+	g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
 
 	g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
 
@@ -2609,7 +2615,12 @@ add_wrappers (MonoAotCompile *acfg)
 			klass = mono_class_get (acfg->image, token);
 			if (klass)
 				add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
+			else
+				mono_loader_clear_error ();
 		}
+
+		/* castclass_with_check wrapper */
+		add_method (acfg, mono_marshal_get_castclass_with_cache ());
 	}
 
 	/* 
@@ -2642,6 +2653,11 @@ add_wrappers (MonoAotCompile *acfg)
 		token = MONO_TOKEN_TYPE_DEF | (i + 1);
 		klass = mono_class_get (acfg->image, token);
 
+		if (!klass) {
+			mono_loader_clear_error ();
+			continue;
+		}
+
 		if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
 			method = mono_get_delegate_invoke (klass);
 
@@ -2749,6 +2765,11 @@ add_wrappers (MonoAotCompile *acfg)
 		token = MONO_TOKEN_TYPE_DEF | (i + 1);
 		klass = mono_class_get (acfg->image, token);
 
+		if (!klass) {
+			mono_loader_clear_error ();
+			continue;
+		}
+
 		if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
 			add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
 			add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
@@ -2807,6 +2828,34 @@ add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force)
 	add_generic_class_with_depth (acfg, klass, 0);
 }
 
+static gboolean
+check_type_depth (MonoType *t, int depth)
+{
+	int i;
+
+	if (depth > 8)
+		return TRUE;
+
+	switch (t->type) {
+	case MONO_TYPE_GENERICINST: {
+		MonoGenericClass *gklass = t->data.generic_class;
+		MonoGenericInst *ginst = gklass->context.class_inst;
+
+		if (ginst) {
+			for (i = 0; i < ginst->type_argc; ++i) {
+				if (check_type_depth (ginst->type_argv [i], depth + 1))
+					return TRUE;
+			}
+		}
+		break;
+	}
+	default:
+		break;
+	}
+
+	return FALSE;
+}
+
 /*
  * add_generic_class:
  *
@@ -2818,9 +2867,6 @@ add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
 	MonoMethod *method;
 	gpointer iter;
 
-	if (depth > 8)
-		return;
-
 	mono_class_init (klass);
 
 	if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
@@ -2832,6 +2878,9 @@ add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
 	if (!klass->generic_class && !klass->rank)
 		return;
 
+	if (check_type_depth (&klass->byval_arg, 0))
+		return;
+
 	iter = NULL;
 	while ((method = mono_class_get_methods (klass, &iter))) {
 		if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
@@ -3080,8 +3129,10 @@ add_generic_instances (MonoAotCompile *acfg)
 		token = MONO_TOKEN_TYPE_SPEC | (i + 1);
 
 		klass = mono_class_get (acfg->image, token);
-		if (!klass || klass->rank)
+		if (!klass || klass->rank) {
+			mono_loader_clear_error ();
 			continue;
+		}
 
 		add_generic_class (acfg, klass, FALSE);
 	}
@@ -3479,6 +3530,7 @@ encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint
 		break;
 	case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
 	case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
+	case MONO_PATCH_INFO_CASTCLASS_CACHE:
 		break;
 	case MONO_PATCH_INFO_METHOD_REL:
 		encode_value ((gint)patch_info->data.offset, p, &p);
@@ -3770,7 +3822,7 @@ emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
 
 	seq_points = cfg->seq_point_info;
 
-	buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
+	buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
 	p = buf = g_malloc (buf_size);
 
 #ifdef MONO_ARCH_HAVE_XP_UNWIND
@@ -3950,6 +4002,8 @@ emit_klass_info (MonoAotCompile *acfg, guint32 token)
 	gpointer iter = NULL;
 
 	if (!klass) {
+		mono_loader_clear_error ();
+
 		buf_size = 16;
 
 		p = buf = g_malloc (buf_size);
@@ -4613,6 +4667,11 @@ can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
 					return TRUE;
 				else
 					return FALSE;
+			case MONO_WRAPPER_CASTCLASS:
+				if (!strcmp (method->name, "__castclass_with_cache"))
+					return TRUE;
+				else
+					return FALSE;
 			default:
 				//printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
 				return FALSE;
@@ -4716,6 +4775,7 @@ compile_method (MonoAotCompile *acfg, MonoMethod *method)
 		return;
 	}
 	if (cfg->exception_type != MONO_EXCEPTION_NONE) {
+		//printf ("E: %s\n", mono_method_full_name (method, TRUE));
 		/* Let the exception happen at runtime */
 		return;
 	}
@@ -4968,7 +5028,8 @@ load_profile_files (MonoAotCompile *acfg)
 	int file_index, res, method_index, i;
 	char ver [256];
 	guint32 token;
-	GList *unordered;
+	GList *unordered, *l;
+	gboolean found;
 
 	file_index = 0;
 	while (TRUE) {
@@ -5014,9 +5075,15 @@ load_profile_files (MonoAotCompile *acfg)
 				token = mono_method_get_token (method);
 				method_index = mono_metadata_token_index (token) - 1;
 
-				if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
-					acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
+				found = FALSE;
+				for (i = 0; i < acfg->method_order->len; ++i) {
+					if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
+						found = TRUE;
+						break;
+					}
 				}
+				if (!found)
+					g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
 			} else {
 				//printf ("No method found matching '%s'.\n", name);
 			}
@@ -5026,15 +5093,20 @@ load_profile_files (MonoAotCompile *acfg)
 
 	/* Add missing methods */
 	unordered = NULL;
-	for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
-		if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
-			unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
+	for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
+		found = FALSE;
+		for (i = 0; i < acfg->method_order->len; ++i) {
+			if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
+				found = TRUE;
+				break;
+			}
+		}
+		if (!found)
+			unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
 	}
 	unordered = g_list_reverse (unordered);
-	if (acfg->method_order)
-		g_list_last (acfg->method_order)->next = unordered;
-	else
-		acfg->method_order = unordered;
+	for (l = unordered; l; l = l->next)
+		g_ptr_array_add (acfg->method_order, l->data);
 }
  
 /* Used by the LLVM backend */
@@ -5154,7 +5226,7 @@ emit_llvm_file (MonoAotCompile *acfg)
 	 * then removing tailcallelim + the global opts, and adding a second gvn.
 	 */
 	opts = g_strdup ("-instcombine -simplifycfg");
-	opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -basiccg -prune-eh -inline -functionattrs -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loopsimplify -domfrontier -loopsimplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loopsimplify -lcssa -iv-users -indvars -loop-deletion -loopsimplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -gvn -simplifycfg -preverify -domtree -verify");
+	opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -basiccg -prune-eh -inline -functionattrs -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loopsimplify -domfrontier -loopsimplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loopsimplify -lcssa -iv-users -indvars -loop-deletion -loopsimplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -preverify -domtree -verify");
 #if 1
 	command = g_strdup_printf ("%sopt -f %s -o temp.opt.bc temp.bc", acfg->aot_opts.llvm_path, opts);
 	printf ("Executing opt: %s\n", command);
@@ -5192,10 +5264,9 @@ emit_llvm_file (MonoAotCompile *acfg)
 static void
 emit_code (MonoAotCompile *acfg)
 {
-	int i;
+	int oindex, i;
 	char symbol [256];
 	char end_symbol [256];
-	GList *l;
 
 #if defined(TARGET_POWERPC64)
 	sprintf (symbol, ".Lgot_addr");
@@ -5241,13 +5312,12 @@ emit_code (MonoAotCompile *acfg)
 		emit_bytes (acfg, pad_buffer, kPaddingSize);
 	}
 #endif
-	
 
-	for (l = acfg->method_order; l != NULL; l = l->next) {
+	for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
 		MonoCompile *cfg;
 		MonoMethod *method;
 
-		i = GPOINTER_TO_UINT (l->data);
+		i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
 
 		cfg = acfg->cfgs [i];
 
@@ -5330,15 +5400,14 @@ emit_code (MonoAotCompile *acfg)
 static void
 emit_info (MonoAotCompile *acfg)
 {
-	int i;
+	int oindex, i;
 	char symbol [256];
-	GList *l;
 	gint32 *offsets;
 
 	offsets = g_new0 (gint32, acfg->nmethods);
 
-	for (l = acfg->method_order; l != NULL; l = l->next) {
-		i = GPOINTER_TO_UINT (l->data);
+	for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
+		i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
 
 		if (acfg->cfgs [i]) {
 			emit_method_info (acfg, acfg->cfgs [i]);
@@ -5860,8 +5929,10 @@ emit_class_name_table (MonoAotCompile *acfg)
 	for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
 		token = MONO_TOKEN_TYPE_DEF | (i + 1);
 		klass = mono_class_get (acfg->image, token);
-		if (!klass)
+		if (!klass) {
+			mono_loader_clear_error ();
 			continue;
+		}
 		full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
 		hash = mono_metadata_str_hash (full_name) % table_size;
 		g_free (full_name);
@@ -6647,6 +6718,7 @@ acfg_create (MonoAssembly *ass, guint32 opts)
 	acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
 	acfg->unwind_ops = g_ptr_array_new ();
 	acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
+	acfg->method_order = g_ptr_array_new ();
 	InitializeCriticalSection (&acfg->mutex);
 
 	return acfg;
diff --git a/mono/mini/aot-runtime.c b/mono/mini/aot-runtime.c
index fc05641..973e405 100644
--- a/mono/mini/aot-runtime.c
+++ b/mono/mini/aot-runtime.c
@@ -654,6 +654,15 @@ decode_method_ref_with_target (MonoAotModule *module, MethodRef *ref, MonoMethod
 				return FALSE;
 			break;
 		}
+		case MONO_WRAPPER_CASTCLASS: {
+			int subtype = decode_value (p, &p);
+
+			if (subtype == MONO_AOT_WRAPPER_CASTCLASS_WITH_CACHE)
+				ref->method = mono_marshal_get_castclass_with_cache ();
+			else
+				g_assert_not_reached ();
+			break;
+		}
 		default:
 			g_assert_not_reached ();
 		}
@@ -2348,6 +2357,7 @@ decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guin
 	case MONO_PATCH_INFO_MONITOR_ENTER:
 	case MONO_PATCH_INFO_MONITOR_EXIT:
 	case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
+	case MONO_PATCH_INFO_CASTCLASS_CACHE:
 		break;
 	case MONO_PATCH_INFO_RGCTX_FETCH: {
 		gboolean res;
@@ -2910,7 +2920,7 @@ mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
 		}
 
 		/* Same for CompareExchange<T> */
-		if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass->image == mono_defaults.corlib && !strcmp (method->klass->name_space, "System.Threading") && !strcmp (method->klass->name, "Interlocked") && !strcmp (method->name, "CompareExchange")) {
+		if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass->image == mono_defaults.corlib && !strcmp (method->klass->name_space, "System.Threading") && !strcmp (method->klass->name, "Interlocked") && !strcmp (method->name, "CompareExchange") && MONO_TYPE_IS_REFERENCE (mono_method_signature (method)->params [1])) {
 			MonoMethod *m;
 			MonoGenericContext ctx;
 			MonoType *args [16];
@@ -3552,25 +3562,38 @@ mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem
 	guint32 got_offset;
 	gpointer code;
 	gpointer *buf;
-	int i;
+	int i, index, real_count;
 	MonoAotModule *amodule;
 
 	code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL);
 
+	real_count = 0;
+	for (i = 0; i < count; ++i) {
+		MonoIMTCheckItem *item = imt_entries [i];
+
+		if (item->is_equals)
+			real_count ++;
+	}
+
 	/* Save the entries into an array */
-	buf = mono_domain_alloc (domain, (count + 1) * 2 * sizeof (gpointer));
+	buf = mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
+	index = 0;
 	for (i = 0; i < count; ++i) {
 		MonoIMTCheckItem *item = imt_entries [i];		
 
+		if (!item->is_equals)
+			continue;
+
 		g_assert (item->key);
 		/* FIXME: */
 		g_assert (!item->has_target_code);
 
-		buf [(i * 2)] = item->key;
-		buf [(i * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
+		buf [(index * 2)] = item->key;
+		buf [(index * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
+		index ++;
 	}
-	buf [(count * 2)] = NULL;
-	buf [(count * 2) + 1] = fail_tramp;
+	buf [(index * 2)] = NULL;
+	buf [(index * 2) + 1] = fail_tramp;
 	
 	amodule->got [got_offset] = buf;
 
diff --git a/mono/mini/cfold.c b/mono/mini/cfold.c
index e59b02a..d9e35d4 100644
--- a/mono/mini/cfold.c
+++ b/mono/mini/cfold.c
@@ -202,8 +202,10 @@ mono_constant_fold_ins (MonoCompile *cfg, MonoInst *ins, MonoInst *arg1, MonoIns
 	case OP_INEG:
 		if (arg1->opcode == OP_ICONST) {
 			/* INEG sets cflags on x86, and the LNEG decomposition depends on that */
-			if ((ins->opcode == OP_INEG) && ins->next && (ins->next->opcode == OP_ADC_IMM))
+#if SIZEOF_REGISTER == 4
+			if (ins->opcode == OP_INEG)
 				return NULL;
+#endif
 			ALLOC_DEST (cfg, dest, ins);
 			switch (ins->opcode) {
 				FOLD_UNOP (OP_INEG,-);
diff --git a/mono/mini/debugger-agent.c b/mono/mini/debugger-agent.c
index f9d4aa2..bac09d8 100644
--- a/mono/mini/debugger-agent.c
+++ b/mono/mini/debugger-agent.c
@@ -252,7 +252,7 @@ typedef struct {
 #define HEADER_LENGTH 11
 
 #define MAJOR_VERSION 2
-#define MINOR_VERSION 2
+#define MINOR_VERSION 3
 
 typedef enum {
 	CMD_SET_VM = 1,
@@ -366,7 +366,8 @@ typedef enum {
 	CMD_THREAD_GET_NAME = 2,
 	CMD_THREAD_GET_STATE = 3,
 	CMD_THREAD_GET_INFO = 4,
-	CMD_THREAD_GET_ID = 5
+	CMD_THREAD_GET_ID = 5,
+	CMD_THREAD_GET_TID = 6
 } CmdThread;
 
 typedef enum {
@@ -931,7 +932,7 @@ mono_debugger_agent_cleanup (void)
 #ifdef HOST_WIN32
 			if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
 				mono_mutex_unlock (&debugger_thread_exited_mutex);
-				Sleep(0);
+				Sleep(1);
 				mono_mutex_lock (&debugger_thread_exited_mutex);
 			}
 #else
@@ -2301,7 +2302,7 @@ suspend_current (void)
 		if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
 		{
 			mono_mutex_unlock (&suspend_mutex);
-			Sleep(0);
+			Sleep(1);
 			mono_mutex_lock (&suspend_mutex);
 		}
 		else
@@ -6422,7 +6423,10 @@ method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, g
 
 			if (handle_class == mono_defaults.typehandle_class) {
 				buffer_add_byte (buf, TOKEN_TYPE_TYPE);
-				buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
+				if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
+					buffer_add_typeid (buf, domain, (MonoClass *) val);
+				else
+					buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
 			} else if (handle_class == mono_defaults.fieldhandle_class) {
 				buffer_add_byte (buf, TOKEN_TYPE_FIELD);
 				buffer_add_fieldid (buf, domain, val);
@@ -6555,6 +6559,9 @@ thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
 	case CMD_THREAD_GET_ID:
 		buffer_add_long (buf, (guint64)(gsize)thread);
 		break;
+	case CMD_THREAD_GET_TID:
+		buffer_add_long (buf, (guint64)thread->tid);
+		break;
 	default:
 		return ERR_NOT_IMPLEMENTED;
 	}
diff --git a/mono/mini/decompose.c b/mono/mini/decompose.c
index 7885bf9..34e9ee9 100644
--- a/mono/mini/decompose.c
+++ b/mono/mini/decompose.c
@@ -1527,6 +1527,7 @@ mono_decompose_soft_float (MonoCompile *cfg)
 						MonoCallInst *call2;
 						MonoInst *iargs [1];
 						MonoInst *conv;
+						GSList *l;
 
 						/* Convert the call into a call returning an int */
 						MONO_INST_NEW_CALL (cfg, call2, OP_CALL);
@@ -1547,6 +1548,10 @@ mono_decompose_soft_float (MonoCompile *cfg)
 						call2->inst.dreg = mono_alloc_ireg (cfg);
 						MONO_ADD_INS (cfg->cbb, (MonoInst*)call2);
 
+						/* Remap OUTARG_VT instructions referencing this call */
+						for (l = call->outarg_vts; l; l = l->next)
+							((MonoInst*)(l->data))->inst_p0 = call2;
+
 						/* FIXME: Optimize this */
 
 						/* Emit an r4->r8 conversion */
diff --git a/mono/mini/driver.c b/mono/mini/driver.c
index b6592dd..a2e7030 100644
--- a/mono/mini/driver.c
+++ b/mono/mini/driver.c
@@ -1393,7 +1393,7 @@ mono_main (int argc, char* argv[])
 			char *build = mono_get_runtime_build_info ();
 			char *gc_descr;
 
-			g_print ("Mono JIT compiler version %s\nCopyright (C) 2002-2010 Novell, Inc and Contributors. www.mono-project.com\n", build);
+			g_print ("Mono JIT compiler version %s\nCopyright (C) 2002-2011 Novell, Inc and Contributors. www.mono-project.com\n", build);
 			g_free (build);
 			g_print (info);
 			gc_descr = mono_gc_get_description ();
diff --git a/mono/mini/exceptions-sparc.c b/mono/mini/exceptions-sparc.c
index 0c47d9d..d44416b 100644
--- a/mono/mini/exceptions-sparc.c
+++ b/mono/mini/exceptions-sparc.c
@@ -351,6 +351,9 @@ mono_arch_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls,
 	if (ji != NULL) {
 		frame->type = FRAME_TYPE_MANAGED;
 
+		if (!ji->method->wrapper_type || ji->method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
+			frame->managed = TRUE;
+
 		if (*lmf && (MONO_CONTEXT_GET_BP (ctx) >= (gpointer)(*lmf)->ebp)) {
 			/* remove any unused lmf */
 			*lmf = (*lmf)->previous_lmf;
diff --git a/mono/mini/exceptions-x86.c b/mono/mini/exceptions-x86.c
index d3f0981..dfbaed6 100644
--- a/mono/mini/exceptions-x86.c
+++ b/mono/mini/exceptions-x86.c
@@ -1295,3 +1295,18 @@ mono_tasklets_arch_restore (void)
 }
 #endif
 
+/*
+ * mono_arch_setup_resume_sighandler_ctx:
+ *
+ *   Setup CTX so execution continues at FUNC.
+ */
+void
+mono_arch_setup_resume_sighandler_ctx (MonoContext *ctx, gpointer func)
+{
+	int align = (((gint32)MONO_CONTEXT_GET_SP (ctx)) % MONO_ARCH_FRAME_ALIGNMENT + 4);
+
+	if (align != 0)
+		MONO_CONTEXT_SET_SP (ctx, (gsize)MONO_CONTEXT_GET_SP (ctx) - align);
+
+	MONO_CONTEXT_SET_IP (ctx, func);
+}
diff --git a/mono/mini/generics.cs b/mono/mini/generics.cs
index b7a3351..ef5f3ac 100644
--- a/mono/mini/generics.cs
+++ b/mono/mini/generics.cs
@@ -1,6 +1,7 @@
 using System;
 using System.Collections.Generic;
 using System.Linq;
+using System.Runtime.CompilerServices;
 
 class Tests {
 
@@ -610,6 +611,40 @@ class Tests {
 		return 0;
 	}
 
+
+	struct RecStruct<T> {
+		public void foo (RecStruct<RecStruct<T>> baz) {
+		}
+	}
+
+	public static int test_0_infinite_generic_recursion () {
+		// Check that the AOT compile can deal with infinite generic recursion through
+		// parameter types
+		RecStruct<int> bla;
+
+		return 0;
+	}
+
+	struct FooStruct {
+	}
+
+	bool IsNull2 <T> (object value) where T : struct {
+		T? item = (T?) value;
+
+		if (item.HasValue)
+			return false;
+
+		return true;
+	}
+
+	public static int test_0_full_aot_nullable_unbox_from_gshared_code () {
+		if (!new Tests ().IsNull2<FooStruct> (null))
+			return 1;
+		if (new Tests ().IsNull2<FooStruct> (new FooStruct ()))
+			return 2;
+		return 0;
+	}
+
 	public static int test_0_partial_sharing () {
 		if (PartialShared1 (new List<string> (), 1) != typeof (string))
 			return 1;
@@ -790,4 +825,28 @@ class Tests {
 	static T Unbox <T> (object o) {
 		return (T) o;
 	}
+
+	interface IDefaultRetriever
+	{
+		T GetDefault<T>();
+	}
+
+	class DefaultRetriever : IDefaultRetriever
+	{
+		[MethodImpl(MethodImplOptions.Synchronized)]
+		public T GetDefault<T>()
+		{
+			return default(T);
+		}
+	}
+
+	[Category ("!FULLAOT")]
+	public static int test_0_regress_668095_synchronized_gshared () {
+		return DoSomething (new DefaultRetriever ());
+	}
+
+    static int DoSomething(IDefaultRetriever foo) {
+		int result = foo.GetDefault<int>();
+		return result;
+	}
 }
diff --git a/mono/mini/iltests.il.in b/mono/mini/iltests.il.in
index 4b415de..7b08b5f 100644
--- a/mono/mini/iltests.il.in
+++ b/mono/mini/iltests.il.in
@@ -2607,4 +2607,19 @@ END:
 		ldc.i4.0
 		ret
 	}
+
+	.method public hidebysig static int32 SizeOfT<T>() cil managed
+  	{
+		.maxstack  8
+    
+		sizeof !!0
+    	ret
+  	}
+
+	.method public static default int32 test_1_sizeof_gshared () cil managed {
+	    call   int32 Tests::SizeOfT<int8>()
+		ldc.i4.1
+		ceq
+		ret
+	}
 }
diff --git a/mono/mini/method-to-ir.c b/mono/mini/method-to-ir.c
index 2957868..d075a81 100644
--- a/mono/mini/method-to-ir.c
+++ b/mono/mini/method-to-ir.c
@@ -2327,9 +2327,6 @@ mono_emit_calli (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args, Mo
 		MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
 	}
 
-	if (rgctx_arg)
-		printf ("MOO!\n");
-
 	call = mono_emit_call_args (cfg, sig, args, TRUE, FALSE, FALSE, rgctx_arg ? TRUE : FALSE);
 
 	call->inst.sreg1 = addr->dreg;
@@ -3157,7 +3154,7 @@ handle_unbox_nullable (MonoCompile* cfg, MonoInst* val, MonoClass* klass, int co
 		addr = emit_get_rgctx_method (cfg, context_used, method,
 									  MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
 
-		rgctx = emit_get_rgctx (cfg, method, context_used);
+		rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
 
 		return mono_emit_calli (cfg, mono_method_signature (method), &val, addr, rgctx);
 	} else {
@@ -4834,7 +4831,7 @@ inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig,
 	guint32 prev_cil_offset_to_bb_len;
 	MonoMethod *prev_current_method;
 	MonoGenericContext *prev_generic_context;
-	gboolean ret_var_set, prev_ret_var_set;
+	gboolean ret_var_set, prev_ret_var_set, virtual = FALSE;
 
 	g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
 
@@ -4881,7 +4878,6 @@ inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig,
 		rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
 	}
 
-
 	prev_locals = cfg->locals;
 	cfg->locals = mono_mempool_alloc0 (cfg->mempool, cheader->num_locals * sizeof (MonoInst*));	
 	for (i = 0; i < cheader->num_locals; ++i)
@@ -4912,7 +4908,10 @@ inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig,
 	prev_generic_context = cfg->generic_context;
 	prev_ret_var_set = cfg->ret_var_set;
 
-	costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
+	if (*ip == CEE_CALLVIRT && !(cmethod->flags & METHOD_ATTRIBUTE_STATIC))
+		virtual = TRUE;
+
+	costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, rvar, dont_inline, sp, real_offset, virtual);
 
 	ret_var_set = cfg->ret_var_set;
 
@@ -8139,7 +8138,10 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 
 				/* inline cache*/
 				/*FIXME AOT support*/
-				EMIT_NEW_PCONST (cfg, args [2], mono_domain_alloc0 (cfg->domain, sizeof (gpointer)));
+				if (cfg->compile_aot)
+					EMIT_NEW_AOTCONST (cfg, args [2], MONO_PATCH_INFO_CASTCLASS_CACHE, NULL);
+				else
+					EMIT_NEW_PCONST (cfg, args [2], mono_domain_alloc0 (cfg->domain, sizeof (gpointer)));
 
 				/*The wrapper doesn't inline well so the bloat of inlining doesn't pay off.*/
 				*sp++ = mono_emit_method_call (cfg, mono_castclass, args, NULL);
@@ -8261,7 +8263,10 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 
 					/* inline cache*/
 					/*FIXME AOT support*/
-					EMIT_NEW_PCONST (cfg, args [2], mono_domain_alloc0 (cfg->domain, sizeof (gpointer)));
+					if (cfg->compile_aot)
+						EMIT_NEW_AOTCONST (cfg, args [2], MONO_PATCH_INFO_CASTCLASS_CACHE, NULL);
+					else
+						EMIT_NEW_PCONST (cfg, args [2], mono_domain_alloc0 (cfg->domain, sizeof (gpointer)));
 
 					/*The wrapper doesn't inline well so the bloat of inlining doesn't pay off.*/
 					*sp++ = mono_emit_method_call (cfg, mono_castclass, args, NULL);
@@ -10303,7 +10308,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 				CHECK_STACK_OVF (1);
 				CHECK_OPSIZE (6);
 				token = read32 (ip + 2);
-				if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC && !method->klass->image->dynamic) {
+				if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC && !method->klass->image->dynamic && !generic_context) {
 					MonoType *type = mono_type_create_from_typespec (image, token);
 					token = mono_type_size (type, &ialign);
 				} else {
diff --git a/mono/mini/mini-arm.c b/mono/mini/mini-arm.c
index 824db1b..3ab3d68 100644
--- a/mono/mini/mini-arm.c
+++ b/mono/mini/mini-arm.c
@@ -1605,6 +1605,7 @@ mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call)
 			ins->inst_p0 = call;
 			ins->inst_p1 = mono_mempool_alloc (cfg->mempool, sizeof (ArgInfo));
 			memcpy (ins->inst_p1, ainfo, sizeof (ArgInfo));
+			mono_call_inst_add_outarg_vt (cfg, call, ins);
 			MONO_ADD_INS (cfg->cbb, ins);
 			break;
 		case RegTypeBase:
diff --git a/mono/mini/mini-codegen.c b/mono/mini/mini-codegen.c
index e9886d8..165b932 100644
--- a/mono/mini/mini-codegen.c
+++ b/mono/mini/mini-codegen.c
@@ -271,6 +271,17 @@ mono_call_inst_add_outarg_reg (MonoCompile *cfg, MonoCallInst *call, int vreg, i
 	}
 }
 
+/*
+ * mono_call_inst_add_outarg_vt:
+ *
+ *   Register OUTARG_VT as belonging to CALL.
+ */
+void
+mono_call_inst_add_outarg_vt (MonoCompile *cfg, MonoCallInst *call, MonoInst *outarg_vt)
+{
+	call->outarg_vts = g_slist_append_mempool (cfg->mempool, call->outarg_vts, outarg_vt);
+}
+
 static void
 resize_spill_info (MonoCompile *cfg, int bank)
 {
diff --git a/mono/mini/mini-exceptions.c b/mono/mini/mini-exceptions.c
index 565b2a1..60cc5d6 100644
--- a/mono/mini/mini-exceptions.c
+++ b/mono/mini/mini-exceptions.c
@@ -1469,6 +1469,13 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
 			if (mono_break_on_exc)
 				G_BREAKPOINT ();
 			mono_debugger_agent_handle_exception (obj, ctx, NULL);
+
+			if (mini_get_debug_options ()->suspend_on_unhandled) {
+				fprintf (stderr, "Unhandled exception, suspending...");
+				while (1)
+					;
+			}
+
 			// FIXME: This runs managed code so it might cause another stack overflow when
 			// we are handling a stack overflow
 			mono_unhandled_exception (obj);
@@ -1991,6 +1998,76 @@ mono_handle_soft_stack_ovf (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx,
 	return FALSE;
 }
 
+typedef struct {
+	FILE *stream;
+	MonoMethod *omethod;
+	int count;
+} PrintOverflowUserData;
+
+static gboolean
+print_overflow_stack_frame (MonoMethod *method, gint32 native_offset, gint32 il_offset, gboolean managed, gpointer data)
+{
+	PrintOverflowUserData *user_data = data;
+	FILE *stream = user_data->stream;
+	gchar *location;
+
+	if (method) {
+		if (user_data->count == 0) {
+			/* The first frame is in its prolog, so a line number cannot be computed */
+			user_data->count ++;
+			return FALSE;
+		}
+
+		/* If this is a one method overflow, skip the other instances */
+		if (method == user_data->omethod)
+			return FALSE;
+
+		location = mono_debug_print_stack_frame (method, native_offset, mono_domain_get ());
+		fprintf (stream, "  %s\n", location);
+		g_free (location);
+
+		if (user_data->count == 1) {
+			fprintf (stream, "  <...>\n");
+			user_data->omethod = method;
+		} else {
+			user_data->omethod = NULL;
+		}
+
+		user_data->count ++;
+	} else
+		fprintf (stream, "  at <unknown> <0x%05x>\n", native_offset);
+
+	return FALSE;
+}
+
+void
+mono_handle_hard_stack_ovf (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx, guint8* fault_addr)
+{
+	PrintOverflowUserData ud;
+	MonoContext mctx;
+
+	/* we don't do much now, but we can warn the user with a useful message */
+	fprintf (stderr, "Stack overflow: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), fault_addr);
+
+#ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
+	mono_arch_sigctx_to_monoctx (ctx, &mctx);
+			
+	fprintf (stderr, "Stacktrace:\n");
+
+	memset (&ud, 0, sizeof (ud));
+	ud.stream = stderr;
+
+	mono_jit_walk_stack_from_ctx (print_overflow_stack_frame, &mctx, MONO_UNWIND_LOOKUP_ACTUAL_METHOD, &ud);
+#else
+	if (ji && ji->method)
+		fprintf (stderr, "At %s\n", mono_method_full_name (ji->method, TRUE));
+	else
+		fprintf (stderr, "At <unmanaged>.\n");
+#endif
+
+	_exit (1);
+}
+
 static gboolean
 print_stack_frame (MonoMethod *method, gint32 native_offset, gint32 il_offset, gboolean managed, gpointer data)
 {
@@ -2199,6 +2276,11 @@ mono_print_thread_dump_internal (void *sigctx, MonoContext *start_ctx)
 #endif
 
 	fprintf (stdout, "%s", text->str);
+
+#if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
+	OutputDebugStringA(text->str);
+#endif
+
 	g_string_free (text, TRUE);
 	fflush (stdout);
 }
@@ -2362,3 +2444,15 @@ mono_install_handler_block_guard (MonoInternalThread *thread, MonoContext *ctx)
 
 #endif
 
+void
+mono_set_cast_details (MonoClass *from, MonoClass *to)
+{
+	MonoJitTlsData *jit_tls = NULL;
+
+	if (mini_get_debug_options ()->better_cast_details) {
+		jit_tls = TlsGetValue (mono_jit_tls_id);
+		jit_tls->class_cast_from = from;
+		jit_tls->class_cast_to = to;
+	}
+}
+
diff --git a/mono/mini/mini-ops.h b/mono/mini/mini-ops.h
index 27b83e7..ffb6a29 100644
--- a/mono/mini/mini-ops.h
+++ b/mono/mini/mini-ops.h
@@ -17,6 +17,10 @@ MINI_OP(OP_ICOMPARE_IMM,	"icompare_imm", NONE, IREG, NONE)
 MINI_OP(OP_LCOMPARE_IMM,	"lcompare_imm", NONE, LREG, NONE)
 MINI_OP(OP_LOCAL,	"local", NONE, NONE, NONE)
 MINI_OP(OP_ARG,		"arg", NONE, NONE, NONE)
+/*
+ * Represents passing a valuetype argument which has not been decomposed yet.
+ * inst_p0 points to the call.
+ */
 MINI_OP(OP_OUTARG_VT,	"outarg_vt", NONE, VREG, NONE)
 MINI_OP(OP_OUTARG_VTRETADDR, "outarg_vtretaddr", IREG, NONE, NONE)
 MINI_OP(OP_SETRET,	"setret", NONE, IREG, NONE)
diff --git a/mono/mini/mini-trampolines.c b/mono/mini/mini-trampolines.c
index 147073b..1ecc080 100644
--- a/mono/mini/mini-trampolines.c
+++ b/mono/mini/mini-trampolines.c
@@ -466,8 +466,10 @@ common_call_trampoline (mgreg_t *regs, guint8 *code, MonoMethod *m, guint8* tram
 			ji = NULL;
 
 		/* Avoid recursion */
-		if (!(ji && ji->method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED))
+		if (!(ji && ji->method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)) {
 			m = mono_marshal_get_synchronized_wrapper (m);
+			need_rgctx_tramp = FALSE;
+		}
 	}
 
 	/* Calls made through delegates on platforms without delegate trampolines */
@@ -909,7 +911,10 @@ mono_delegate_trampoline (mgreg_t *regs, guint8 *code, gpointer *tramp_data, gui
 			mono_error_raise_exception (&err);
 
 		callvirt = !delegate->target && sig->hasthis;
-		if (delegate->target && method->flags & METHOD_ATTRIBUTE_VIRTUAL && method->klass->flags & TYPE_ATTRIBUTE_ABSTRACT) {
+		if (delegate->target && 
+			method->flags & METHOD_ATTRIBUTE_VIRTUAL && 
+			method->flags & METHOD_ATTRIBUTE_ABSTRACT &&
+			method->klass->flags & TYPE_ATTRIBUTE_ABSTRACT) {
 			method = mono_object_get_virtual_method (delegate->target, method);
 			enable_caching = FALSE;
 		}
diff --git a/mono/mini/mini-x86.c b/mono/mini/mini-x86.c
index 0ac10c1..f0f59b0 100644
--- a/mono/mini/mini-x86.c
+++ b/mono/mini/mini-x86.c
@@ -1803,6 +1803,13 @@ if (ins->inst_true_bb->native_offset) { \
 static guint8*
 emit_call (MonoCompile *cfg, guint8 *code, guint32 patch_type, gconstpointer data)
 {
+	/*The address must be 4 bytes aligned to avoid spanning multiple cache lines.
+	This is required for code patching to be safe on SMP machines.
+	*/
+	guint32 pad_size = (guint32)(code + 1 - cfg->native_code) & 0x3;
+	if (pad_size)
+		x86_padding (code, pad_size);
+
 	mono_add_patch_info (cfg, code - cfg->native_code, patch_type, data);
 	x86_call_code (code, 0);
 
diff --git a/mono/mini/mini-x86.h b/mono/mini/mini-x86.h
index 3cc5b44..6ebcc39 100644
--- a/mono/mini/mini-x86.h
+++ b/mono/mini/mini-x86.h
@@ -318,6 +318,7 @@ typedef struct {
 #define MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD 1
 
 #define MONO_ARCH_HAVE_CARD_TABLE_WBARRIER 1
+#define MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX 1
 #define MONO_ARCH_GC_MAPS_SUPPORTED 1
 
 gboolean
diff --git a/mono/mini/mini.c b/mono/mini/mini.c
index 2cbbabe..fa4151b 100644
--- a/mono/mini/mini.c
+++ b/mono/mini/mini.c
@@ -6,7 +6,7 @@
  *   Dietmar Maurer (dietmar at ximian.com)
  *
  * Copyright 2002-2003 Ximian, Inc.
- * Coprygith 2003-2010 Novell, Inc.
+ * Copyright 2003-2010 Novell, Inc.
  */
 
 #define MONO_LLVM_IN_MINI 1
@@ -2860,10 +2860,11 @@ mono_patch_info_hash (gconstpointer data)
 	switch (ji->type) {
 	case MONO_PATCH_INFO_RVA:
 	case MONO_PATCH_INFO_LDSTR:
-	case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
 	case MONO_PATCH_INFO_LDTOKEN:
 	case MONO_PATCH_INFO_DECLSEC:
 		return (ji->type << 8) | ji->data.token->token;
+	case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
+		return (ji->type << 8) | ji->data.token->token | (ji->data.token->has_context ? (gsize)ji->data.token->context.class_inst : 0);
 	case MONO_PATCH_INFO_INTERNAL_METHOD:
 		return (ji->type << 8) | g_str_hash (ji->data.name);
 	case MONO_PATCH_INFO_VTABLE:
@@ -3230,6 +3231,10 @@ mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code,
 		target = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
 		break;
 	}
+	case MONO_PATCH_INFO_CASTCLASS_CACHE: {
+		target = mono_domain_alloc0 (domain, sizeof (gpointer));
+		break;
+	}
 	default:
 		g_assert_not_reached ();
 	}
@@ -3549,6 +3554,17 @@ mono_codegen (MonoCompile *cfg)
 	MonoBasicBlock *bb;
 	int max_epilog_size;
 	guint8 *code;
+	MonoDomain *code_domain;
+
+	if (mono_using_xdebug)
+		/*
+		 * Recent gdb versions have trouble processing symbol files containing
+		 * overlapping address ranges, so allocate all code from the code manager
+		 * of the root domain. (#666152).
+		 */
+		code_domain = mono_get_root_domain ();
+	else
+		code_domain = cfg->domain;
 
 #if defined(__native_client_codegen__) && defined(__native_client__)
 	void *code_dest;
@@ -3636,13 +3652,17 @@ mono_codegen (MonoCompile *cfg)
 		mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
 		mono_domain_unlock (cfg->domain);
 
-		code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size + unwindlen);
+		if (mono_using_xdebug)
+			/* See the comment for cfg->code_domain */
+			code = mono_domain_code_reserve (code_domain, cfg->code_size + unwindlen);
+		else
+			code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size + unwindlen);
 	} else {
 		guint unwindlen = 0;
 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
 		unwindlen = mono_arch_unwindinfo_get_size (cfg->arch.unwindinfo);
 #endif
-		code = mono_domain_code_reserve (cfg->domain, cfg->code_size + unwindlen);
+		code = mono_domain_code_reserve (code_domain, cfg->code_size + unwindlen);
 	}
 #if defined(__native_client_codegen__) && defined(__native_client__)
 	nacl_allow_target_modification (TRUE);
@@ -3715,9 +3735,12 @@ if (valgrind_register){
 	mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
 
 	if (cfg->method->dynamic) {
-		mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
+		if (mono_using_xdebug)
+			mono_domain_code_commit (code_domain, cfg->native_code, cfg->code_size, cfg->code_len);
+		else
+			mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
 	} else {
-		mono_domain_code_commit (cfg->domain, cfg->native_code, cfg->code_size, cfg->code_len);
+		mono_domain_code_commit (code_domain, cfg->native_code, cfg->code_size, cfg->code_len);
 	}
 #if defined(__native_client_codegen__) && defined(__native_client__)
 	cfg->native_code = code_dest;
@@ -5801,20 +5824,14 @@ SIG_HANDLER_SIGNATURE (mono_sigsegv_signal_handler)
 	}
 #endif
 
-	/* The hard-guard page has been hit: there is not much we can do anymore
-	 * Print a hopefully clear message and abort.
-	 */
 	if (jit_tls->stack_size && 
 		ABS ((guint8*)fault_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 8192 * sizeof (gpointer)) {
-		const char *method;
-		/* we don't do much now, but we can warn the user with a useful message */
-		fprintf (stderr, "Stack overflow: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
-		if (ji && ji->method)
-			method = mono_method_full_name (ji->method, TRUE);
-		else
-			method = "Unmanaged";
-		fprintf (stderr, "At %s\n", method);
-		_exit (1);
+		/*
+		 * The hard-guard page has been hit: there is not much we can do anymore
+		 * Print a hopefully clear message and abort.
+		 */
+		mono_handle_hard_stack_ovf (jit_tls, ji, ctx, (guint8*)info->si_addr);
+		g_assert_not_reached ();
 	} else {
 		/* The original handler might not like that it is executed on an altstack... */
 		if (!ji && mono_chain_signal (SIG_HANDLER_PARAMS))
@@ -5944,6 +5961,8 @@ mini_parse_debug_options (void)
 			debug_options.no_gdb_backtrace = TRUE;
 		else if (!strcmp (arg, "suspend-on-sigsegv"))
 			debug_options.suspend_on_sigsegv = TRUE;
+		else if (!strcmp (arg, "suspend-on-unhandled"))
+			debug_options.suspend_on_unhandled = TRUE;
 		else if (!strcmp (arg, "dont-free-domains"))
 			mono_dont_free_domains = TRUE;
 		else if (!strcmp (arg, "dyn-runtime-invoke"))
@@ -5960,7 +5979,7 @@ mini_parse_debug_options (void)
 			debug_options.better_cast_details = TRUE;
 		else {
 			fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
-			fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'reverse-pinvoke-exceptions', 'collect-pagefault-stats', 'break-on-unverified', 'no-gdb-backtrace', 'dont-free-domains', 'suspend-on-sigsegv', 'dyn-runtime-invoke', 'gdb', 'explicit-null-checks', 'init-stacks'\n");
+			fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'reverse-pinvoke-exceptions', 'collect-pagefault-stats', 'break-on-unverified', 'no-gdb-backtrace', 'dont-free-domains', 'suspend-on-sigsegv', 'suspend-on-unhandled', 'dyn-runtime-invoke', 'gdb', 'explicit-null-checks', 'init-stacks'\n");
 			exit (1);
 		}
 	}
@@ -6151,6 +6170,7 @@ mini_init (const char *filename, const char *runtime_version)
 	callbacks.create_ftnptr = mini_create_ftnptr;
 	callbacks.get_addr_from_ftnptr = mini_get_addr_from_ftnptr;
 	callbacks.get_runtime_build_info = mono_get_runtime_build_info;
+	callbacks.set_cast_details = mono_set_cast_details;
 
 #ifdef MONO_ARCH_HAVE_IMT
 	if (mono_use_imt) {
diff --git a/mono/mini/mini.h b/mono/mini/mini.h
index f0f9709..7f670cb 100644
--- a/mono/mini/mini.h
+++ b/mono/mini/mini.h
@@ -4,6 +4,9 @@
 #include "config.h"
 #include <glib.h>
 #include <signal.h>
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
 #include <mono/metadata/loader.h>
 #include <mono/metadata/mempool.h>
 #include <mono/utils/monobitset.h>
@@ -799,6 +802,7 @@ struct MonoCallInst {
 	regmask_t used_fregs;
 	GSList *out_ireg_args;
 	GSList *out_freg_args;
+	GSList *outarg_vts;
 #ifdef ENABLE_LLVM
 	LLVMCallInfo *cinfo;
 	int rgctx_arg_reg, imt_arg_reg;
@@ -1581,6 +1585,7 @@ typedef struct {
 	gboolean mdb_optimizations;
 	gboolean no_gdb_backtrace;
 	gboolean suspend_on_sigsegv;
+	gboolean suspend_on_unhandled;
 	gboolean dyn_runtime_invoke;
 	gboolean gdb;
 	gboolean gen_seq_points;
@@ -1969,6 +1974,7 @@ void     *mono_arch_instrument_epilog           (MonoCompile *cfg, void *func, v
 void     *mono_arch_instrument_epilog_full     (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments, gboolean preserve_argument_registers) MONO_INTERNAL;
 void      mono_codegen                          (MonoCompile *cfg) MONO_INTERNAL;
 void      mono_call_inst_add_outarg_reg         (MonoCompile *cfg, MonoCallInst *call, int vreg, int hreg, int bank) MONO_LLVM_INTERNAL;
+void      mono_call_inst_add_outarg_vt          (MonoCompile *cfg, MonoCallInst *call, MonoInst *outarg_vt) MONO_INTERNAL;
 const char *mono_arch_regname                   (int reg) MONO_INTERNAL;
 const char *mono_arch_fregname                  (int reg) MONO_INTERNAL;
 void      mono_arch_exceptions_init             (void) MONO_INTERNAL;
@@ -2050,6 +2056,7 @@ gpointer  mono_arch_get_throw_pending_exception (MonoTrampInfo **info, gboolean
 gboolean mono_arch_handle_exception             (void *sigctx, gpointer obj, gboolean test_only) MONO_INTERNAL;
 void     mono_arch_handle_altstack_exception    (void *sigctx, gpointer fault_addr, gboolean stack_ovf) MONO_INTERNAL;
 gboolean mono_handle_soft_stack_ovf             (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx, guint8* fault_addr) MONO_INTERNAL;
+void     mono_handle_hard_stack_ovf             (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx, guint8* fault_addr) MONO_INTERNAL;
 gpointer mono_arch_ip_from_context              (void *sigctx) MONO_INTERNAL;
 void     mono_arch_sigctx_to_monoctx            (void *sigctx, MonoContext *ctx) MONO_INTERNAL;
 void     mono_arch_monoctx_to_sigctx            (MonoContext *mctx, void *ctx) MONO_INTERNAL;
@@ -2140,6 +2147,7 @@ MonoBoolean ves_icall_get_frame_info            (gint32 skip, MonoBoolean need_f
 						 gint32 *iloffset, gint32 *native_offset,
 						 MonoString **file, gint32 *line, gint32 *column) MONO_INTERNAL;
 MonoString *ves_icall_System_Exception_get_trace (MonoException *exc) MONO_INTERNAL;
+void mono_set_cast_details                      (MonoClass *from, MonoClass *to) MONO_INTERNAL;
 
 /* Dominator/SSA methods */
 void        mono_compile_dominator_info         (MonoCompile *cfg, int dom_flags) MONO_INTERNAL;
@@ -2431,6 +2439,7 @@ enum {
 	MONO_AOT_WRAPPER_ELEMENT_ADDR,
 	MONO_AOT_WRAPPER_PTR_TO_STRUCTURE,
 	MONO_AOT_WRAPPER_STRUCTURE_TO_PTR,
+	MONO_AOT_WRAPPER_CASTCLASS_WITH_CACHE,
 	MONO_AOT_WRAPPER_LAST
 };
 
diff --git a/mono/mini/objects.cs b/mono/mini/objects.cs
index 1454af7..3d849c6 100644
--- a/mono/mini/objects.cs
+++ b/mono/mini/objects.cs
@@ -1352,6 +1352,19 @@ ncells ) {
 			return 1;
 	}
 
+	struct AStruct2 {
+		public int i;
+		public int j;
+	}
+
+	static float pass_vtype_return_float (AStruct2 s) {
+		return s.i + s.j == 6 ? 1.0f : -1.0f;
+	}
+
+	public static int test_0_vtype_arg_soft_float () {
+		return pass_vtype_return_float (new AStruct2 () { i = 2, j = 4 }) > 0.0 ? 0 : 1;
+	}
+
 	static int range_check_strlen (int i, string s) {
 		if (i < 0 || i > s.Length)
 			return 1;
diff --git a/mono/mini/patch-info.h b/mono/mini/patch-info.h
index 5e51ace..add6537 100644
--- a/mono/mini/patch-info.h
+++ b/mono/mini/patch-info.h
@@ -41,4 +41,5 @@ PATCH_INFO(MSCORLIB_GOT_ADDR, "mscorlib_got_addr")
 PATCH_INFO(SEQ_POINT_INFO, "seq_point_info")
 PATCH_INFO(LLVM_IMT_TRAMPOLINE, "llvm_imt_trampoline")
 PATCH_INFO(GC_CARD_TABLE_ADDR, "gc_card_table_addr")
+PATCH_INFO(CASTCLASS_CACHE, "castclass_cache")
 PATCH_INFO(NONE, "none")
diff --git a/mono/mini/tramp-arm.c b/mono/mini/tramp-arm.c
index 20b2ec8..f352ed6 100644
--- a/mono/mini/tramp-arm.c
+++ b/mono/mini/tramp-arm.c
@@ -269,8 +269,21 @@ mono_arch_create_generic_trampoline (MonoTrampolineType tramp_type, MonoTrampInf
 		code += 4;
 	}
 
+	/* Align stack to 8 */
+	/* FIXME: Do this properly at the beginning */
+	g_assert (STACK % 8 == 4);
+	ARM_SUB_REG_IMM8 (code, ARMREG_SP, ARMREG_SP, 4);
+	cfa_offset += 4;
+	mono_add_unwind_op_def_cfa (unwind_ops, code, buf, ARMREG_SP, cfa_offset);
+
 	ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
 	code = emit_bx (code, ARMREG_IP);
+
+	/* Restore stack */
+	ARM_ADD_REG_IMM8 (code, ARMREG_SP, ARMREG_SP, 4);
+	cfa_offset -= 4;
+	mono_add_unwind_op_def_cfa (unwind_ops, code, buf, ARMREG_SP, cfa_offset);
+
 	
 	/* OK, code address is now on r0. Move it to the place on the stack
 	 * where IP was saved (it is now no more useful to us and it can be
diff --git a/mono/profiler/ChangeLog b/mono/profiler/ChangeLog
index b43d50d..d414d15 100644
--- a/mono/profiler/ChangeLog
+++ b/mono/profiler/ChangeLog
@@ -1,3 +1,9 @@
+2009-10-03  Hib Eris  <hib at hiberis.nl>
+
+	Include config.h in mono-profiler-aot.c
+
+	This change is nescessary for compiling with a mingw-w64 compiler.
+
 2011-01-03  Zoltan Varga  <vargaz at gmail.com>
 
 	.gitignore.
diff --git a/mono/profiler/mono-profiler-aot.c b/mono/profiler/mono-profiler-aot.c
index aa5a6ca..080ccfa 100644
--- a/mono/profiler/mono-profiler-aot.c
+++ b/mono/profiler/mono-profiler-aot.c
@@ -11,6 +11,7 @@
  * allowing more efficient function ordering in the AOT files.
  */
 
+#include <config.h>
 #include <mono/metadata/profiler.h>
 #include <mono/metadata/tokentype.h>
 #include <mono/metadata/tabledefs.h>
diff --git a/mono/tests/ChangeLog b/mono/tests/ChangeLog
index c43f64a..42ec574 100644
--- a/mono/tests/ChangeLog
+++ b/mono/tests/ChangeLog
@@ -1,3 +1,15 @@
+2011-02-13  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix reading of cattr arguments of type Type[]. Fixes #670331.
+
+2011-01-27  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix compilation of tests/assemblyresolve with newer mcs-es.
+
+2011-01-24  Zoltan Varga  <vargaz at gmail.com>
+
+	Dist finally_guard.cs.
+
 2011-01-04  Rodrigo Kumpera  <kumpera at gmail.com>
 
 	Make test messages more usefull
diff --git a/mono/tests/Makefile.am b/mono/tests/Makefile.am
index 333b0d8..b081b63 100644
--- a/mono/tests/Makefile.am
+++ b/mono/tests/Makefile.am
@@ -376,7 +376,8 @@ BASE_TEST_CS_SRC=		\
 TEST_CS_SRC_DIST=	\
 	$(BASE_TEST_CS_SRC)	\
 	async-exc-compilation.cs \
-	filter-stack.cs
+	filter-stack.cs	\
+	finally_guard.cs
 
 TEST_CS_SRC_GEN = \
 	runtime-invoke.gen.cs \
diff --git a/mono/tests/Makefile.in b/mono/tests/Makefile.in
index f1c5342..d466a7c 100644
--- a/mono/tests/Makefile.in
+++ b/mono/tests/Makefile.in
@@ -640,7 +640,8 @@ BASE_TEST_CS_SRC = \
 TEST_CS_SRC_DIST = \
 	$(BASE_TEST_CS_SRC)	\
 	async-exc-compilation.cs \
-	filter-stack.cs
+	filter-stack.cs	\
+	finally_guard.cs
 
 TEST_CS_SRC_GEN = \
 	runtime-invoke.gen.cs \
diff --git a/mono/tests/assemblyresolve/Makefile.am b/mono/tests/assemblyresolve/Makefile.am
index c22878b..a60bf31 100644
--- a/mono/tests/assemblyresolve/Makefile.am
+++ b/mono/tests/assemblyresolve/Makefile.am
@@ -13,7 +13,7 @@ test/asm.dll: test/.dirstamp
 deps/test.dll deps/TestBase.dll: deps/.dirstamp
 
 test/asm.dll: deps/test.dll asm.cs
-	$(MCS) -out:test/asm.dll -r:deps/test.dll $(srcdir)/asm.cs
+	$(MCS) -out:test/asm.dll -r:deps/TestBase.dll -r:deps/test.dll $(srcdir)/asm.cs
 
 deps/test.dll: deps/TestBase.dll Test.cs
 	$(MCS) -out:deps/test.dll -r:deps/TestBase.dll $(srcdir)/Test.cs
@@ -22,3 +22,6 @@ deps/TestBase.dll: TestBase.cs
 	$(MCS) -out:deps/TestBase.dll $(srcdir)/TestBase.cs
 
 EXTRA_DIST = asm.cs Test.cs TestBase.cs
+
+clean:
+	rm -f deps/*.dll test/*.dll
diff --git a/mono/tests/assemblyresolve/Makefile.in b/mono/tests/assemblyresolve/Makefile.in
index 3b5ff6e..0309088 100644
--- a/mono/tests/assemblyresolve/Makefile.in
+++ b/mono/tests/assemblyresolve/Makefile.in
@@ -345,8 +345,6 @@ distclean-generic:
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
 	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
 clean-am: clean-generic clean-libtool mostlyclean-am
 
 distclean: distclean-am
@@ -423,13 +421,16 @@ test/asm.dll: test/.dirstamp
 deps/test.dll deps/TestBase.dll: deps/.dirstamp
 
 test/asm.dll: deps/test.dll asm.cs
-	$(MCS) -out:test/asm.dll -r:deps/test.dll $(srcdir)/asm.cs
+	$(MCS) -out:test/asm.dll -r:deps/TestBase.dll -r:deps/test.dll $(srcdir)/asm.cs
 
 deps/test.dll: deps/TestBase.dll Test.cs
 	$(MCS) -out:deps/test.dll -r:deps/TestBase.dll $(srcdir)/Test.cs
 
 deps/TestBase.dll: TestBase.cs
 	$(MCS) -out:deps/TestBase.dll $(srcdir)/TestBase.cs
+
+clean:
+	rm -f deps/*.dll test/*.dll
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff --git a/mono/tests/cas/assembly/ChangeLog b/mono/tests/cas/assembly/ChangeLog
index 14265da..5a90c14 100644
--- a/mono/tests/cas/assembly/ChangeLog
+++ b/mono/tests/cas/assembly/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-25  Zoltan Varga  <vargaz at gmail.com>
+
+	Fix up CAS tests a bit.
+
 2007-08-01  Sebastien Pouliot  <sebastien at ximian.com>
 
 	* all.net_1_1.txt, min.net_1_1.txt, none.net_1_1.txt, opt.net_1_1.txt,
diff --git a/mono/tests/cas/assembly/ChangeLog b/mono/tests/cas/assembly/ChangeLog.old
similarity index 100%
copy from mono/tests/cas/assembly/ChangeLog
copy to mono/tests/cas/assembly/ChangeLog.old
diff --git a/mono/tests/cas/assembly/Makefile.am b/mono/tests/cas/assembly/Makefile.am
index abc615e..4a2b8ea 100644
--- a/mono/tests/cas/assembly/Makefile.am
+++ b/mono/tests/cas/assembly/Makefile.am
@@ -5,7 +5,7 @@ RUNTIME = $(with_mono_path) $(top_builddir)/runtime/mono-wrapper --debug
 CAS_RUNTIME = $(RUNTIME) --security
 
 CSCOMPILE = $(RUNTIME) $(mcs_topdir)/class/lib/net_2_0/gmcs.exe -debug
-PERMVIEW = $(RUNTIME2) $(mcs_topdir)/tools/security/permview.exe
+PERMVIEW = $(RUNTIME) $(mcs_topdir)/tools/security/permview.exe
 PROFILE = net_2_0
 
 tests: all.exe min.exe opt.exe ref.exe none.exe
diff --git a/mono/tests/cas/assembly/Makefile.in b/mono/tests/cas/assembly/Makefile.in
index 62834de..0c46767 100644
--- a/mono/tests/cas/assembly/Makefile.in
+++ b/mono/tests/cas/assembly/Makefile.in
@@ -247,7 +247,7 @@ with_mono_path = MONO_PATH=$(mcs_topdir)/class/lib/net_2_0
 RUNTIME = $(with_mono_path) $(top_builddir)/runtime/mono-wrapper --debug
 CAS_RUNTIME = $(RUNTIME) --security
 CSCOMPILE = $(RUNTIME) $(mcs_topdir)/class/lib/net_2_0/gmcs.exe -debug
-PERMVIEW = $(RUNTIME2) $(mcs_topdir)/tools/security/permview.exe
+PERMVIEW = $(RUNTIME) $(mcs_topdir)/tools/security/permview.exe
 PROFILE = net_2_0
 TEST_FILES = all min opt ref none
 EXTRA_DIST = all.cs min.cs opt.cs ref.cs none.cs \
diff --git a/mono/tests/cattr-object.cs b/mono/tests/cattr-object.cs
index 51db9c5..4738a63 100644
--- a/mono/tests/cattr-object.cs
+++ b/mono/tests/cattr-object.cs
@@ -1,24 +1,32 @@
 using System;
+using System.Collections.Generic;
 
 [My((long)1)]
 [My(TypeCode.Empty)]
 [My(typeof(System.Enum))]
+[My(new Type[] { typeof(IEnumerable<string>), typeof(IList<string>) })]
 class T {
 	static int Main() {
 		object[] a = Attribute.GetCustomAttributes (typeof (T), false);
-		if (a.Length != 3)
+		if (a.Length != 4)
 			return 1;
 		foreach (object o in a) {
 			My attr = (My)o;
 			if (attr.obj.GetType () == typeof(long)) {
 				long val = (long)attr.obj;
-				Console.WriteLine ("got value: {0}", val);
 				if (val != 1)
 					return 2;
 			} else if (attr.obj.GetType () == typeof(TypeCode)) {
 				int val = (int)attr.obj;
 				if (val != (int)TypeCode.Empty)
 					return 3;
+			} else if (attr.obj.GetType () == typeof(Type[])) {
+				Type[] arr = (Type[])attr.obj;
+
+				if (arr [0] != typeof (IEnumerable<string>))
+					return 6;
+				if (arr [1] != typeof (IList<string>))
+					return 7;
 			} else {
 				Type t = attr.obj as Type;
 				if (t == null)
diff --git a/mono/tests/finally_guard.cs b/mono/tests/finally_guard.cs
new file mode 100644
index 0000000..f95f712
--- /dev/null
+++ b/mono/tests/finally_guard.cs
@@ -0,0 +1,226 @@
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Threading;
+using System.Runtime.CompilerServices;
+
+
+class Driver {
+	static int result;
+	static bool finally_done;
+	static ManualResetEvent handle;
+	static Thread thread;
+	static object broken;
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	static void ThrowE () {
+		broken.ToString ();		
+	}
+
+	static bool InterruptRequested () {
+		return (Thread.CurrentThread.ThreadState & ThreadState.AbortRequested) == ThreadState.AbortRequested;
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void SleepLoop () {
+		for (int i = 0; i < 10; ++i) {
+			Console.WriteLine ("step {0} - {1}", i, Thread.CurrentThread.ThreadState);
+			if (InterruptRequested ())
+				break;
+			Thread.Sleep (100);
+		}
+
+		if (!InterruptRequested ())
+			result |= 0x1;
+
+		try {
+			ThrowE ();
+		} catch (Exception e) {
+			Console.WriteLine ("caught/0 {0} from inside the prot block", e.GetType ());
+			if (!(e is NullReferenceException))
+				result |= 0x2;
+		}
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	public static void CancelAbort () {
+		object lk = new object ();
+		Console.WriteLine ("step 0 - {0}", Thread.CurrentThread.ThreadState);
+		//lock (lk) { Monitor.Wait (lk, 100); }
+		Console.WriteLine ("step 1 - {0}", Thread.CurrentThread.ThreadState);
+		Thread.ResetAbort ();
+	}
+
+	/////////////////////////////////////////////////////
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	static void InnerFromEH0 () {
+		thread = Thread.CurrentThread;
+		MethodInfo mi = typeof (Driver).GetMethod ("SleepLoop");
+		try {
+			try {
+				throw new ArgumentException ();
+			} finally {	
+				handle.Set ();
+				SleepLoop ();
+				Console.WriteLine ("done");
+				finally_done = true;
+			}
+			Console.WriteLine ("After finally");
+			result |= 0x10;
+		} catch (Exception e) {
+			if (!(e is ArgumentException))
+				result |= 0x4;
+			Console.WriteLine ("caught/1 a {0} while on {1} res {2}", e.GetType (), Thread.CurrentThread.ThreadState, result);
+		}
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	static void GuardFromEH0 () {
+		try {
+			InnerFromEH0 ();
+		} catch (Exception e) {
+			if (!(e is ThreadAbortException))
+				result |= 0x8;
+			Console.WriteLine ("caught/2 a {0} while on {1} res {2}", e.GetType (), Thread.CurrentThread.ThreadState, result);
+		}
+	}
+
+
+	public static int test_0_abort_finally_after_throw () {
+		finally_done = false;
+		result = 0;
+		Action ac = GuardFromEH0;
+		handle = new ManualResetEvent (false);
+		var res = ac.BeginInvoke (null, null);
+		handle.WaitOne ();
+		Console.WriteLine ("aborting");
+		thread.Abort ();
+		Console.WriteLine ("aborted");
+		res.AsyncWaitHandle.WaitOne ();
+		Console.WriteLine ("waited");
+		if (!finally_done)
+			result |= 0x100;
+		return result;
+	}
+
+	/////////////////////////////////////////////////////
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	static void InnerFromEH1 () {
+		thread = Thread.CurrentThread;
+		MethodInfo mi = typeof (Driver).GetMethod ("SleepLoop");
+		try {
+			try {
+				throw new ArgumentException ();
+			} finally {	
+				handle.Set ();
+				SleepLoop ();
+				CancelAbort ();
+				Console.WriteLine ("done");
+				finally_done = true;
+			}
+			Console.WriteLine ("After finally");
+			result |= 0x10;
+		} catch (Exception e) {
+			if (!(e is ArgumentException))
+				result |= 0x4;
+			Console.WriteLine ("caught/3 a {0} while on {1} res {2}", e.GetType (), Thread.CurrentThread.ThreadState, result);
+		}
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	static void GuardFromEH1 () {
+		try {
+			InnerFromEH1 ();
+		} catch (Exception e) {
+			result |= 0x8;
+			Console.WriteLine ("caught/4 a {0} while on {1}", e.GetType (), Thread.CurrentThread.ThreadState);
+		}
+	}
+
+	public static int test_0_abort_finally_and_cancel () {
+		finally_done = false;
+		result = 0;
+		Action ac = GuardFromEH1;
+		handle = new ManualResetEvent (false);
+		var res = ac.BeginInvoke (null, null);
+		handle.WaitOne ();
+		Console.WriteLine ("aborting");
+		thread.Abort ();
+		Console.WriteLine ("aborted");
+		res.AsyncWaitHandle.WaitOne ();
+		Console.WriteLine ("waited");
+		if (!finally_done)
+			result |= 0x100;
+		return result;
+	}
+
+	/////////////////////////////////////////////////////
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	static void InnerFromEH () {
+		thread = Thread.CurrentThread;
+		MethodInfo mi = typeof (Driver).GetMethod ("SleepLoop");
+		try {
+			try {
+				Console.WriteLine ("try block");
+			} finally {	
+				handle.Set ();
+				SleepLoop ();
+				Console.WriteLine ("done");
+				finally_done = true;
+			}
+			Console.WriteLine ("After finally");
+			result |= 0x10;
+		} catch (Exception e) {
+			if (!(e is ThreadAbortException))
+				result |= 0x4;
+			Console.WriteLine ("caught/5 a {0} while on {1} res {2}", e.GetType (), Thread.CurrentThread.ThreadState, result);
+		}
+	}
+
+	[MethodImplAttribute (MethodImplOptions.NoInlining)]
+	static void GuardFromEH () {
+		try {
+			InnerFromEH ();
+		} catch (Exception e) {
+			if (!(e is ThreadAbortException))
+				result |= 0x8;
+			Console.WriteLine ("caught/6 a {0} while on {1} res {2}", e.GetType (), Thread.CurrentThread.ThreadState, result);
+		}
+	}
+
+
+	public static int test_0_finally_after_try () {
+		AppDomain.CurrentDomain.UnhandledException += (obj, sender) => {
+			Console.WriteLine ("Unhandled {0}",  sender.ExceptionObject);
+		};
+
+		finally_done = false;
+		result = 0;
+		Action ac = GuardFromEH;
+		handle = new ManualResetEvent (false);
+		var res = ac.BeginInvoke (null, null);
+		handle.WaitOne ();
+		Console.WriteLine ("aborting");
+		thread.Abort ();
+		Console.WriteLine ("aborted");
+		res.AsyncWaitHandle.WaitOne ();
+		Console.WriteLine ("waited");
+		if (!finally_done)
+			result |= 0x100;
+		return result;
+	}
+	/////////////////////////////////////////////////////
+
+	static int Main (string[] args)
+	{
+		AppDomain.CurrentDomain.UnhandledException += (obj, sender) => {
+			Console.WriteLine ("Unhandled {0}",  sender.ExceptionObject);
+		};
+
+		return TestDriver.RunTests (typeof (Driver), args);
+	}
+}
+
+
diff --git a/mono/utils/ChangeLog b/mono/utils/ChangeLog
index 9c81fd0..871d301 100644
--- a/mono/utils/ChangeLog
+++ b/mono/utils/ChangeLog
@@ -1,3 +1,13 @@
+2011-01-29  Marek Habersack  <grendel at twistedcode.net>
+
+	[runtime] Use IOAMP-aware method of looking for domain
+	configuration file
+
+2011-01-24  Geoff Norton  <grompf at sublimeintervention.com>
+
+	Avoid leaking the vmmap allocated by the kernel for the
+	thread_act_array_t
+
 2011-01-18  Zoltan Varga  <vargaz at gmail.com>
 
 	Make the stacks of aot image non-executable.
diff --git a/mono/utils/mach-support.c b/mono/utils/mach-support.c
index 8e3984e..1d39e86 100644
--- a/mono/utils/mach-support.c
+++ b/mono/utils/mach-support.c
@@ -35,4 +35,10 @@ mono_mach_get_threads (thread_act_array_t *threads, guint32 *count)
 
 	return ret;
 }
+
+kern_return_t
+mono_mach_free_threads (thread_act_array_t threads, guint32 count)
+{
+	return vm_deallocate(current_task (), (vm_address_t) threads, sizeof (thread_t) * count);
+}
 #endif
diff --git a/mono/utils/mach-support.h b/mono/utils/mach-support.h
index 4be7e57..8eae6d5 100644
--- a/mono/utils/mach-support.h
+++ b/mono/utils/mach-support.h
@@ -28,6 +28,7 @@ void mono_mach_arch_thread_state_to_mcontext (thread_state_t state, mcontext_t c
 
 int mono_mach_arch_get_thread_state_size (void) MONO_INTERNAL;
 kern_return_t mono_mach_get_threads (thread_act_array_t *threads, guint32 *count) MONO_INTERNAL;
+kern_return_t mono_mach_free_threads (thread_act_array_t threads, guint32 count) MONO_INTERNAL;
 kern_return_t mono_mach_arch_get_thread_state (thread_port_t thread, thread_state_t state, mach_msg_type_number_t *count) MONO_INTERNAL;
 void *mono_mach_arch_get_tls_value_from_thread (thread_port_t thread, guint32 key) MONO_INTERNAL;
 
diff --git a/mono/utils/mono-io-portability.c b/mono/utils/mono-io-portability.c
index 5a48418..20cc96b 100644
--- a/mono/utils/mono-io-portability.c
+++ b/mono/utils/mono-io-portability.c
@@ -25,7 +25,6 @@ mono_portability_helpers_init (void)
 gchar *
 mono_portability_find_file (const gchar *pathname, gboolean last_exists)
 {
-	g_assert_not_reached();
 	return NULL;
 }
 
@@ -147,7 +146,11 @@ static inline void do_mono_profiler_iomap (GString **report, const char *pathnam
 gchar *mono_portability_find_file (const gchar *pathname, gboolean last_exists)
 {
 	GString *report = NULL;
-	gchar *ret = mono_portability_find_file_internal (&report, pathname, last_exists);
+	gchar *ret;
+	
+	if (!pathname || !pathname [0])
+		return NULL;
+	ret = mono_portability_find_file_internal (&report, pathname, last_exists);
 
 	if (report)
 		g_string_free (report, TRUE);
diff --git a/msvc/ChangeLog b/msvc/ChangeLog
index 711373e..cc7eaa9 100644
--- a/msvc/ChangeLog
+++ b/msvc/ChangeLog
@@ -1,3 +1,7 @@
+2011-01-19  Andrew Jorgensen  <ajorgensen at novell.com>
+
+	Dist more files needed by MSVC build
+
 2011-01-11  Geoff Norton  <grompf at sublimeintervention.com>
 
 	Fix the win32 build
diff --git a/msvc/Makefile.am b/msvc/Makefile.am
index 3efb344..7e9ea66 100644
--- a/msvc/Makefile.am
+++ b/msvc/Makefile.am
@@ -16,7 +16,16 @@ VCPROJS =					\
 
 VCXPROJS = $(wildcard *.vcxproj)
 
-EXTRA_DIST = create-windef.pl mono.def README mono.sln winsetup.bat $(VCPROJS) $(VCXPROJS)
+EXTRA_DIST = \
+	     $(VCPROJS) \
+	     $(VCXPROJS) \
+	     README \
+	     create-windef.pl \
+	     mono.def \
+	     mono.sln \
+	     monoposixhelper.def \
+	     runmdesc.bat \
+	     winsetup.bat
 
 update-def:
 	perl create-windef.pl mono.def
diff --git a/msvc/Makefile.in b/msvc/Makefile.in
index b8c90a7..eb25fd0 100644
--- a/msvc/Makefile.in
+++ b/msvc/Makefile.in
@@ -260,7 +260,17 @@ VCPROJS = \
 	teste.vcproj
 
 VCXPROJS = $(wildcard *.vcxproj)
-EXTRA_DIST = create-windef.pl mono.def README mono.sln winsetup.bat $(VCPROJS) $(VCXPROJS)
+EXTRA_DIST = \
+	     $(VCPROJS) \
+	     $(VCXPROJS) \
+	     README \
+	     create-windef.pl \
+	     mono.def \
+	     mono.sln \
+	     monoposixhelper.def \
+	     runmdesc.bat \
+	     winsetup.bat
+
 all: all-am
 
 .SUFFIXES:
diff --git a/msvc/monoposixhelper.def b/msvc/monoposixhelper.def
new file mode 100644
index 0000000..fca1c3d
--- /dev/null
+++ b/msvc/monoposixhelper.def
@@ -0,0 +1,100 @@
+LIBRARY MonoPosixHelper.dll
+EXPORTS
+Mono_Posix_FromAccessModes
+Mono_Posix_FromConfstrName
+Mono_Posix_FromDirectoryNotifyFlags
+Mono_Posix_FromErrno
+Mono_Posix_FromFcntlCommand
+Mono_Posix_FromFilePermissions
+Mono_Posix_FromLockType
+Mono_Posix_FromLockfCommand
+Mono_Posix_FromMlockallFlags
+Mono_Posix_FromMmapFlags
+Mono_Posix_FromMmapProts
+Mono_Posix_FromMountFlags
+Mono_Posix_FromMremapFlags
+Mono_Posix_FromMsyncFlags
+Mono_Posix_FromOpenFlags
+Mono_Posix_FromPathconfName
+Mono_Posix_FromPollEvents
+Mono_Posix_FromPosixFadviseAdvice
+Mono_Posix_FromPosixMadviseAdvice
+Mono_Posix_FromSeekFlags
+Mono_Posix_FromSignum
+Mono_Posix_FromSysconfName
+Mono_Posix_FromSyslogFacility
+Mono_Posix_FromSyslogLevel
+Mono_Posix_FromSyslogOptions
+Mono_Posix_FromWaitOptions
+Mono_Posix_FromXattrFlags
+Mono_Posix_Stdlib_BUFSIZ
+Mono_Posix_Stdlib_CreateFilePosition
+Mono_Posix_Stdlib_DumpFilePosition
+Mono_Posix_Stdlib_EOF
+Mono_Posix_Stdlib_EXIT_FAILURE
+Mono_Posix_Stdlib_EXIT_SUCCESS
+Mono_Posix_Stdlib_FILENAME_MAX
+Mono_Posix_Stdlib_FOPEN_MAX
+Mono_Posix_Stdlib_InvokeSignalHandler
+Mono_Posix_Stdlib_L_tmpnam
+Mono_Posix_Stdlib_MB_CUR_MAX
+Mono_Posix_Stdlib_RAND_MAX
+Mono_Posix_Stdlib_SIG_DFL
+Mono_Posix_Stdlib_SIG_ERR
+Mono_Posix_Stdlib_SIG_IGN
+Mono_Posix_Stdlib_SetLastError
+Mono_Posix_Stdlib_TMP_MAX
+Mono_Posix_Stdlib__IOFBF
+Mono_Posix_Stdlib__IOLBF
+Mono_Posix_Stdlib__IONBF
+Mono_Posix_Stdlib_calloc
+Mono_Posix_Stdlib_clearerr
+Mono_Posix_Stdlib_fgetpos
+Mono_Posix_Stdlib_fread
+Mono_Posix_Stdlib_fseek
+Mono_Posix_Stdlib_fsetpos
+Mono_Posix_Stdlib_ftell
+Mono_Posix_Stdlib_fwrite
+Mono_Posix_Stdlib_malloc
+Mono_Posix_Stdlib_perror
+Mono_Posix_Stdlib_realloc
+Mono_Posix_Stdlib_rewind
+Mono_Posix_Stdlib_setbuf
+Mono_Posix_Stdlib_setvbuf
+Mono_Posix_Stdlib_stderr
+Mono_Posix_Stdlib_stdin
+Mono_Posix_Stdlib_stdout
+Mono_Posix_Stdlib_strlen
+Mono_Posix_ToAccessModes
+Mono_Posix_ToConfstrName
+Mono_Posix_ToDirectoryNotifyFlags
+Mono_Posix_ToErrno
+Mono_Posix_ToFcntlCommand
+Mono_Posix_ToFilePermissions
+Mono_Posix_ToLockType
+Mono_Posix_ToLockfCommand
+Mono_Posix_ToMlockallFlags
+Mono_Posix_ToMmapFlags
+Mono_Posix_ToMmapProts
+Mono_Posix_ToMountFlags
+Mono_Posix_ToMremapFlags
+Mono_Posix_ToMsyncFlags
+Mono_Posix_ToOpenFlags
+Mono_Posix_ToPathconfName
+Mono_Posix_ToPollEvents
+Mono_Posix_ToPosixFadviseAdvice
+Mono_Posix_ToPosixMadviseAdvice
+Mono_Posix_ToSeekFlags
+Mono_Posix_ToSignum
+Mono_Posix_ToSysconfName
+Mono_Posix_ToSyslogFacility
+Mono_Posix_ToSyslogLevel
+Mono_Posix_ToSyslogOptions
+Mono_Posix_ToWaitOptions
+Mono_Posix_ToXattrFlags
+CreateZStream
+CloseZStream
+ReadZStream
+WriteZStream
+Flush
+
diff --git a/msvc/runmdesc.bat b/msvc/runmdesc.bat
new file mode 100755
index 0000000..8d08934
--- /dev/null
+++ b/msvc/runmdesc.bat
@@ -0,0 +1,22 @@
+ at echo off
+rem This runs genmdesc on the x86 files when called on Visual Studio
+echo Running genmdesc
+cd ..\mono\mini
+set PATH=%PATH%;%MONO_DEPENDENCIES_PREFIX%\bin
+if "%2" == "Win32" goto x86
+if "%2" == "x64" goto x64
+goto error
+:x86
+echo Platform detected is x86...
+%1 cpu-x86.h x86_desc cpu-x86.md
+goto end
+:x64
+echo Platform detected is x64...
+%1 cpu-amd64.h amd64_desc cpu-amd64.md
+goto end
+:error
+echo Error: unsupported platform
+exit /b 100
+:end
+echo done
+
diff --git a/po/mcs/de.gmo b/po/mcs/de.gmo
index 5bc93a1..3329354 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 156aac9..18cd54e 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: 2011-01-18 10:45-0700\n"
+"POT-Creation-Date: 2011-02-14 10:10-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"
@@ -30,7 +30,7 @@ msgid ""
 "mismatch"
 msgstr ""
 
-#: mcs/mcs/anonymous.cs:909 mcs/mcs/ecore.cs:4524
+#: mcs/mcs/anonymous.cs:909 mcs/mcs/ecore.cs:4522
 #, csharp-format
 msgid "Delegate `{0}' does not take `{1}' arguments"
 msgstr ""
@@ -116,7 +116,7 @@ msgstr ""
 msgid "Cannot assign to `{0}' because it is a `{1}'"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:196
+#: mcs/mcs/attribute.cs:201
 #, csharp-format
 msgid ""
 "`{0}' is not a valid named attribute argument. Named attribute arguments "
@@ -124,88 +124,88 @@ msgid ""
 "properties which are public and not static"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:205
+#: mcs/mcs/attribute.cs:210
 #, csharp-format
 msgid ""
 "`{0}' is not a valid named attribute argument because it is not a valid "
 "attribute parameter type"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:211
+#: mcs/mcs/attribute.cs:216
 msgid "An attribute argument cannot be dynamic expression"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:216
+#: mcs/mcs/attribute.cs:221
 msgid "The Guid attribute must be specified with the ComImport attribute"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:221
+#: mcs/mcs/attribute.cs:226
 #, csharp-format
 msgid "Do not use `{0}' directly. Use parameter modifier `this' instead"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:226
+#: mcs/mcs/attribute.cs:231
 #, csharp-format
 msgid "Do not use `{0}' directly. Use `dynamic' keyword instead"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:235
+#: mcs/mcs/attribute.cs:240
 #, csharp-format
 msgid "Error during emitting `{0}' attribute. The reason is `{1}'"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:266
+#: mcs/mcs/attribute.cs:271
 #, csharp-format
 msgid "`{0}': is not an attribute class"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:302
+#: mcs/mcs/attribute.cs:307
 #, csharp-format
 msgid ""
 "`{0}' is ambiguous between `{1}' and `{2}'. Use either `@{0}' or `{0}"
 "Attribute'"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:385
+#: mcs/mcs/attribute.cs:390
 #, csharp-format
 msgid "Cannot apply attribute class `{0}' because it is abstract"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:453
+#: mcs/mcs/attribute.cs:458
 #, csharp-format
 msgid "Duplicate named attribute `{0}' argument"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:730
+#: mcs/mcs/attribute.cs:735
 #, csharp-format
 msgid ""
 "`{0}' is not a valid attribute location for this declaration. Valid "
 "attribute locations for this declaration are `{1}'"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:1004
+#: mcs/mcs/attribute.cs:1006
 #, csharp-format
 msgid ""
 "The attribute `{0}' is not valid on this declaration type. It is valid on `"
 "{1}' declarations only"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:1022
+#: mcs/mcs/attribute.cs:1028
 #, csharp-format
 msgid "The argument to the `{0}' attribute must be a valid identifier"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:1035
+#: mcs/mcs/attribute.cs:1041
 #, csharp-format
 msgid "Invalid value for argument to `{0}' attribute"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:1341
+#: mcs/mcs/attribute.cs:1348
 #, csharp-format
 msgid "The attribute `{0}' cannot be applied multiple times"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:1603
+#: mcs/mcs/attribute.cs:1676
 #, csharp-format
 msgid "`{0}' is obsolete: `{1}'"
 msgstr "`{0}' ist veraltet: `{1}'"
@@ -1415,7 +1415,7 @@ msgstr "Methodennamen erwartet"
 msgid "Error generating XML documentation file `{0}' (`{1}')"
 msgstr "Fehler beim erstellen der XML-Dokumentationsdatei `{0}' (`{1}')"
 
-#: mcs/mcs/driver.cs:96 mcs/mcs/driver.cs:467 mcs/mcs/driver.cs:470
+#: mcs/mcs/driver.cs:96 mcs/mcs/driver.cs:475 mcs/mcs/driver.cs:478
 msgid "Source file `"
 msgstr ""
 
@@ -1443,145 +1443,145 @@ msgstr ""
 msgid "Unable to open response file: "
 msgstr ""
 
-#: mcs/mcs/driver.cs:422 mcs/mcs/driver.cs:432
+#: mcs/mcs/driver.cs:430 mcs/mcs/driver.cs:440
 msgid "No files to compile were specified"
 msgstr "Es wurden keine Dateien zum kompilieren angegeben"
 
-#: mcs/mcs/driver.cs:504
+#: mcs/mcs/driver.cs:512
 msgid "Warning level must be in the range 0-4"
 msgstr ""
 
-#: mcs/mcs/driver.cs:538
+#: mcs/mcs/driver.cs:546
 msgid "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS"
 msgstr ""
 
-#: mcs/mcs/driver.cs:547
+#: mcs/mcs/driver.cs:555
 msgid "Compatibility: Use -unsafe instead of --unsafe"
 msgstr ""
 
-#: mcs/mcs/driver.cs:558
+#: mcs/mcs/driver.cs:566
 msgid "Compatibility: Use -d:SYMBOL instead of --define SYMBOL"
 msgstr ""
 
-#: mcs/mcs/driver.cs:572
+#: mcs/mcs/driver.cs:580
 msgid "Compatibility: Use -out:FILE instead of --output FILE or -o FILE"
 msgstr ""
 
-#: mcs/mcs/driver.cs:581
+#: mcs/mcs/driver.cs:589
 msgid "Compatibility: Use -checked instead of --checked"
 msgstr ""
 
-#: mcs/mcs/driver.cs:591
+#: mcs/mcs/driver.cs:599
 msgid "Compatibility: Use -linkres:VALUE instead of --linkres VALUE"
 msgstr ""
 
-#: mcs/mcs/driver.cs:594
+#: mcs/mcs/driver.cs:602
 msgid "Missing argument to --linkres"
 msgstr "Fehlendes Argument bei --linkres"
 
-#: mcs/mcs/driver.cs:603
+#: mcs/mcs/driver.cs:611
 msgid "Compatibility: Use -res:VALUE instead of --res VALUE"
 msgstr ""
 
-#: mcs/mcs/driver.cs:606
+#: mcs/mcs/driver.cs:614
 msgid "Missing argument to --resource"
 msgstr "Fehlendes Argument bei --resource"
 
-#: mcs/mcs/driver.cs:614
+#: mcs/mcs/driver.cs:622
 msgid "Compatibility: Use -target:KIND instead of --target KIND"
 msgstr ""
 
-#: mcs/mcs/driver.cs:646
+#: mcs/mcs/driver.cs:654
 msgid "Compatibility: Use -r:LIBRARY instead of -r library"
 msgstr ""
 
-#: mcs/mcs/driver.cs:665
+#: mcs/mcs/driver.cs:673
 msgid "Compatibility: Use -lib:ARG instead of --L arg"
 msgstr ""
 
-#: mcs/mcs/driver.cs:678
+#: mcs/mcs/driver.cs:686
 msgid "Compatibility: Use -nostdlib instead of --nostdlib"
 msgstr ""
 
-#: mcs/mcs/driver.cs:683
+#: mcs/mcs/driver.cs:691
 msgid "Compatibility: Use -nowarn instead of --nowarn"
 msgstr ""
 
-#: mcs/mcs/driver.cs:700
+#: mcs/mcs/driver.cs:708
 msgid "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL"
 msgstr ""
 
-#: mcs/mcs/driver.cs:704
+#: mcs/mcs/driver.cs:712
 msgid "--wlevel requires a value from 0 to 4"
 msgstr "--wlevel benötigt einen Wert zwischen 0 und 4"
 
-#: mcs/mcs/driver.cs:713
+#: mcs/mcs/driver.cs:721
 msgid "--mcs-debug requires an argument"
 msgstr "--mcs-debug benötigt ein Argument"
 
-#: mcs/mcs/driver.cs:720
+#: mcs/mcs/driver.cs:728
 msgid "Invalid argument to --mcs-debug"
 msgstr "Ungültiges Argument für --mcs-debug"
 
-#: mcs/mcs/driver.cs:730
+#: mcs/mcs/driver.cs:738
 msgid "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN"
 msgstr ""
 
-#: mcs/mcs/driver.cs:732
+#: mcs/mcs/driver.cs:740
 msgid "--recurse requires an argument"
 msgstr "--recurse benötigt ein Argument"
 
-#: mcs/mcs/driver.cs:743
+#: mcs/mcs/driver.cs:751
 msgid "Compatibility: Use -debug option instead of -g or --debug"
 msgstr ""
 
-#: mcs/mcs/driver.cs:748
+#: mcs/mcs/driver.cs:756
 msgid "Compatibility: Use -noconfig option instead of --noconfig"
 msgstr ""
 
-#: mcs/mcs/driver.cs:912
+#: mcs/mcs/driver.cs:920
 #, csharp-format
 msgid "Invalid conditional define symbol `{0}'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:963
+#: mcs/mcs/driver.cs:971
 #, csharp-format
 msgid ""
 "Invalid resource visibility option `{0}'. Use either `public' or `private' "
 "instead"
 msgstr ""
 
-#: mcs/mcs/driver.cs:969
+#: mcs/mcs/driver.cs:977
 #, csharp-format
 msgid "Wrong number of arguments for option `{0}'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1007
+#: mcs/mcs/driver.cs:1015
 msgid "Cannot specify multiple aliases using single /reference option"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1035 mcs/mcs/driver.cs:1047
+#: mcs/mcs/driver.cs:1043 mcs/mcs/driver.cs:1055
 msgid ""
 "Cannot specify the `win32res' and the `win32ico' compiler option at the same "
 "time"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1162
+#: mcs/mcs/driver.cs:1170
 #, csharp-format
 msgid "`{0}' is not a valid warning number"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1192
+#: mcs/mcs/driver.cs:1200
 msgid ""
 "Invalid platform type for -platform. Valid options are `anycpu', `x86', "
 "`x64' or `itanium'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1212
+#: mcs/mcs/driver.cs:1220
 msgid "Invalid sdk version name"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1310
+#: mcs/mcs/driver.cs:1318
 #, fuzzy, csharp-format
 msgid ""
 "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or "
@@ -1590,43 +1590,43 @@ msgstr ""
 "Ungültige Option `{0}' für /langversion. Es muss entweder `ISO-1', `ISO-2' "
 "oder `Default' sein"
 
-#: mcs/mcs/driver.cs:1330
+#: mcs/mcs/driver.cs:1338
 #, csharp-format
 msgid "Code page `{0}' is invalid or not installed"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1345
+#: mcs/mcs/driver.cs:1353
 #, csharp-format
 msgid "Unrecognized command-line option: `{0}'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1350
+#: mcs/mcs/driver.cs:1358
 #, csharp-format
 msgid "Missing file specification for `{0}' option"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1355
+#: mcs/mcs/driver.cs:1363
 #, fuzzy, csharp-format
 msgid "Missing argument for `{0}' option"
 msgstr "Fehlendes Argument bei --linkres"
 
-#: mcs/mcs/driver.cs:1390
+#: mcs/mcs/driver.cs:1398
 #, fuzzy, csharp-format
 msgid "Invalid reference alias `{0}='. Missing filename"
 msgstr "Ungültiger Referenz Alias '"
 
-#: mcs/mcs/driver.cs:1395
+#: mcs/mcs/driver.cs:1403
 #, fuzzy, csharp-format
 msgid ""
 "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier"
 msgstr "Ungültiger externer Alias für /reference. Alias '"
 
-#: mcs/mcs/driver.cs:1411
+#: mcs/mcs/driver.cs:1419
 #, csharp-format
 msgid "The resource identifier `{0}' has already been used in this assembly"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1472
+#: mcs/mcs/driver.cs:1480
 msgid ""
 "If no source files are specified you must specify the output file with -out:"
 msgstr ""
@@ -1699,7 +1699,7 @@ msgstr ""
 msgid "The operation in question is undefined on void pointers"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:438 mcs/mcs/statement.cs:2558 mcs/mcs/statement.cs:2560
+#: mcs/mcs/ecore.cs:438 mcs/mcs/statement.cs:2559 mcs/mcs/statement.cs:2561
 #, csharp-format
 msgid "Internal compiler error: {0}"
 msgstr ""
@@ -1858,7 +1858,7 @@ msgid ""
 "The type `{0}' does not contain a constructor that takes `{1}' arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4334
+#: mcs/mcs/ecore.cs:4332
 #, csharp-format
 msgid ""
 "Type `{0}' does not contain a member `{1}' and the best extension method "
@@ -1866,156 +1866,156 @@ msgid ""
 "without the extension method syntax"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4355
+#: mcs/mcs/ecore.cs:4353
 #, csharp-format
 msgid ""
 "The call is ambiguous between the following methods or properties: `{0}' and "
 "`{1}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4415
+#: mcs/mcs/ecore.cs:4413
 #, csharp-format
 msgid ""
 "The best overloaded collection initalizer method `{0}' cannot have 'ref', or "
 "`out' modifier"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4419
+#: mcs/mcs/ecore.cs:4417
 #, csharp-format
 msgid ""
 "The best overloaded collection initalizer method `{0}' has some invalid "
 "arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4422
+#: mcs/mcs/ecore.cs:4420
 #, csharp-format
 msgid "Delegate `{0}' has some invalid arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4426
+#: mcs/mcs/ecore.cs:4424
 #, csharp-format
 msgid "The best overloaded method match for `{0}' has some invalid arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4436
+#: mcs/mcs/ecore.cs:4434
 #, csharp-format
 msgid ""
 "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' "
 "modifier"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4439
+#: mcs/mcs/ecore.cs:4437
 #, csharp-format
 msgid "Argument `#{0}' is missing `{1}' modifier"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4452
+#: mcs/mcs/ecore.cs:4450
 #, csharp-format
 msgid "Argument `#{0}' cannot convert `{1}' expression to type `{2}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4500
+#: mcs/mcs/ecore.cs:4498
 #, csharp-format
 msgid ""
 "The type arguments for method `{0}' cannot be inferred from the usage. Try "
 "specifying the type arguments explicitly"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4529
+#: mcs/mcs/ecore.cs:4527
 #, csharp-format
 msgid "No overload for method `{0}' takes `{1}' arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4582
+#: mcs/mcs/ecore.cs:4580
 #, csharp-format
 msgid "The delegate `{0}' does not contain a parameter named `{1}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4587
+#: mcs/mcs/ecore.cs:4585
 #, csharp-format
 msgid ""
 "The best overloaded method match for `{0}' does not contain a parameter "
 "named `{1}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4597
+#: mcs/mcs/ecore.cs:4595
 #, csharp-format
 msgid ""
 "Named argument `{0}' cannot be used for a parameter which has positional "
 "argument specified"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4910
+#: mcs/mcs/ecore.cs:4908
 msgid ""
 "You cannot use fixed size buffers contained in unfixed expressions. Try "
 "using the fixed statement"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4915
+#: mcs/mcs/ecore.cs:4913
 #, csharp-format
 msgid "`{0}': Fixed size buffers can only be accessed through locals or fields"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5310
+#: mcs/mcs/ecore.cs:5308
 #, fuzzy, csharp-format
 msgid "Property or event `{0}' is not supported by the C# language"
 msgstr ""
 "Die Eigenschaft `{0}' wird von der C# Sprache nicht unterstützt. Rufen Sie "
 "die `{1}'-Accessormethode direkt auf."
 
-#: mcs/mcs/ecore.cs:5471
+#: mcs/mcs/ecore.cs:5469
 #, csharp-format
 msgid "A range variable `{0}' may not be passes as `ref' or `out' parameter"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5519
+#: mcs/mcs/ecore.cs:5517
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because it "
 "lacks the `get' accessor"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5526
+#: mcs/mcs/ecore.cs:5524
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because the get "
 "accessor is inaccessible"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5545
+#: mcs/mcs/ecore.cs:5543
 #, csharp-format
 msgid "Property or indexer `{0}' cannot be assigned to (it is read-only)"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5553
+#: mcs/mcs/ecore.cs:5551
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because the set "
 "accessor is inaccessible"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5714
+#: mcs/mcs/ecore.cs:5712
 #, csharp-format
 msgid ""
 "The event `{0}' can only appear on the left hand side of `+=' or `-=' "
 "operator"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5718
+#: mcs/mcs/ecore.cs:5716
 #, csharp-format
 msgid ""
 "The event `{0}' can only appear on the left hand side of += or -= when used "
 "outside of the type `{1}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5882
+#: mcs/mcs/ecore.cs:5880
 #, csharp-format
 msgid ""
 "An implicitly typed local variable declaration cannot be initialized with `"
 "{0}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5896
+#: mcs/mcs/ecore.cs:5894
 msgid ""
 "The contextual keyword `var' may only appear within a local variable "
 "declaration"
@@ -2037,7 +2037,7 @@ msgstr ""
 msgid "Type byte, sbyte, short, ushort, int, uint, long or ulong expected"
 msgstr "Typ byte, sbyte, short, ushort, int, uint, long oder ulong erwartet"
 
-#: mcs/mcs/eval.cs:626
+#: mcs/mcs/eval.cs:643
 msgid "Detection Parsing Error"
 msgstr ""
 
@@ -2241,7 +2241,7 @@ msgid "Cannot create an array with a negative size"
 msgstr ""
 
 #: mcs/mcs/expression.cs:6096 mcs/mcs/expression.cs:6104
-#: mcs/mcs/statement.cs:1009 mcs/mcs/statement.cs:3055
+#: mcs/mcs/statement.cs:1002 mcs/mcs/statement.cs:3056
 msgid "A constant value is expected"
 msgstr ""
 
@@ -2601,7 +2601,7 @@ msgid "Cannot yield in the body of a finally clause"
 msgstr ""
 
 #: mcs/mcs/flowanalysis.cs:927 mcs/mcs/flowanalysis.cs:943
-#: mcs/mcs/flowanalysis.cs:979 mcs/mcs/statement.cs:694
+#: mcs/mcs/flowanalysis.cs:979 mcs/mcs/statement.cs:687
 msgid "Control cannot leave the body of a finally clause"
 msgstr ""
 
@@ -2778,7 +2778,7 @@ msgstr ""
 "Der Typ `{0}' muss ein Referenztyp sein, damit er als `{1}'-Parameter in "
 "generischen Typ oder in der generischen Methode `{2}' verwendet werden kann."
 
-#: mcs/mcs/import.cs:1711
+#: mcs/mcs/import.cs:1712
 #, csharp-format
 msgid ""
 "The type `{0}' is defined in an assembly that is not referenced. Consider "
@@ -2808,7 +2808,7 @@ msgstr ""
 msgid "Iterators cannot have unsafe parameters or yield types"
 msgstr ""
 
-#: mcs/mcs/iterators.cs:888 mcs/mcs/statement.cs:4324
+#: mcs/mcs/iterators.cs:888 mcs/mcs/statement.cs:4325
 msgid "Unsafe code may not appear in iterators"
 msgstr ""
 
@@ -2852,22 +2852,22 @@ msgstr ""
 msgid "A range variable `{0}' cannot be initialized with `{1}'"
 msgstr ""
 
-#: mcs/mcs/linq.cs:750
+#: mcs/mcs/linq.cs:747
 #, csharp-format
 msgid "A range variable `{0}' conflicts with a previous declaration of `{0}'"
 msgstr ""
 
-#: mcs/mcs/linq.cs:757
+#: mcs/mcs/linq.cs:754
 #, csharp-format
 msgid "A range variable `{0}' has already been declared in this scope"
 msgstr ""
 
-#: mcs/mcs/linq.cs:764
+#: mcs/mcs/linq.cs:761
 #, csharp-format
 msgid "A range variable `{0}' conflicts with a method type parameter"
 msgstr ""
 
-#: mcs/mcs/linq.cs:796
+#: mcs/mcs/linq.cs:793
 #, csharp-format
 msgid ""
 "A range variable `{0}' cannot be assigned to. Consider using `let' clause to "
@@ -3284,95 +3284,95 @@ msgstr ""
 msgid "The params parameter must be a single dimensional array"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:288
+#: mcs/mcs/parameter.cs:301
 msgid "An out parameter cannot have the `In' attribute"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:293
+#: mcs/mcs/parameter.cs:306
 msgid ""
 "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:300
+#: mcs/mcs/parameter.cs:313
 msgid ""
 "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and "
 "`Out' attributes or neither"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:310
+#: mcs/mcs/parameter.cs:324
 #, csharp-format
 msgid "Cannot specify `{0}' attribute on optional parameter `{1}'"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:320
+#: mcs/mcs/parameter.cs:369
+#, csharp-format
+msgid "Method or delegate parameter cannot be of type `{0}'"
+msgstr ""
+
+#: mcs/mcs/parameter.cs:379
+#, csharp-format
+msgid "`{0}': static types cannot be used as parameters"
+msgstr ""
+
+#: mcs/mcs/parameter.cs:385
+#, csharp-format
+msgid "The extension method cannot be of type `{0}'"
+msgstr ""
+
+#: mcs/mcs/parameter.cs:425
 #, csharp-format
 msgid ""
 "Argument of type `{0}' is not applicable for the DefaultParameterValue "
 "attribute"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:323
+#: mcs/mcs/parameter.cs:429
 #, csharp-format
 msgid ""
 "The DefaultParameterValue attribute is not applicable on parameters of type `"
 "{0}'"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:334
+#: mcs/mcs/parameter.cs:457
 msgid "The type of the default value should match the type of the parameter"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:376
-#, csharp-format
-msgid "Method or delegate parameter cannot be of type `{0}'"
-msgstr ""
-
-#: mcs/mcs/parameter.cs:386
-#, csharp-format
-msgid "`{0}': static types cannot be used as parameters"
+#: mcs/mcs/parameter.cs:602
+msgid "An expression tree parameter cannot use `ref' or `out' modifier"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:392
+#: mcs/mcs/parameter.cs:1074
 #, csharp-format
-msgid "The extension method cannot be of type `{0}'"
+msgid "The parameter name `{0}' conflicts with a compiler generated name"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:448
+#: mcs/mcs/parameter.cs:1220
 #, csharp-format
 msgid ""
 "The expression being assigned to optional parameter `{0}' must be a constant "
 "or default value"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:464
+#: mcs/mcs/parameter.cs:1237
 #, csharp-format
 msgid ""
 "The expression being assigned to nullable optional parameter `{0}' must be "
 "default value"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:472
+#: mcs/mcs/parameter.cs:1245
 #, csharp-format
 msgid ""
 "Optional parameter `{0}' of type `{1}' can only be initialized with `null'"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:482
+#: mcs/mcs/parameter.cs:1256
 #, csharp-format
 msgid ""
 "Optional parameter expression of type `{0}' cannot be converted to parameter "
 "type `{1}'"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:624
-msgid "An expression tree parameter cannot use `ref' or `out' modifier"
-msgstr ""
-
-#: mcs/mcs/parameter.cs:1096
-#, csharp-format
-msgid "The parameter name `{0}' conflicts with a compiler generated name"
-msgstr ""
-
 #: mcs/mcs/pending.cs:443
 #, csharp-format
 msgid ""
@@ -3479,7 +3479,7 @@ msgstr ""
 msgid "Cannot set the `IndexerName' attribute on an indexer marked override"
 msgstr ""
 
-#: mcs/mcs/reflection.cs:239
+#: mcs/mcs/reflection.cs:255
 msgid "Could not access the key inside the container `"
 msgstr ""
 
@@ -3500,60 +3500,60 @@ msgid ""
 "tree"
 msgstr ""
 
-#: mcs/mcs/statement.cs:740
+#: mcs/mcs/statement.cs:733
 #, csharp-format
 msgid ""
 "An object of a type convertible to `{0}' is required for the return statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:753
+#: mcs/mcs/statement.cs:746
 #, csharp-format
 msgid ""
 "`{0}': A return keyword must not be followed by any expression when method "
 "returns void"
 msgstr ""
 
-#: mcs/mcs/statement.cs:778
+#: mcs/mcs/statement.cs:771
 #, csharp-format
 msgid ""
 "Cannot convert `{0}' to delegate type `{1}' because some of the return types "
 "in the block are not implicitly convertible to the delegate return type"
 msgstr ""
 
-#: mcs/mcs/statement.cs:806
+#: mcs/mcs/statement.cs:799
 msgid ""
 "Cannot return a value from iterators. Use the yield return statement to "
 "return a value, or yield break to end the iteration"
 msgstr ""
 
-#: mcs/mcs/statement.cs:963 mcs/mcs/statement.cs:997
+#: mcs/mcs/statement.cs:956 mcs/mcs/statement.cs:990
 msgid "A goto case is only valid inside a switch statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1076 mcs/mcs/statement.cs:4726
+#: mcs/mcs/statement.cs:1069 mcs/mcs/statement.cs:4727
 msgid "The type caught or thrown must be derived from System.Exception"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1298
+#: mcs/mcs/statement.cs:1291
 msgid "A fixed statement cannot use an implicitly typed local variable"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1303
+#: mcs/mcs/statement.cs:1296
 msgid "An implicitly typed local variable cannot be a constant"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1308
+#: mcs/mcs/statement.cs:1301
 msgid ""
 "An implicitly typed local variable declarator must include an initializer"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1313
+#: mcs/mcs/statement.cs:1306
 msgid ""
 "An implicitly typed local variable declaration cannot include multiple "
 "declarators"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1883
+#: mcs/mcs/statement.cs:1876
 #, csharp-format
 msgid ""
 "A local variable named `{0}' cannot be declared in this scope because it "
@@ -3561,111 +3561,111 @@ msgid ""
 "scope to denote something else"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1894
+#: mcs/mcs/statement.cs:1887
 #, csharp-format
 msgid ""
 "`{0}': An anonymous type cannot have multiple properties with the same name"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1897
+#: mcs/mcs/statement.cs:1890
 #, csharp-format
 msgid "The parameter name `{0}' is a duplicate"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1904
+#: mcs/mcs/statement.cs:1897
 #, csharp-format
 msgid "A local variable named `{0}' is already defined in this scope"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1910
+#: mcs/mcs/statement.cs:1903
 #, csharp-format
 msgid ""
 "The type parameter name `{0}' is the same as local variable or parameter name"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2482
+#: mcs/mcs/statement.cs:2477
 #, csharp-format
 msgid ""
 "The out parameter `{0}' must be assigned to before control leaves the "
 "current method"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2573
+#: mcs/mcs/statement.cs:2574
 #, csharp-format
 msgid "`{0}': not all code paths return a value"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2577
+#: mcs/mcs/statement.cs:2578
 #, csharp-format
 msgid "Not all code paths return a value in anonymous method of type `{0}'"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2748
+#: mcs/mcs/statement.cs:2749
 #, csharp-format
 msgid "The label `{0}' is a duplicate"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2757 mcs/mcs/statement.cs:2768
+#: mcs/mcs/statement.cs:2758 mcs/mcs/statement.cs:2769
 #, csharp-format
 msgid ""
 "The label `{0}' shadows another label by the same name in a contained scope"
 msgstr ""
 
-#: mcs/mcs/statement.cs:3088
+#: mcs/mcs/statement.cs:3089
 #, csharp-format
 msgid "The label `case {0}:' already occurs in this switch statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:3629
+#: mcs/mcs/statement.cs:3630
 #, csharp-format
 msgid ""
 "A switch expression of type `{0}' cannot be converted to an integral type, "
 "bool, char, string, enum or nullable type"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4114
+#: mcs/mcs/statement.cs:4115
 #, csharp-format
 msgid "`{0}' is not a reference type as required by the lock statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4455
+#: mcs/mcs/statement.cs:4456
 msgid "The type of locals declared in a fixed statement must be a pointer type"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4471
+#: mcs/mcs/statement.cs:4472
 msgid ""
 "The right hand side of a fixed statement assignment may not be a cast "
 "expression"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4542
+#: mcs/mcs/statement.cs:4543
 msgid ""
 "You cannot use the fixed statement to take the address of an already fixed "
 "expression"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4856
+#: mcs/mcs/statement.cs:4857
 #, csharp-format
 msgid ""
 "A previous catch clause already catches all exceptions of this or a super "
 "type `{0}'"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5029
+#: mcs/mcs/statement.cs:5030
 #, csharp-format
 msgid ""
 "`{0}': type used in a using statement must be implicitly convertible to "
 "`System.IDisposable'"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5451
+#: mcs/mcs/statement.cs:5452
 #, csharp-format
 msgid ""
 "foreach statement requires that the return type `{0}' of `{1}' must have a "
 "suitable public MoveNext method and public Current property"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5491
+#: mcs/mcs/statement.cs:5492
 #, csharp-format
 msgid ""
 "foreach statement cannot operate on variables of type `{0}' because it "
@@ -3673,18 +3673,18 @@ msgid ""
 "implementation"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5516
+#: mcs/mcs/statement.cs:5517
 #, csharp-format
 msgid ""
 "foreach statement cannot operate on variables of type `{0}' because it does "
 "not contain a definition for `{1}' or is inaccessible"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5722
+#: mcs/mcs/statement.cs:5723
 msgid "Use of null is not valid in this context"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5732
+#: mcs/mcs/statement.cs:5733
 #, csharp-format
 msgid "Foreach statement cannot operate on a `{0}'"
 msgstr ""
diff --git a/po/mcs/es.gmo b/po/mcs/es.gmo
index 77abf9a..9f0f3c2 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 8159da1..f805c61 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: 2011-01-18 10:45-0700\n"
+"POT-Creation-Date: 2011-02-14 10:10-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"
@@ -34,7 +34,7 @@ msgid ""
 "mismatch"
 msgstr ""
 
-#: mcs/mcs/anonymous.cs:909 mcs/mcs/ecore.cs:4524
+#: mcs/mcs/anonymous.cs:909 mcs/mcs/ecore.cs:4522
 #, csharp-format
 msgid "Delegate `{0}' does not take `{1}' arguments"
 msgstr "El delegado `{0} no toma {1} argumentos"
@@ -134,7 +134,7 @@ msgstr "Un árbol de expresiones no puede contener un operador de asignación"
 msgid "Cannot assign to `{0}' because it is a `{1}'"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:196
+#: mcs/mcs/attribute.cs:201
 #, csharp-format
 msgid ""
 "`{0}' is not a valid named attribute argument. Named attribute arguments "
@@ -142,49 +142,49 @@ msgid ""
 "properties which are public and not static"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:205
+#: mcs/mcs/attribute.cs:210
 #, csharp-format
 msgid ""
 "`{0}' is not a valid named attribute argument because it is not a valid "
 "attribute parameter type"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:211
+#: mcs/mcs/attribute.cs:216
 #, fuzzy
 msgid "An attribute argument cannot be dynamic expression"
 msgstr ""
 "Los métodos anónimos no pueden ser convertidos a árboles de expresiones"
 
-#: mcs/mcs/attribute.cs:216
+#: mcs/mcs/attribute.cs:221
 msgid "The Guid attribute must be specified with the ComImport attribute"
 msgstr ""
 "El atributo Guid debe de ser especificado junto con el atributo ComImport"
 
-#: mcs/mcs/attribute.cs:221
+#: mcs/mcs/attribute.cs:226
 #, csharp-format
 msgid "Do not use `{0}' directly. Use parameter modifier `this' instead"
 msgstr ""
 "No use `{0}' directamente.   Use el modificador de parámetro `this' en su "
 "lugar"
 
-#: mcs/mcs/attribute.cs:226
+#: mcs/mcs/attribute.cs:231
 #, fuzzy, csharp-format
 msgid "Do not use `{0}' directly. Use `dynamic' keyword instead"
 msgstr ""
 "No use `{0}' directamente.   Use el modificador de parámetro `this' en su "
 "lugar"
 
-#: mcs/mcs/attribute.cs:235
+#: mcs/mcs/attribute.cs:240
 #, csharp-format
 msgid "Error during emitting `{0}' attribute. The reason is `{1}'"
 msgstr "Error al emitir el atributo `{0}'.   La razón es `{1}'"
 
-#: mcs/mcs/attribute.cs:266
+#: mcs/mcs/attribute.cs:271
 #, csharp-format
 msgid "`{0}': is not an attribute class"
 msgstr "`{0}' no es una clase atributo"
 
-#: mcs/mcs/attribute.cs:302
+#: mcs/mcs/attribute.cs:307
 #, fuzzy, csharp-format
 msgid ""
 "`{0}' is ambiguous between `{1}' and `{2}'. Use either `@{0}' or `{0}"
@@ -193,47 +193,47 @@ msgstr ""
 "`{0}' produce una amiguedad entre `{0}' y `{0}Attribute'.   Use `@{0}' o `{0}"
 "Attribute'"
 
-#: mcs/mcs/attribute.cs:385
+#: mcs/mcs/attribute.cs:390
 #, csharp-format
 msgid "Cannot apply attribute class `{0}' because it is abstract"
 msgstr "No es posible aplicar el atributo `{0}' ya que es abstracto"
 
-#: mcs/mcs/attribute.cs:453
+#: mcs/mcs/attribute.cs:458
 #, csharp-format
 msgid "Duplicate named attribute `{0}' argument"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:730
+#: mcs/mcs/attribute.cs:735
 #, csharp-format
 msgid ""
 "`{0}' is not a valid attribute location for this declaration. Valid "
 "attribute locations for this declaration are `{1}'"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:1004
+#: mcs/mcs/attribute.cs:1006
 #, csharp-format
 msgid ""
 "The attribute `{0}' is not valid on this declaration type. It is valid on `"
 "{1}' declarations only"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:1022
+#: mcs/mcs/attribute.cs:1028
 #, csharp-format
 msgid "The argument to the `{0}' attribute must be a valid identifier"
 msgstr ""
 "El argumento pasado al atributo `{0}' debe de ser un identificador válido"
 
-#: mcs/mcs/attribute.cs:1035
+#: mcs/mcs/attribute.cs:1041
 #, fuzzy, csharp-format
 msgid "Invalid value for argument to `{0}' attribute"
 msgstr "Valor inválido pasado a `System.AttributeUsage'"
 
-#: mcs/mcs/attribute.cs:1341
+#: mcs/mcs/attribute.cs:1348
 #, csharp-format
 msgid "The attribute `{0}' cannot be applied multiple times"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:1603
+#: mcs/mcs/attribute.cs:1676
 #, csharp-format
 msgid "`{0}' is obsolete: `{1}'"
 msgstr ""
@@ -1532,7 +1532,7 @@ msgstr ""
 msgid "Error generating XML documentation file `{0}' (`{1}')"
 msgstr ""
 
-#: mcs/mcs/driver.cs:96 mcs/mcs/driver.cs:467 mcs/mcs/driver.cs:470
+#: mcs/mcs/driver.cs:96 mcs/mcs/driver.cs:475 mcs/mcs/driver.cs:478
 msgid "Source file `"
 msgstr ""
 
@@ -1560,188 +1560,188 @@ msgstr ""
 msgid "Unable to open response file: "
 msgstr ""
 
-#: mcs/mcs/driver.cs:422 mcs/mcs/driver.cs:432
+#: mcs/mcs/driver.cs:430 mcs/mcs/driver.cs:440
 msgid "No files to compile were specified"
 msgstr ""
 
-#: mcs/mcs/driver.cs:504
+#: mcs/mcs/driver.cs:512
 msgid "Warning level must be in the range 0-4"
 msgstr ""
 
-#: mcs/mcs/driver.cs:538
+#: mcs/mcs/driver.cs:546
 msgid "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS"
 msgstr ""
 
-#: mcs/mcs/driver.cs:547
+#: mcs/mcs/driver.cs:555
 msgid "Compatibility: Use -unsafe instead of --unsafe"
 msgstr ""
 
-#: mcs/mcs/driver.cs:558
+#: mcs/mcs/driver.cs:566
 msgid "Compatibility: Use -d:SYMBOL instead of --define SYMBOL"
 msgstr ""
 
-#: mcs/mcs/driver.cs:572
+#: mcs/mcs/driver.cs:580
 msgid "Compatibility: Use -out:FILE instead of --output FILE or -o FILE"
 msgstr ""
 
-#: mcs/mcs/driver.cs:581
+#: mcs/mcs/driver.cs:589
 msgid "Compatibility: Use -checked instead of --checked"
 msgstr ""
 
-#: mcs/mcs/driver.cs:591
+#: mcs/mcs/driver.cs:599
 msgid "Compatibility: Use -linkres:VALUE instead of --linkres VALUE"
 msgstr ""
 
-#: mcs/mcs/driver.cs:594
+#: mcs/mcs/driver.cs:602
 msgid "Missing argument to --linkres"
 msgstr ""
 
-#: mcs/mcs/driver.cs:603
+#: mcs/mcs/driver.cs:611
 msgid "Compatibility: Use -res:VALUE instead of --res VALUE"
 msgstr ""
 
-#: mcs/mcs/driver.cs:606
+#: mcs/mcs/driver.cs:614
 msgid "Missing argument to --resource"
 msgstr ""
 
-#: mcs/mcs/driver.cs:614
+#: mcs/mcs/driver.cs:622
 msgid "Compatibility: Use -target:KIND instead of --target KIND"
 msgstr ""
 
-#: mcs/mcs/driver.cs:646
+#: mcs/mcs/driver.cs:654
 msgid "Compatibility: Use -r:LIBRARY instead of -r library"
 msgstr ""
 
-#: mcs/mcs/driver.cs:665
+#: mcs/mcs/driver.cs:673
 msgid "Compatibility: Use -lib:ARG instead of --L arg"
 msgstr ""
 
-#: mcs/mcs/driver.cs:678
+#: mcs/mcs/driver.cs:686
 msgid "Compatibility: Use -nostdlib instead of --nostdlib"
 msgstr ""
 
-#: mcs/mcs/driver.cs:683
+#: mcs/mcs/driver.cs:691
 msgid "Compatibility: Use -nowarn instead of --nowarn"
 msgstr ""
 
-#: mcs/mcs/driver.cs:700
+#: mcs/mcs/driver.cs:708
 msgid "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL"
 msgstr ""
 
-#: mcs/mcs/driver.cs:704
+#: mcs/mcs/driver.cs:712
 msgid "--wlevel requires a value from 0 to 4"
 msgstr ""
 
-#: mcs/mcs/driver.cs:713
+#: mcs/mcs/driver.cs:721
 msgid "--mcs-debug requires an argument"
 msgstr ""
 
-#: mcs/mcs/driver.cs:720
+#: mcs/mcs/driver.cs:728
 msgid "Invalid argument to --mcs-debug"
 msgstr ""
 
-#: mcs/mcs/driver.cs:730
+#: mcs/mcs/driver.cs:738
 msgid "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN"
 msgstr ""
 
-#: mcs/mcs/driver.cs:732
+#: mcs/mcs/driver.cs:740
 msgid "--recurse requires an argument"
 msgstr ""
 
-#: mcs/mcs/driver.cs:743
+#: mcs/mcs/driver.cs:751
 msgid "Compatibility: Use -debug option instead of -g or --debug"
 msgstr ""
 
-#: mcs/mcs/driver.cs:748
+#: mcs/mcs/driver.cs:756
 msgid "Compatibility: Use -noconfig option instead of --noconfig"
 msgstr ""
 
-#: mcs/mcs/driver.cs:912
+#: mcs/mcs/driver.cs:920
 #, csharp-format
 msgid "Invalid conditional define symbol `{0}'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:963
+#: mcs/mcs/driver.cs:971
 #, csharp-format
 msgid ""
 "Invalid resource visibility option `{0}'. Use either `public' or `private' "
 "instead"
 msgstr ""
 
-#: mcs/mcs/driver.cs:969
+#: mcs/mcs/driver.cs:977
 #, csharp-format
 msgid "Wrong number of arguments for option `{0}'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1007
+#: mcs/mcs/driver.cs:1015
 msgid "Cannot specify multiple aliases using single /reference option"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1035 mcs/mcs/driver.cs:1047
+#: mcs/mcs/driver.cs:1043 mcs/mcs/driver.cs:1055
 msgid ""
 "Cannot specify the `win32res' and the `win32ico' compiler option at the same "
 "time"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1162
+#: mcs/mcs/driver.cs:1170
 #, csharp-format
 msgid "`{0}' is not a valid warning number"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1192
+#: mcs/mcs/driver.cs:1200
 msgid ""
 "Invalid platform type for -platform. Valid options are `anycpu', `x86', "
 "`x64' or `itanium'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1212
+#: mcs/mcs/driver.cs:1220
 msgid "Invalid sdk version name"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1310
+#: mcs/mcs/driver.cs:1318
 #, csharp-format
 msgid ""
 "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or "
 "`Default'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1330
+#: mcs/mcs/driver.cs:1338
 #, csharp-format
 msgid "Code page `{0}' is invalid or not installed"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1345
+#: mcs/mcs/driver.cs:1353
 #, csharp-format
 msgid "Unrecognized command-line option: `{0}'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1350
+#: mcs/mcs/driver.cs:1358
 #, csharp-format
 msgid "Missing file specification for `{0}' option"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1355
+#: mcs/mcs/driver.cs:1363
 #, csharp-format
 msgid "Missing argument for `{0}' option"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1390
+#: mcs/mcs/driver.cs:1398
 #, csharp-format
 msgid "Invalid reference alias `{0}='. Missing filename"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1395
+#: mcs/mcs/driver.cs:1403
 #, csharp-format
 msgid ""
 "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1411
+#: mcs/mcs/driver.cs:1419
 #, csharp-format
 msgid "The resource identifier `{0}' has already been used in this assembly"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1472
+#: mcs/mcs/driver.cs:1480
 msgid ""
 "If no source files are specified you must specify the output file with -out:"
 msgstr ""
@@ -1815,7 +1815,7 @@ msgstr ""
 msgid "The operation in question is undefined on void pointers"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:438 mcs/mcs/statement.cs:2558 mcs/mcs/statement.cs:2560
+#: mcs/mcs/ecore.cs:438 mcs/mcs/statement.cs:2559 mcs/mcs/statement.cs:2561
 #, csharp-format
 msgid "Internal compiler error: {0}"
 msgstr ""
@@ -1972,7 +1972,7 @@ msgid ""
 "The type `{0}' does not contain a constructor that takes `{1}' arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4334
+#: mcs/mcs/ecore.cs:4332
 #, csharp-format
 msgid ""
 "Type `{0}' does not contain a member `{1}' and the best extension method "
@@ -1980,154 +1980,154 @@ msgid ""
 "without the extension method syntax"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4355
+#: mcs/mcs/ecore.cs:4353
 #, csharp-format
 msgid ""
 "The call is ambiguous between the following methods or properties: `{0}' and "
 "`{1}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4415
+#: mcs/mcs/ecore.cs:4413
 #, csharp-format
 msgid ""
 "The best overloaded collection initalizer method `{0}' cannot have 'ref', or "
 "`out' modifier"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4419
+#: mcs/mcs/ecore.cs:4417
 #, csharp-format
 msgid ""
 "The best overloaded collection initalizer method `{0}' has some invalid "
 "arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4422
+#: mcs/mcs/ecore.cs:4420
 #, csharp-format
 msgid "Delegate `{0}' has some invalid arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4426
+#: mcs/mcs/ecore.cs:4424
 #, csharp-format
 msgid "The best overloaded method match for `{0}' has some invalid arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4436
+#: mcs/mcs/ecore.cs:4434
 #, csharp-format
 msgid ""
 "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' "
 "modifier"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4439
+#: mcs/mcs/ecore.cs:4437
 #, csharp-format
 msgid "Argument `#{0}' is missing `{1}' modifier"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4452
+#: mcs/mcs/ecore.cs:4450
 #, csharp-format
 msgid "Argument `#{0}' cannot convert `{1}' expression to type `{2}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4500
+#: mcs/mcs/ecore.cs:4498
 #, csharp-format
 msgid ""
 "The type arguments for method `{0}' cannot be inferred from the usage. Try "
 "specifying the type arguments explicitly"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4529
+#: mcs/mcs/ecore.cs:4527
 #, csharp-format
 msgid "No overload for method `{0}' takes `{1}' arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4582
+#: mcs/mcs/ecore.cs:4580
 #, fuzzy, csharp-format
 msgid "The delegate `{0}' does not contain a parameter named `{1}'"
 msgstr "El delegado `{0} no toma {1} argumentos"
 
-#: mcs/mcs/ecore.cs:4587
+#: mcs/mcs/ecore.cs:4585
 #, csharp-format
 msgid ""
 "The best overloaded method match for `{0}' does not contain a parameter "
 "named `{1}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4597
+#: mcs/mcs/ecore.cs:4595
 #, csharp-format
 msgid ""
 "Named argument `{0}' cannot be used for a parameter which has positional "
 "argument specified"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4910
+#: mcs/mcs/ecore.cs:4908
 msgid ""
 "You cannot use fixed size buffers contained in unfixed expressions. Try "
 "using the fixed statement"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4915
+#: mcs/mcs/ecore.cs:4913
 #, csharp-format
 msgid "`{0}': Fixed size buffers can only be accessed through locals or fields"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5310
+#: mcs/mcs/ecore.cs:5308
 #, csharp-format
 msgid "Property or event `{0}' is not supported by the C# language"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5471
+#: mcs/mcs/ecore.cs:5469
 #, csharp-format
 msgid "A range variable `{0}' may not be passes as `ref' or `out' parameter"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5519
+#: mcs/mcs/ecore.cs:5517
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because it "
 "lacks the `get' accessor"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5526
+#: mcs/mcs/ecore.cs:5524
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because the get "
 "accessor is inaccessible"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5545
+#: mcs/mcs/ecore.cs:5543
 #, csharp-format
 msgid "Property or indexer `{0}' cannot be assigned to (it is read-only)"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5553
+#: mcs/mcs/ecore.cs:5551
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because the set "
 "accessor is inaccessible"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5714
+#: mcs/mcs/ecore.cs:5712
 #, csharp-format
 msgid ""
 "The event `{0}' can only appear on the left hand side of `+=' or `-=' "
 "operator"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5718
+#: mcs/mcs/ecore.cs:5716
 #, csharp-format
 msgid ""
 "The event `{0}' can only appear on the left hand side of += or -= when used "
 "outside of the type `{1}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5882
+#: mcs/mcs/ecore.cs:5880
 #, csharp-format
 msgid ""
 "An implicitly typed local variable declaration cannot be initialized with `"
 "{0}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5896
+#: mcs/mcs/ecore.cs:5894
 msgid ""
 "The contextual keyword `var' may only appear within a local variable "
 "declaration"
@@ -2149,7 +2149,7 @@ msgstr ""
 msgid "Type byte, sbyte, short, ushort, int, uint, long or ulong expected"
 msgstr ""
 
-#: mcs/mcs/eval.cs:626
+#: mcs/mcs/eval.cs:643
 msgid "Detection Parsing Error"
 msgstr ""
 
@@ -2353,7 +2353,7 @@ msgid "Cannot create an array with a negative size"
 msgstr ""
 
 #: mcs/mcs/expression.cs:6096 mcs/mcs/expression.cs:6104
-#: mcs/mcs/statement.cs:1009 mcs/mcs/statement.cs:3055
+#: mcs/mcs/statement.cs:1002 mcs/mcs/statement.cs:3056
 msgid "A constant value is expected"
 msgstr ""
 
@@ -2719,7 +2719,7 @@ msgid "Cannot yield in the body of a finally clause"
 msgstr ""
 
 #: mcs/mcs/flowanalysis.cs:927 mcs/mcs/flowanalysis.cs:943
-#: mcs/mcs/flowanalysis.cs:979 mcs/mcs/statement.cs:694
+#: mcs/mcs/flowanalysis.cs:979 mcs/mcs/statement.cs:687
 msgid "Control cannot leave the body of a finally clause"
 msgstr ""
 
@@ -2882,7 +2882,7 @@ msgid ""
 "method `{2}'. There is no implicit reference conversion from `{0}' to `{3}'"
 msgstr ""
 
-#: mcs/mcs/import.cs:1711
+#: mcs/mcs/import.cs:1712
 #, csharp-format
 msgid ""
 "The type `{0}' is defined in an assembly that is not referenced. Consider "
@@ -2912,7 +2912,7 @@ msgstr ""
 msgid "Iterators cannot have unsafe parameters or yield types"
 msgstr ""
 
-#: mcs/mcs/iterators.cs:888 mcs/mcs/statement.cs:4324
+#: mcs/mcs/iterators.cs:888 mcs/mcs/statement.cs:4325
 msgid "Unsafe code may not appear in iterators"
 msgstr ""
 
@@ -2956,22 +2956,22 @@ msgstr ""
 msgid "A range variable `{0}' cannot be initialized with `{1}'"
 msgstr ""
 
-#: mcs/mcs/linq.cs:750
+#: mcs/mcs/linq.cs:747
 #, csharp-format
 msgid "A range variable `{0}' conflicts with a previous declaration of `{0}'"
 msgstr ""
 
-#: mcs/mcs/linq.cs:757
+#: mcs/mcs/linq.cs:754
 #, csharp-format
 msgid "A range variable `{0}' has already been declared in this scope"
 msgstr ""
 
-#: mcs/mcs/linq.cs:764
+#: mcs/mcs/linq.cs:761
 #, csharp-format
 msgid "A range variable `{0}' conflicts with a method type parameter"
 msgstr ""
 
-#: mcs/mcs/linq.cs:796
+#: mcs/mcs/linq.cs:793
 #, csharp-format
 msgid ""
 "A range variable `{0}' cannot be assigned to. Consider using `let' clause to "
@@ -3371,97 +3371,97 @@ msgstr ""
 msgid "The params parameter must be a single dimensional array"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:288
+#: mcs/mcs/parameter.cs:301
 msgid "An out parameter cannot have the `In' attribute"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:293
+#: mcs/mcs/parameter.cs:306
 msgid ""
 "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:300
+#: mcs/mcs/parameter.cs:313
 msgid ""
 "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and "
 "`Out' attributes or neither"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:310
+#: mcs/mcs/parameter.cs:324
 #, fuzzy, csharp-format
 msgid "Cannot specify `{0}' attribute on optional parameter `{1}'"
 msgstr ""
 "No puede especificar el atributo `DefaultMember' en un tipo que contiene un "
 "indexador"
 
-#: mcs/mcs/parameter.cs:320
+#: mcs/mcs/parameter.cs:369
+#, csharp-format
+msgid "Method or delegate parameter cannot be of type `{0}'"
+msgstr ""
+
+#: mcs/mcs/parameter.cs:379
+#, csharp-format
+msgid "`{0}': static types cannot be used as parameters"
+msgstr ""
+
+#: mcs/mcs/parameter.cs:385
+#, csharp-format
+msgid "The extension method cannot be of type `{0}'"
+msgstr ""
+
+#: mcs/mcs/parameter.cs:425
 #, csharp-format
 msgid ""
 "Argument of type `{0}' is not applicable for the DefaultParameterValue "
 "attribute"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:323
+#: mcs/mcs/parameter.cs:429
 #, csharp-format
 msgid ""
 "The DefaultParameterValue attribute is not applicable on parameters of type `"
 "{0}'"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:334
+#: mcs/mcs/parameter.cs:457
 msgid "The type of the default value should match the type of the parameter"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:376
-#, csharp-format
-msgid "Method or delegate parameter cannot be of type `{0}'"
-msgstr ""
-
-#: mcs/mcs/parameter.cs:386
-#, csharp-format
-msgid "`{0}': static types cannot be used as parameters"
+#: mcs/mcs/parameter.cs:602
+msgid "An expression tree parameter cannot use `ref' or `out' modifier"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:392
+#: mcs/mcs/parameter.cs:1074
 #, csharp-format
-msgid "The extension method cannot be of type `{0}'"
+msgid "The parameter name `{0}' conflicts with a compiler generated name"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:448
+#: mcs/mcs/parameter.cs:1220
 #, csharp-format
 msgid ""
 "The expression being assigned to optional parameter `{0}' must be a constant "
 "or default value"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:464
+#: mcs/mcs/parameter.cs:1237
 #, csharp-format
 msgid ""
 "The expression being assigned to nullable optional parameter `{0}' must be "
 "default value"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:472
+#: mcs/mcs/parameter.cs:1245
 #, csharp-format
 msgid ""
 "Optional parameter `{0}' of type `{1}' can only be initialized with `null'"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:482
+#: mcs/mcs/parameter.cs:1256
 #, csharp-format
 msgid ""
 "Optional parameter expression of type `{0}' cannot be converted to parameter "
 "type `{1}'"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:624
-msgid "An expression tree parameter cannot use `ref' or `out' modifier"
-msgstr ""
-
-#: mcs/mcs/parameter.cs:1096
-#, csharp-format
-msgid "The parameter name `{0}' conflicts with a compiler generated name"
-msgstr ""
-
 #: mcs/mcs/pending.cs:443
 #, csharp-format
 msgid ""
@@ -3571,7 +3571,7 @@ msgstr ""
 "No puede especificar el atributo `DefaultMember' en un tipo que contiene un "
 "indexador"
 
-#: mcs/mcs/reflection.cs:239
+#: mcs/mcs/reflection.cs:255
 msgid "Could not access the key inside the container `"
 msgstr ""
 
@@ -3595,60 +3595,60 @@ msgid ""
 "tree"
 msgstr ""
 
-#: mcs/mcs/statement.cs:740
+#: mcs/mcs/statement.cs:733
 #, csharp-format
 msgid ""
 "An object of a type convertible to `{0}' is required for the return statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:753
+#: mcs/mcs/statement.cs:746
 #, csharp-format
 msgid ""
 "`{0}': A return keyword must not be followed by any expression when method "
 "returns void"
 msgstr ""
 
-#: mcs/mcs/statement.cs:778
+#: mcs/mcs/statement.cs:771
 #, csharp-format
 msgid ""
 "Cannot convert `{0}' to delegate type `{1}' because some of the return types "
 "in the block are not implicitly convertible to the delegate return type"
 msgstr ""
 
-#: mcs/mcs/statement.cs:806
+#: mcs/mcs/statement.cs:799
 msgid ""
 "Cannot return a value from iterators. Use the yield return statement to "
 "return a value, or yield break to end the iteration"
 msgstr ""
 
-#: mcs/mcs/statement.cs:963 mcs/mcs/statement.cs:997
+#: mcs/mcs/statement.cs:956 mcs/mcs/statement.cs:990
 msgid "A goto case is only valid inside a switch statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1076 mcs/mcs/statement.cs:4726
+#: mcs/mcs/statement.cs:1069 mcs/mcs/statement.cs:4727
 msgid "The type caught or thrown must be derived from System.Exception"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1298
+#: mcs/mcs/statement.cs:1291
 msgid "A fixed statement cannot use an implicitly typed local variable"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1303
+#: mcs/mcs/statement.cs:1296
 msgid "An implicitly typed local variable cannot be a constant"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1308
+#: mcs/mcs/statement.cs:1301
 msgid ""
 "An implicitly typed local variable declarator must include an initializer"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1313
+#: mcs/mcs/statement.cs:1306
 msgid ""
 "An implicitly typed local variable declaration cannot include multiple "
 "declarators"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1883
+#: mcs/mcs/statement.cs:1876
 #, csharp-format
 msgid ""
 "A local variable named `{0}' cannot be declared in this scope because it "
@@ -3656,7 +3656,7 @@ msgid ""
 "scope to denote something else"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1894
+#: mcs/mcs/statement.cs:1887
 #, csharp-format
 msgid ""
 "`{0}': An anonymous type cannot have multiple properties with the same name"
@@ -3664,17 +3664,17 @@ msgstr ""
 "`{0}' An tipo anónimo no puede tener multiples propiedades con el mismo "
 "nombre"
 
-#: mcs/mcs/statement.cs:1897
+#: mcs/mcs/statement.cs:1890
 #, csharp-format
 msgid "The parameter name `{0}' is a duplicate"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1904
+#: mcs/mcs/statement.cs:1897
 #, csharp-format
 msgid "A local variable named `{0}' is already defined in this scope"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1910
+#: mcs/mcs/statement.cs:1903
 #, fuzzy, csharp-format
 msgid ""
 "The type parameter name `{0}' is the same as local variable or parameter name"
@@ -3682,89 +3682,89 @@ msgstr ""
 "El tipo parametrizado `{0}' tiene el mimo nombre que el tipo contenedor, o "
 "el método"
 
-#: mcs/mcs/statement.cs:2482
+#: mcs/mcs/statement.cs:2477
 #, csharp-format
 msgid ""
 "The out parameter `{0}' must be assigned to before control leaves the "
 "current method"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2573
+#: mcs/mcs/statement.cs:2574
 #, csharp-format
 msgid "`{0}': not all code paths return a value"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2577
+#: mcs/mcs/statement.cs:2578
 #, csharp-format
 msgid "Not all code paths return a value in anonymous method of type `{0}'"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2748
+#: mcs/mcs/statement.cs:2749
 #, csharp-format
 msgid "The label `{0}' is a duplicate"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2757 mcs/mcs/statement.cs:2768
+#: mcs/mcs/statement.cs:2758 mcs/mcs/statement.cs:2769
 #, csharp-format
 msgid ""
 "The label `{0}' shadows another label by the same name in a contained scope"
 msgstr ""
 
-#: mcs/mcs/statement.cs:3088
+#: mcs/mcs/statement.cs:3089
 #, csharp-format
 msgid "The label `case {0}:' already occurs in this switch statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:3629
+#: mcs/mcs/statement.cs:3630
 #, csharp-format
 msgid ""
 "A switch expression of type `{0}' cannot be converted to an integral type, "
 "bool, char, string, enum or nullable type"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4114
+#: mcs/mcs/statement.cs:4115
 #, csharp-format
 msgid "`{0}' is not a reference type as required by the lock statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4455
+#: mcs/mcs/statement.cs:4456
 msgid "The type of locals declared in a fixed statement must be a pointer type"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4471
+#: mcs/mcs/statement.cs:4472
 msgid ""
 "The right hand side of a fixed statement assignment may not be a cast "
 "expression"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4542
+#: mcs/mcs/statement.cs:4543
 msgid ""
 "You cannot use the fixed statement to take the address of an already fixed "
 "expression"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4856
+#: mcs/mcs/statement.cs:4857
 #, csharp-format
 msgid ""
 "A previous catch clause already catches all exceptions of this or a super "
 "type `{0}'"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5029
+#: mcs/mcs/statement.cs:5030
 #, csharp-format
 msgid ""
 "`{0}': type used in a using statement must be implicitly convertible to "
 "`System.IDisposable'"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5451
+#: mcs/mcs/statement.cs:5452
 #, csharp-format
 msgid ""
 "foreach statement requires that the return type `{0}' of `{1}' must have a "
 "suitable public MoveNext method and public Current property"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5491
+#: mcs/mcs/statement.cs:5492
 #, csharp-format
 msgid ""
 "foreach statement cannot operate on variables of type `{0}' because it "
@@ -3772,18 +3772,18 @@ msgid ""
 "implementation"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5516
+#: mcs/mcs/statement.cs:5517
 #, csharp-format
 msgid ""
 "foreach statement cannot operate on variables of type `{0}' because it does "
 "not contain a definition for `{1}' or is inaccessible"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5722
+#: mcs/mcs/statement.cs:5723
 msgid "Use of null is not valid in this context"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5732
+#: mcs/mcs/statement.cs:5733
 #, csharp-format
 msgid "Foreach statement cannot operate on a `{0}'"
 msgstr "El mandato `foreach' no puede operar en un `{0}'"
diff --git a/po/mcs/ja.gmo b/po/mcs/ja.gmo
index 07261da..a02f7ad 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 62af1d5..e07ca15 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: 2011-01-18 10:45-0700\n"
+"POT-Creation-Date: 2011-02-14 10:10-0700\n"
 "PO-Revision-Date: \n"
 "Last-Translator: Atsushi Eno <atsushi at ximian.com>\n"
 "Language-Team: \n"
@@ -29,7 +29,7 @@ msgid ""
 "mismatch"
 msgstr "パラメータ不一致のため、`{0}' をデリゲート型 `{1}'に変換できません"
 
-#: mcs/mcs/anonymous.cs:909 mcs/mcs/ecore.cs:4524
+#: mcs/mcs/anonymous.cs:909 mcs/mcs/ecore.cs:4522
 #, csharp-format
 msgid "Delegate `{0}' does not take `{1}' arguments"
 msgstr "デリゲート `{0}' は `{1}' 個の引数をもちません"
@@ -123,7 +123,7 @@ msgstr "式ツリーは代入オペレータを含むことができません"
 msgid "Cannot assign to `{0}' because it is a `{1}'"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:196
+#: mcs/mcs/attribute.cs:201
 #, csharp-format
 msgid ""
 "`{0}' is not a valid named attribute argument. Named attribute arguments "
@@ -134,7 +134,7 @@ msgstr ""
 "み専用ではなくstaticでも定数でもないフィールドか、またはpublicでstaticではな"
 "い読み書き可能なプロパティでなければなりません"
 
-#: mcs/mcs/attribute.cs:205
+#: mcs/mcs/attribute.cs:210
 #, csharp-format
 msgid ""
 "`{0}' is not a valid named attribute argument because it is not a valid "
@@ -143,38 +143,38 @@ msgstr ""
 "`{0}' は、有効な属性パラメータ型ではないため、有効な名前付き属性の引数ではあ"
 "りません"
 
-#: mcs/mcs/attribute.cs:211
+#: mcs/mcs/attribute.cs:216
 #, fuzzy
 msgid "An attribute argument cannot be dynamic expression"
 msgstr "匿名メソッドを式ツリーに変換することはできません"
 
-#: mcs/mcs/attribute.cs:216
+#: mcs/mcs/attribute.cs:221
 msgid "The Guid attribute must be specified with the ComImport attribute"
 msgstr "Guid属性はComImport属性とともに指定されなければなりません"
 
-#: mcs/mcs/attribute.cs:221
+#: mcs/mcs/attribute.cs:226
 #, csharp-format
 msgid "Do not use `{0}' directly. Use parameter modifier `this' instead"
 msgstr ""
 "`{0}' を直接使用せず、代わりにパラメータ修飾子 `this' を使用してください"
 
-#: mcs/mcs/attribute.cs:226
+#: mcs/mcs/attribute.cs:231
 #, fuzzy, csharp-format
 msgid "Do not use `{0}' directly. Use `dynamic' keyword instead"
 msgstr ""
 "`{0}' を直接使用せず、代わりにパラメータ修飾子 `this' を使用してください"
 
-#: mcs/mcs/attribute.cs:235
+#: mcs/mcs/attribute.cs:240
 #, csharp-format
 msgid "Error during emitting `{0}' attribute. The reason is `{1}'"
 msgstr "`{0}' の属性の出力中にエラーが発生しました。理由: '{1}'"
 
-#: mcs/mcs/attribute.cs:266
+#: mcs/mcs/attribute.cs:271
 #, csharp-format
 msgid "`{0}': is not an attribute class"
 msgstr "`{0}' は属性クラスではありません"
 
-#: mcs/mcs/attribute.cs:302
+#: mcs/mcs/attribute.cs:307
 #, fuzzy, csharp-format
 msgid ""
 "`{0}' is ambiguous between `{1}' and `{2}'. Use either `@{0}' or `{0}"
@@ -183,17 +183,17 @@ msgstr ""
 "`{0} は `{0}' と `{0}Attribute' の間で曖昧です。`@{0}' または `{0}Attribute' "
 "を使用してください"
 
-#: mcs/mcs/attribute.cs:385
+#: mcs/mcs/attribute.cs:390
 #, csharp-format
 msgid "Cannot apply attribute class `{0}' because it is abstract"
 msgstr "属性クラス `{0}' はabstractなので適用できません"
 
-#: mcs/mcs/attribute.cs:453
+#: mcs/mcs/attribute.cs:458
 #, fuzzy, csharp-format
 msgid "Duplicate named attribute `{0}' argument"
 msgstr "属性の引数名 '{0}' が重複しています"
 
-#: mcs/mcs/attribute.cs:730
+#: mcs/mcs/attribute.cs:735
 #, csharp-format
 msgid ""
 "`{0}' is not a valid attribute location for this declaration. Valid "
@@ -202,29 +202,29 @@ msgstr ""
 "`{0}' の属性の位置はその宣言からは有効ではありません。宣言されている有効な属"
 "性の位置は `{1}' です"
 
-#: mcs/mcs/attribute.cs:1004
+#: mcs/mcs/attribute.cs:1006
 #, csharp-format
 msgid ""
 "The attribute `{0}' is not valid on this declaration type. It is valid on `"
 "{1}' declarations only"
 msgstr "属性 `{0}' はこの宣言型では無効です。 `{1}' の宣言でのみ有効です"
 
-#: mcs/mcs/attribute.cs:1022
+#: mcs/mcs/attribute.cs:1028
 #, csharp-format
 msgid "The argument to the `{0}' attribute must be a valid identifier"
 msgstr "`{0}' 属性への引数は有効な識別子である必要があります"
 
-#: mcs/mcs/attribute.cs:1035
+#: mcs/mcs/attribute.cs:1041
 #, fuzzy, csharp-format
 msgid "Invalid value for argument to `{0}' attribute"
 msgstr "`System.AttributeUsage' 属性への無効な引数値です"
 
-#: mcs/mcs/attribute.cs:1341
+#: mcs/mcs/attribute.cs:1348
 #, csharp-format
 msgid "The attribute `{0}' cannot be applied multiple times"
 msgstr "属性 `{0}' は複数回指定することができません"
 
-#: mcs/mcs/attribute.cs:1603
+#: mcs/mcs/attribute.cs:1676
 #, csharp-format
 msgid "`{0}' is obsolete: `{1}'"
 msgstr "`{0}'は廃止されています: `{1}'"
@@ -1487,7 +1487,7 @@ msgstr ""
 msgid "Error generating XML documentation file `{0}' (`{1}')"
 msgstr ""
 
-#: mcs/mcs/driver.cs:96 mcs/mcs/driver.cs:467 mcs/mcs/driver.cs:470
+#: mcs/mcs/driver.cs:96 mcs/mcs/driver.cs:475 mcs/mcs/driver.cs:478
 msgid "Source file `"
 msgstr ""
 
@@ -1515,188 +1515,188 @@ msgstr "レスポンスファイル `"
 msgid "Unable to open response file: "
 msgstr "レスポンスファイルが開けません"
 
-#: mcs/mcs/driver.cs:422 mcs/mcs/driver.cs:432
+#: mcs/mcs/driver.cs:430 mcs/mcs/driver.cs:440
 msgid "No files to compile were specified"
 msgstr "コンパイルするファイルが指定されていません"
 
-#: mcs/mcs/driver.cs:504
+#: mcs/mcs/driver.cs:512
 msgid "Warning level must be in the range 0-4"
 msgstr ""
 
-#: mcs/mcs/driver.cs:538
+#: mcs/mcs/driver.cs:546
 msgid "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS"
 msgstr ""
 
-#: mcs/mcs/driver.cs:547
+#: mcs/mcs/driver.cs:555
 msgid "Compatibility: Use -unsafe instead of --unsafe"
 msgstr ""
 
-#: mcs/mcs/driver.cs:558
+#: mcs/mcs/driver.cs:566
 msgid "Compatibility: Use -d:SYMBOL instead of --define SYMBOL"
 msgstr ""
 
-#: mcs/mcs/driver.cs:572
+#: mcs/mcs/driver.cs:580
 msgid "Compatibility: Use -out:FILE instead of --output FILE or -o FILE"
 msgstr ""
 
-#: mcs/mcs/driver.cs:581
+#: mcs/mcs/driver.cs:589
 msgid "Compatibility: Use -checked instead of --checked"
 msgstr ""
 
-#: mcs/mcs/driver.cs:591
+#: mcs/mcs/driver.cs:599
 msgid "Compatibility: Use -linkres:VALUE instead of --linkres VALUE"
 msgstr ""
 
-#: mcs/mcs/driver.cs:594
+#: mcs/mcs/driver.cs:602
 msgid "Missing argument to --linkres"
 msgstr ""
 
-#: mcs/mcs/driver.cs:603
+#: mcs/mcs/driver.cs:611
 msgid "Compatibility: Use -res:VALUE instead of --res VALUE"
 msgstr ""
 
-#: mcs/mcs/driver.cs:606
+#: mcs/mcs/driver.cs:614
 msgid "Missing argument to --resource"
 msgstr ""
 
-#: mcs/mcs/driver.cs:614
+#: mcs/mcs/driver.cs:622
 msgid "Compatibility: Use -target:KIND instead of --target KIND"
 msgstr ""
 
-#: mcs/mcs/driver.cs:646
+#: mcs/mcs/driver.cs:654
 msgid "Compatibility: Use -r:LIBRARY instead of -r library"
 msgstr ""
 
-#: mcs/mcs/driver.cs:665
+#: mcs/mcs/driver.cs:673
 msgid "Compatibility: Use -lib:ARG instead of --L arg"
 msgstr ""
 
-#: mcs/mcs/driver.cs:678
+#: mcs/mcs/driver.cs:686
 msgid "Compatibility: Use -nostdlib instead of --nostdlib"
 msgstr ""
 
-#: mcs/mcs/driver.cs:683
+#: mcs/mcs/driver.cs:691
 msgid "Compatibility: Use -nowarn instead of --nowarn"
 msgstr ""
 
-#: mcs/mcs/driver.cs:700
+#: mcs/mcs/driver.cs:708
 msgid "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL"
 msgstr ""
 
-#: mcs/mcs/driver.cs:704
+#: mcs/mcs/driver.cs:712
 msgid "--wlevel requires a value from 0 to 4"
 msgstr ""
 
-#: mcs/mcs/driver.cs:713
+#: mcs/mcs/driver.cs:721
 msgid "--mcs-debug requires an argument"
 msgstr ""
 
-#: mcs/mcs/driver.cs:720
+#: mcs/mcs/driver.cs:728
 msgid "Invalid argument to --mcs-debug"
 msgstr ""
 
-#: mcs/mcs/driver.cs:730
+#: mcs/mcs/driver.cs:738
 msgid "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN"
 msgstr ""
 
-#: mcs/mcs/driver.cs:732
+#: mcs/mcs/driver.cs:740
 msgid "--recurse requires an argument"
 msgstr ""
 
-#: mcs/mcs/driver.cs:743
+#: mcs/mcs/driver.cs:751
 msgid "Compatibility: Use -debug option instead of -g or --debug"
 msgstr ""
 
-#: mcs/mcs/driver.cs:748
+#: mcs/mcs/driver.cs:756
 msgid "Compatibility: Use -noconfig option instead of --noconfig"
 msgstr ""
 
-#: mcs/mcs/driver.cs:912
+#: mcs/mcs/driver.cs:920
 #, csharp-format
 msgid "Invalid conditional define symbol `{0}'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:963
+#: mcs/mcs/driver.cs:971
 #, csharp-format
 msgid ""
 "Invalid resource visibility option `{0}'. Use either `public' or `private' "
 "instead"
 msgstr ""
 
-#: mcs/mcs/driver.cs:969
+#: mcs/mcs/driver.cs:977
 #, csharp-format
 msgid "Wrong number of arguments for option `{0}'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1007
+#: mcs/mcs/driver.cs:1015
 msgid "Cannot specify multiple aliases using single /reference option"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1035 mcs/mcs/driver.cs:1047
+#: mcs/mcs/driver.cs:1043 mcs/mcs/driver.cs:1055
 msgid ""
 "Cannot specify the `win32res' and the `win32ico' compiler option at the same "
 "time"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1162
+#: mcs/mcs/driver.cs:1170
 #, csharp-format
 msgid "`{0}' is not a valid warning number"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1192
+#: mcs/mcs/driver.cs:1200
 msgid ""
 "Invalid platform type for -platform. Valid options are `anycpu', `x86', "
 "`x64' or `itanium'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1212
+#: mcs/mcs/driver.cs:1220
 msgid "Invalid sdk version name"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1310
+#: mcs/mcs/driver.cs:1318
 #, csharp-format
 msgid ""
 "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or "
 "`Default'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1330
+#: mcs/mcs/driver.cs:1338
 #, csharp-format
 msgid "Code page `{0}' is invalid or not installed"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1345
+#: mcs/mcs/driver.cs:1353
 #, csharp-format
 msgid "Unrecognized command-line option: `{0}'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1350
+#: mcs/mcs/driver.cs:1358
 #, csharp-format
 msgid "Missing file specification for `{0}' option"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1355
+#: mcs/mcs/driver.cs:1363
 #, csharp-format
 msgid "Missing argument for `{0}' option"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1390
+#: mcs/mcs/driver.cs:1398
 #, csharp-format
 msgid "Invalid reference alias `{0}='. Missing filename"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1395
+#: mcs/mcs/driver.cs:1403
 #, csharp-format
 msgid ""
 "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1411
+#: mcs/mcs/driver.cs:1419
 #, csharp-format
 msgid "The resource identifier `{0}' has already been used in this assembly"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1472
+#: mcs/mcs/driver.cs:1480
 msgid ""
 "If no source files are specified you must specify the output file with -out:"
 msgstr ""
@@ -1770,7 +1770,7 @@ msgstr ""
 msgid "The operation in question is undefined on void pointers"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:438 mcs/mcs/statement.cs:2558 mcs/mcs/statement.cs:2560
+#: mcs/mcs/ecore.cs:438 mcs/mcs/statement.cs:2559 mcs/mcs/statement.cs:2561
 #, csharp-format
 msgid "Internal compiler error: {0}"
 msgstr ""
@@ -1927,7 +1927,7 @@ msgid ""
 "The type `{0}' does not contain a constructor that takes `{1}' arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4334
+#: mcs/mcs/ecore.cs:4332
 #, csharp-format
 msgid ""
 "Type `{0}' does not contain a member `{1}' and the best extension method "
@@ -1935,154 +1935,154 @@ msgid ""
 "without the extension method syntax"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4355
+#: mcs/mcs/ecore.cs:4353
 #, csharp-format
 msgid ""
 "The call is ambiguous between the following methods or properties: `{0}' and "
 "`{1}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4415
+#: mcs/mcs/ecore.cs:4413
 #, csharp-format
 msgid ""
 "The best overloaded collection initalizer method `{0}' cannot have 'ref', or "
 "`out' modifier"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4419
+#: mcs/mcs/ecore.cs:4417
 #, csharp-format
 msgid ""
 "The best overloaded collection initalizer method `{0}' has some invalid "
 "arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4422
+#: mcs/mcs/ecore.cs:4420
 #, csharp-format
 msgid "Delegate `{0}' has some invalid arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4426
+#: mcs/mcs/ecore.cs:4424
 #, csharp-format
 msgid "The best overloaded method match for `{0}' has some invalid arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4436
+#: mcs/mcs/ecore.cs:4434
 #, csharp-format
 msgid ""
 "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' "
 "modifier"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4439
+#: mcs/mcs/ecore.cs:4437
 #, csharp-format
 msgid "Argument `#{0}' is missing `{1}' modifier"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4452
+#: mcs/mcs/ecore.cs:4450
 #, csharp-format
 msgid "Argument `#{0}' cannot convert `{1}' expression to type `{2}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4500
+#: mcs/mcs/ecore.cs:4498
 #, csharp-format
 msgid ""
 "The type arguments for method `{0}' cannot be inferred from the usage. Try "
 "specifying the type arguments explicitly"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4529
+#: mcs/mcs/ecore.cs:4527
 #, csharp-format
 msgid "No overload for method `{0}' takes `{1}' arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4582
+#: mcs/mcs/ecore.cs:4580
 #, fuzzy, csharp-format
 msgid "The delegate `{0}' does not contain a parameter named `{1}'"
 msgstr "デリゲート `{0}' は `{1}' 個の引数をもちません"
 
-#: mcs/mcs/ecore.cs:4587
+#: mcs/mcs/ecore.cs:4585
 #, csharp-format
 msgid ""
 "The best overloaded method match for `{0}' does not contain a parameter "
 "named `{1}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4597
+#: mcs/mcs/ecore.cs:4595
 #, csharp-format
 msgid ""
 "Named argument `{0}' cannot be used for a parameter which has positional "
 "argument specified"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4910
+#: mcs/mcs/ecore.cs:4908
 msgid ""
 "You cannot use fixed size buffers contained in unfixed expressions. Try "
 "using the fixed statement"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4915
+#: mcs/mcs/ecore.cs:4913
 #, csharp-format
 msgid "`{0}': Fixed size buffers can only be accessed through locals or fields"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5310
+#: mcs/mcs/ecore.cs:5308
 #, csharp-format
 msgid "Property or event `{0}' is not supported by the C# language"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5471
+#: mcs/mcs/ecore.cs:5469
 #, csharp-format
 msgid "A range variable `{0}' may not be passes as `ref' or `out' parameter"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5519
+#: mcs/mcs/ecore.cs:5517
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because it "
 "lacks the `get' accessor"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5526
+#: mcs/mcs/ecore.cs:5524
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because the get "
 "accessor is inaccessible"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5545
+#: mcs/mcs/ecore.cs:5543
 #, csharp-format
 msgid "Property or indexer `{0}' cannot be assigned to (it is read-only)"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5553
+#: mcs/mcs/ecore.cs:5551
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because the set "
 "accessor is inaccessible"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5714
+#: mcs/mcs/ecore.cs:5712
 #, csharp-format
 msgid ""
 "The event `{0}' can only appear on the left hand side of `+=' or `-=' "
 "operator"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5718
+#: mcs/mcs/ecore.cs:5716
 #, csharp-format
 msgid ""
 "The event `{0}' can only appear on the left hand side of += or -= when used "
 "outside of the type `{1}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5882
+#: mcs/mcs/ecore.cs:5880
 #, csharp-format
 msgid ""
 "An implicitly typed local variable declaration cannot be initialized with `"
 "{0}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5896
+#: mcs/mcs/ecore.cs:5894
 msgid ""
 "The contextual keyword `var' may only appear within a local variable "
 "declaration"
@@ -2104,7 +2104,7 @@ msgstr ""
 msgid "Type byte, sbyte, short, ushort, int, uint, long or ulong expected"
 msgstr ""
 
-#: mcs/mcs/eval.cs:626
+#: mcs/mcs/eval.cs:643
 msgid "Detection Parsing Error"
 msgstr ""
 
@@ -2308,7 +2308,7 @@ msgid "Cannot create an array with a negative size"
 msgstr ""
 
 #: mcs/mcs/expression.cs:6096 mcs/mcs/expression.cs:6104
-#: mcs/mcs/statement.cs:1009 mcs/mcs/statement.cs:3055
+#: mcs/mcs/statement.cs:1002 mcs/mcs/statement.cs:3056
 msgid "A constant value is expected"
 msgstr ""
 
@@ -2669,7 +2669,7 @@ msgid "Cannot yield in the body of a finally clause"
 msgstr ""
 
 #: mcs/mcs/flowanalysis.cs:927 mcs/mcs/flowanalysis.cs:943
-#: mcs/mcs/flowanalysis.cs:979 mcs/mcs/statement.cs:694
+#: mcs/mcs/flowanalysis.cs:979 mcs/mcs/statement.cs:687
 msgid "Control cannot leave the body of a finally clause"
 msgstr ""
 
@@ -2832,7 +2832,7 @@ msgid ""
 "method `{2}'. There is no implicit reference conversion from `{0}' to `{3}'"
 msgstr ""
 
-#: mcs/mcs/import.cs:1711
+#: mcs/mcs/import.cs:1712
 #, csharp-format
 msgid ""
 "The type `{0}' is defined in an assembly that is not referenced. Consider "
@@ -2862,7 +2862,7 @@ msgstr ""
 msgid "Iterators cannot have unsafe parameters or yield types"
 msgstr ""
 
-#: mcs/mcs/iterators.cs:888 mcs/mcs/statement.cs:4324
+#: mcs/mcs/iterators.cs:888 mcs/mcs/statement.cs:4325
 msgid "Unsafe code may not appear in iterators"
 msgstr ""
 
@@ -2906,22 +2906,22 @@ msgstr ""
 msgid "A range variable `{0}' cannot be initialized with `{1}'"
 msgstr ""
 
-#: mcs/mcs/linq.cs:750
+#: mcs/mcs/linq.cs:747
 #, csharp-format
 msgid "A range variable `{0}' conflicts with a previous declaration of `{0}'"
 msgstr ""
 
-#: mcs/mcs/linq.cs:757
+#: mcs/mcs/linq.cs:754
 #, csharp-format
 msgid "A range variable `{0}' has already been declared in this scope"
 msgstr ""
 
-#: mcs/mcs/linq.cs:764
+#: mcs/mcs/linq.cs:761
 #, csharp-format
 msgid "A range variable `{0}' conflicts with a method type parameter"
 msgstr ""
 
-#: mcs/mcs/linq.cs:796
+#: mcs/mcs/linq.cs:793
 #, csharp-format
 msgid ""
 "A range variable `{0}' cannot be assigned to. Consider using `let' clause to "
@@ -3329,95 +3329,95 @@ msgstr ""
 msgid "The params parameter must be a single dimensional array"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:288
+#: mcs/mcs/parameter.cs:301
 msgid "An out parameter cannot have the `In' attribute"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:293
+#: mcs/mcs/parameter.cs:306
 msgid ""
 "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:300
+#: mcs/mcs/parameter.cs:313
 msgid ""
 "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and "
 "`Out' attributes or neither"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:310
+#: mcs/mcs/parameter.cs:324
 #, fuzzy, csharp-format
 msgid "Cannot specify `{0}' attribute on optional parameter `{1}'"
 msgstr "インデクサを含む型には`DefaultMember'属性を指定できません"
 
-#: mcs/mcs/parameter.cs:320
+#: mcs/mcs/parameter.cs:369
+#, csharp-format
+msgid "Method or delegate parameter cannot be of type `{0}'"
+msgstr ""
+
+#: mcs/mcs/parameter.cs:379
+#, csharp-format
+msgid "`{0}': static types cannot be used as parameters"
+msgstr ""
+
+#: mcs/mcs/parameter.cs:385
+#, fuzzy, csharp-format
+msgid "The extension method cannot be of type `{0}'"
+msgstr "`{0}': 拡張メソッドはネストしたクラスの中では定義できません"
+
+#: mcs/mcs/parameter.cs:425
 #, csharp-format
 msgid ""
 "Argument of type `{0}' is not applicable for the DefaultParameterValue "
 "attribute"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:323
+#: mcs/mcs/parameter.cs:429
 #, csharp-format
 msgid ""
 "The DefaultParameterValue attribute is not applicable on parameters of type `"
 "{0}'"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:334
+#: mcs/mcs/parameter.cs:457
 msgid "The type of the default value should match the type of the parameter"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:376
-#, csharp-format
-msgid "Method or delegate parameter cannot be of type `{0}'"
+#: mcs/mcs/parameter.cs:602
+msgid "An expression tree parameter cannot use `ref' or `out' modifier"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:386
+#: mcs/mcs/parameter.cs:1074
 #, csharp-format
-msgid "`{0}': static types cannot be used as parameters"
+msgid "The parameter name `{0}' conflicts with a compiler generated name"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:392
-#, fuzzy, csharp-format
-msgid "The extension method cannot be of type `{0}'"
-msgstr "`{0}': 拡張メソッドはネストしたクラスの中では定義できません"
-
-#: mcs/mcs/parameter.cs:448
+#: mcs/mcs/parameter.cs:1220
 #, csharp-format
 msgid ""
 "The expression being assigned to optional parameter `{0}' must be a constant "
 "or default value"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:464
+#: mcs/mcs/parameter.cs:1237
 #, csharp-format
 msgid ""
 "The expression being assigned to nullable optional parameter `{0}' must be "
 "default value"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:472
+#: mcs/mcs/parameter.cs:1245
 #, csharp-format
 msgid ""
 "Optional parameter `{0}' of type `{1}' can only be initialized with `null'"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:482
+#: mcs/mcs/parameter.cs:1256
 #, csharp-format
 msgid ""
 "Optional parameter expression of type `{0}' cannot be converted to parameter "
 "type `{1}'"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:624
-msgid "An expression tree parameter cannot use `ref' or `out' modifier"
-msgstr ""
-
-#: mcs/mcs/parameter.cs:1096
-#, csharp-format
-msgid "The parameter name `{0}' conflicts with a compiler generated name"
-msgstr ""
-
 #: mcs/mcs/pending.cs:443
 #, csharp-format
 msgid ""
@@ -3525,7 +3525,7 @@ msgstr ""
 msgid "Cannot set the `IndexerName' attribute on an indexer marked override"
 msgstr "インデクサを含む型には`DefaultMember'属性を指定できません"
 
-#: mcs/mcs/reflection.cs:239
+#: mcs/mcs/reflection.cs:255
 msgid "Could not access the key inside the container `"
 msgstr ""
 
@@ -3546,60 +3546,60 @@ msgid ""
 "tree"
 msgstr ""
 
-#: mcs/mcs/statement.cs:740
+#: mcs/mcs/statement.cs:733
 #, csharp-format
 msgid ""
 "An object of a type convertible to `{0}' is required for the return statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:753
+#: mcs/mcs/statement.cs:746
 #, csharp-format
 msgid ""
 "`{0}': A return keyword must not be followed by any expression when method "
 "returns void"
 msgstr ""
 
-#: mcs/mcs/statement.cs:778
+#: mcs/mcs/statement.cs:771
 #, csharp-format
 msgid ""
 "Cannot convert `{0}' to delegate type `{1}' because some of the return types "
 "in the block are not implicitly convertible to the delegate return type"
 msgstr ""
 
-#: mcs/mcs/statement.cs:806
+#: mcs/mcs/statement.cs:799
 msgid ""
 "Cannot return a value from iterators. Use the yield return statement to "
 "return a value, or yield break to end the iteration"
 msgstr ""
 
-#: mcs/mcs/statement.cs:963 mcs/mcs/statement.cs:997
+#: mcs/mcs/statement.cs:956 mcs/mcs/statement.cs:990
 msgid "A goto case is only valid inside a switch statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1076 mcs/mcs/statement.cs:4726
+#: mcs/mcs/statement.cs:1069 mcs/mcs/statement.cs:4727
 msgid "The type caught or thrown must be derived from System.Exception"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1298
+#: mcs/mcs/statement.cs:1291
 msgid "A fixed statement cannot use an implicitly typed local variable"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1303
+#: mcs/mcs/statement.cs:1296
 msgid "An implicitly typed local variable cannot be a constant"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1308
+#: mcs/mcs/statement.cs:1301
 msgid ""
 "An implicitly typed local variable declarator must include an initializer"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1313
+#: mcs/mcs/statement.cs:1306
 msgid ""
 "An implicitly typed local variable declaration cannot include multiple "
 "declarators"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1883
+#: mcs/mcs/statement.cs:1876
 #, csharp-format
 msgid ""
 "A local variable named `{0}' cannot be declared in this scope because it "
@@ -3607,112 +3607,112 @@ msgid ""
 "scope to denote something else"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1894
+#: mcs/mcs/statement.cs:1887
 #, csharp-format
 msgid ""
 "`{0}': An anonymous type cannot have multiple properties with the same name"
 msgstr "`{0}': 匿名型は同一の名前で複数のプロパティをもつことができません"
 
-#: mcs/mcs/statement.cs:1897
+#: mcs/mcs/statement.cs:1890
 #, csharp-format
 msgid "The parameter name `{0}' is a duplicate"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1904
+#: mcs/mcs/statement.cs:1897
 #, csharp-format
 msgid "A local variable named `{0}' is already defined in this scope"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1910
+#: mcs/mcs/statement.cs:1903
 #, fuzzy, csharp-format
 msgid ""
 "The type parameter name `{0}' is the same as local variable or parameter name"
 msgstr ""
 "型パラメータ `{0}' が、その宣言型あるいはメソッドと同じ名前になっています"
 
-#: mcs/mcs/statement.cs:2482
+#: mcs/mcs/statement.cs:2477
 #, csharp-format
 msgid ""
 "The out parameter `{0}' must be assigned to before control leaves the "
 "current method"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2573
+#: mcs/mcs/statement.cs:2574
 #, csharp-format
 msgid "`{0}': not all code paths return a value"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2577
+#: mcs/mcs/statement.cs:2578
 #, csharp-format
 msgid "Not all code paths return a value in anonymous method of type `{0}'"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2748
+#: mcs/mcs/statement.cs:2749
 #, csharp-format
 msgid "The label `{0}' is a duplicate"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2757 mcs/mcs/statement.cs:2768
+#: mcs/mcs/statement.cs:2758 mcs/mcs/statement.cs:2769
 #, csharp-format
 msgid ""
 "The label `{0}' shadows another label by the same name in a contained scope"
 msgstr ""
 
-#: mcs/mcs/statement.cs:3088
+#: mcs/mcs/statement.cs:3089
 #, csharp-format
 msgid "The label `case {0}:' already occurs in this switch statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:3629
+#: mcs/mcs/statement.cs:3630
 #, csharp-format
 msgid ""
 "A switch expression of type `{0}' cannot be converted to an integral type, "
 "bool, char, string, enum or nullable type"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4114
+#: mcs/mcs/statement.cs:4115
 #, csharp-format
 msgid "`{0}' is not a reference type as required by the lock statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4455
+#: mcs/mcs/statement.cs:4456
 msgid "The type of locals declared in a fixed statement must be a pointer type"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4471
+#: mcs/mcs/statement.cs:4472
 msgid ""
 "The right hand side of a fixed statement assignment may not be a cast "
 "expression"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4542
+#: mcs/mcs/statement.cs:4543
 msgid ""
 "You cannot use the fixed statement to take the address of an already fixed "
 "expression"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4856
+#: mcs/mcs/statement.cs:4857
 #, csharp-format
 msgid ""
 "A previous catch clause already catches all exceptions of this or a super "
 "type `{0}'"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5029
+#: mcs/mcs/statement.cs:5030
 #, csharp-format
 msgid ""
 "`{0}': type used in a using statement must be implicitly convertible to "
 "`System.IDisposable'"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5451
+#: mcs/mcs/statement.cs:5452
 #, csharp-format
 msgid ""
 "foreach statement requires that the return type `{0}' of `{1}' must have a "
 "suitable public MoveNext method and public Current property"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5491
+#: mcs/mcs/statement.cs:5492
 #, csharp-format
 msgid ""
 "foreach statement cannot operate on variables of type `{0}' because it "
@@ -3720,18 +3720,18 @@ msgid ""
 "implementation"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5516
+#: mcs/mcs/statement.cs:5517
 #, csharp-format
 msgid ""
 "foreach statement cannot operate on variables of type `{0}' because it does "
 "not contain a definition for `{1}' or is inaccessible"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5722
+#: mcs/mcs/statement.cs:5723
 msgid "Use of null is not valid in this context"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5732
+#: mcs/mcs/statement.cs:5733
 #, csharp-format
 msgid "Foreach statement cannot operate on a `{0}'"
 msgstr ""
diff --git a/po/mcs/mcs.pot b/po/mcs/mcs.pot
index a65f70d..8708165 100644
--- a/po/mcs/mcs.pot
+++ b/po/mcs/mcs.pot
@@ -8,7 +8,7 @@ msgid ""
 msgstr ""
 "Project-Id-Version: mono 2.10\n"
 "Report-Msgid-Bugs-To: http://www.mono-project.com/Bugs\n"
-"POT-Creation-Date: 2011-01-18 10:45-0700\n"
+"POT-Creation-Date: 2011-02-14 10:10-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"
@@ -33,7 +33,7 @@ msgid ""
 "mismatch"
 msgstr ""
 
-#: mcs/mcs/anonymous.cs:909 mcs/mcs/ecore.cs:4524
+#: mcs/mcs/anonymous.cs:909 mcs/mcs/ecore.cs:4522
 #, csharp-format
 msgid "Delegate `{0}' does not take `{1}' arguments"
 msgstr ""
@@ -119,7 +119,7 @@ msgstr ""
 msgid "Cannot assign to `{0}' because it is a `{1}'"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:196
+#: mcs/mcs/attribute.cs:201
 #, csharp-format
 msgid ""
 "`{0}' is not a valid named attribute argument. Named attribute arguments "
@@ -127,88 +127,88 @@ msgid ""
 "properties which are public and not static"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:205
+#: mcs/mcs/attribute.cs:210
 #, csharp-format
 msgid ""
 "`{0}' is not a valid named attribute argument because it is not a valid "
 "attribute parameter type"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:211
+#: mcs/mcs/attribute.cs:216
 msgid "An attribute argument cannot be dynamic expression"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:216
+#: mcs/mcs/attribute.cs:221
 msgid "The Guid attribute must be specified with the ComImport attribute"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:221
+#: mcs/mcs/attribute.cs:226
 #, csharp-format
 msgid "Do not use `{0}' directly. Use parameter modifier `this' instead"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:226
+#: mcs/mcs/attribute.cs:231
 #, csharp-format
 msgid "Do not use `{0}' directly. Use `dynamic' keyword instead"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:235
+#: mcs/mcs/attribute.cs:240
 #, csharp-format
 msgid "Error during emitting `{0}' attribute. The reason is `{1}'"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:266
+#: mcs/mcs/attribute.cs:271
 #, csharp-format
 msgid "`{0}': is not an attribute class"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:302
+#: mcs/mcs/attribute.cs:307
 #, csharp-format
 msgid ""
 "`{0}' is ambiguous between `{1}' and `{2}'. Use either `@{0}' or `{0}"
 "Attribute'"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:385
+#: mcs/mcs/attribute.cs:390
 #, csharp-format
 msgid "Cannot apply attribute class `{0}' because it is abstract"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:453
+#: mcs/mcs/attribute.cs:458
 #, csharp-format
 msgid "Duplicate named attribute `{0}' argument"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:730
+#: mcs/mcs/attribute.cs:735
 #, csharp-format
 msgid ""
 "`{0}' is not a valid attribute location for this declaration. Valid "
 "attribute locations for this declaration are `{1}'"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:1004
+#: mcs/mcs/attribute.cs:1006
 #, csharp-format
 msgid ""
 "The attribute `{0}' is not valid on this declaration type. It is valid on `"
 "{1}' declarations only"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:1022
+#: mcs/mcs/attribute.cs:1028
 #, csharp-format
 msgid "The argument to the `{0}' attribute must be a valid identifier"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:1035
+#: mcs/mcs/attribute.cs:1041
 #, csharp-format
 msgid "Invalid value for argument to `{0}' attribute"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:1341
+#: mcs/mcs/attribute.cs:1348
 #, csharp-format
 msgid "The attribute `{0}' cannot be applied multiple times"
 msgstr ""
 
-#: mcs/mcs/attribute.cs:1603
+#: mcs/mcs/attribute.cs:1676
 #, csharp-format
 msgid "`{0}' is obsolete: `{1}'"
 msgstr ""
@@ -1395,7 +1395,7 @@ msgstr ""
 msgid "Error generating XML documentation file `{0}' (`{1}')"
 msgstr ""
 
-#: mcs/mcs/driver.cs:96 mcs/mcs/driver.cs:467 mcs/mcs/driver.cs:470
+#: mcs/mcs/driver.cs:96 mcs/mcs/driver.cs:475 mcs/mcs/driver.cs:478
 msgid "Source file `"
 msgstr ""
 
@@ -1423,188 +1423,188 @@ msgstr ""
 msgid "Unable to open response file: "
 msgstr ""
 
-#: mcs/mcs/driver.cs:422 mcs/mcs/driver.cs:432
+#: mcs/mcs/driver.cs:430 mcs/mcs/driver.cs:440
 msgid "No files to compile were specified"
 msgstr ""
 
-#: mcs/mcs/driver.cs:504
+#: mcs/mcs/driver.cs:512
 msgid "Warning level must be in the range 0-4"
 msgstr ""
 
-#: mcs/mcs/driver.cs:538
+#: mcs/mcs/driver.cs:546
 msgid "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS"
 msgstr ""
 
-#: mcs/mcs/driver.cs:547
+#: mcs/mcs/driver.cs:555
 msgid "Compatibility: Use -unsafe instead of --unsafe"
 msgstr ""
 
-#: mcs/mcs/driver.cs:558
+#: mcs/mcs/driver.cs:566
 msgid "Compatibility: Use -d:SYMBOL instead of --define SYMBOL"
 msgstr ""
 
-#: mcs/mcs/driver.cs:572
+#: mcs/mcs/driver.cs:580
 msgid "Compatibility: Use -out:FILE instead of --output FILE or -o FILE"
 msgstr ""
 
-#: mcs/mcs/driver.cs:581
+#: mcs/mcs/driver.cs:589
 msgid "Compatibility: Use -checked instead of --checked"
 msgstr ""
 
-#: mcs/mcs/driver.cs:591
+#: mcs/mcs/driver.cs:599
 msgid "Compatibility: Use -linkres:VALUE instead of --linkres VALUE"
 msgstr ""
 
-#: mcs/mcs/driver.cs:594
+#: mcs/mcs/driver.cs:602
 msgid "Missing argument to --linkres"
 msgstr ""
 
-#: mcs/mcs/driver.cs:603
+#: mcs/mcs/driver.cs:611
 msgid "Compatibility: Use -res:VALUE instead of --res VALUE"
 msgstr ""
 
-#: mcs/mcs/driver.cs:606
+#: mcs/mcs/driver.cs:614
 msgid "Missing argument to --resource"
 msgstr ""
 
-#: mcs/mcs/driver.cs:614
+#: mcs/mcs/driver.cs:622
 msgid "Compatibility: Use -target:KIND instead of --target KIND"
 msgstr ""
 
-#: mcs/mcs/driver.cs:646
+#: mcs/mcs/driver.cs:654
 msgid "Compatibility: Use -r:LIBRARY instead of -r library"
 msgstr ""
 
-#: mcs/mcs/driver.cs:665
+#: mcs/mcs/driver.cs:673
 msgid "Compatibility: Use -lib:ARG instead of --L arg"
 msgstr ""
 
-#: mcs/mcs/driver.cs:678
+#: mcs/mcs/driver.cs:686
 msgid "Compatibility: Use -nostdlib instead of --nostdlib"
 msgstr ""
 
-#: mcs/mcs/driver.cs:683
+#: mcs/mcs/driver.cs:691
 msgid "Compatibility: Use -nowarn instead of --nowarn"
 msgstr ""
 
-#: mcs/mcs/driver.cs:700
+#: mcs/mcs/driver.cs:708
 msgid "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL"
 msgstr ""
 
-#: mcs/mcs/driver.cs:704
+#: mcs/mcs/driver.cs:712
 msgid "--wlevel requires a value from 0 to 4"
 msgstr ""
 
-#: mcs/mcs/driver.cs:713
+#: mcs/mcs/driver.cs:721
 msgid "--mcs-debug requires an argument"
 msgstr ""
 
-#: mcs/mcs/driver.cs:720
+#: mcs/mcs/driver.cs:728
 msgid "Invalid argument to --mcs-debug"
 msgstr ""
 
-#: mcs/mcs/driver.cs:730
+#: mcs/mcs/driver.cs:738
 msgid "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN"
 msgstr ""
 
-#: mcs/mcs/driver.cs:732
+#: mcs/mcs/driver.cs:740
 msgid "--recurse requires an argument"
 msgstr ""
 
-#: mcs/mcs/driver.cs:743
+#: mcs/mcs/driver.cs:751
 msgid "Compatibility: Use -debug option instead of -g or --debug"
 msgstr ""
 
-#: mcs/mcs/driver.cs:748
+#: mcs/mcs/driver.cs:756
 msgid "Compatibility: Use -noconfig option instead of --noconfig"
 msgstr ""
 
-#: mcs/mcs/driver.cs:912
+#: mcs/mcs/driver.cs:920
 #, csharp-format
 msgid "Invalid conditional define symbol `{0}'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:963
+#: mcs/mcs/driver.cs:971
 #, csharp-format
 msgid ""
 "Invalid resource visibility option `{0}'. Use either `public' or `private' "
 "instead"
 msgstr ""
 
-#: mcs/mcs/driver.cs:969
+#: mcs/mcs/driver.cs:977
 #, csharp-format
 msgid "Wrong number of arguments for option `{0}'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1007
+#: mcs/mcs/driver.cs:1015
 msgid "Cannot specify multiple aliases using single /reference option"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1035 mcs/mcs/driver.cs:1047
+#: mcs/mcs/driver.cs:1043 mcs/mcs/driver.cs:1055
 msgid ""
 "Cannot specify the `win32res' and the `win32ico' compiler option at the same "
 "time"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1162
+#: mcs/mcs/driver.cs:1170
 #, csharp-format
 msgid "`{0}' is not a valid warning number"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1192
+#: mcs/mcs/driver.cs:1200
 msgid ""
 "Invalid platform type for -platform. Valid options are `anycpu', `x86', "
 "`x64' or `itanium'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1212
+#: mcs/mcs/driver.cs:1220
 msgid "Invalid sdk version name"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1310
+#: mcs/mcs/driver.cs:1318
 #, csharp-format
 msgid ""
 "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or "
 "`Default'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1330
+#: mcs/mcs/driver.cs:1338
 #, csharp-format
 msgid "Code page `{0}' is invalid or not installed"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1345
+#: mcs/mcs/driver.cs:1353
 #, csharp-format
 msgid "Unrecognized command-line option: `{0}'"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1350
+#: mcs/mcs/driver.cs:1358
 #, csharp-format
 msgid "Missing file specification for `{0}' option"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1355
+#: mcs/mcs/driver.cs:1363
 #, csharp-format
 msgid "Missing argument for `{0}' option"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1390
+#: mcs/mcs/driver.cs:1398
 #, csharp-format
 msgid "Invalid reference alias `{0}='. Missing filename"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1395
+#: mcs/mcs/driver.cs:1403
 #, csharp-format
 msgid ""
 "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1411
+#: mcs/mcs/driver.cs:1419
 #, csharp-format
 msgid "The resource identifier `{0}' has already been used in this assembly"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1472
+#: mcs/mcs/driver.cs:1480
 msgid ""
 "If no source files are specified you must specify the output file with -out:"
 msgstr ""
@@ -1677,7 +1677,7 @@ msgstr ""
 msgid "The operation in question is undefined on void pointers"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:438 mcs/mcs/statement.cs:2558 mcs/mcs/statement.cs:2560
+#: mcs/mcs/ecore.cs:438 mcs/mcs/statement.cs:2559 mcs/mcs/statement.cs:2561
 #, csharp-format
 msgid "Internal compiler error: {0}"
 msgstr ""
@@ -1834,7 +1834,7 @@ msgid ""
 "The type `{0}' does not contain a constructor that takes `{1}' arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4334
+#: mcs/mcs/ecore.cs:4332
 #, csharp-format
 msgid ""
 "Type `{0}' does not contain a member `{1}' and the best extension method "
@@ -1842,154 +1842,154 @@ msgid ""
 "without the extension method syntax"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4355
+#: mcs/mcs/ecore.cs:4353
 #, csharp-format
 msgid ""
 "The call is ambiguous between the following methods or properties: `{0}' and "
 "`{1}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4415
+#: mcs/mcs/ecore.cs:4413
 #, csharp-format
 msgid ""
 "The best overloaded collection initalizer method `{0}' cannot have 'ref', or "
 "`out' modifier"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4419
+#: mcs/mcs/ecore.cs:4417
 #, csharp-format
 msgid ""
 "The best overloaded collection initalizer method `{0}' has some invalid "
 "arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4422
+#: mcs/mcs/ecore.cs:4420
 #, csharp-format
 msgid "Delegate `{0}' has some invalid arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4426
+#: mcs/mcs/ecore.cs:4424
 #, csharp-format
 msgid "The best overloaded method match for `{0}' has some invalid arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4436
+#: mcs/mcs/ecore.cs:4434
 #, csharp-format
 msgid ""
 "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' "
 "modifier"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4439
+#: mcs/mcs/ecore.cs:4437
 #, csharp-format
 msgid "Argument `#{0}' is missing `{1}' modifier"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4452
+#: mcs/mcs/ecore.cs:4450
 #, csharp-format
 msgid "Argument `#{0}' cannot convert `{1}' expression to type `{2}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4500
+#: mcs/mcs/ecore.cs:4498
 #, csharp-format
 msgid ""
 "The type arguments for method `{0}' cannot be inferred from the usage. Try "
 "specifying the type arguments explicitly"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4529
+#: mcs/mcs/ecore.cs:4527
 #, csharp-format
 msgid "No overload for method `{0}' takes `{1}' arguments"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4582
+#: mcs/mcs/ecore.cs:4580
 #, csharp-format
 msgid "The delegate `{0}' does not contain a parameter named `{1}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4587
+#: mcs/mcs/ecore.cs:4585
 #, csharp-format
 msgid ""
 "The best overloaded method match for `{0}' does not contain a parameter "
 "named `{1}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4597
+#: mcs/mcs/ecore.cs:4595
 #, csharp-format
 msgid ""
 "Named argument `{0}' cannot be used for a parameter which has positional "
 "argument specified"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4910
+#: mcs/mcs/ecore.cs:4908
 msgid ""
 "You cannot use fixed size buffers contained in unfixed expressions. Try "
 "using the fixed statement"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4915
+#: mcs/mcs/ecore.cs:4913
 #, csharp-format
 msgid "`{0}': Fixed size buffers can only be accessed through locals or fields"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5310
+#: mcs/mcs/ecore.cs:5308
 #, csharp-format
 msgid "Property or event `{0}' is not supported by the C# language"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5471
+#: mcs/mcs/ecore.cs:5469
 #, csharp-format
 msgid "A range variable `{0}' may not be passes as `ref' or `out' parameter"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5519
+#: mcs/mcs/ecore.cs:5517
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because it "
 "lacks the `get' accessor"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5526
+#: mcs/mcs/ecore.cs:5524
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because the get "
 "accessor is inaccessible"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5545
+#: mcs/mcs/ecore.cs:5543
 #, csharp-format
 msgid "Property or indexer `{0}' cannot be assigned to (it is read-only)"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5553
+#: mcs/mcs/ecore.cs:5551
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because the set "
 "accessor is inaccessible"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5714
+#: mcs/mcs/ecore.cs:5712
 #, csharp-format
 msgid ""
 "The event `{0}' can only appear on the left hand side of `+=' or `-=' "
 "operator"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5718
+#: mcs/mcs/ecore.cs:5716
 #, csharp-format
 msgid ""
 "The event `{0}' can only appear on the left hand side of += or -= when used "
 "outside of the type `{1}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5882
+#: mcs/mcs/ecore.cs:5880
 #, csharp-format
 msgid ""
 "An implicitly typed local variable declaration cannot be initialized with `"
 "{0}'"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:5896
+#: mcs/mcs/ecore.cs:5894
 msgid ""
 "The contextual keyword `var' may only appear within a local variable "
 "declaration"
@@ -2011,7 +2011,7 @@ msgstr ""
 msgid "Type byte, sbyte, short, ushort, int, uint, long or ulong expected"
 msgstr ""
 
-#: mcs/mcs/eval.cs:626
+#: mcs/mcs/eval.cs:643
 msgid "Detection Parsing Error"
 msgstr ""
 
@@ -2215,7 +2215,7 @@ msgid "Cannot create an array with a negative size"
 msgstr ""
 
 #: mcs/mcs/expression.cs:6096 mcs/mcs/expression.cs:6104
-#: mcs/mcs/statement.cs:1009 mcs/mcs/statement.cs:3055
+#: mcs/mcs/statement.cs:1002 mcs/mcs/statement.cs:3056
 msgid "A constant value is expected"
 msgstr ""
 
@@ -2573,7 +2573,7 @@ msgid "Cannot yield in the body of a finally clause"
 msgstr ""
 
 #: mcs/mcs/flowanalysis.cs:927 mcs/mcs/flowanalysis.cs:943
-#: mcs/mcs/flowanalysis.cs:979 mcs/mcs/statement.cs:694
+#: mcs/mcs/flowanalysis.cs:979 mcs/mcs/statement.cs:687
 msgid "Control cannot leave the body of a finally clause"
 msgstr ""
 
@@ -2734,7 +2734,7 @@ msgid ""
 "method `{2}'. There is no implicit reference conversion from `{0}' to `{3}'"
 msgstr ""
 
-#: mcs/mcs/import.cs:1711
+#: mcs/mcs/import.cs:1712
 #, csharp-format
 msgid ""
 "The type `{0}' is defined in an assembly that is not referenced. Consider "
@@ -2764,7 +2764,7 @@ msgstr ""
 msgid "Iterators cannot have unsafe parameters or yield types"
 msgstr ""
 
-#: mcs/mcs/iterators.cs:888 mcs/mcs/statement.cs:4324
+#: mcs/mcs/iterators.cs:888 mcs/mcs/statement.cs:4325
 msgid "Unsafe code may not appear in iterators"
 msgstr ""
 
@@ -2808,22 +2808,22 @@ msgstr ""
 msgid "A range variable `{0}' cannot be initialized with `{1}'"
 msgstr ""
 
-#: mcs/mcs/linq.cs:750
+#: mcs/mcs/linq.cs:747
 #, csharp-format
 msgid "A range variable `{0}' conflicts with a previous declaration of `{0}'"
 msgstr ""
 
-#: mcs/mcs/linq.cs:757
+#: mcs/mcs/linq.cs:754
 #, csharp-format
 msgid "A range variable `{0}' has already been declared in this scope"
 msgstr ""
 
-#: mcs/mcs/linq.cs:764
+#: mcs/mcs/linq.cs:761
 #, csharp-format
 msgid "A range variable `{0}' conflicts with a method type parameter"
 msgstr ""
 
-#: mcs/mcs/linq.cs:796
+#: mcs/mcs/linq.cs:793
 #, csharp-format
 msgid ""
 "A range variable `{0}' cannot be assigned to. Consider using `let' clause to "
@@ -3217,95 +3217,95 @@ msgstr ""
 msgid "The params parameter must be a single dimensional array"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:288
+#: mcs/mcs/parameter.cs:301
 msgid "An out parameter cannot have the `In' attribute"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:293
+#: mcs/mcs/parameter.cs:306
 msgid ""
 "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:300
+#: mcs/mcs/parameter.cs:313
 msgid ""
 "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and "
 "`Out' attributes or neither"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:310
+#: mcs/mcs/parameter.cs:324
 #, csharp-format
 msgid "Cannot specify `{0}' attribute on optional parameter `{1}'"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:320
+#: mcs/mcs/parameter.cs:369
+#, csharp-format
+msgid "Method or delegate parameter cannot be of type `{0}'"
+msgstr ""
+
+#: mcs/mcs/parameter.cs:379
+#, csharp-format
+msgid "`{0}': static types cannot be used as parameters"
+msgstr ""
+
+#: mcs/mcs/parameter.cs:385
+#, csharp-format
+msgid "The extension method cannot be of type `{0}'"
+msgstr ""
+
+#: mcs/mcs/parameter.cs:425
 #, csharp-format
 msgid ""
 "Argument of type `{0}' is not applicable for the DefaultParameterValue "
 "attribute"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:323
+#: mcs/mcs/parameter.cs:429
 #, csharp-format
 msgid ""
 "The DefaultParameterValue attribute is not applicable on parameters of type `"
 "{0}'"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:334
+#: mcs/mcs/parameter.cs:457
 msgid "The type of the default value should match the type of the parameter"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:376
-#, csharp-format
-msgid "Method or delegate parameter cannot be of type `{0}'"
-msgstr ""
-
-#: mcs/mcs/parameter.cs:386
-#, csharp-format
-msgid "`{0}': static types cannot be used as parameters"
+#: mcs/mcs/parameter.cs:602
+msgid "An expression tree parameter cannot use `ref' or `out' modifier"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:392
+#: mcs/mcs/parameter.cs:1074
 #, csharp-format
-msgid "The extension method cannot be of type `{0}'"
+msgid "The parameter name `{0}' conflicts with a compiler generated name"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:448
+#: mcs/mcs/parameter.cs:1220
 #, csharp-format
 msgid ""
 "The expression being assigned to optional parameter `{0}' must be a constant "
 "or default value"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:464
+#: mcs/mcs/parameter.cs:1237
 #, csharp-format
 msgid ""
 "The expression being assigned to nullable optional parameter `{0}' must be "
 "default value"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:472
+#: mcs/mcs/parameter.cs:1245
 #, csharp-format
 msgid ""
 "Optional parameter `{0}' of type `{1}' can only be initialized with `null'"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:482
+#: mcs/mcs/parameter.cs:1256
 #, csharp-format
 msgid ""
 "Optional parameter expression of type `{0}' cannot be converted to parameter "
 "type `{1}'"
 msgstr ""
 
-#: mcs/mcs/parameter.cs:624
-msgid "An expression tree parameter cannot use `ref' or `out' modifier"
-msgstr ""
-
-#: mcs/mcs/parameter.cs:1096
-#, csharp-format
-msgid "The parameter name `{0}' conflicts with a compiler generated name"
-msgstr ""
-
 #: mcs/mcs/pending.cs:443
 #, csharp-format
 msgid ""
@@ -3412,7 +3412,7 @@ msgstr ""
 msgid "Cannot set the `IndexerName' attribute on an indexer marked override"
 msgstr ""
 
-#: mcs/mcs/reflection.cs:239
+#: mcs/mcs/reflection.cs:255
 msgid "Could not access the key inside the container `"
 msgstr ""
 
@@ -3433,60 +3433,60 @@ msgid ""
 "tree"
 msgstr ""
 
-#: mcs/mcs/statement.cs:740
+#: mcs/mcs/statement.cs:733
 #, csharp-format
 msgid ""
 "An object of a type convertible to `{0}' is required for the return statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:753
+#: mcs/mcs/statement.cs:746
 #, csharp-format
 msgid ""
 "`{0}': A return keyword must not be followed by any expression when method "
 "returns void"
 msgstr ""
 
-#: mcs/mcs/statement.cs:778
+#: mcs/mcs/statement.cs:771
 #, csharp-format
 msgid ""
 "Cannot convert `{0}' to delegate type `{1}' because some of the return types "
 "in the block are not implicitly convertible to the delegate return type"
 msgstr ""
 
-#: mcs/mcs/statement.cs:806
+#: mcs/mcs/statement.cs:799
 msgid ""
 "Cannot return a value from iterators. Use the yield return statement to "
 "return a value, or yield break to end the iteration"
 msgstr ""
 
-#: mcs/mcs/statement.cs:963 mcs/mcs/statement.cs:997
+#: mcs/mcs/statement.cs:956 mcs/mcs/statement.cs:990
 msgid "A goto case is only valid inside a switch statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1076 mcs/mcs/statement.cs:4726
+#: mcs/mcs/statement.cs:1069 mcs/mcs/statement.cs:4727
 msgid "The type caught or thrown must be derived from System.Exception"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1298
+#: mcs/mcs/statement.cs:1291
 msgid "A fixed statement cannot use an implicitly typed local variable"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1303
+#: mcs/mcs/statement.cs:1296
 msgid "An implicitly typed local variable cannot be a constant"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1308
+#: mcs/mcs/statement.cs:1301
 msgid ""
 "An implicitly typed local variable declarator must include an initializer"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1313
+#: mcs/mcs/statement.cs:1306
 msgid ""
 "An implicitly typed local variable declaration cannot include multiple "
 "declarators"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1883
+#: mcs/mcs/statement.cs:1876
 #, csharp-format
 msgid ""
 "A local variable named `{0}' cannot be declared in this scope because it "
@@ -3494,111 +3494,111 @@ msgid ""
 "scope to denote something else"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1894
+#: mcs/mcs/statement.cs:1887
 #, csharp-format
 msgid ""
 "`{0}': An anonymous type cannot have multiple properties with the same name"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1897
+#: mcs/mcs/statement.cs:1890
 #, csharp-format
 msgid "The parameter name `{0}' is a duplicate"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1904
+#: mcs/mcs/statement.cs:1897
 #, csharp-format
 msgid "A local variable named `{0}' is already defined in this scope"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1910
+#: mcs/mcs/statement.cs:1903
 #, csharp-format
 msgid ""
 "The type parameter name `{0}' is the same as local variable or parameter name"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2482
+#: mcs/mcs/statement.cs:2477
 #, csharp-format
 msgid ""
 "The out parameter `{0}' must be assigned to before control leaves the "
 "current method"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2573
+#: mcs/mcs/statement.cs:2574
 #, csharp-format
 msgid "`{0}': not all code paths return a value"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2577
+#: mcs/mcs/statement.cs:2578
 #, csharp-format
 msgid "Not all code paths return a value in anonymous method of type `{0}'"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2748
+#: mcs/mcs/statement.cs:2749
 #, csharp-format
 msgid "The label `{0}' is a duplicate"
 msgstr ""
 
-#: mcs/mcs/statement.cs:2757 mcs/mcs/statement.cs:2768
+#: mcs/mcs/statement.cs:2758 mcs/mcs/statement.cs:2769
 #, csharp-format
 msgid ""
 "The label `{0}' shadows another label by the same name in a contained scope"
 msgstr ""
 
-#: mcs/mcs/statement.cs:3088
+#: mcs/mcs/statement.cs:3089
 #, csharp-format
 msgid "The label `case {0}:' already occurs in this switch statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:3629
+#: mcs/mcs/statement.cs:3630
 #, csharp-format
 msgid ""
 "A switch expression of type `{0}' cannot be converted to an integral type, "
 "bool, char, string, enum or nullable type"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4114
+#: mcs/mcs/statement.cs:4115
 #, csharp-format
 msgid "`{0}' is not a reference type as required by the lock statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4455
+#: mcs/mcs/statement.cs:4456
 msgid "The type of locals declared in a fixed statement must be a pointer type"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4471
+#: mcs/mcs/statement.cs:4472
 msgid ""
 "The right hand side of a fixed statement assignment may not be a cast "
 "expression"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4542
+#: mcs/mcs/statement.cs:4543
 msgid ""
 "You cannot use the fixed statement to take the address of an already fixed "
 "expression"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4856
+#: mcs/mcs/statement.cs:4857
 #, csharp-format
 msgid ""
 "A previous catch clause already catches all exceptions of this or a super "
 "type `{0}'"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5029
+#: mcs/mcs/statement.cs:5030
 #, csharp-format
 msgid ""
 "`{0}': type used in a using statement must be implicitly convertible to "
 "`System.IDisposable'"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5451
+#: mcs/mcs/statement.cs:5452
 #, csharp-format
 msgid ""
 "foreach statement requires that the return type `{0}' of `{1}' must have a "
 "suitable public MoveNext method and public Current property"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5491
+#: mcs/mcs/statement.cs:5492
 #, csharp-format
 msgid ""
 "foreach statement cannot operate on variables of type `{0}' because it "
@@ -3606,18 +3606,18 @@ msgid ""
 "implementation"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5516
+#: mcs/mcs/statement.cs:5517
 #, csharp-format
 msgid ""
 "foreach statement cannot operate on variables of type `{0}' because it does "
 "not contain a definition for `{1}' or is inaccessible"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5722
+#: mcs/mcs/statement.cs:5723
 msgid "Use of null is not valid in this context"
 msgstr ""
 
-#: mcs/mcs/statement.cs:5732
+#: mcs/mcs/statement.cs:5733
 #, csharp-format
 msgid "Foreach statement cannot operate on a `{0}'"
 msgstr ""
diff --git a/po/mcs/pt_BR.gmo b/po/mcs/pt_BR.gmo
index d61d7c3..d776c87 100644
Binary files a/po/mcs/pt_BR.gmo and b/po/mcs/pt_BR.gmo differ
diff --git a/po/mcs/pt_BR.po b/po/mcs/pt_BR.po
index d02a330..5aee92e 100644
--- a/po/mcs/pt_BR.po
+++ b/po/mcs/pt_BR.po
@@ -7,7 +7,7 @@ msgid ""
 msgstr ""
 "Project-Id-Version: mono 2.1\n"
 "Report-Msgid-Bugs-To: http://www.mono-project.com/Bugs\n"
-"POT-Creation-Date: 2011-01-18 10:45-0700\n"
+"POT-Creation-Date: 2011-02-14 10:10-0700\n"
 "PO-Revision-Date: 2009-03-01 07:52-0300\n"
 "Last-Translator: Rodrigo Luiz Marques Flores <mail at rodrigoflores.org>\n"
 "Language-Team: pt-BR <mono-list at lists.ximian.com>\n"
@@ -37,7 +37,7 @@ msgstr ""
 "Não foi possível converter \"{0}\" para um tipo delegate \"{1}\"pois os "
 "parâmetros não conferem"
 
-#: mcs/mcs/anonymous.cs:909 mcs/mcs/ecore.cs:4524
+#: mcs/mcs/anonymous.cs:909 mcs/mcs/ecore.cs:4522
 #, csharp-format
 msgid "Delegate `{0}' does not take `{1}' arguments"
 msgstr "Delegate \"{0}\" não recebe \"{1}\" argumentos"
@@ -142,7 +142,7 @@ msgstr "Uma árvore de expressão não pode conter um operador de atribuição"
 msgid "Cannot assign to `{0}' because it is a `{1}'"
 msgstr "Não foi possível atribuir a \"{0}\" por que este é um \"{1}\""
 
-#: mcs/mcs/attribute.cs:196
+#: mcs/mcs/attribute.cs:201
 #, csharp-format
 msgid ""
 "`{0}' is not a valid named attribute argument. Named attribute arguments "
@@ -154,7 +154,7 @@ msgstr ""
 "constantes ou possuir propriedades de leitura-escrita que são públicas e não "
 "estáticas"
 
-#: mcs/mcs/attribute.cs:205
+#: mcs/mcs/attribute.cs:210
 #, csharp-format
 msgid ""
 "`{0}' is not a valid named attribute argument because it is not a valid "
@@ -163,40 +163,40 @@ msgstr ""
 "\"{0}\" não é um atributo nomeado válida para um argumento de atributo por "
 "quê não é um tipo de parâmetro de atributo válido"
 
-#: mcs/mcs/attribute.cs:211
+#: mcs/mcs/attribute.cs:216
 #, fuzzy
 msgid "An attribute argument cannot be dynamic expression"
 msgstr "\"{0}\": um argumento de atributo não pode usar parâmetros de tipo"
 
-#: mcs/mcs/attribute.cs:216
+#: mcs/mcs/attribute.cs:221
 msgid "The Guid attribute must be specified with the ComImport attribute"
 msgstr "O atributo Guid deve ser especificado com o atributo ComImport"
 
-#: mcs/mcs/attribute.cs:221
+#: mcs/mcs/attribute.cs:226
 #, csharp-format
 msgid "Do not use `{0}' directly. Use parameter modifier `this' instead"
 msgstr ""
 "Não use \"{0}\" diretamente. Ao invés disso, use o modificador de parâmetro "
 "\"this\""
 
-#: mcs/mcs/attribute.cs:226
+#: mcs/mcs/attribute.cs:231
 #, fuzzy, csharp-format
 msgid "Do not use `{0}' directly. Use `dynamic' keyword instead"
 msgstr ""
 "Não use \"{0}\" diretamente. Ao invés disso, use o modificador de parâmetro "
 "\"this\""
 
-#: mcs/mcs/attribute.cs:235
+#: mcs/mcs/attribute.cs:240
 #, csharp-format
 msgid "Error during emitting `{0}' attribute. The reason is `{1}'"
 msgstr "Erro enquanto emitia o atributo \"{0}\". O motivo é \"{1}\""
 
-#: mcs/mcs/attribute.cs:266
+#: mcs/mcs/attribute.cs:271
 #, csharp-format
 msgid "`{0}': is not an attribute class"
 msgstr "\"{0}\" não é uma classe de atributos"
 
-#: mcs/mcs/attribute.cs:302
+#: mcs/mcs/attribute.cs:307
 #, fuzzy, csharp-format
 msgid ""
 "`{0}' is ambiguous between `{1}' and `{2}'. Use either `@{0}' or `{0}"
@@ -205,18 +205,18 @@ msgstr ""
 "\"{0}\" está ambíguo entre \"{0}\" e \"{0}Atributo\". Utilize \"@{0}\" ou "
 "\"{0}Atributo\""
 
-#: mcs/mcs/attribute.cs:385
+#: mcs/mcs/attribute.cs:390
 #, csharp-format
 msgid "Cannot apply attribute class `{0}' because it is abstract"
 msgstr ""
 "Não foi possível aplicar a classe de atributo \"{0}\" por que esta é abstrata"
 
-#: mcs/mcs/attribute.cs:453
+#: mcs/mcs/attribute.cs:458
 #, fuzzy, csharp-format
 msgid "Duplicate named attribute `{0}' argument"
 msgstr "argumento de atributo nomeado \"{0}\" duplicado"
 
-#: mcs/mcs/attribute.cs:730
+#: mcs/mcs/attribute.cs:735
 #, csharp-format
 msgid ""
 "`{0}' is not a valid attribute location for this declaration. Valid "
@@ -225,7 +225,7 @@ msgstr ""
 "\"{0}\" não é uma localização de atributo válido para esta declaração. "
 "Localizações de atributos válidos para esta declaração são \"{1}\""
 
-#: mcs/mcs/attribute.cs:1004
+#: mcs/mcs/attribute.cs:1006
 #, csharp-format
 msgid ""
 "The attribute `{0}' is not valid on this declaration type. It is valid on `"
@@ -234,23 +234,23 @@ msgstr ""
 "O atributo \"{0}\" não é válido neste tipo de declaração. Isso é válido "
 "somente nas declarações \"{1}\""
 
-#: mcs/mcs/attribute.cs:1022
+#: mcs/mcs/attribute.cs:1028
 #, csharp-format
 msgid "The argument to the `{0}' attribute must be a valid identifier"
 msgstr "O argumento para o atributo \"{0}\" deve ser um identificador válido"
 
-#: mcs/mcs/attribute.cs:1035
+#: mcs/mcs/attribute.cs:1041
 #, fuzzy, csharp-format
 msgid "Invalid value for argument to `{0}' attribute"
 msgstr ""
 "Valor inválido para o argumento para o atributo \"System.AttributeUsage\""
 
-#: mcs/mcs/attribute.cs:1341
+#: mcs/mcs/attribute.cs:1348
 #, csharp-format
 msgid "The attribute `{0}' cannot be applied multiple times"
 msgstr "O atributo \"{0}\" não pode ser aplicado múltiplas vezes"
 
-#: mcs/mcs/attribute.cs:1603
+#: mcs/mcs/attribute.cs:1676
 #, csharp-format
 msgid "`{0}' is obsolete: `{1}'"
 msgstr "\"{0}\" é obsoleto: \"{1}\""
@@ -1597,7 +1597,7 @@ msgstr "Nome do método esperado"
 msgid "Error generating XML documentation file `{0}' (`{1}')"
 msgstr "Erro ao gerar arquivo de documentação XML \"{0}\" (\"{1}\")"
 
-#: mcs/mcs/driver.cs:96 mcs/mcs/driver.cs:467 mcs/mcs/driver.cs:470
+#: mcs/mcs/driver.cs:96 mcs/mcs/driver.cs:475 mcs/mcs/driver.cs:478
 msgid "Source file `"
 msgstr "Arquivo fonte \""
 
@@ -1627,112 +1627,112 @@ msgstr "Arquivo de resposta \""
 msgid "Unable to open response file: "
 msgstr "Não foi possível abrir arquivo de resposta: "
 
-#: mcs/mcs/driver.cs:422 mcs/mcs/driver.cs:432
+#: mcs/mcs/driver.cs:430 mcs/mcs/driver.cs:440
 msgid "No files to compile were specified"
 msgstr "Nenhum arquivo para compilar foi especificado"
 
-#: mcs/mcs/driver.cs:504
+#: mcs/mcs/driver.cs:512
 msgid "Warning level must be in the range 0-4"
 msgstr "Nível de avisis deve estar no intervalo 0-4"
 
-#: mcs/mcs/driver.cs:538
+#: mcs/mcs/driver.cs:546
 msgid "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS"
 msgstr ""
 "Compatibilidade: Utilize -main:CLASSE ao invés de --main CLASSE ou -m CLASSE"
 
-#: mcs/mcs/driver.cs:547
+#: mcs/mcs/driver.cs:555
 msgid "Compatibility: Use -unsafe instead of --unsafe"
 msgstr "Compatibilidade: Utilize -unsafe ao invés de --unsafe"
 
-#: mcs/mcs/driver.cs:558
+#: mcs/mcs/driver.cs:566
 msgid "Compatibility: Use -d:SYMBOL instead of --define SYMBOL"
 msgstr "Compatibilidade: Utilize -d:SÍMBOLO ao invés de --define SÍMBOLO"
 
-#: mcs/mcs/driver.cs:572
+#: mcs/mcs/driver.cs:580
 msgid "Compatibility: Use -out:FILE instead of --output FILE or -o FILE"
 msgstr ""
 "Compatibilidade: Utilize -out ARQUIVO ao invés de --output ARQUIVO ou -o "
 "ARQUIVO"
 
-#: mcs/mcs/driver.cs:581
+#: mcs/mcs/driver.cs:589
 msgid "Compatibility: Use -checked instead of --checked"
 msgstr "Compatibilidade: Utilize -checked ao invés de --checked"
 
-#: mcs/mcs/driver.cs:591
+#: mcs/mcs/driver.cs:599
 msgid "Compatibility: Use -linkres:VALUE instead of --linkres VALUE"
 msgstr "Compatibilidade: Utilize -linkres:VALOR ao invés de --linkres VALOR"
 
-#: mcs/mcs/driver.cs:594
+#: mcs/mcs/driver.cs:602
 msgid "Missing argument to --linkres"
 msgstr "Argumento faltando para --linkres"
 
-#: mcs/mcs/driver.cs:603
+#: mcs/mcs/driver.cs:611
 msgid "Compatibility: Use -res:VALUE instead of --res VALUE"
 msgstr "Compatibilidade: Utilize -res:VALOR ao invés de --res VALOR"
 
-#: mcs/mcs/driver.cs:606
+#: mcs/mcs/driver.cs:614
 msgid "Missing argument to --resource"
 msgstr "Argumento faltando para --resource"
 
-#: mcs/mcs/driver.cs:614
+#: mcs/mcs/driver.cs:622
 msgid "Compatibility: Use -target:KIND instead of --target KIND"
 msgstr "Compatibilidade: Utilize -target:KIND ao invés de --target KIND"
 
-#: mcs/mcs/driver.cs:646
+#: mcs/mcs/driver.cs:654
 msgid "Compatibility: Use -r:LIBRARY instead of -r library"
 msgstr "Compatibilidade: Utilize -r:BIBLIOTECA ao invés de -r biblioteca"
 
-#: mcs/mcs/driver.cs:665
+#: mcs/mcs/driver.cs:673
 msgid "Compatibility: Use -lib:ARG instead of --L arg"
 msgstr "Compatibilidade: Utilize -lib:ARG ao invés de --L arg"
 
-#: mcs/mcs/driver.cs:678
+#: mcs/mcs/driver.cs:686
 msgid "Compatibility: Use -nostdlib instead of --nostdlib"
 msgstr "Compatibilidade: Utilize -nostdlib ao invés de --nostdlib"
 
-#: mcs/mcs/driver.cs:683
+#: mcs/mcs/driver.cs:691
 msgid "Compatibility: Use -nowarn instead of --nowarn"
 msgstr "Compatibilidade: Utilize -nowarn ao invés de --nowarn"
 
-#: mcs/mcs/driver.cs:700
+#: mcs/mcs/driver.cs:708
 msgid "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL"
 msgstr "Compatibilidade: Utilize -warn:NÍVEL ao invés de --wlevel NÍVEL"
 
-#: mcs/mcs/driver.cs:704
+#: mcs/mcs/driver.cs:712
 msgid "--wlevel requires a value from 0 to 4"
 msgstr "--wlevel requer um valor de 0 a 4"
 
-#: mcs/mcs/driver.cs:713
+#: mcs/mcs/driver.cs:721
 msgid "--mcs-debug requires an argument"
 msgstr "--mcs-debug requer um argumento"
 
-#: mcs/mcs/driver.cs:720
+#: mcs/mcs/driver.cs:728
 msgid "Invalid argument to --mcs-debug"
 msgstr "Argumento inválido para --mcs-debug"
 
-#: mcs/mcs/driver.cs:730
+#: mcs/mcs/driver.cs:738
 msgid "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN"
 msgstr ""
 "Compatibilidade: Utilize a opção -recurse:PADRÂO ao invés de --recurse PADRÃO"
 
-#: mcs/mcs/driver.cs:732
+#: mcs/mcs/driver.cs:740
 msgid "--recurse requires an argument"
 msgstr "--recurse requer um argumento"
 
-#: mcs/mcs/driver.cs:743
+#: mcs/mcs/driver.cs:751
 msgid "Compatibility: Use -debug option instead of -g or --debug"
 msgstr "Compatibilidade: Utilize a opção -debug ao invés de -g ou --debug"
 
-#: mcs/mcs/driver.cs:748
+#: mcs/mcs/driver.cs:756
 msgid "Compatibility: Use -noconfig option instead of --noconfig"
 msgstr "Compatibilidade: Utilize a opção -noconfig ao invés de --noconfig"
 
-#: mcs/mcs/driver.cs:912
+#: mcs/mcs/driver.cs:920
 #, csharp-format
 msgid "Invalid conditional define symbol `{0}'"
 msgstr "Símbolo de definição condicional \"{0}\" inválido"
 
-#: mcs/mcs/driver.cs:963
+#: mcs/mcs/driver.cs:971
 #, csharp-format
 msgid ""
 "Invalid resource visibility option `{0}'. Use either `public' or `private' "
@@ -1741,16 +1741,16 @@ msgstr ""
 "Opção de visibilidade de recurso \"{0}\" inválida. Utilize, ao invés disto, "
 "\"public\" ou \"private\""
 
-#: mcs/mcs/driver.cs:969
+#: mcs/mcs/driver.cs:977
 #, csharp-format
 msgid "Wrong number of arguments for option `{0}'"
 msgstr "Número de argumentos incorreto para a opção \"{0}\""
 
-#: mcs/mcs/driver.cs:1007
+#: mcs/mcs/driver.cs:1015
 msgid "Cannot specify multiple aliases using single /reference option"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1035 mcs/mcs/driver.cs:1047
+#: mcs/mcs/driver.cs:1043 mcs/mcs/driver.cs:1055
 msgid ""
 "Cannot specify the `win32res' and the `win32ico' compiler option at the same "
 "time"
@@ -1758,12 +1758,12 @@ msgstr ""
 "Não se pode especificar as opções de compilador \"win32res\" e o \"win32ico"
 "\" ao mesmo tempo"
 
-#: mcs/mcs/driver.cs:1162
+#: mcs/mcs/driver.cs:1170
 #, csharp-format
 msgid "`{0}' is not a valid warning number"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1192
+#: mcs/mcs/driver.cs:1200
 #, fuzzy
 msgid ""
 "Invalid platform type for -platform. Valid options are `anycpu', `x86', "
@@ -1772,11 +1772,11 @@ msgstr ""
 "Tipo alvo inválido para -target. Opções válidas são \"exe\", \"winexe\", "
 "\"library\" ou \"module\""
 
-#: mcs/mcs/driver.cs:1212
+#: mcs/mcs/driver.cs:1220
 msgid "Invalid sdk version name"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1310
+#: mcs/mcs/driver.cs:1318
 #, fuzzy, csharp-format
 msgid ""
 "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or "
@@ -1785,43 +1785,43 @@ msgstr ""
 "Opção \"{0}\" inválida para /langversion. Este deve ser \"ISO-1\" ou \"ISO-2"
 "\" ou \"Default\""
 
-#: mcs/mcs/driver.cs:1330
+#: mcs/mcs/driver.cs:1338
 #, csharp-format
 msgid "Code page `{0}' is invalid or not installed"
 msgstr "Código de página \"{0}\" é inválido ou não está instalado"
 
-#: mcs/mcs/driver.cs:1345
+#: mcs/mcs/driver.cs:1353
 #, csharp-format
 msgid "Unrecognized command-line option: `{0}'"
 msgstr "Opção de linha de comando não reconhecida: \"{0}\""
 
-#: mcs/mcs/driver.cs:1350
+#: mcs/mcs/driver.cs:1358
 #, csharp-format
 msgid "Missing file specification for `{0}' option"
 msgstr ""
 
-#: mcs/mcs/driver.cs:1355
+#: mcs/mcs/driver.cs:1363
 #, fuzzy, csharp-format
 msgid "Missing argument for `{0}' option"
 msgstr "Argumento faltando para --linkres"
 
-#: mcs/mcs/driver.cs:1390
+#: mcs/mcs/driver.cs:1398
 #, fuzzy, csharp-format
 msgid "Invalid reference alias `{0}='. Missing filename"
 msgstr "Apelido de referência inválido"
 
-#: mcs/mcs/driver.cs:1395
+#: mcs/mcs/driver.cs:1403
 #, fuzzy, csharp-format
 msgid ""
 "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier"
 msgstr "Apelido externo inválido para /reference. Apelido \"'"
 
-#: mcs/mcs/driver.cs:1411
+#: mcs/mcs/driver.cs:1419
 #, csharp-format
 msgid "The resource identifier `{0}' has already been used in this assembly"
 msgstr "O identificador do recurso \"{0}\" já foi utilizado neste assembly"
 
-#: mcs/mcs/driver.cs:1472
+#: mcs/mcs/driver.cs:1480
 msgid ""
 "If no source files are specified you must specify the output file with -out:"
 msgstr ""
@@ -1906,7 +1906,7 @@ msgstr ""
 msgid "The operation in question is undefined on void pointers"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:438 mcs/mcs/statement.cs:2558 mcs/mcs/statement.cs:2560
+#: mcs/mcs/ecore.cs:438 mcs/mcs/statement.cs:2559 mcs/mcs/statement.cs:2561
 #, csharp-format
 msgid "Internal compiler error: {0}"
 msgstr ""
@@ -2098,7 +2098,7 @@ msgid ""
 msgstr ""
 "O tipo \"{0}\" não contém um construtor que aceite os argumentos \"{1}\""
 
-#: mcs/mcs/ecore.cs:4334
+#: mcs/mcs/ecore.cs:4332
 #, fuzzy, csharp-format
 msgid ""
 "Type `{0}' does not contain a member `{1}' and the best extension method "
@@ -2108,7 +2108,7 @@ msgstr ""
 "Tipo \"{0}\" não contém um membro \"{1}\" e o melhor método de extensão "
 "sobrecarregado \"{2}\" tem alguns argumentos inválidos"
 
-#: mcs/mcs/ecore.cs:4355
+#: mcs/mcs/ecore.cs:4353
 #, csharp-format
 msgid ""
 "The call is ambiguous between the following methods or properties: `{0}' and "
@@ -2117,7 +2117,7 @@ msgstr ""
 "Essa chamada é ambígua entre os seguintes métodos ou propriedades: \"{0}\" e "
 "\"{1}\""
 
-#: mcs/mcs/ecore.cs:4415
+#: mcs/mcs/ecore.cs:4413
 #, csharp-format
 msgid ""
 "The best overloaded collection initalizer method `{0}' cannot have 'ref', or "
@@ -2126,7 +2126,7 @@ msgstr ""
 "O melhor método sobrecarregado de coleção \"{0}\" não pode ter o modificador "
 "\"ref\" ou \"out\""
 
-#: mcs/mcs/ecore.cs:4419
+#: mcs/mcs/ecore.cs:4417
 #, csharp-format
 msgid ""
 "The best overloaded collection initalizer method `{0}' has some invalid "
@@ -2135,18 +2135,18 @@ msgstr ""
 "O melhor método sobrecarregado inicializador de coleção \"{0}\" tem alguns "
 "argumentos inválidos"
 
-#: mcs/mcs/ecore.cs:4422
+#: mcs/mcs/ecore.cs:4420
 #, csharp-format
 msgid "Delegate `{0}' has some invalid arguments"
 msgstr "Delegate \"{0}\" tem alguns argumentos inválidos"
 
-#: mcs/mcs/ecore.cs:4426
+#: mcs/mcs/ecore.cs:4424
 #, csharp-format
 msgid "The best overloaded method match for `{0}' has some invalid arguments"
 msgstr ""
 "O melhor método sobrecarregado para \"{0}\" tem alguns argumentos inválidos"
 
-#: mcs/mcs/ecore.cs:4436
+#: mcs/mcs/ecore.cs:4434
 #, csharp-format
 msgid ""
 "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' "
@@ -2155,18 +2155,18 @@ msgstr ""
 "Argumento \"#{0}\" não requer o modificador \"{1}\". Considere remover o "
 "modificador \"{1}\""
 
-#: mcs/mcs/ecore.cs:4439
+#: mcs/mcs/ecore.cs:4437
 #, csharp-format
 msgid "Argument `#{0}' is missing `{1}' modifier"
 msgstr "Argumento \"#{0}\" não encontrou o modificador \"{1}\""
 
-#: mcs/mcs/ecore.cs:4452
+#: mcs/mcs/ecore.cs:4450
 #, csharp-format
 msgid "Argument `#{0}' cannot convert `{1}' expression to type `{2}'"
 msgstr ""
 "Argumento \"#{0}\" não pôde converter a expressão \"{1}\" para o tipo \"{2}\""
 
-#: mcs/mcs/ecore.cs:4500
+#: mcs/mcs/ecore.cs:4498
 #, csharp-format
 msgid ""
 "The type arguments for method `{0}' cannot be inferred from the usage. Try "
@@ -2175,17 +2175,17 @@ msgstr ""
 "O argumentos de tipo para o método \"{0}\" não pôde ser inferido do uso. "
 "Tente especificar os tipos dos argumentos explicitamente"
 
-#: mcs/mcs/ecore.cs:4529
+#: mcs/mcs/ecore.cs:4527
 #, csharp-format
 msgid "No overload for method `{0}' takes `{1}' arguments"
 msgstr "Sem sobrecarga para o método \"{0}\" aceitar os argumentos \"{1}\""
 
-#: mcs/mcs/ecore.cs:4582
+#: mcs/mcs/ecore.cs:4580
 #, fuzzy, csharp-format
 msgid "The delegate `{0}' does not contain a parameter named `{1}'"
 msgstr "O tipo aninhado \"{0}\" não existe no tipo \"{1}\""
 
-#: mcs/mcs/ecore.cs:4587
+#: mcs/mcs/ecore.cs:4585
 #, fuzzy, csharp-format
 msgid ""
 "The best overloaded method match for `{0}' does not contain a parameter "
@@ -2193,14 +2193,14 @@ msgid ""
 msgstr ""
 "O melhor método sobrecarregado para \"{0}\" tem alguns argumentos inválidos"
 
-#: mcs/mcs/ecore.cs:4597
+#: mcs/mcs/ecore.cs:4595
 #, csharp-format
 msgid ""
 "Named argument `{0}' cannot be used for a parameter which has positional "
 "argument specified"
 msgstr ""
 
-#: mcs/mcs/ecore.cs:4910
+#: mcs/mcs/ecore.cs:4908
 msgid ""
 "You cannot use fixed size buffers contained in unfixed expressions. Try "
 "using the fixed statement"
@@ -2208,28 +2208,28 @@ msgstr ""
 "Você não pode usar buffers de tamanho fixo contidos em expressões não "
 "fixadas. Tente utilizar a declaração fixa"
 
-#: mcs/mcs/ecore.cs:4915
+#: mcs/mcs/ecore.cs:4913
 #, csharp-format
 msgid "`{0}': Fixed size buffers can only be accessed through locals or fields"
 msgstr ""
 "\"{0}\": Buffers de tamanho fixo podem apenas ser acessados atravéis de "
 "locais ou campos"
 
-#: mcs/mcs/ecore.cs:5310
+#: mcs/mcs/ecore.cs:5308
 #, fuzzy, csharp-format
 msgid "Property or event `{0}' is not supported by the C# language"
 msgstr ""
 "A propriedade \"{0}\" não tem suporte na linguagem C#. Tente chamar o método "
 "acessor \"{1}\" diretamente"
 
-#: mcs/mcs/ecore.cs:5471
+#: mcs/mcs/ecore.cs:5469
 #, csharp-format
 msgid "A range variable `{0}' may not be passes as `ref' or `out' parameter"
 msgstr ""
 "Uma variável de intervalo \"{0}\" não deve ser passada como parâmetros \"ref"
 "\" ou \"out\""
 
-#: mcs/mcs/ecore.cs:5519
+#: mcs/mcs/ecore.cs:5517
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because it "
@@ -2238,7 +2238,7 @@ msgstr ""
 "A propriedade ou indexador \"{0}\" não pôde ser utilizada nesse contexto "
 "porque falta o acessor \"get\""
 
-#: mcs/mcs/ecore.cs:5526
+#: mcs/mcs/ecore.cs:5524
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because the get "
@@ -2247,14 +2247,14 @@ msgstr ""
 "A propriedade ou indexador \"{0}\" não pôde ser utilizada nesse contexto "
 "porque o acessor get está inacessível"
 
-#: mcs/mcs/ecore.cs:5545
+#: mcs/mcs/ecore.cs:5543
 #, fuzzy, csharp-format
 msgid "Property or indexer `{0}' cannot be assigned to (it is read-only)"
 msgstr ""
 "Propriedade ou indexador \"{0}\" não pôde ser atribuida (ela é somente "
 "leitura)"
 
-#: mcs/mcs/ecore.cs:5553
+#: mcs/mcs/ecore.cs:5551
 #, csharp-format
 msgid ""
 "The property or indexer `{0}' cannot be used in this context because the set "
@@ -2263,7 +2263,7 @@ msgstr ""
 "A propriedade ou indexador \"{0}\" não pôde ser utilizada neste contexto por "
 "que o acessor do conjunto está inacessível"
 
-#: mcs/mcs/ecore.cs:5714
+#: mcs/mcs/ecore.cs:5712
 #, csharp-format
 msgid ""
 "The event `{0}' can only appear on the left hand side of `+=' or `-=' "
@@ -2272,7 +2272,7 @@ msgstr ""
 "O evento \"{0}\" pode apenas aparecer no lado esquerdo do operador \"+=\" ou "
 "\"-=\""
 
-#: mcs/mcs/ecore.cs:5718
+#: mcs/mcs/ecore.cs:5716
 #, csharp-format
 msgid ""
 "The event `{0}' can only appear on the left hand side of += or -= when used "
@@ -2281,7 +2281,7 @@ msgstr ""
 "O evento \"{0}\" pode apenas aparecer no lado esquerdo do operador += ou -= "
 "quando utilizado fora do tipo \"{1}\""
 
-#: mcs/mcs/ecore.cs:5882
+#: mcs/mcs/ecore.cs:5880
 #, csharp-format
 msgid ""
 "An implicitly typed local variable declaration cannot be initialized with `"
@@ -2290,7 +2290,7 @@ msgstr ""
 "Uma declaração de variável local tipada implicitamente não pode ser "
 "inicializada com \"{0}\""
 
-#: mcs/mcs/ecore.cs:5896
+#: mcs/mcs/ecore.cs:5894
 msgid ""
 "The contextual keyword `var' may only appear within a local variable "
 "declaration"
@@ -2315,7 +2315,7 @@ msgstr "Um ítem em uma enumeração não pode ter um identificador \"{0}\""
 msgid "Type byte, sbyte, short, ushort, int, uint, long or ulong expected"
 msgstr "Tipo byte, sbyte, short, ushort, int, uint, long ou ulong esperado"
 
-#: mcs/mcs/eval.cs:626
+#: mcs/mcs/eval.cs:643
 msgid "Detection Parsing Error"
 msgstr "Erro na Análise de Detecção"
 
@@ -2561,7 +2561,7 @@ msgid "Cannot create an array with a negative size"
 msgstr "Não foi possível criar um array com um tamanho negativo"
 
 #: mcs/mcs/expression.cs:6096 mcs/mcs/expression.cs:6104
-#: mcs/mcs/statement.cs:1009 mcs/mcs/statement.cs:3055
+#: mcs/mcs/statement.cs:1002 mcs/mcs/statement.cs:3056
 msgid "A constant value is expected"
 msgstr "Um valor constante é esperado"
 
@@ -2998,7 +2998,7 @@ msgid "Cannot yield in the body of a finally clause"
 msgstr "Não foi possível deixar no corpo uma cláusula final"
 
 #: mcs/mcs/flowanalysis.cs:927 mcs/mcs/flowanalysis.cs:943
-#: mcs/mcs/flowanalysis.cs:979 mcs/mcs/statement.cs:694
+#: mcs/mcs/flowanalysis.cs:979 mcs/mcs/statement.cs:687
 msgid "Control cannot leave the body of a finally clause"
 msgstr "O controle não pode deixar o corpo de uma cláusula final"
 
@@ -3199,7 +3199,7 @@ msgstr ""
 "genérico ou método \"{2}\". O tipo anulável \"{0}\" nunca satisfaz a "
 "restrição de interface do tipo \"{3}\""
 
-#: mcs/mcs/import.cs:1711
+#: mcs/mcs/import.cs:1712
 #, csharp-format
 msgid ""
 "The type `{0}' is defined in an assembly that is not referenced. Consider "
@@ -3232,7 +3232,7 @@ msgstr "__arglist não é permitida em parâmetros de listas de iteradores"
 msgid "Iterators cannot have unsafe parameters or yield types"
 msgstr "Iteradores não podem ter parâmetros inseguros ou tipos yield"
 
-#: mcs/mcs/iterators.cs:888 mcs/mcs/statement.cs:4324
+#: mcs/mcs/iterators.cs:888 mcs/mcs/statement.cs:4325
 msgid "Unsafe code may not appear in iterators"
 msgstr "Código inseguro não pode aparecer em iteradores"
 
@@ -3284,25 +3284,25 @@ msgid "A range variable `{0}' cannot be initialized with `{1}'"
 msgstr ""
 "Uma variável de intervalo \"{0}\" nâo pode ser inicializada com \"{1}\""
 
-#: mcs/mcs/linq.cs:750
+#: mcs/mcs/linq.cs:747
 #, csharp-format
 msgid "A range variable `{0}' conflicts with a previous declaration of `{0}'"
 msgstr ""
 "Uma variável de intervalo \"{0}\" conflita com um declaração anterior de "
 "\"{0}\""
 
-#: mcs/mcs/linq.cs:757
+#: mcs/mcs/linq.cs:754
 #, csharp-format
 msgid "A range variable `{0}' has already been declared in this scope"
 msgstr "Uma variável de intervalor \"{0}\" já foi declarada neste escopo"
 
-#: mcs/mcs/linq.cs:764
+#: mcs/mcs/linq.cs:761
 #, csharp-format
 msgid "A range variable `{0}' conflicts with a method type parameter"
 msgstr ""
 "Uma variável de intervalor \"{0}\" conflita com um método de tipo parâmetro"
 
-#: mcs/mcs/linq.cs:796
+#: mcs/mcs/linq.cs:793
 #, csharp-format
 msgid ""
 "A range variable `{0}' cannot be assigned to. Consider using `let' clause to "
@@ -3778,18 +3778,18 @@ msgstr ""
 msgid "The params parameter must be a single dimensional array"
 msgstr "O parâmetro params deve ser um array de uma dimensão"
 
-#: mcs/mcs/parameter.cs:288
+#: mcs/mcs/parameter.cs:301
 msgid "An out parameter cannot have the `In' attribute"
 msgstr "Um parâmetro externo não pode ter o atributo \"In\""
 
-#: mcs/mcs/parameter.cs:293
+#: mcs/mcs/parameter.cs:306
 msgid ""
 "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead"
 msgstr ""
 "Não use \"System.ParamArrayAttribute\". Ao invés disso, use a palavra chave "
 "\"params\""
 
-#: mcs/mcs/parameter.cs:300
+#: mcs/mcs/parameter.cs:313
 msgid ""
 "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and "
 "`Out' attributes or neither"
@@ -3797,61 +3797,73 @@ msgstr ""
 "Não foi possível especificar somente o atributo \"Out\" em um parâmetro ref. "
 "Utilize ambos os atributos \"In\" e \"Out\" ou nenhum"
 
-#: mcs/mcs/parameter.cs:310
+#: mcs/mcs/parameter.cs:324
 #, fuzzy, csharp-format
 msgid "Cannot specify `{0}' attribute on optional parameter `{1}'"
 msgstr ""
 "Não foi possível especificar o atributo \"DefaultMember\" no tipo contendo "
 "um indexador"
 
-#: mcs/mcs/parameter.cs:320
+#: mcs/mcs/parameter.cs:369
+#, csharp-format
+msgid "Method or delegate parameter cannot be of type `{0}'"
+msgstr "Método ou parâmetro delegate não pode ser do tipo \"{0}\""
+
+#: mcs/mcs/parameter.cs:379
+#, csharp-format
+msgid "`{0}': static types cannot be used as parameters"
+msgstr "\"{0}\": tipos estáticos não podem ser utilizados como parâmetros"
+
+#: mcs/mcs/parameter.cs:385
+#, fuzzy, csharp-format
+msgid "The extension method cannot be of type `{0}'"
+msgstr "O tipo do método de extenção não pode ser \"{0}\""
+
+#: mcs/mcs/parameter.cs:425
 #, fuzzy, csharp-format
 msgid ""
 "Argument of type `{0}' is not applicable for the DefaultParameterValue "
 "attribute"
 msgstr "Argumento do tipo \"{0}\" não é aplicável para o atributo DefaultValue"
 
-#: mcs/mcs/parameter.cs:323
+#: mcs/mcs/parameter.cs:429
 #, fuzzy, csharp-format
 msgid ""
 "The DefaultParameterValue attribute is not applicable on parameters of type `"
 "{0}'"
 msgstr "O atributo DefaultValue não é aplicável em parâmetros do tipo \"{0}\""
 
-#: mcs/mcs/parameter.cs:334
+#: mcs/mcs/parameter.cs:457
 msgid "The type of the default value should match the type of the parameter"
 msgstr "O tipo de valor padrão deve ter o mesmo tipo do parâmetro"
 
-#: mcs/mcs/parameter.cs:376
-#, csharp-format
-msgid "Method or delegate parameter cannot be of type `{0}'"
-msgstr "Método ou parâmetro delegate não pode ser do tipo \"{0}\""
+#: mcs/mcs/parameter.cs:602
+msgid "An expression tree parameter cannot use `ref' or `out' modifier"
+msgstr ""
+"Um parâmetro de árvore de expressão não pode usar modificadores \"ref\" ou "
+"\"out\""
 
-#: mcs/mcs/parameter.cs:386
+#: mcs/mcs/parameter.cs:1074
 #, csharp-format
-msgid "`{0}': static types cannot be used as parameters"
-msgstr "\"{0}\": tipos estáticos não podem ser utilizados como parâmetros"
-
-#: mcs/mcs/parameter.cs:392
-#, fuzzy, csharp-format
-msgid "The extension method cannot be of type `{0}'"
-msgstr "O tipo do método de extenção não pode ser \"{0}\""
+msgid "The parameter name `{0}' conflicts with a compiler generated name"
+msgstr ""
+"O nome do parâmetro \"{0}\" conflita com um nome gerado pelo compilador"
 
-#: mcs/mcs/parameter.cs:448
+#: mcs/mcs/parameter.cs:1220
 #, fuzzy, csharp-format
 msgid ""
 "The expression being assigned to optional parameter `{0}' must be a constant "
 "or default value"
 msgstr "A expressão sendo atribuída a \"{0}\" deve ser constante"
 
-#: mcs/mcs/parameter.cs:464
+#: mcs/mcs/parameter.cs:1237
 #, fuzzy, csharp-format
 msgid ""
 "The expression being assigned to nullable optional parameter `{0}' must be "
 "default value"
 msgstr "A expressão sendo atribuída a \"{0}\" deve ser constante"
 
-#: mcs/mcs/parameter.cs:472
+#: mcs/mcs/parameter.cs:1245
 #, fuzzy, csharp-format
 msgid ""
 "Optional parameter `{0}' of type `{1}' can only be initialized with `null'"
@@ -3859,7 +3871,7 @@ msgstr ""
 "A constante \"{0}\" do tipo de referência \"{1}\" só pode ser inicializada "
 "com null"
 
-#: mcs/mcs/parameter.cs:482
+#: mcs/mcs/parameter.cs:1256
 #, fuzzy, csharp-format
 msgid ""
 "Optional parameter expression of type `{0}' cannot be converted to parameter "
@@ -3868,18 +3880,6 @@ msgstr ""
 "Tipo de instância do método de extensão \"{0}\" não pode ser convertido para "
 "\"{1}\""
 
-#: mcs/mcs/parameter.cs:624
-msgid "An expression tree parameter cannot use `ref' or `out' modifier"
-msgstr ""
-"Um parâmetro de árvore de expressão não pode usar modificadores \"ref\" ou "
-"\"out\""
-
-#: mcs/mcs/parameter.cs:1096
-#, csharp-format
-msgid "The parameter name `{0}' conflicts with a compiler generated name"
-msgstr ""
-"O nome do parâmetro \"{0}\" conflita com um nome gerado pelo compilador"
-
 #: mcs/mcs/pending.cs:443
 #, csharp-format
 msgid ""
@@ -4012,7 +4012,7 @@ msgstr ""
 "Não foi possível definir o atributo \"IndexerName\" em um indexador marcado "
 "como sobrescrito"
 
-#: mcs/mcs/reflection.cs:239
+#: mcs/mcs/reflection.cs:255
 msgid "Could not access the key inside the container `"
 msgstr "Não foi possível acessar a chave dentro do tipo no qual está definido"
 
@@ -4040,13 +4040,13 @@ msgstr ""
 "Uma expressão lambda com um corpo de declarações não pode ser convertida "
 "para uma árvore de expressão"
 
-#: mcs/mcs/statement.cs:740
+#: mcs/mcs/statement.cs:733
 #, csharp-format
 msgid ""
 "An object of a type convertible to `{0}' is required for the return statement"
 msgstr ""
 
-#: mcs/mcs/statement.cs:753
+#: mcs/mcs/statement.cs:746
 #, csharp-format
 msgid ""
 "`{0}': A return keyword must not be followed by any expression when method "
@@ -4055,7 +4055,7 @@ msgstr ""
 "\"{0}\": Uma palavra chave return não deve ser seguida por nenhuma expressão "
 "quando o método retornar void"
 
-#: mcs/mcs/statement.cs:778
+#: mcs/mcs/statement.cs:771
 #, csharp-format
 msgid ""
 "Cannot convert `{0}' to delegate type `{1}' because some of the return types "
@@ -4065,7 +4065,7 @@ msgstr ""
 "alguns dos tipos de retorno no bloco não são implicitamente conversíveis no "
 "tipo de retorno delegate"
 
-#: mcs/mcs/statement.cs:806
+#: mcs/mcs/statement.cs:799
 msgid ""
 "Cannot return a value from iterators. Use the yield return statement to "
 "return a value, or yield break to end the iteration"
@@ -4073,32 +4073,32 @@ msgstr ""
 "Não foi possível devolver um valor de iteradores. Use a declaração yield do "
 "return para devolver um valor, ou yield break para terminar a iteração"
 
-#: mcs/mcs/statement.cs:963 mcs/mcs/statement.cs:997
+#: mcs/mcs/statement.cs:956 mcs/mcs/statement.cs:990
 msgid "A goto case is only valid inside a switch statement"
 msgstr "Um case do goto é válido somente dentro de uma declaração switch"
 
-#: mcs/mcs/statement.cs:1076 mcs/mcs/statement.cs:4726
+#: mcs/mcs/statement.cs:1069 mcs/mcs/statement.cs:4727
 msgid "The type caught or thrown must be derived from System.Exception"
 msgstr ""
 
-#: mcs/mcs/statement.cs:1298
+#: mcs/mcs/statement.cs:1291
 msgid "A fixed statement cannot use an implicitly typed local variable"
 msgstr ""
 "Uma declaração fixa não pode utilizar uma variável local tipada "
 "implicitamente"
 
-#: mcs/mcs/statement.cs:1303
+#: mcs/mcs/statement.cs:1296
 msgid "An implicitly typed local variable cannot be a constant"
 msgstr "Uma variável local implicitamente tipada não pode ser uma constante"
 
-#: mcs/mcs/statement.cs:1308
+#: mcs/mcs/statement.cs:1301
 msgid ""
 "An implicitly typed local variable declarator must include an initializer"
 msgstr ""
 "Uma declaração de variável local tipada implicitamente deve incluir um "
 "inicializador"
 
-#: mcs/mcs/statement.cs:1313
+#: mcs/mcs/statement.cs:1306
 msgid ""
 "An implicitly typed local variable declaration cannot include multiple "
 "declarators"
@@ -4106,7 +4106,7 @@ msgstr ""
 "Uma declaração de variável local tipada implicitamente não pode incluir "
 "múltiplos declaradores"
 
-#: mcs/mcs/statement.cs:1883
+#: mcs/mcs/statement.cs:1876
 #, csharp-format
 msgid ""
 "A local variable named `{0}' cannot be declared in this scope because it "
@@ -4117,30 +4117,30 @@ msgstr ""
 "esta daria um significado distinto para \"{0}\", que já é usada em um escopo "
 "\"{1}\" para denotar outra coisa"
 
-#: mcs/mcs/statement.cs:1894
+#: mcs/mcs/statement.cs:1887
 #, csharp-format
 msgid ""
 "`{0}': An anonymous type cannot have multiple properties with the same name"
 msgstr ""
 "\"{0}\": Um tipo anônimo não pode ter múltiplas propriedades com o mesmo nome"
 
-#: mcs/mcs/statement.cs:1897
+#: mcs/mcs/statement.cs:1890
 #, csharp-format
 msgid "The parameter name `{0}' is a duplicate"
 msgstr "O nome do parâmetro \"{0}\" é uma duplicata"
 
-#: mcs/mcs/statement.cs:1904
+#: mcs/mcs/statement.cs:1897
 #, csharp-format
 msgid "A local variable named `{0}' is already defined in this scope"
 msgstr "Uma variável local nomeada \"{0}\" já foi definida neste escopo"
 
-#: mcs/mcs/statement.cs:1910
+#: mcs/mcs/statement.cs:1903
 #, fuzzy, csharp-format
 msgid ""
 "The type parameter name `{0}' is the same as local variable or parameter name"
 msgstr "O nome do tipo parâmetro \"{0}\" é o mesmo que \"{1}\""
 
-#: mcs/mcs/statement.cs:2482
+#: mcs/mcs/statement.cs:2477
 #, csharp-format
 msgid ""
 "The out parameter `{0}' must be assigned to before control leaves the "
@@ -4149,60 +4149,60 @@ msgstr ""
 "O parâmetro externo \"{0}\" deve estar atribuída para antes que o controle "
 "deixe o método atual"
 
-#: mcs/mcs/statement.cs:2573
+#: mcs/mcs/statement.cs:2574
 #, csharp-format
 msgid "`{0}': not all code paths return a value"
 msgstr "\"{0}\": nem todos caminhos de códigos devolvem um valor"
 
-#: mcs/mcs/statement.cs:2577
+#: mcs/mcs/statement.cs:2578
 #, csharp-format
 msgid "Not all code paths return a value in anonymous method of type `{0}'"
 msgstr ""
 "Nem todos os caminhos de código devolvem um valor num método anônimo do tipo "
 "\"{0}\""
 
-#: mcs/mcs/statement.cs:2748
+#: mcs/mcs/statement.cs:2749
 #, csharp-format
 msgid "The label `{0}' is a duplicate"
 msgstr "O rótulo \"{0}\" é uma duplicata"
 
-#: mcs/mcs/statement.cs:2757 mcs/mcs/statement.cs:2768
+#: mcs/mcs/statement.cs:2758 mcs/mcs/statement.cs:2769
 #, csharp-format
 msgid ""
 "The label `{0}' shadows another label by the same name in a contained scope"
 msgstr ""
 "O rótulo \"{0}\" esconde outro rótulo pelo mesmo nome em um escopo contido"
 
-#: mcs/mcs/statement.cs:3088
+#: mcs/mcs/statement.cs:3089
 #, csharp-format
 msgid "The label `case {0}:' already occurs in this switch statement"
 msgstr "O rótulo \"case {0}:\" já ocorre nesta declaração de switch"
 
-#: mcs/mcs/statement.cs:3629
+#: mcs/mcs/statement.cs:3630
 #, csharp-format
 msgid ""
 "A switch expression of type `{0}' cannot be converted to an integral type, "
 "bool, char, string, enum or nullable type"
 msgstr ""
 
-#: mcs/mcs/statement.cs:4114
+#: mcs/mcs/statement.cs:4115
 #, csharp-format
 msgid "`{0}' is not a reference type as required by the lock statement"
 msgstr ""
 "\"{0}\" não é um tipo de referência como necessário para a declaração lock"
 
-#: mcs/mcs/statement.cs:4455
+#: mcs/mcs/statement.cs:4456
 msgid "The type of locals declared in a fixed statement must be a pointer type"
 msgstr ""
 "O tipo de locais declarados em uma declaração fixa devem ser tipos ponteiros"
 
-#: mcs/mcs/statement.cs:4471
+#: mcs/mcs/statement.cs:4472
 msgid ""
 "The right hand side of a fixed statement assignment may not be a cast "
 "expression"
 msgstr "O lado direito de uma declaração fixa não deve ser uma expressão cast"
 
-#: mcs/mcs/statement.cs:4542
+#: mcs/mcs/statement.cs:4543
 msgid ""
 "You cannot use the fixed statement to take the address of an already fixed "
 "expression"
@@ -4210,7 +4210,7 @@ msgstr ""
 "Você não pode usar a declaração fixa para pegar o endereço de uma expressão "
 "já fixa"
 
-#: mcs/mcs/statement.cs:4856
+#: mcs/mcs/statement.cs:4857
 #, csharp-format
 msgid ""
 "A previous catch clause already catches all exceptions of this or a super "
@@ -4219,7 +4219,7 @@ msgstr ""
 "Uma cláusula catch anterior já pega todas as exceções do this ou um tipo "
 "super \"{0}\""
 
-#: mcs/mcs/statement.cs:5029
+#: mcs/mcs/statement.cs:5030
 #, csharp-format
 msgid ""
 "`{0}': type used in a using statement must be implicitly convertible to "
@@ -4228,7 +4228,7 @@ msgstr ""
 "\"{0}\": tipo utilizado em uma declaração em uso deve ser implicitamente "
 "conversível para \"System.IDisposable\""
 
-#: mcs/mcs/statement.cs:5451
+#: mcs/mcs/statement.cs:5452
 #, csharp-format
 msgid ""
 "foreach statement requires that the return type `{0}' of `{1}' must have a "
@@ -4237,7 +4237,7 @@ msgstr ""
 "declaração do foreach requer que o tipo de retorno \"{0}\" de \"{1}\" deve "
 "ter um método apropriado público MoveNext e a propriedade pública Current"
 
-#: mcs/mcs/statement.cs:5491
+#: mcs/mcs/statement.cs:5492
 #, csharp-format
 msgid ""
 "foreach statement cannot operate on variables of type `{0}' because it "
@@ -4248,7 +4248,7 @@ msgstr ""
 "estas contém múltiplas implementações de \"{1}\". Tente um casting para uma "
 "implementação específica"
 
-#: mcs/mcs/statement.cs:5516
+#: mcs/mcs/statement.cs:5517
 #, fuzzy, csharp-format
 msgid ""
 "foreach statement cannot operate on variables of type `{0}' because it does "
@@ -4257,11 +4257,11 @@ msgstr ""
 "declaração do foreach não pode operar em variáveis do tipo \"{0}\" pois "
 "estas não contém uma definição para \"GetEnumerator\" ou não estão acessíveis"
 
-#: mcs/mcs/statement.cs:5722
+#: mcs/mcs/statement.cs:5723
 msgid "Use of null is not valid in this context"
 msgstr "Uso do null é inválido neste contexto"
 
-#: mcs/mcs/statement.cs:5732
+#: mcs/mcs/statement.cs:5733
 #, csharp-format
 msgid "Foreach statement cannot operate on a `{0}'"
 msgstr "Declaração do foreach não pode operar em um \"{0}\""
diff --git a/support/ChangeLog b/support/ChangeLog
index 45e9dfc..dd77a0f 100644
--- a/support/ChangeLog
+++ b/support/ChangeLog
@@ -1,3 +1,11 @@
+2011-02-12  Gonzalo Paniagua Javier  <gonzalo.mono at gmail.com>
+
+	[gzip] Allow partial flush
+
+	When Flush() is called explicitly, do a Z_PARTIAL_FLUSH to force
+	gzip into giving us whatever is available. Less efficient, but
+	compatible with MS.
+
 2010-11-14  Zoltan Varga  <vargaz at gmail.com>
 
 	Remove the unused and incomplete CMake build scripts for now.
diff --git a/support/zlib-helper.c b/support/zlib-helper.c
index 66b5866..6cfeb8c 100644
--- a/support/zlib-helper.c
+++ b/support/zlib-helper.c
@@ -42,6 +42,7 @@ gint CloseZStream (ZStream *zstream);
 gint Flush (ZStream *stream);
 gint ReadZStream (ZStream *stream, guchar *buffer, gint length);
 gint WriteZStream (ZStream *stream, guchar *buffer, gint length);
+static gint flush_internal (ZStream *stream, gboolean is_final);
 
 static void *
 z_alloc (void *opaque, gsize nitems, gsize item_size)
@@ -106,7 +107,7 @@ CloseZStream (ZStream *zstream)
 		if (zstream->stream->total_in > 0) {
 			do {
 				status = deflate (zstream->stream, Z_FINISH);
-				flush_status = Flush (zstream);
+				flush_status = flush_internal (zstream, TRUE);
 			} while (status == Z_OK); /* We want Z_STREAM_END or error here here */
 			if (status == Z_STREAM_END)
 				status = flush_status;
@@ -132,23 +133,36 @@ write_to_managed (ZStream *stream)
 	if (zs->avail_out != BUFFER_SIZE) {
 		n = stream->func (stream->buffer, BUFFER_SIZE - zs->avail_out, stream->gchandle);
 		zs->next_out = stream->buffer;
-		zs->avail_out =  BUFFER_SIZE;
+		zs->avail_out = BUFFER_SIZE;
 		if (n < 0)
 			return IO_ERROR;
 	}
 	return 0;
 }
 
-gint
-Flush (ZStream *stream)
+static gint
+flush_internal (ZStream *stream, gboolean is_final)
 {
+	gint status;
+
 	if (!stream->compress)
 		return 0;
 
+	if (!is_final) {
+		status = deflate (stream->stream, Z_PARTIAL_FLUSH);
+		if (status != Z_OK && status != Z_STREAM_END)
+			return status;
+	}
 	return write_to_managed (stream);
 }
 
 gint
+Flush (ZStream *stream)
+{
+	return flush_internal (stream, FALSE);
+}
+
+gint
 ReadZStream (ZStream *stream, guchar *buffer, gint length)
 {
 	gint n;
diff --git a/winconfig.h b/winconfig.h
new file mode 100644
index 0000000..fcd1425
--- /dev/null
+++ b/winconfig.h
@@ -0,0 +1,605 @@
+/* config.h.  Generated from config.h.in by configure.  */
+/* config.h.in.  Generated from configure.in by autoheader.  */
+
+/* The architecture this is running on */
+#if defined(_M_IA64)
+#define ARCHITECTURE "ia64"
+#elif defined(_M_AMD64)
+#define ARCHITECTURE "amd64"
+#elif defined(_M_IX86)
+#define ARCHITECTURE "x86"
+#else
+#error Unknown architecture
+#endif
+
+/*
+ * Features that are not required in the Windows port
+ */
+#define DISABLE_PORTABILITY 1
+
+/* Windows does not have symlinks */
+#define PLATFORM_NO_SYMLINKS 1
+
+/* String of disabled features */
+#define DISABLED_FEATURES "none"
+
+/* Disable AOT support */
+/* #undef DISABLE_AOT */
+
+/* Disable COM support */
+/* #undef DISABLE_COM */
+
+/* Disable runtime debugging support */
+/* #undef DISABLE_DEBUG */
+
+/* Disable System.Decimal support */
+/* #undef DISABLE_DECIMAL */
+
+/* Disable generics support */
+/* #undef DISABLE_GENERICS */
+
+/* Disable support for huge assemblies */
+/* #undef DISABLE_LARGE_CODE */
+
+/* Disable support debug logging */
+/* #undef DISABLE_LOGGING */
+
+/* Disable P/Invoke support */
+/* #undef DISABLE_PINVOKE */
+
+/* Disable default profiler support */
+/* #undef DISABLE_PROFILER */
+
+/* Disable reflection emit support */
+/* #undef DISABLE_REFLECTION_EMIT */
+
+/* Disable inter-process shared handles */
+/* #undef DISABLE_SHARED_HANDLES */
+
+/* Disable advanced SSA JIT optimizations */
+/* #undef DISABLE_SSA */
+
+/* Enable DTrace probes */
+/* #undef ENABLE_DTRACE */
+
+/* Has the 'aintl' function */
+/* #undef HAVE_AINTL */
+
+/* Supports C99 array initialization */
+/* #undef HAVE_ARRAY_ELEM_INIT */
+
+/* Define to 1 if you have the <attr/xattr.h> header file. */
+/* #undef HAVE_ATTR_XATTR_H */
+
+/* Define to 1 if you have the `backtrace_symbols' function. */
+/* #undef HAVE_BACKTRACE_SYMBOLS */
+
+/* Define to 1 if the system has the type `blkcnt_t'. */
+/* #undef HAVE_BLKCNT_T */
+
+/* Define to 1 if the system has the type `blksize_t'. */
+/* #undef HAVE_BLKSIZE_T */
+
+/* Have Boehm GC */
+#define HAVE_BOEHM_GC 1
+
+#define DEFAULT_GC_NAME "Boehm"
+
+/* Define to 1 if you have the <checklist.h> header file. */
+/* #undef HAVE_CHECKLIST_H */
+
+/* Have /dev/random */
+#define HAVE_CRYPT_RNG 1
+
+/* Define to 1 if you have the <curses.h> header file. */
+/* #undef HAVE_CURSES_H */
+
+/* Define to 1 if you have the <dirent.h> header file. */
+/* #define HAVE_DIRENT_H 1 */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+/* #undef HAVE_DLFCN_H */
+
+/* dlopen-based dynamic loader available */
+/* #undef HAVE_DL_LOADER */
+
+/* Define to 1 if you have the <elf.h> header file. */
+/* #undef HAVE_ELF_H */
+
+/* epoll supported */
+/* #undef HAVE_EPOLL */
+
+/* Define to 1 if you have the `epoll_ctl' function. */
+/* #undef HAVE_EPOLL_CTL */
+
+/* Define to 1 if you have the <execinfo.h> header file. */
+/* #undef HAVE_EXECINFO_H */
+
+/* Define to 1 if you have the `fgetgrent' function. */
+/* #undef HAVE_FGETGRENT */
+
+/* Define to 1 if you have the `fgetpwent' function. */
+/* #undef HAVE_FGETPWENT */
+
+/* Define to 1 if you have the `finite' function. */
+/* #undef HAVE_FINITE */
+
+/* Define to 1 if you have the <fstab.h> header file. */
+/* #undef HAVE_FSTAB_H */
+
+/* Define to 1 if you have the `fstatfs' function. */
+/* #undef HAVE_FSTATFS */
+
+/* Define to 1 if you have the `fstatvfs' function. */
+/* #undef HAVE_FSTATVFS */
+
+/* Have GC_enable */
+#define HAVE_GC_ENABLE 1
+
+/* Have GC_gcj_malloc */
+#define HAVE_GC_GCJ_MALLOC 1
+
+/* Define to 1 if you have the <gc/gc.h> header file. */
+/* #undef HAVE_GC_GC_H */
+
+/* Have gc.h */
+#define HAVE_GC_H 1
+
+/* Define to 1 if you have the `getdomainname' function. */
+/* #undef HAVE_GETDOMAINNAME */
+
+/* Define to 1 if you have the `getfsstat' function. */
+/* #undef HAVE_GETFSSTAT */
+
+/* Define to 1 if you have the `getgrgid_r' function. */
+/* #undef HAVE_GETGRGID_R */
+
+/* Define to 1 if you have the `getgrnam_r' function. */
+/* #undef HAVE_GETGRNAM_R */
+
+/* Have gethostbyname2_r */
+/* #undef HAVE_GETHOSTBYNAME2_R */
+
+/* Define to 1 if you have the `getpriority' function. */
+/* #undef HAVE_GETPRIORITY */
+
+/* Define to 1 if you have the `GetProcessId' function. */
+#if (_WIN32_WINNT >= 0x0502)
+#define HAVE_GETPROCESSID 1
+#endif
+
+/* Define to 1 if you have the `getpwnam_r' function. */
+/* #undef HAVE_GETPWNAM_R */
+
+/* Define to 1 if you have the `getpwuid_r' function. */
+/* #undef HAVE_GETPWUID_R */
+
+/* Define to 1 if you have the `getresuid' function. */
+/* #undef HAVE_GETRESUID */
+
+/* Define to 1 if you have the `getrusage' function. */
+/* #undef HAVE_GETRUSAGE */
+
+/* Define to 1 if you have the <grp.h> header file. */
+/* #undef HAVE_GRP_H */
+
+/* Define to 1 if you have the <ieeefp.h> header file. */
+/* #undef HAVE_IEEEFP_H */
+
+/* Define to 1 if you have the `inet_aton' function. */
+/* #undef HAVE_INET_ATON */
+
+/* Define to 1 if you have the `inet_pton' function. */
+/* #undef HAVE_INET_PTON */
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Have IPV6_PKTINFO */
+/* #undef HAVE_IPV6_PKTINFO */
+
+/* Have IP_DONTFRAGMENT */
+/* #undef HAVE_IP_DONTFRAGMENT */
+
+/* Have IP_MTU_DISCOVER */
+/* #undef HAVE_IP_MTU_DISCOVER */
+
+/* Have IP_PKTINFO */
+/* #undef HAVE_IP_PKTINFO */
+
+/* Define to 1 if you have the `isfinite' function. */
+/* #undef HAVE_ISFINITE */
+
+/* isinf available */
+#define HAVE_ISINF 1
+
+/* Define to 1 if you have the `kqueue' function. */
+/* #undef HAVE_KQUEUE */
+
+/* Have __thread keyword */
+/* #undef HAVE_KW_THREAD */
+
+/* Have large file support */
+/* #undef HAVE_LARGE_FILE_SUPPORT */
+
+/* Define to 1 if you have the `unwind' library (-lunwind). */
+/* #undef HAVE_LIBUNWIND */
+
+/* Define to 1 if you have the <linux/rtc.h> header file. */
+/* #undef HAVE_LINUX_RTC_H */
+
+/* Define to 1 if you have the `lutimes' function. */
+/* #undef HAVE_LUTIMES */
+
+/* Define to 1 if you have the `madvise' function. */
+/* #undef HAVE_MADVISE */
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mkstemp' function. */
+/* #undef HAVE_MKSTEMP */
+
+/* Define to 1 if you have the `mmap' function. */
+/* #undef HAVE_MMAP */
+
+/* The GC can move objects. */
+/* #undef HAVE_MOVING_COLLECTOR */
+
+/* Define to 1 if you have the `mremap' function. */
+/* #undef HAVE_MREMAP */
+
+/* Have MSG_NOSIGNAL */
+/* #undef HAVE_MSG_NOSIGNAL */
+
+/* Define to 1 if you have the <netdb.h> header file. */
+/* #undef HAVE_NETDB_H */
+
+/* Define to 1 if you have the <net/if.h> header file. */
+/* #undef HAVE_NET_IF_H */
+
+/* No GC support. */
+/* #undef HAVE_NULL_GC */
+
+/* Have oprofile support */
+/* #undef HAVE_OPROFILE */
+
+/* Define to 1 if you have the `poll' function. */
+/* #undef HAVE_POLL */
+
+/* Define to 1 if you have the <poll.h> header file. */
+/* #undef HAVE_POLL_H */
+
+/* Define to 1 if you have the `posix_fadvise' function. */
+/* #undef HAVE_POSIX_FADVISE */
+
+/* Define to 1 if you have the `posix_fallocate' function. */
+/* #undef HAVE_POSIX_FALLOCATE */
+
+/* Define to 1 if you have the `posix_madvise' function. */
+/* #undef HAVE_POSIX_MADVISE */
+
+/* Define to 1 if you have the `pthread_attr_getstack' function. */
+/* #undef HAVE_PTHREAD_ATTR_GETSTACK */
+
+/* Define to 1 if you have the `pthread_attr_get_np' function. */
+/* #undef HAVE_PTHREAD_ATTR_GET_NP */
+
+/* Define to 1 if you have the `pthread_attr_setstacksize' function. */
+/* #undef HAVE_PTHREAD_ATTR_SETSTACKSIZE */
+
+/* Define to 1 if you have the `pthread_getattr_np' function. */
+/* #undef HAVE_PTHREAD_GETATTR_NP */
+
+/* Define to 1 if you have the `pthread_get_stackaddr_np' function. */
+/* #undef HAVE_PTHREAD_GET_STACKADDR_NP */
+
+/* Define to 1 if you have the `pthread_get_stacksize_np' function. */
+/* #undef HAVE_PTHREAD_GET_STACKSIZE_NP */
+
+/* Define to 1 if you have the <pthread.h> header file. */
+/* #undef HAVE_PTHREAD_H */
+
+/* Define to 1 if you have the `pthread_mutex_timedlock' function. */
+/* #undef HAVE_PTHREAD_MUTEX_TIMEDLOCK */
+
+/* Define to 1 if you have the `remap_file_pages' function. */
+/* #undef HAVE_REMAP_FILE_PAGES */
+
+/* Define to 1 if you have the `sched_setaffinity' function. */
+/* #undef HAVE_SCHED_SETAFFINITY */
+
+/* Define to 1 if you have the <semaphore.h> header file. */
+/* #undef HAVE_SEMAPHORE_H */
+
+/* Define to 1 if you have the `sendfile' function. */
+/* #undef HAVE_SENDFILE */
+
+/* Define to 1 if you have the `setdomainname' function. */
+/* #undef HAVE_SETDOMAINNAME */
+
+/* Define to 1 if you have the `sethostid' function. */
+/* #undef HAVE_SETHOSTID */
+
+/* Define to 1 if you have the `setpriority' function. */
+/* #undef HAVE_SETPRIORITY */
+
+/* Define to 1 if you have the `setresuid' function. */
+/* #undef HAVE_SETRESUID */
+
+/* Using the simple generational GC. */
+/* #undef HAVE_SGEN_GC */
+
+/* Have signbit */
+/* #undef HAVE_SIGNBIT */
+
+/* Can get interface list */
+/* #undef HAVE_SIOCGIFCONF */
+
+/* sockaddr_in6 has sin6_len */
+/* #undef HAVE_SOCKADDR_IN6_SIN_LEN */
+
+/* sockaddr_in has sin_len */
+/* #undef HAVE_SOCKADDR_IN_SIN_LEN */
+
+/* Have socklen_t */
+/* #undef HAVE_SOCKLEN_T */
+
+/* Have SOL_IP */
+/* #undef HAVE_SOL_IP */
+
+/* Have SOL_IPV6 */
+/* #undef HAVE_SOL_IPV6 */
+
+/* Have SOL_TCP */
+/* #undef HAVE_SOL_TCP */
+
+/* Define to 1 if you have the `statfs' function. */
+/* #undef HAVE_STATFS */
+
+/* Define to 1 if you have the `statvfs' function. */
+/* #undef HAVE_STATVFS */
+
+/* Define to 1 if you have the <stdint.h> header file. */
+/* #define HAVE_STDINT_H 1 */
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the `stime' function. */
+/* #undef HAVE_STIME */
+
+/* Define to 1 if you have the `strerror_r' function. */
+/* #undef HAVE_STRERROR_R */
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if `d_off' is member of `struct dirent'. */
+/* #undef HAVE_STRUCT_DIRENT_D_OFF */
+
+/* Define to 1 if `d_reclen' is member of `struct dirent'. */
+/* #undef HAVE_STRUCT_DIRENT_D_RECLEN */
+
+/* Define to 1 if `d_type' is member of `struct dirent'. */
+/* #undef HAVE_STRUCT_DIRENT_D_TYPE */
+
+/* Have struct ip_mreq */
+#define HAVE_STRUCT_IP_MREQ 1
+
+/* Have struct ip_mreqn */
+/* #undef HAVE_STRUCT_IP_MREQN */
+
+/* Define to 1 if the system has the type `struct pollfd'. */
+/* #undef HAVE_STRUCT_POLLFD */
+
+/* Define to 1 if the system has the type `struct stat'. */
+/* #undef HAVE_STRUCT_STAT */
+
+/* Define to 1 if the system has the type `struct timeval'. */
+/* #undef HAVE_STRUCT_TIMEVAL */
+
+/* Define to 1 if the system has the type `struct timezone'. */
+/* #undef HAVE_STRUCT_TIMEZONE */
+
+/* Define to 1 if the system has the type `struct utimbuf'. */
+/* #undef HAVE_STRUCT_UTIMBUF */
+
+/* Define to 1 if the system has the type `suseconds_t'. */
+/* #undef HAVE_SUSECONDS_T */
+
+/* Define to 1 if you have the <syslog.h> header file. */
+/* #undef HAVE_SYSLOG_H */
+
+/* Define to 1 if you have the <sys/epoll.h> header file. */
+/* #undef HAVE_SYS_EPOLL_H */
+
+/* Define to 1 if you have the <sys/extattr.h> header file. */
+/* #undef HAVE_SYS_EXTATTR_H */
+
+/* Define to 1 if you have the <sys/filio.h> header file. */
+/* #undef HAVE_SYS_FILIO_H */
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+/* #undef HAVE_SYS_IOCTL_H */
+
+/* Define to 1 if you have the <sys/mkdev.h> header file. */
+/* #undef HAVE_SYS_MKDEV_H */
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+/* #undef HAVE_SYS_MMAN_H */
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+/* #undef HAVE_SYS_PARAM_H */
+
+/* Define to 1 if you have the <sys/poll.h> header file. */
+/* #undef HAVE_SYS_POLL_H */
+
+/* Define to 1 if you have the <sys/sdt.h> header file. */
+/* #undef HAVE_SYS_SDT_H */
+
+/* Define to 1 if you have the <sys/sendfile.h> header file. */
+/* #undef HAVE_SYS_SENDFILE_H */
+
+/* Define to 1 if you have the <sys/sockio.h> header file. */
+/* #undef HAVE_SYS_SOCKIO_H */
+
+/* Define to 1 if you have the <sys/statvfs.h> header file. */
+/* #undef HAVE_SYS_STATVFS_H */
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/syscall.h> header file. */
+/* #undef HAVE_SYS_SYSCALL_H */
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+/* #undef HAVE_SYS_TIME_H */
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/un.h> header file. */
+/* #undef HAVE_SYS_UN_H */
+
+/* Define to 1 if you have the <sys/utime.h> header file. */
+#define HAVE_SYS_UTIME_H 1
+
+/* Define to 1 if you have the <sys/vfstab.h> header file. */
+/* #undef HAVE_SYS_VFSTAB_H */
+
+/* Define to 1 if you have the <sys/wait.h> header file. */
+/* #undef HAVE_SYS_WAIT_H */
+
+/* Define to 1 if you have the <sys/xattr.h> header file. */
+/* #undef HAVE_SYS_XATTR_H */
+
+/* Define to 1 if you have the <termios.h> header file. */
+/* #undef HAVE_TERMIOS_H */
+
+/* Define to 1 if you have the <term.h> header file. */
+/* #undef HAVE_TERM_H */
+
+/* Have timezone variable */
+/* #undef HAVE_TIMEZONE */
+
+/* tld_model available */
+/* #undef HAVE_TLS_MODEL_ATTR */
+
+/* Have tm_gmtoff */
+/* #undef HAVE_TM_GMTOFF */
+
+/* Define to 1 if you have the `trunc' function. */
+#define HAVE_TRUNC 1
+
+/* Define to 1 if you have the `ttyname_r' function. */
+/* #undef HAVE_TTYNAME_R */
+
+/* Define to 1 if you have the <unistd.h> header file. */
+/* #define HAVE_UNISTD_H 1 */
+
+/* Define to 1 if you have the <utime.h> header file. */
+/* #define HAVE_UTIME_H 1 */
+
+/* Define to 1 if you have the <valgrind/memcheck.h> header file. */
+/* #undef HAVE_VALGRIND_MEMCHECK_H */
+
+/* Support for the visibility ("hidden") attribute */
+/* #define HAVE_VISIBILITY_HIDDEN 1 */
+
+/* Define to 1 if you have the `vsnprintf' function. */
+/* #undef HAVE_VSNPRINTF */
+
+/* Define to 1 if you have the <wchar.h> header file. */
+#define HAVE_WCHAR_H 1
+
+/* Have a working sigaltstack */
+/* #undef HAVE_WORKING_SIGALTSTACK */
+
+/* The GC needs write barriers. */
+/* #undef HAVE_WRITE_BARRIERS */
+
+/* Have system zlib */
+/* #define HAVE_ZLIB 1 */
+
+/* Architecture uses registers for Parameters */
+/* #undef MONO_ARCH_REGPARMS */
+
+/* Enable the allocation and indexing of arrays greater than Int32.MaxValue */
+/* #undef MONO_BIG_ARRAYS */
+
+/* The Mono Debugger is supported on this platform */
+/* #undef MONO_DEBUGGER_SUPPORTED */
+
+/* Sizeof sock_un.sun_path */
+/* #undef MONO_SIZEOF_SUNPATH */
+
+/* Xen-specific behaviour */
+#define MONO_XEN_OPT 1
+
+/* Length of zero length arrays */
+#define MONO_ZERO_LEN_ARRAY 1
+
+/* Name of /dev/random */
+#define NAME_DEV_RANDOM ""
+
+/* Define if Unix sockets cannot be created in an anonymous namespace */
+/* #undef NEED_LINK_UNLINK */
+
+/* Name of package */
+#define PACKAGE "mono"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "Hans_Boehm at hp.com"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libgc-mono"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libgc-mono 6.6"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libgc-mono"
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "6.6"
+
+/* Platform is Win32 */
+#define HOST_WIN32 1
+#define TARGET_WIN32 1
+
+/* pthread_t is a pointer */
+/* #undef PTHREAD_POINTER_ID */
+
+/* The size of `size_t', as computed by sizeof. */
+/* #undef SIZEOF_SIZE_T */
+
+/* The size of a `void *', as computed by sizeof. */
+#ifdef _WIN64
+#define SIZEOF_VOID_P 8
+#else
+#define SIZEOF_VOID_P 4
+#endif
+
+#define SIZEOF_REGISTER SIZEOF_VOID_P
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* GC description */
+#define USED_GC_NAME "Included Boehm (with typed GC)"
+
+/* Use included libgc */
+#define USE_INCLUDED_LIBGC 1
+
+/* ... */
+/* #undef USE_MACH_SEMA */
+
+/* Use mono_mutex_t */
+/* #undef USE_MONO_MUTEX */
+
+/* Version number of package */
+#define VERSION "2.10"

-- 
mono



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