diff options
author | Mark Spruiell <mes@zeroc.com> | 2011-05-09 16:24:52 -0700 |
---|---|---|
committer | Mark Spruiell <mes@zeroc.com> | 2011-05-09 16:24:52 -0700 |
commit | 5d7de7f8f909d7a4910531a077e514955a1b0fdc (patch) | |
tree | 77b437188795dab60de6fbc5212528b0d88c182f /cs/src | |
parent | Ice 3.4.2 installer updates (diff) | |
download | ice-5d7de7f8f909d7a4910531a077e514955a1b0fdc.tar.bz2 ice-5d7de7f8f909d7a4910531a077e514955a1b0fdc.tar.xz ice-5d7de7f8f909d7a4910531a077e514955a1b0fdc.zip |
merging .NET Compact Framework support
Diffstat (limited to 'cs/src')
45 files changed, 2085 insertions, 381 deletions
diff --git a/cs/src/Glacier2/Application.cs b/cs/src/Glacier2/Application.cs index f45ca47544d..e3460fd1a3e 100644 --- a/cs/src/Glacier2/Application.cs +++ b/cs/src/Glacier2/Application.cs @@ -189,7 +189,8 @@ public abstract class Application : Ice.Application throw new SessionNotExistException(); } - lock(this) + mutex__.Lock(); + try { if(_adapter == null) { @@ -197,6 +198,10 @@ public abstract class Application : Ice.Application _adapter.activate(); } } + finally + { + mutex__.Unlock(); + } return _adapter; } @@ -243,7 +248,8 @@ public abstract class Application : Ice.Application public void run() { - lock(this) + _m.Lock(); + try { while(!_done) { @@ -261,29 +267,39 @@ public abstract class Application : Ice.Application if(!_done) { - Monitor.Wait(this, (int)_period); + _m.TimedWait((int)_period); } } } + finally + { + _m.Unlock(); + } } public void done() { - lock(this) + _m.Lock(); + try { if(!_done) { _done = true; - Monitor.PulseAll(this); + _m.NotifyAll(); } } + finally + { + _m.Unlock(); + } } private Application _app; private Glacier2.RouterPrx _router; private long _period; private bool _done = false; + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); } protected override int @@ -434,11 +450,12 @@ public abstract class Application : Ice.Application ignoreInterrupt(); } - lock(mutex__) + mutex__.Lock(); + try { while(callbackInProgress__) { - Monitor.Wait(mutex__); + mutex__.Wait(); } if(destroyed__) @@ -455,6 +472,10 @@ public abstract class Application : Ice.Application // } } + finally + { + mutex__.Unlock(); + } if(ping != null) { @@ -462,6 +483,10 @@ public abstract class Application : Ice.Application ping = null; while(true) { +#if COMPACT + pingThread.Join(); + break; +#else try { pingThread.Join(); @@ -470,6 +495,7 @@ public abstract class Application : Ice.Application catch(ThreadInterruptedException) { } +#endif } pingThread = null; } diff --git a/cs/src/Glacier2/SessionHelper.cs b/cs/src/Glacier2/SessionHelper.cs index 4faaf4ab467..05e19d1ca58 100644 --- a/cs/src/Glacier2/SessionHelper.cs +++ b/cs/src/Glacier2/SessionHelper.cs @@ -56,7 +56,8 @@ public class SessionHelper public void run() { - lock(this) + _m.Lock(); + try { while(true) { @@ -74,13 +75,17 @@ public class SessionHelper if(!_done) { +#if COMPACT + _m.TimedWait(_period); +#else try { - System.Threading.Monitor.Wait(this, _period); + _m.TimedWait(_period); } catch(ThreadInterruptedException) { } +#endif } if(_done) @@ -89,25 +94,36 @@ public class SessionHelper } } } + finally + { + _m.Unlock(); + } } public void done() { - lock(this) + _m.Lock(); + try { if(!_done) { _done = true; - System.Threading.Monitor.Pulse(this); + _m.Notify(); } } + finally + { + _m.Unlock(); + } } private SessionHelper _session; private Glacier2.RouterPrx _router; private int _period; private bool _done = false; + + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); } /// <summary> @@ -430,6 +446,10 @@ public class SessionHelper sessionRefresh.done(); while(true) { +#if COMPACT + _refreshThread.Join(); + break; +#else try { _refreshThread.Join(); @@ -438,6 +458,7 @@ public class SessionHelper catch(ThreadInterruptedException) { } +#endif } _refreshThread = null; } @@ -511,8 +532,13 @@ public class SessionHelper })).Start(); } +#if COMPACT + private void + dispatchCallback(Ice.VoidAction callback, Ice.Connection conn) +#else private void dispatchCallback(System.Action callback, Ice.Connection conn) +#endif { if(_initData.dispatcher != null) { @@ -524,8 +550,13 @@ public class SessionHelper } } +#if COMPACT + private void + dispatchCallbackAndWait(Ice.VoidAction callback) +#else private void dispatchCallbackAndWait(System.Action callback) +#endif { if(_initData.dispatcher != null) { diff --git a/cs/src/Ice/Application.cs b/cs/src/Ice/Application.cs index b4e97a53cd8..bc27cc0ade7 100644 --- a/cs/src/Ice/Application.cs +++ b/cs/src/Ice/Application.cs @@ -18,14 +18,17 @@ namespace Ice internal static class NativeMethods { +#if !COMPACT // - // It's not necessary to wrap DllImport in conditional compilation. The binding occurs - // at run time, and it will never be executed on Mono. + // Technically it's not necessary to wrap DllImport in conditional compilation because + // the binding occurs at run time and it will never be executed on Mono. However, it + // causes problems for the Compact Framework. // [DllImport("kernel32.dll")] [return: MarshalAsAttribute(UnmanagedType.Bool)] internal static extern bool SetConsoleCtrlHandler(CtrlCEventHandler eh, [MarshalAsAttribute(UnmanagedType.Bool)]bool add); +#endif } /// <summary> @@ -204,6 +207,9 @@ namespace Ice int status; +#if COMPACT + status = doMain(args, initData); +#else if(signalPolicy__ == SignalPolicy.HandleSignals) { if(IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows) @@ -224,6 +230,7 @@ namespace Ice { status = doMain(args, initData); } +#endif return status; } @@ -259,15 +266,20 @@ namespace Ice { if(signalPolicy__ == SignalPolicy.HandleSignals) { - lock(mutex__) + mutex__.Lock(); + try { if(_callback == _holdCallback) { released__ = true; - Monitor.Pulse(mutex__); + mutex__.Notify(); } _callback = _destroyCallback; } + finally + { + mutex__.Unlock(); + } } else { @@ -283,15 +295,20 @@ namespace Ice { if(signalPolicy__ == SignalPolicy.HandleSignals) { - lock(mutex__) + mutex__.Lock(); + try { if(_callback == _holdCallback) { released__ = true; - Monitor.Pulse(mutex__); + mutex__.Notify(); } _callback = _shutdownCallback; } + finally + { + mutex__.Unlock(); + } } else { @@ -307,15 +324,20 @@ namespace Ice { if(signalPolicy__ == SignalPolicy.HandleSignals) { - lock(mutex__) + mutex__.Lock(); + try { if(_callback == _holdCallback) { released__ = true; - Monitor.Pulse(mutex__); + mutex__.Notify(); } _callback = null; } + finally + { + mutex__.Unlock(); + } } else { @@ -332,15 +354,20 @@ namespace Ice { if(signalPolicy__ == SignalPolicy.HandleSignals) { - lock(mutex__) + mutex__.Lock(); + try { if(_callback == _holdCallback) { released__ = true; - Monitor.Pulse(mutex__); + mutex__.Notify(); } _callback = _userCallback; } + finally + { + mutex__.Unlock(); + } } else { @@ -356,7 +383,8 @@ namespace Ice { if(signalPolicy__ == SignalPolicy.HandleSignals) { - lock(mutex__) + mutex__.Lock(); + try { if(_callback != _holdCallback) { @@ -366,6 +394,10 @@ namespace Ice } // else, we were already holding signals } + finally + { + mutex__.Unlock(); + } } else { @@ -382,7 +414,8 @@ namespace Ice { if(signalPolicy__ == SignalPolicy.HandleSignals) { - lock(mutex__) + mutex__.Lock(); + try { if(_callback == _holdCallback) { @@ -395,10 +428,14 @@ namespace Ice released__ = true; _callback = _previousCallback; - Monitor.Pulse(mutex__); + mutex__.Notify(); } // Else nothing to release. } + finally + { + mutex__.Unlock(); + } } else { @@ -414,10 +451,15 @@ namespace Ice /// <returns>True if a signal caused the communicator to shut down; false otherwise.</returns> public static bool interrupted() { - lock(mutex__) + mutex__.Lock(); + try { return interrupted__; } + finally + { + mutex__.Unlock(); + } } protected virtual int doMain(string[] args, InitializationData initData) @@ -474,11 +516,12 @@ namespace Ice ignoreInterrupt(); } - lock(mutex__) + mutex__.Lock(); + try { while(callbackInProgress__) { - Monitor.Wait(mutex__); + mutex__.Wait(); } if(destroyed__) { @@ -495,6 +538,10 @@ namespace Ice } _application = null; } + finally + { + mutex__.Unlock(); + } if(communicator__ != null) { @@ -524,10 +571,17 @@ namespace Ice private static void signalHandler(int sig) { Callback callback; - lock(mutex__) + + mutex__.Lock(); + try { callback = _callback; } + finally + { + mutex__.Unlock(); + } + if(callback != null) { try @@ -547,11 +601,12 @@ namespace Ice private static void holdInterruptCallback(int sig) { Callback callback = null; - lock(mutex__) + mutex__.Lock(); + try { while(!released__) { - Monitor.Wait(mutex__); + mutex__.Wait(); } if(destroyed__) @@ -564,6 +619,10 @@ namespace Ice callback = _callback; } + finally + { + mutex__.Unlock(); + } if(callback != null) { @@ -576,7 +635,8 @@ namespace Ice // private static void destroyOnInterruptCallback(int sig) { - lock(mutex__) + mutex__.Lock(); + try { if(destroyed__) { @@ -595,6 +655,10 @@ namespace Ice interrupted__ = true; destroyed__ = true; } + finally + { + mutex__.Unlock(); + } try { @@ -606,16 +670,22 @@ namespace Ice Util.getProcessLogger().error("(while destroying in response to signal " + sig + "):\n" + ex); } - lock(mutex__) + mutex__.Lock(); + try { callbackInProgress__ = false; - Monitor.Pulse(mutex__); + mutex__.Notify(); + } + finally + { + mutex__.Unlock(); } } private static void shutdownOnInterruptCallback(int sig) { - lock(mutex__) + mutex__.Lock(); + try { if(destroyed__) { @@ -633,6 +703,10 @@ namespace Ice callbackInProgress__ = true; interrupted__ = true; } + finally + { + mutex__.Unlock(); + } try { @@ -644,16 +718,22 @@ namespace Ice Util.getProcessLogger().error("(while shutting down in response to signal " + sig + "):\n" + ex); } - lock(mutex__) + mutex__.Lock(); + try { callbackInProgress__ = false; - Monitor.Pulse(mutex__); + mutex__.Notify(); + } + finally + { + mutex__.Unlock(); } } private static void userCallbackOnInterruptCallback(int sig) { - lock(mutex__) + mutex__.Lock(); + try { if(destroyed__) { @@ -668,6 +748,10 @@ namespace Ice callbackInProgress__ = true; interrupted__ = true; } + finally + { + mutex__.Unlock(); + } try { @@ -679,14 +763,19 @@ namespace Ice Util.getProcessLogger().error("(while interrupting in response to signal " + sig + "):\n" + ex); } - lock(mutex__) + mutex__.Lock(); + try { callbackInProgress__ = false; - Monitor.Pulse(mutex__); + mutex__.Notify(); + } + finally + { + mutex__.Unlock(); } } - protected static readonly object mutex__ = new object(); + protected static readonly IceUtilInternal.Monitor mutex__ = new IceUtilInternal.Monitor(); protected static bool callbackInProgress__ = false; protected static bool destroyed__ = false; @@ -727,6 +816,7 @@ namespace Ice private delegate void SignalHandler(int sig); private static readonly SignalHandler _handler = new SignalHandler(signalHandler); +#if !COMPACT private Signals _signals; private interface Signals @@ -816,9 +906,9 @@ namespace Ice _handler(sig); return true; } - #endif } +#endif } delegate bool CtrlCEventHandler(int sig); diff --git a/cs/src/Ice/AssemblyUtil.cs b/cs/src/Ice/AssemblyUtil.cs index 41b7b5ab717..389669de568 100644 --- a/cs/src/Ice/AssemblyUtil.cs +++ b/cs/src/Ice/AssemblyUtil.cs @@ -12,6 +12,7 @@ namespace IceInternal using System; using System.Collections; + using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading; @@ -55,6 +56,32 @@ namespace IceInternal xp_ = v.Major == 5 && v.Minor == 1; // Are we running on XP? osx_ = false; + +#if COMPACT + // + // Populate the _iceAssemblies list with the fully-qualified names + // of the standard Ice assemblies. The fully-qualified name looks + // like this: + // + // Ice, Version=X.Y.Z.0, Culture=neutral, PublicKeyToken=... + // + string name = Assembly.GetExecutingAssembly().FullName; + _iceAssemblies.Add(name); + int pos = name.IndexOf(','); + if(pos >= 0 && pos < name.Length - 1) + { + // + // Strip off the leading assembly name and use the remainder of the + // string to compose the names of the other standard assemblies. + // + string suffix = name.Substring(pos + 1); + _iceAssemblies.Add("Glacier2," + suffix); + _iceAssemblies.Add("IceBox," + suffix); + _iceAssemblies.Add("IceGrid," + suffix); + _iceAssemblies.Add("IcePatch2," + suffix); + _iceAssemblies.Add("IceStorm," + suffix); + } +#else if(platform_ == Platform.NonWindows) { try @@ -81,11 +108,14 @@ namespace IceInternal { } } +#endif } - public static Type findType(string csharpId) + public static Type findType(Instance instance, string csharpId) { +#if !COMPACT loadAssemblies(); // Lazy initialization +#endif lock(_mutex) { @@ -94,6 +124,33 @@ namespace IceInternal { return t; } +#if COMPACT + string[] assemblies = instance.factoryAssemblies(); + for(int i = 0; i < assemblies.Length; ++i) + { + string s = csharpId + "," + assemblies[i]; + if((t = Type.GetType(s)) != null) + { + _typeTable[csharpId] = t; + return t; + } + } + // + // As a last resort, look for the type in the standard Ice assemblies. + // This avoids the need for a program to set a property such as: + // + // Ice.FactoryAssemblies=Ice + // + foreach(string a in _iceAssemblies) + { + string s = csharpId + "," + a; + if((t = Type.GetType(s)) != null) + { + _typeTable[csharpId] = t; + return t; + } + } +#else foreach(Assembly a in _loadedAssemblies.Values) { if((t = a.GetType(csharpId)) != null) @@ -102,10 +159,12 @@ namespace IceInternal return t; } } +#endif } return null; } +#if !COMPACT public static Type[] findTypesWithPrefix(string prefix) { IceUtilInternal.LinkedList l = new IceUtilInternal.LinkedList(); @@ -134,6 +193,7 @@ namespace IceInternal } return result; } +#endif public static object createInstance(Type t) { @@ -156,6 +216,7 @@ namespace IceInternal return t.GetConstructor(constructor).Invoke(new object[]{}); } +#if !COMPACT // // Make sure that all assemblies that are referenced by this process // are actually loaded. This is necessary so we can use reflection @@ -208,6 +269,9 @@ namespace IceInternal private static bool _assembliesLoaded = false; private static Hashtable _loadedAssemblies = new Hashtable(); // <string, Assembly> pairs. +#else + private static List<string> _iceAssemblies = new List<string>(); +#endif private static Hashtable _typeTable = new Hashtable(); // <type name, Type> pairs. private static Mutex _mutex = new Mutex(); diff --git a/cs/src/Ice/AsyncIOThread.cs b/cs/src/Ice/AsyncIOThread.cs index 9b00acc8298..fbd06625de9 100644 --- a/cs/src/Ice/AsyncIOThread.cs +++ b/cs/src/Ice/AsyncIOThread.cs @@ -37,21 +37,31 @@ namespace IceInternal public void queue(ThreadPoolWorkItem callback) { - lock(this) + _m.Lock(); + try { Debug.Assert(!_destroyed); _queue.AddLast(callback); - Monitor.Pulse(this); + _m.Notify(); + } + finally + { + _m.Unlock(); } } public void destroy() { - lock(this) + _m.Lock(); + try { Debug.Assert(!_destroyed); _destroyed = true; - Monitor.Pulse(this); + _m.Notify(); + } + finally + { + _m.Unlock(); } } @@ -68,7 +78,8 @@ namespace IceInternal LinkedList<ThreadPoolWorkItem> queue = new LinkedList<ThreadPoolWorkItem>(); while(true) { - lock(this) + _m.Lock(); + try { if(_destroyed && _queue.Count == 0) { @@ -77,13 +88,17 @@ namespace IceInternal while(!_destroyed && _queue.Count == 0) { - Monitor.Wait(this); + _m.Wait(); } LinkedList<ThreadPoolWorkItem> tmp = queue; queue = _queue; _queue = tmp; } + finally + { + _m.Unlock(); + } foreach(ThreadPoolWorkItem cb in queue) { @@ -148,5 +163,6 @@ namespace IceInternal } private HelperThread _thread; + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); } } diff --git a/cs/src/Ice/BasicStream.cs b/cs/src/Ice/BasicStream.cs index 50c4dd12328..145077735e6 100644 --- a/cs/src/Ice/BasicStream.cs +++ b/cs/src/Ice/BasicStream.cs @@ -15,12 +15,14 @@ namespace IceInternal using System.Collections.Generic; using System.Diagnostics; using System.Reflection; +#if !COMPACT using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; +#endif using System.Threading; -#if !MANAGED +#if !MANAGED && !COMPACT internal static class NativeMethods { [DllImport("bzip2.dll")] @@ -50,7 +52,7 @@ namespace IceInternal static BasicStream() { -#if MANAGED +#if MANAGED || COMPACT // // Protocol compression is not supported when using managed code. // @@ -767,6 +769,7 @@ namespace IceInternal public virtual void writeSerializable(object o) { +#if !COMPACT if(o == null) { writeSize(0); @@ -783,6 +786,9 @@ namespace IceInternal { throw new Ice.MarshalException("cannot serialize object:", ex); } +#else + throw new Ice.MarshalException("serialization not supported"); +#endif } public virtual byte readByte() @@ -868,6 +874,7 @@ namespace IceInternal public virtual object readSerializable() { +#if !COMPACT int sz = readAndCheckSeqSize(1); if(sz == 0) { @@ -883,6 +890,9 @@ namespace IceInternal { throw new Ice.MarshalException("cannot deserialize object:", ex); } +#else + throw new Ice.MarshalException("serialization not supported"); +#endif } public virtual void writeBool(bool v) @@ -2509,7 +2519,7 @@ namespace IceInternal _readEncapsStack.patchMap.Remove(patchIndex); } -#if !MANAGED +#if !MANAGED && !COMPACT static string getBZ2Error(int error) { string rc; @@ -2578,7 +2588,7 @@ namespace IceInternal public bool compress(ref BasicStream cstream, int headerSize, int compressionLevel) { -#if MANAGED +#if MANAGED || COMPACT cstream = this; return false; #else @@ -2646,7 +2656,7 @@ namespace IceInternal public BasicStream uncompress(int headerSize) { -#if MANAGED +#if MANAGED || COMPACT return this; #else if(!_bzlibInstalled) @@ -2743,7 +2753,7 @@ namespace IceInternal try { - Type c = AssemblyUtil.findType(typeToClass(id)); + Type c = AssemblyUtil.findType(instance_, typeToClass(id)); if(c == null) { return null; @@ -2832,7 +2842,7 @@ namespace IceInternal { try { - Type c = AssemblyUtil.findType(typeToClass(id)); + Type c = AssemblyUtil.findType(instance_, typeToClass(id)); if(c == null) { return null; diff --git a/cs/src/Ice/ByteBuffer.cs b/cs/src/Ice/ByteBuffer.cs index 828d875e647..7f4034ea6ce 100644 --- a/cs/src/Ice/ByteBuffer.cs +++ b/cs/src/Ice/ByteBuffer.cs @@ -42,7 +42,7 @@ namespace IceInternal { if(capacity < 0) { - throw new ArgumentOutOfRangeException("capacity", capacity, "capacity must be non-negative"); + throwOutOfRange("capacity", capacity, "capacity must be non-negative"); } ByteBuffer ret = new ByteBuffer(); ret._position = 0; @@ -62,11 +62,11 @@ namespace IceInternal { if(pos < 0) { - throw new ArgumentOutOfRangeException("pos", pos, "position must be non-negative"); + throwOutOfRange("pos", pos, "position must be non-negative"); } if(pos > _limit) { - throw new ArgumentOutOfRangeException("pos", pos, "position must be less than limit"); + throwOutOfRange("pos", pos, "position must be less than limit"); } _position = pos; return this; @@ -81,11 +81,11 @@ namespace IceInternal { if(newLimit < 0) { - throw new ArgumentOutOfRangeException("newLimit", newLimit, "limit must be non-negative"); + throwOutOfRange("newLimit", newLimit, "limit must be non-negative"); } if(newLimit > _capacity) { - throw new ArgumentOutOfRangeException("newLimit", newLimit, "limit must be less than capacity"); + throwOutOfRange("newLimit", newLimit, "limit must be less than capacity"); } _limit = newLimit; return this; @@ -124,16 +124,15 @@ namespace IceInternal { if(startIndex < 0) { - throw new ArgumentOutOfRangeException("startIndex", startIndex, "startIndex must be non-negative"); + throwOutOfRange("startIndex", startIndex, "startIndex must be non-negative"); } if(startIndex >= _position) { - throw new ArgumentOutOfRangeException("startIndex", startIndex, - "startIndex must be less than position"); + throwOutOfRange("startIndex", startIndex, "startIndex must be less than position"); } if(length < 0) { - throw new ArgumentOutOfRangeException("length", length, "length must be non-negative"); + throwOutOfRange("length", length, "length must be non-negative"); } if(startIndex + length > _position) { @@ -168,12 +167,11 @@ namespace IceInternal { if(offset < 0) { - throw new ArgumentOutOfRangeException("offset", offset, "offset must be non-negative"); + throwOutOfRange("offset", offset, "offset must be non-negative"); } if(offset + length > System.Buffer.ByteLength(b)) { - throw new ArgumentOutOfRangeException("length", length, - "insufficient room beyond given offset in destination array"); + throwOutOfRange("length", length, "insufficient room beyond given offset in destination array"); } checkUnderflow(length); System.Buffer.BlockCopy(_bytes, _position, b, offset, length); @@ -197,12 +195,11 @@ namespace IceInternal { if(offset < 0) { - throw new ArgumentOutOfRangeException("offset", offset, "offset must be non-negative"); + throwOutOfRange("offset", offset, "offset must be non-negative"); } if(offset + length > System.Buffer.ByteLength(b)) { - throw new ArgumentOutOfRangeException("length", length, - "insufficient data beyond given offset in source array"); + throwOutOfRange("length", length, "insufficient data beyond given offset in source array"); } if(length > 0) { @@ -276,7 +273,7 @@ namespace IceInternal public byte b7; } -#if !MANAGED +#if !MANAGED && !COMPACT unsafe #endif public short getShort() @@ -284,7 +281,7 @@ namespace IceInternal checkUnderflow(2); if(NO._o == _order) { -#if !MANAGED +#if !MANAGED && !COMPACT fixed(byte* p = &_bytes[_position]) { _valBytes.shortVal = *((short*)p); @@ -324,7 +321,7 @@ namespace IceInternal _position += len; } -#if !MANAGED +#if !MANAGED && !COMPACT unsafe #endif public ByteBuffer putShort(short val) @@ -333,7 +330,7 @@ namespace IceInternal _valBytes.shortVal = val; if(NO._o == _order) { -#if !MANAGED +#if !MANAGED && !COMPACT fixed(byte* p = &_bytes[_position]) { *((short*)p) = _valBytes.shortVal; @@ -374,7 +371,7 @@ namespace IceInternal return this; } -#if !MANAGED +#if !MANAGED && !COMPACT unsafe #endif public int getInt() @@ -382,7 +379,7 @@ namespace IceInternal checkUnderflow(4); if(NO._o == _order) { -#if !MANAGED +#if !MANAGED && !COMPACT fixed(byte* p = &_bytes[_position]) { _valBytes.intVal = *((int*)p); @@ -435,23 +432,23 @@ namespace IceInternal return this; } -#if !MANAGED +#if !MANAGED && !COMPACT unsafe #endif public ByteBuffer putInt(int pos, int val) { if(pos < 0) { - throw new ArgumentOutOfRangeException("pos", pos, "position must be non-negative"); + throwOutOfRange("pos", pos, "position must be non-negative"); } if(pos + 4 > _limit) { - throw new ArgumentOutOfRangeException("pos", pos, "position must be less than limit - 4"); + throwOutOfRange("pos", pos, "position must be less than limit - 4"); } _valBytes.intVal = val; if(NO._o == _order) { -#if !MANAGED +#if !MANAGED && !COMPACT fixed(byte* p = &_bytes[pos]) { *((int*)p) = _valBytes.intVal; @@ -497,7 +494,7 @@ namespace IceInternal return this; } -#if !MANAGED +#if !MANAGED && !COMPACT unsafe #endif public long getLong() @@ -505,7 +502,7 @@ namespace IceInternal checkUnderflow(8); if(NO._o == _order) { -#if !MANAGED +#if !MANAGED && !COMPACT fixed(byte* p = &_bytes[_position]) { _valBytes.longVal = *((long*)p); @@ -563,7 +560,7 @@ namespace IceInternal _position += len; } -#if !MANAGED +#if !MANAGED && !COMPACT unsafe #endif public ByteBuffer putLong(long val) @@ -572,7 +569,7 @@ namespace IceInternal _valBytes.longVal = val; if(NO._o == _order) { -#if !MANAGED +#if !MANAGED && !COMPACT fixed(byte* p = &_bytes[_position]) { *((long*)p) = _valBytes.longVal; @@ -631,7 +628,7 @@ namespace IceInternal return this; } -#if !MANAGED +#if !MANAGED && !COMPACT unsafe #endif public float getFloat() @@ -639,7 +636,7 @@ namespace IceInternal checkUnderflow(4); if(NO._o == _order) { -#if !MANAGED +#if !MANAGED && !COMPACT fixed(byte* p = &_bytes[_position]) { _valBytes.floatVal = *((float*)p); @@ -685,7 +682,7 @@ namespace IceInternal _position += len; } -#if !MANAGED +#if !MANAGED && !COMPACT unsafe #endif public ByteBuffer putFloat(float val) @@ -694,7 +691,7 @@ namespace IceInternal _valBytes.floatVal = val; if(NO._o == _order) { -#if !MANAGED +#if !MANAGED && !COMPACT fixed(byte* p = &_bytes[_position]) { *((float*)p) = _valBytes.floatVal; @@ -741,7 +738,7 @@ namespace IceInternal return this; } -#if !MANAGED +#if !MANAGED && !COMPACT unsafe #endif public double getDouble() @@ -749,7 +746,7 @@ namespace IceInternal checkUnderflow(8); if(NO._o == _order) { -#if !MANAGED +#if !MANAGED && !COMPACT fixed(byte* p = &_bytes[_position]) { _valBytes.doubleVal = *((double*)p); @@ -807,7 +804,7 @@ namespace IceInternal _position += len; } -#if !MANAGED +#if !MANAGED && !COMPACT unsafe #endif public ByteBuffer putDouble(double val) @@ -816,7 +813,7 @@ namespace IceInternal _valBytes.doubleVal = val; if(NO._o == _order) { -#if !MANAGED +#if !MANAGED && !COMPACT fixed(byte* p = &_bytes[_position]) { *((double*)p) = _valBytes.doubleVal; @@ -926,5 +923,14 @@ namespace IceInternal { } } + + private static void throwOutOfRange(string param, object value, string message) + { +#if COMPACT + throw new ArgumentOutOfRangeException(param, message); +#else + throw new ArgumentOutOfRangeException(param, value, message); +#endif + } } } diff --git a/cs/src/Ice/ConnectRequestHandler.cs b/cs/src/Ice/ConnectRequestHandler.cs index fd07078e3b7..df5f91265ef 100644 --- a/cs/src/Ice/ConnectRequestHandler.cs +++ b/cs/src/Ice/ConnectRequestHandler.cs @@ -45,7 +45,8 @@ namespace IceInternal { _reference.getConnection(this); - lock(this) + _m.Lock(); + try { if(initialized()) { @@ -59,15 +60,20 @@ namespace IceInternal return this; } } + finally + { + _m.Unlock(); + } } public void prepareBatchRequest(BasicStream os) { - lock(this) + _m.Lock(); + try { while(_batchRequestInProgress) { - Monitor.Wait(this); + _m.Wait(); } if(!initialized()) @@ -77,18 +83,23 @@ namespace IceInternal return; } } + finally + { + _m.Unlock(); + } _connection.prepareBatchRequest(os); } public void finishBatchRequest(BasicStream os) { - lock(this) + _m.Lock(); + try { if(!initialized()) { Debug.Assert(_batchRequestInProgress); _batchRequestInProgress = false; - Monitor.PulseAll(this); + _m.NotifyAll(); _batchStream.swap(os); @@ -102,18 +113,23 @@ namespace IceInternal return; } } + finally + { + _m.Unlock(); + } _connection.finishBatchRequest(os, _compress); } public void abortBatchRequest() { - lock(this) + _m.Lock(); + try { if(!initialized()) { Debug.Assert(_batchRequestInProgress); _batchRequestInProgress = false; - Monitor.PulseAll(this); + _m.NotifyAll(); BasicStream dummy = new BasicStream(_reference.getInstance(), _batchAutoFlush); _batchStream.swap(dummy); @@ -122,6 +138,10 @@ namespace IceInternal return; } } + finally + { + _m.Unlock(); + } _connection.abortBatchRequest(); } @@ -141,7 +161,8 @@ namespace IceInternal public bool sendAsyncRequest(OutgoingAsync @out, out Ice.AsyncCallback sentCallback) { - lock(this) + _m.Lock(); + try { if(!initialized()) { @@ -150,6 +171,10 @@ namespace IceInternal return false; } } + finally + { + _m.Unlock(); + } return _connection.sendAsyncRequest(@out, _compress, _response, out sentCallback); } @@ -160,7 +185,8 @@ namespace IceInternal public bool flushAsyncBatchRequests(BatchOutgoingAsync @out, out Ice.AsyncCallback sentCallback) { - lock(this) + _m.Lock(); + try { if(!initialized()) { @@ -169,31 +195,45 @@ namespace IceInternal return false; } } + finally + { + _m.Unlock(); + } return _connection.flushAsyncBatchRequests(@out, out sentCallback); } public Outgoing getOutgoing(string operation, Ice.OperationMode mode, Dictionary<string, string> context) { - lock(this) + _m.Lock(); + try { if(!initialized()) { return new IceInternal.Outgoing(this, operation, mode, context); } } + finally + { + _m.Unlock(); + } return _connection.getOutgoing(this, operation, mode, context); } public void reclaimOutgoing(Outgoing og) { - lock(this) + _m.Lock(); + try { if(_connection == null) { return; } } + finally + { + _m.Unlock(); + } _connection.reclaimOutgoing(og); } @@ -207,16 +247,21 @@ namespace IceInternal { if(waitInit) { - lock(this) + _m.Lock(); + try { // // Wait for the connection establishment to complete or fail. // while(!_initialized && _exception == null) { - Monitor.Wait(this); + _m.Wait(); } } + finally + { + _m.Unlock(); + } } if(_exception != null) @@ -236,7 +281,8 @@ namespace IceInternal public void setConnection(Ice.ConnectionI connection, bool compress) { - lock(this) + _m.Lock(); + try { Debug.Assert(_exception == null && _connection == null); Debug.Assert(_updateRequestHandler || _requests.Count == 0); @@ -244,6 +290,10 @@ namespace IceInternal _connection = connection; _compress = compress; } + finally + { + _m.Unlock(); + } // // If this proxy is for a non-local object, and we are using a router, then @@ -263,7 +313,8 @@ namespace IceInternal public void setException(Ice.LocalException ex) { - lock(this) + _m.Lock(); + try { Debug.Assert(!_initialized && _exception == null); Debug.Assert(_updateRequestHandler || _requests.Count == 0); @@ -285,7 +336,11 @@ namespace IceInternal }); } - Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } } @@ -328,7 +383,7 @@ namespace IceInternal { while(_flushing && _exception == null) { - Monitor.Wait(this); + _m.Wait(); } if(_exception != null) @@ -344,13 +399,14 @@ namespace IceInternal private void flushRequests() { - lock(this) + _m.Lock(); + try { Debug.Assert(_connection != null && !_initialized); while(_batchRequestInProgress) { - Monitor.Wait(this); + _m.Wait(); } // @@ -360,6 +416,10 @@ namespace IceInternal // _flushing = true; } + finally + { + _m.Unlock(); + } LinkedList<Request> sentCallbacks = new LinkedList<Request>(); try @@ -411,7 +471,8 @@ namespace IceInternal } catch(LocalExceptionWrapper ex) { - lock(this) + _m.Lock(); + try { Debug.Assert(_exception == null && _requests.Count > 0); _exception = ex.get(); @@ -420,10 +481,15 @@ namespace IceInternal flushRequestsWithException(ex); }); } + finally + { + _m.Unlock(); + } } catch(Ice.LocalException ex) { - lock(this) + _m.Lock(); + try { Debug.Assert(_exception == null && _requests.Count > 0); _exception = ex; @@ -432,6 +498,10 @@ namespace IceInternal flushRequestsWithException(ex); }); } + finally + { + _m.Unlock(); + } } if(sentCallbacks.Count > 0) @@ -467,7 +537,8 @@ namespace IceInternal _proxy.setRequestHandler__(_delegate, new ConnectionRequestHandler(_reference, _connection, _compress)); } - lock(this) + _m.Lock(); + try { Debug.Assert(!_initialized); if(_exception == null) @@ -477,7 +548,11 @@ namespace IceInternal } _proxy = null; // Break cyclic reference count. _delegate = null; // Break cyclic reference count. - Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } } @@ -534,5 +609,7 @@ namespace IceInternal private int _batchRequestsSize; private BasicStream _batchStream; private bool _updateRequestHandler; + + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); } } diff --git a/cs/src/Ice/ConnectionFactory.cs b/cs/src/Ice/ConnectionFactory.cs index 0b908a0d73e..11b72a87553 100644 --- a/cs/src/Ice/ConnectionFactory.cs +++ b/cs/src/Ice/ConnectionFactory.cs @@ -54,7 +54,8 @@ namespace IceInternal public void destroy() { - lock(this) + _m.Lock(); + try { if(_destroyed) { @@ -70,14 +71,19 @@ namespace IceInternal } _destroyed = true; - Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } } public void waitUntilFinished() { Dictionary<Connector, ICollection<Ice.ConnectionI>> connections = null; - lock(this) + _m.Lock(); + try { // // First we wait until the factory is destroyed. We also @@ -87,7 +93,7 @@ namespace IceInternal // while(!_destroyed || _pending.Count > 0 || _pendingConnectCount > 0) { - Monitor.Wait(this); + _m.Wait(); } // @@ -96,6 +102,10 @@ namespace IceInternal // connections = new Dictionary<Connector, ICollection<Ice.ConnectionI>>(_connections); } + finally + { + _m.Unlock(); + } // // Now we wait until the destruction of each connection is finished. @@ -108,7 +118,8 @@ namespace IceInternal } } - lock(this) + _m.Lock(); + try { // Ensure all the connections are finished and reapable at this point. ICollection<Ice.ConnectionI> cons = _reaper.swapConnections(); @@ -129,6 +140,10 @@ namespace IceInternal Debug.Assert(_connectionsByEndpoint.Count == 0); } } + finally + { + _m.Unlock(); + } } public Ice.ConnectionI create(EndpointI[] endpts, bool hasMore, Ice.EndpointSelectionType selType, @@ -317,7 +332,8 @@ namespace IceInternal public void setRouterInfo(IceInternal.RouterInfo routerInfo) { - lock(this) + _m.Lock(); + try { if(_destroyed) { @@ -370,11 +386,16 @@ namespace IceInternal } } } + finally + { + _m.Unlock(); + } } public void removeAdapter(Ice.ObjectAdapter adapter) { - lock(this) + _m.Lock(); + try { if(_destroyed) { @@ -392,13 +413,18 @@ namespace IceInternal } } } + finally + { + _m.Unlock(); + } } public void flushAsyncBatchRequests(CommunicatorBatchOutgoingAsync outAsync) { ICollection<Ice.ConnectionI> c = new List<Ice.ConnectionI>(); - lock(this) + _m.Lock(); + try { if(!_destroyed) { @@ -414,6 +440,10 @@ namespace IceInternal } } } + finally + { + _m.Unlock(); + } foreach(Ice.ConnectionI conn in c) { @@ -462,7 +492,8 @@ namespace IceInternal private Ice.ConnectionI findConnection(List<EndpointI> endpoints, out bool compress) { - lock(this) + _m.Lock(); + try { if(_destroyed) { @@ -500,6 +531,10 @@ namespace IceInternal compress = false; // Satisfy the compiler return null; } + finally + { + _m.Unlock(); + } } // @@ -552,7 +587,8 @@ namespace IceInternal // the asynchronous requests waiting on a connection to be established. // - lock(this) + _m.Lock(); + try { if(_destroyed) { @@ -560,24 +596,34 @@ namespace IceInternal } ++_pendingConnectCount; } + finally + { + _m.Unlock(); + } } internal void decPendingConnectCount() { - lock(this) + _m.Lock(); + try { --_pendingConnectCount; Debug.Assert(_pendingConnectCount >= 0); if(_destroyed && _pendingConnectCount == 0) { - Monitor.PulseAll(this); + _m.NotifyAll(); } } + finally + { + _m.Unlock(); + } } private Ice.ConnectionI getConnection(List<ConnectorInfo> connectors, ConnectCallback cb, out bool compress) { - lock(this) + _m.Lock(); + try { if(_destroyed) { @@ -629,7 +675,7 @@ namespace IceInternal // if(cb == null) { - Monitor.Wait(this); + _m.Wait(); } else { @@ -647,6 +693,10 @@ namespace IceInternal } } } + finally + { + _m.Unlock(); + } // // At this point, we're responsible for establishing the connection to one of @@ -665,7 +715,8 @@ namespace IceInternal private Ice.ConnectionI createConnection(Transceiver transceiver, ConnectorInfo ci) { - lock(this) + _m.Lock(); + try { Debug.Assert(_pending.ContainsKey(ci.connector) && transceiver != null); @@ -703,6 +754,10 @@ namespace IceInternal _connectionsByEndpoint.Add(connection.endpoint().compress(true), connection); return connection; } + finally + { + _m.Unlock(); + } } private void finishGetConnection(List<ConnectorInfo> connectors, @@ -717,7 +772,8 @@ namespace IceInternal } HashSet<ConnectCallback> callbacks = new HashSet<ConnectCallback>(); - lock(this) + _m.Lock(); + try { foreach(ConnectorInfo c in connectors) { @@ -748,7 +804,11 @@ namespace IceInternal { cc.removeFromPending(); } - Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } bool compress; @@ -781,7 +841,8 @@ namespace IceInternal } HashSet<ConnectCallback> callbacks = new HashSet<ConnectCallback>(); - lock(this) + _m.Lock(); + try { foreach(ConnectorInfo c in connectors) { @@ -808,7 +869,11 @@ namespace IceInternal Debug.Assert(!failedCallbacks.Contains(cc)); cc.removeFromPending(); } - Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } foreach(ConnectCallback cc in callbacks) @@ -1205,39 +1270,57 @@ namespace IceInternal private int _pendingConnectCount; private static System.Random rand_ = new System.Random(unchecked((int)System.DateTime.Now.Ticks)); + + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); } public sealed class IncomingConnectionFactory : EventHandler, Ice.ConnectionI.StartCallback { public void activate() { - lock(this) + _m.Lock(); + try { setState(StateActive); } + finally + { + _m.Unlock(); + } } public void hold() { - lock(this) + _m.Lock(); + try { setState(StateHolding); } + finally + { + _m.Unlock(); + } } public void destroy() { - lock(this) + _m.Lock(); + try { setState(StateClosed); } + finally + { + _m.Unlock(); + } } public void waitUntilHolding() { ICollection<Ice.ConnectionI> connections; - lock(this) + _m.Lock(); + try { // // First we wait until the connection factory itself is in @@ -1245,7 +1328,7 @@ namespace IceInternal // while(_state < StateHolding) { - Monitor.Wait(this); + _m.Wait(); } // @@ -1254,6 +1337,10 @@ namespace IceInternal // connections = new List<Ice.ConnectionI>(_connections); } + finally + { + _m.Unlock(); + } // // Now we wait until each connection is in holding state. @@ -1268,7 +1355,8 @@ namespace IceInternal { ICollection<Ice.ConnectionI> connections = null; - lock(this) + _m.Lock(); + try { // // First we wait until the factory is destroyed. If we are using @@ -1276,7 +1364,7 @@ namespace IceInternal // while(_state != StateFinished) { - Monitor.Wait(this); + _m.Wait(); } // @@ -1290,13 +1378,18 @@ namespace IceInternal // connections = new List<Ice.ConnectionI>(_connections); } + finally + { + _m.Unlock(); + } foreach(Ice.ConnectionI connection in connections) { connection.waitUntilFinished(); } - lock(this) + _m.Lock(); + try { // Ensure all the connections are finished and reapable at this point. ICollection<Ice.ConnectionI> cons = _reaper.swapConnections(); @@ -1307,6 +1400,10 @@ namespace IceInternal } _connections.Clear(); } + finally + { + _m.Unlock(); + } } public EndpointI endpoint() @@ -1317,7 +1414,8 @@ namespace IceInternal public ICollection<Ice.ConnectionI> connections() { - lock(this) + _m.Lock(); + try { ICollection<Ice.ConnectionI> connections = new List<Ice.ConnectionI>(); @@ -1334,6 +1432,10 @@ namespace IceInternal return connections; } + finally + { + _m.Unlock(); + } } public void flushAsyncBatchRequests(CommunicatorBatchOutgoingAsync outAsync) @@ -1378,7 +1480,9 @@ namespace IceInternal } finally { +#if !COMPACT System.Environment.FailFast(s); +#endif } return false; } @@ -1403,7 +1507,9 @@ namespace IceInternal } finally { +#if !COMPACT System.Environment.FailFast(s); +#endif } return false; } @@ -1421,9 +1527,10 @@ namespace IceInternal { Ice.ConnectionI connection = null; - ThreadPoolMessage msg = new ThreadPoolMessage(this); + ThreadPoolMessage msg = new ThreadPoolMessage(_m); - lock(this) + _m.Lock(); + try { if(!msg.startIOScope(ref current)) { @@ -1472,7 +1579,9 @@ namespace IceInternal } finally { +#if !COMPACT System.Environment.FailFast(s); +#endif } } @@ -1520,6 +1629,10 @@ namespace IceInternal msg.finishIOScope(ref current); } } + finally + { + _m.Unlock(); + } Debug.Assert(connection != null); connection.start(this); @@ -1527,11 +1640,16 @@ namespace IceInternal public override void finished(ref ThreadPoolCurrent current) { - lock(this) + _m.Lock(); + try { Debug.Assert(_state == StateClosed); setState(StateFinished); } + finally + { + _m.Unlock(); + } } public override string ToString() @@ -1550,7 +1668,8 @@ namespace IceInternal // public void connectionStartCompleted(Ice.ConnectionI connection) { - lock(this) + _m.Lock(); + try { // // Initially, connections are in the holding state. If the factory is active @@ -1561,11 +1680,16 @@ namespace IceInternal connection.activate(); } } + finally + { + _m.Unlock(); + } } public void connectionStartFailed(Ice.ConnectionI connection, Ice.LocalException ex) { - lock(this) + _m.Lock(); + try { if(_state >= StateClosed) { @@ -1577,6 +1701,10 @@ namespace IceInternal warning(ex); } } + finally + { + _m.Unlock(); + } } public IncomingConnectionFactory(Instance instance, EndpointI endpoint, Ice.ObjectAdapter adapter, @@ -1739,7 +1867,7 @@ namespace IceInternal } _state = state; - Monitor.PulseAll(this); + _m.NotifyAll(); } private void warning(Ice.LocalException ex) @@ -1762,6 +1890,8 @@ namespace IceInternal private HashSet<Ice.ConnectionI> _connections; private int _state; + + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); } } diff --git a/cs/src/Ice/ConnectionI.cs b/cs/src/Ice/ConnectionI.cs index c4aee3ae6fa..46b3f1f34f6 100644 --- a/cs/src/Ice/ConnectionI.cs +++ b/cs/src/Ice/ConnectionI.cs @@ -42,7 +42,8 @@ namespace Ice { try { - lock(this) + _m.Lock(); + try { // // The connection might already be closed if the communicator was destroyed. @@ -66,7 +67,7 @@ namespace Ice // while(_state <= StateNotValidated) { - Monitor.Wait(this); + _m.Wait(); } if(_state >= StateClosing) @@ -81,6 +82,10 @@ namespace Ice // setState(StateHolding); } + finally + { + _m.Unlock(); + } } catch(LocalException ex) { @@ -105,7 +110,8 @@ namespace Ice public void activate() { - lock(this) + _m.Lock(); + try { if(_state <= StateNotValidated) { @@ -119,11 +125,16 @@ namespace Ice setState(StateActive); } + finally + { + _m.Unlock(); + } } public void hold() { - lock(this) + _m.Lock(); + try { if(_state <= StateNotValidated) { @@ -132,6 +143,10 @@ namespace Ice setState(StateHolding); } + finally + { + _m.Unlock(); + } } // DestructionReason. @@ -140,7 +155,8 @@ namespace Ice public void destroy(int reason) { - lock(this) + _m.Lock(); + try { switch(reason) { @@ -157,11 +173,16 @@ namespace Ice } } } + finally + { + _m.Unlock(); + } } public void close(bool force) { - lock(this) + _m.Lock(); + try { if(force) { @@ -178,20 +199,29 @@ namespace Ice // while(_requests.Count != 0 || _asyncRequests.Count != 0) { - Monitor.Wait(this); + _m.Wait(); } setState(StateClosing, new CloseConnectionException()); } } + finally + { + _m.Unlock(); + } } public bool isActiveOrHolding() { - lock(this) + _m.Lock(); + try { return _state > StateNotValidated && _state < StateClosing; } + finally + { + _m.Unlock(); + } } public bool isFinished() @@ -201,7 +231,7 @@ namespace Ice // threads operating in this connection object, connection // destruction is considered as not yet finished. // - if(!Monitor.TryEnter(this)) + if(!_m.TryLock()) { return false; } @@ -217,14 +247,15 @@ namespace Ice } finally { - Monitor.Exit(this); + _m.Unlock(); } return true; } public void throwException() { - lock(this) + _m.Lock(); + try { if(_exception != null) { @@ -232,22 +263,32 @@ namespace Ice throw _exception; } } + finally + { + _m.Unlock(); + } } public void waitUntilHolding() { - lock(this) + _m.Lock(); + try { while(_state < StateHolding || _dispatchCount > 0) { - Monitor.Wait(this); + _m.Wait(); } } + finally + { + _m.Unlock(); + } } public void waitUntilFinished() { - lock(this) + _m.Lock(); + try { // // We wait indefinitely until the connection is finished and all @@ -257,7 +298,7 @@ namespace Ice // while(_state < StateFinished || _dispatchCount > 0) { - Monitor.Wait(this); + _m.Wait(); } Debug.Assert(_state == StateFinished && _dispatchCount == 0); @@ -267,11 +308,15 @@ namespace Ice // _adapter = null; } + finally + { + _m.Unlock(); + } } public void monitor(long now) { - if(!Monitor.TryEnter(this)) + if(!_m.TryLock()) { return; } @@ -302,7 +347,7 @@ namespace Ice } finally { - Monitor.Exit(this); + _m.Unlock(); } } @@ -310,7 +355,8 @@ namespace Ice { IceInternal.BasicStream os = og.ostr(); - lock(this) + _m.Lock(); + try { if(_exception != null) { @@ -377,6 +423,10 @@ namespace Ice return sent; } + finally + { + _m.Unlock(); + } } public bool sendAsyncRequest(IceInternal.OutgoingAsync og, bool compress, bool response, @@ -384,7 +434,8 @@ namespace Ice { IceInternal.BasicStream os = og.ostr__; - lock(this) + _m.Lock(); + try { if(_exception != null) { @@ -448,18 +499,23 @@ namespace Ice } return sent; } + finally + { + _m.Unlock(); + } } public void prepareBatchRequest(IceInternal.BasicStream os) { - lock(this) + _m.Lock(); + try { // // Wait if flushing is currently in progress. // while(_batchStreamInUse && _exception == null) { - Monitor.Wait(this); + _m.Wait(); } if(_exception != null) @@ -504,13 +560,18 @@ namespace Ice // finishBatchRequest() or abortBatchRequest() is called. // } + finally + { + _m.Unlock(); + } } public void finishBatchRequest(IceInternal.BasicStream os, bool compress) { try { - lock(this) + _m.Lock(); + try { // // Get the batch stream back. @@ -624,7 +685,11 @@ namespace Ice // Debug.Assert(_batchStreamInUse); _batchStreamInUse = false; - Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } } catch(LocalException) @@ -636,7 +701,8 @@ namespace Ice public void abortBatchRequest() { - lock(this) + _m.Lock(); + try { _batchStream = new IceInternal.BasicStream(_instance, _batchAutoFlush); _batchRequestNum = 0; @@ -645,7 +711,11 @@ namespace Ice Debug.Assert(_batchStreamInUse); _batchStreamInUse = false; - Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } } @@ -698,11 +768,12 @@ namespace Ice public bool flushBatchRequests(IceInternal.BatchOutgoing @out) { - lock(this) + _m.Lock(); + try { while(_batchStreamInUse && _exception == null) { - Monitor.Wait(this); + _m.Wait(); } if(_exception != null) @@ -747,15 +818,20 @@ namespace Ice return sent; } + finally + { + _m.Unlock(); + } } public bool flushAsyncBatchRequests(IceInternal.BatchOutgoingAsync outAsync, out Ice.AsyncCallback sentCallback) { - lock(this) + _m.Lock(); + try { while(_batchStreamInUse && _exception == null) { - Monitor.Wait(this); + _m.Wait(); } if(_exception != null) @@ -803,11 +879,16 @@ namespace Ice _batchMarker = 0; return sent; } + finally + { + _m.Unlock(); + } } public void sendResponse(IceInternal.BasicStream os, byte compressFlag) { - lock(this) + _m.Lock(); + try { Debug.Assert(_state > StateNotValidated); @@ -819,7 +900,7 @@ namespace Ice { _reaper.add(this); } - Monitor.PulseAll(this); + _m.NotifyAll(); } if(_state >= StateClosed) @@ -840,11 +921,16 @@ namespace Ice setState(StateClosed, ex); } } + finally + { + _m.Unlock(); + } } public void sendNoResponse() { - lock(this) + _m.Lock(); + try { Debug.Assert(_state > StateNotValidated); @@ -856,7 +942,7 @@ namespace Ice { _reaper.add(this); } - Monitor.PulseAll(this); + _m.NotifyAll(); } if(_state >= StateClosed) @@ -875,6 +961,10 @@ namespace Ice setState(StateClosed, ex); } } + finally + { + _m.Unlock(); + } } public IceInternal.EndpointI endpoint() @@ -889,7 +979,8 @@ namespace Ice public void setAdapter(ObjectAdapter adapter) { - lock(this) + _m.Lock(); + try { if(_state <= StateNotValidated || _state >= StateClosing) { @@ -917,14 +1008,23 @@ namespace Ice // registered, even if we add or remove an object adapter. // } + finally + { + _m.Unlock(); + } } public ObjectAdapter getAdapter() { - lock(this) + _m.Lock(); + try { return _adapter; } + finally + { + _m.Unlock(); + } } public Endpoint getEndpoint() @@ -1002,8 +1102,9 @@ namespace Ice Queue<OutgoingMessage> sentCBs = null; MessageInfo info = new MessageInfo(); - IceInternal.ThreadPoolMessage msg = new IceInternal.ThreadPoolMessage(this); - lock(this) + IceInternal.ThreadPoolMessage msg = new IceInternal.ThreadPoolMessage(_m); + _m.Lock(); + try { if(!msg.startIOScope(ref current)) { @@ -1259,6 +1360,10 @@ namespace Ice msg.destroy(ref c); }); } + finally + { + _m.Unlock(); + } } private void dispatch(StartCallback startCB, Queue<OutgoingMessage> sentCBs, MessageInfo info) @@ -1308,7 +1413,8 @@ namespace Ice // if(sentCBs != null || info.outAsync != null) { - lock(this) + _m.Lock(); + try { if(--_dispatchCount == 0) { @@ -1327,19 +1433,28 @@ namespace Ice { _reaper.add(this); } - Monitor.PulseAll(this); + _m.NotifyAll(); } } + finally + { + _m.Unlock(); + } } } public override void finished(ref IceInternal.ThreadPoolCurrent current) { - lock(this) + _m.Lock(); + try { Debug.Assert(_state == StateClosed); unscheduleTimeout(IceInternal.SocketOperation.Read | IceInternal.SocketOperation.Write); } + finally + { + _m.Unlock(); + } // // If there are no callbacks to call, we don't call ioCompleted() since we're not going @@ -1454,7 +1569,8 @@ namespace Ice // This must be done last as this will cause waitUntilFinished() to return (and communicator // objects such as the timer might be destroyed too). // - lock(this) + _m.Lock(); + try { setState(StateFinished); if(_dispatchCount == 0) @@ -1462,6 +1578,10 @@ namespace Ice _reaper.add(this); } } + finally + { + _m.Unlock(); + } } public override string ToString() @@ -1471,7 +1591,8 @@ namespace Ice public void timedOut() { - lock(this) + _m.Lock(); + try { if(_state <= StateNotValidated) { @@ -1486,6 +1607,10 @@ namespace Ice setState(StateClosed, new CloseTimeoutException()); } } + finally + { + _m.Unlock(); + } } public string type() @@ -1501,7 +1626,8 @@ namespace Ice public ConnectionInfo getInfo() { - lock(this) + _m.Lock(); + try { if(_state >= StateClosed) { @@ -1512,6 +1638,10 @@ namespace Ice info.incoming = _connector == null; return info; } + finally + { + _m.Unlock(); + } } public string ice_toString_() @@ -1521,10 +1651,15 @@ namespace Ice public void exception(LocalException ex) { - lock(this) + _m.Lock(); + try { setState(StateClosed, ex); } + finally + { + _m.Unlock(); + } } public void invokeException(LocalException ex, int invokeNum) @@ -1534,7 +1669,8 @@ namespace Ice // called in case of a fatal exception we decrement _dispatchCount here. // - lock(this) + _m.Lock(); + try { setState(StateClosed, ex); @@ -1549,10 +1685,14 @@ namespace Ice { _reaper.add(this); } - Monitor.PulseAll(this); + _m.NotifyAll(); } } } + finally + { + _m.Unlock(); + } } static ConnectionI() @@ -1845,7 +1985,7 @@ namespace Ice _state = state; - Monitor.PulseAll(this); + _m.NotifyAll(); if(_state == StateClosing && _dispatchCount == 0) { @@ -2335,7 +2475,7 @@ namespace Ice } _asyncRequests.Remove(info.requestId); } - Monitor.PulseAll(this); // Notify threads blocked in close(false) + _m.NotifyAll(); // Notify threads blocked in close(false) break; } @@ -2743,5 +2883,7 @@ namespace Ice private static bool _compressionSupported; private bool _cacheBuffers; + + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); } } diff --git a/cs/src/Ice/DefaultsAndOverrides.cs b/cs/src/Ice/DefaultsAndOverrides.cs index 24586a453cc..4ddd401754e 100644 --- a/cs/src/Ice/DefaultsAndOverrides.cs +++ b/cs/src/Ice/DefaultsAndOverrides.cs @@ -66,6 +66,10 @@ namespace IceInternal overrideCloseTimeoutValue = -1; } +#if COMPACT + overrideCompress = false; + overrideCompressValue = false; +#else val = properties.getProperty("Ice.Override.Compress"); if(val.Length > 0) { @@ -83,6 +87,7 @@ namespace IceInternal overrideCompress = !BasicStream.compressible(); overrideCompressValue = false; } +#endif val = properties.getProperty("Ice.Override.Secure"); if(val.Length > 0) diff --git a/cs/src/Ice/EndpointHostResolver.cs b/cs/src/Ice/EndpointHostResolver.cs index 983e18c0128..8edfd620446 100644 --- a/cs/src/Ice/EndpointHostResolver.cs +++ b/cs/src/Ice/EndpointHostResolver.cs @@ -54,7 +54,8 @@ namespace IceInternal return; } - lock(this) + _m.Lock(); + try { Debug.Assert(!_destroyed); @@ -64,17 +65,26 @@ namespace IceInternal entry.endpoint = endpoint; entry.callback = callback; _queue.AddLast(entry); - Monitor.Pulse(this); + _m.Notify(); + } + finally + { + _m.Unlock(); } } public void destroy() { - lock(this) + _m.Lock(); + try { Debug.Assert(!_destroyed); _destroyed = true; - Monitor.Pulse(this); + _m.Notify(); + } + finally + { + _m.Unlock(); } } @@ -91,11 +101,12 @@ namespace IceInternal while(true) { ResolveEntry resolve; - lock(this) + _m.Lock(); + try { while(!_destroyed && _queue.Count == 0) { - Monitor.Wait(this); + _m.Wait(); } if(_destroyed) @@ -106,6 +117,10 @@ namespace IceInternal resolve = _queue.First.Value; _queue.RemoveFirst(); } + finally + { + _m.Unlock(); + } try { @@ -184,5 +199,7 @@ namespace IceInternal } private HelperThread _thread; + + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); } } diff --git a/cs/src/Ice/HashSet.cs b/cs/src/Ice/HashSet.cs new file mode 100644 index 00000000000..7fe6453451f --- /dev/null +++ b/cs/src/Ice/HashSet.cs @@ -0,0 +1,114 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2010 ZeroC, Inc. All rights reserved. +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +#if COMPACT + +// +// System.Collections.Generic.HashSet is not available in the .NET Compact Framework. +// This class is a minimal implementation that provides only the methods required by +// Ice internals. +// +using System; +using System.Collections.Generic; + +namespace IceInternal +{ + public class HashSet<T> : ICollection<T> + { + public HashSet() + { + entries_ = new Dictionary<T, bool>(); + } + + public HashSet(int capacity) + { + entries_ = new Dictionary<T, bool>(capacity); + } + + void ICollection<T>.Add(T item) + { + try + { + entries_.Add(item, false); + } + catch(ArgumentException) + { + // Item already present. + } + } + + public bool Add(T item) + { + try + { + entries_.Add(item, false); + } + catch(ArgumentException) + { + return false; // Item already present. + } + return true; + } + + public void Clear() + { + entries_.Clear(); + } + + public bool Contains(T item) + { + return entries_.ContainsKey(item); + } + + public void CopyTo(T[] a, int idx) + { + entries_.Keys.CopyTo(a, idx); + } + + public void CopyTo(T[] a) + { + entries_.Keys.CopyTo(a, 0); + } + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return entries_.Keys.GetEnumerator(); + } + + public IEnumerator<T> GetEnumerator() + { + return entries_.Keys.GetEnumerator(); + } + + public bool Remove(T item) + { + return entries_.Remove(item); + } + + public int Count + { + get + { + return entries_.Count; + } + } + + public bool IsReadOnly + { + get + { + return false; + } + } + + private Dictionary<T, bool> entries_; + } +} + +#endif diff --git a/cs/src/Ice/Instance.cs b/cs/src/Ice/Instance.cs index 94904edb5c6..7450d2b5f36 100644 --- a/cs/src/Ice/Instance.cs +++ b/cs/src/Ice/Instance.cs @@ -48,7 +48,14 @@ namespace IceInternal Debug.Assert(_defaultsAndOverrides != null); return _defaultsAndOverrides; } - + +#if COMPACT + public string[] factoryAssemblies() + { + return _factoryAssemblies; + } +#endif + public RouterManager routerManager() { lock(this) @@ -664,8 +671,7 @@ namespace IceInternal else if(logfile.Length != 0 || Ice.Util.getProcessLogger() is Ice.LoggerI) { // - // If Ice.LogFile set, default ConsoleTraceListener disabled. - // Otherwise default enabled. + // Ice.ConsoleListener is enabled by default unless Ice.LogFile is set. // bool console = _initData.properties.getPropertyAsIntWithDefault("Ice.ConsoleListener", @@ -682,7 +688,11 @@ namespace IceInternal _traceLevels = new TraceLevels(_initData.properties); _defaultsAndOverrides = new DefaultsAndOverrides(_initData.properties); - + +#if COMPACT + _factoryAssemblies = _initData.properties.getPropertyAsList("Ice.FactoryAssemblies"); +#endif + { const int defaultMessageSizeMax = 1024; int num = @@ -1072,6 +1082,9 @@ namespace IceInternal private Ice.InitializationData _initData; // Immutable, not reset by destroy(). private TraceLevels _traceLevels; // Immutable, not reset by destroy(). private DefaultsAndOverrides _defaultsAndOverrides; // Immutable, not reset by destroy(). +#if COMPACT + private string[] _factoryAssemblies; // Immutable, not reset by destroy(). +#endif private int _messageSizeMax; // Immutable, not reset by destroy(). private int _clientACM; // Immutable, not reset by destroy(). private int _serverACM; // Immutable, not reset by destroy(). diff --git a/cs/src/Ice/LinkedList.cs b/cs/src/Ice/LinkedList.cs index a5c227114cc..b9d2aa846e5 100644 --- a/cs/src/Ice/LinkedList.cs +++ b/cs/src/Ice/LinkedList.cs @@ -71,7 +71,11 @@ namespace IceUtilInternal } if(index < 0) { +#if COMPACT + throw new ArgumentOutOfRangeException("index", "index must not be less than zero"); +#else throw new ArgumentOutOfRangeException("index", _count, "index must not be less than zero"); +#endif } if(index >= array.Length) { diff --git a/cs/src/Ice/LocatorInfo.cs b/cs/src/Ice/LocatorInfo.cs index 0268d767b62..236c02aab6b 100644 --- a/cs/src/Ice/LocatorInfo.cs +++ b/cs/src/Ice/LocatorInfo.cs @@ -84,14 +84,15 @@ namespace IceInternal readonly Reference _ref; readonly int _ttl; readonly GetEndpointsCallback _callback; - }; + } private abstract class Request { public void addCallback(Reference @ref, Reference wellKnownRef, int ttl, GetEndpointsCallback cb) { - lock(this) + _m.Lock(); + try { RequestCallback callback = new RequestCallback(@ref, ttl, cb); if(_response) @@ -117,12 +118,17 @@ namespace IceInternal } } } + finally + { + _m.Unlock(); + } } public EndpointI[] getEndpoints(Reference @ref, Reference wellKnownRef, int ttl, out bool cached) { - lock(this) + _m.Lock(); + try { if(!_response || _exception == null) { @@ -139,7 +145,7 @@ namespace IceInternal while(!_response && _exception == null) { - Monitor.Wait(this); + _m.Wait(); } } @@ -175,6 +181,10 @@ namespace IceInternal } return endpoints == null ? new EndpointI[0] : endpoints; } + finally + { + _m.Unlock(); + } } public Request(LocatorInfo locatorInfo, Reference @ref) @@ -188,7 +198,8 @@ namespace IceInternal public void response(Ice.ObjectPrx proxy) { - lock(this) + _m.Lock(); + try { _locatorInfo.finishRequest(_ref, _wellKnownRefs, proxy, false); _response = true; @@ -197,7 +208,11 @@ namespace IceInternal { callback.response(_locatorInfo, proxy); } - Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } } @@ -210,7 +225,8 @@ namespace IceInternal return; } - lock(this) + _m.Lock(); + try { _locatorInfo.finishRequest(_ref, _wellKnownRefs, null, ex is Ice.UserException); _exception = ex; @@ -218,7 +234,11 @@ namespace IceInternal { callback.exception(_locatorInfo, ex); } - Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } } @@ -233,7 +253,9 @@ namespace IceInternal private bool _response; private Ice.ObjectPrx _proxy; private Ice.Exception _exception; - }; + + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); + } private class ObjectRequest : Request { diff --git a/cs/src/Ice/LoggerI.cs b/cs/src/Ice/LoggerI.cs index 5c5cdce9520..877dd4ebcf6 100644 --- a/cs/src/Ice/LoggerI.cs +++ b/cs/src/Ice/LoggerI.cs @@ -13,6 +13,9 @@ namespace Ice { using System.Diagnostics; using System.Globalization; +#if COMPACT + using System.IO; +#endif public abstract class LoggerI : Logger { @@ -119,17 +122,53 @@ namespace Ice } } +#if COMPACT public sealed class TraceLoggerI : LoggerI { public TraceLoggerI(string prefix, string file, bool console) : base(prefix) { + _console = console; + if(file.Length != 0) { _file = file; - Trace.Listeners.Add(new TextWriterTraceListener(file)); + FileStream fs = new FileStream(file, FileMode.Append, FileAccess.Write, FileShare.None); + _writer = new StreamWriter(fs); + } + else + { + _writer = System.Console.Error; } + } + + public override Logger cloneWithPrefix(string prefix) + { + return new TraceLoggerI(prefix, _file, _console); + } + + protected override void write(string message) + { + _writer.WriteLine(message); + } + + private string _file = ""; + private bool _console = false; + private TextWriter _writer; + } +#else + public sealed class TraceLoggerI : LoggerI + { + public TraceLoggerI(string prefix, string file, bool console) + : base(prefix) + { _console = console; + + if(file.Length != 0) + { + _file = file; + Trace.Listeners.Add(new TextWriterTraceListener(file)); + } if(console && !Trace.Listeners.Contains(_consoleListener)) { Trace.Listeners.Add(_consoleListener); @@ -151,4 +190,5 @@ namespace Ice private bool _console = false; internal static ConsoleTraceListener _consoleListener = new ConsoleTraceListener(true); } +#endif } diff --git a/cs/src/Ice/Makefile b/cs/src/Ice/Makefile index cff91416406..f7615ae6841 100644 --- a/cs/src/Ice/Makefile +++ b/cs/src/Ice/Makefile @@ -55,6 +55,7 @@ SRCS = Acceptor.cs \ LocatorInfo.cs \ LoggerI.cs \ LoggerPlugin.cs \ + Monitor.cs \ Network.cs \ ObjectAdapterFactory.cs \ ObjectAdapterI.cs \ diff --git a/cs/src/Ice/Makefile.mak b/cs/src/Ice/Makefile.mak index 06f752780b4..035d07faae5 100644 --- a/cs/src/Ice/Makefile.mak +++ b/cs/src/Ice/Makefile.mak @@ -46,6 +46,7 @@ SRCS = Acceptor.cs \ EndpointHostResolver.cs \
EventHandler.cs \
Exception.cs \
+ HashSet.cs \
ImplicitContextI.cs \
IncomingAsync.cs \
Incoming.cs \
@@ -55,6 +56,7 @@ SRCS = Acceptor.cs \ LocatorInfo.cs \
LoggerI.cs \
LoggerPlugin.cs \
+ Monitor.cs \
Network.cs \
ObjectAdapterFactory.cs \
ObjectAdapterI.cs \
diff --git a/cs/src/Ice/Monitor.cs b/cs/src/Ice/Monitor.cs new file mode 100644 index 00000000000..b722cf36ecd --- /dev/null +++ b/cs/src/Ice/Monitor.cs @@ -0,0 +1,270 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2010 ZeroC, Inc. All rights reserved. +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +// +// The System.Threading.Monitor class in the Compact Framework does not +// support the Wait/Pulse/PulseAll methods, so we implement our own +// Monitor here. +// +// For non-CF builds, our Monitor simply wraps the standard Monitor class. +// +// All code that uses a monitor for waiting/signaling must now use the +// following locking style: +// +// IceUtilInternal.Monitor mon = new IceUtilInternal.Monitor(); +// mon.Lock(); +// try +// { +// // Wait or Notify ... +// } +// finally +// { +// mon.Unlock(); +// } +// +namespace IceUtilInternal +{ +#if COMPACT + + using System; + using System.Collections.Generic; + using System.Diagnostics; + + public class Monitor + { + public Monitor() + { + _waitQueue = new LinkedList<System.Threading.EventWaitHandle>(); + _mutex = new System.Threading.Mutex(); + _lockCount = 0; + } + + public void Lock() + { + _mutex.WaitOne(); + _lockCount++; // Keep track of recursive locks. + } + + public void Unlock() + { + _lockCount--; // Keep track of recursive locks. + _mutex.ReleaseMutex(); + } + + public bool TryLock() + { + bool result = _mutex.WaitOne(0, false); + if(result) + { + _lockCount++; // Keep track of recursive locks. + } + return result; + } + + public void Wait() + { + // + // Push an event onto the wait queue. Eventually, a call to Notify or NotifyAll + // will remove the event from the wait queue and signal it. + // + System.Threading.EventWaitHandle e = new System.Threading.AutoResetEvent(false); + _waitQueue.AddLast(e); + + // + // Preserve the lock count until we reaquire the lock. + // + int lockCount = _lockCount; + _lockCount = 0; + + // + // Fully release the lock. + // + for(int i = 0; i < lockCount; ++i) + { + _mutex.ReleaseMutex(); + } + + // + // Wait for the event to be set. + // + e.WaitOne(); + + // + // Reacquire the lock the same number of times. + // + for(int i = 0; i < lockCount; ++i) + { + _mutex.WaitOne(); + } + + _lockCount = lockCount; + + // + // It is safe to close the event now because no other thread will use it (Notify + // or NotifyAll has already removed the event from the wait queue). + // + e.Close(); + } + + public bool TimedWait(int timeout) + { + // + // Push an event onto the wait queue. The event is removed from the queue if + // Notify or NotifyAll is called, otherwise we have to remove it explicitly. + // We use a LinkedListNode here because we can remove it in O(1) time. + // + System.Threading.EventWaitHandle e = new System.Threading.AutoResetEvent(false); + LinkedListNode<System.Threading.EventWaitHandle> node = + new LinkedListNode<System.Threading.EventWaitHandle>(e); + _waitQueue.AddLast(node); + + // + // Preserve the lock count until we reaquire the lock. + // + int lockCount = _lockCount; + _lockCount = 0; + + // + // Fully release the lock. + // + for(int i = 0; i < lockCount; ++i) + { + _mutex.ReleaseMutex(); + } + + // + // Wait for the event to be set or the timeout to expire. + // + bool b = e.WaitOne(timeout, false); + + // + // NOTE: There's a race here if the timeout expired: another thread could + // acquire the lock and call Notify. In turn, Notify could remove this event + // from the wait queue and set it. Now we have a situation where the timeout + // technically expired but the event was actually set. If we still treat this + // as an expired timeout then the Notify will have been lost. + // + // The timeout isn't precise because we also have to wait an indeterminate + // time to reacquire the lock. The simplest solution therefore is to check + // the event one more time after acquiring the lock - if it's set now, we + // act as if the wait succeeded. This might be an issue for a general-purpose + // monitor implementation, but for Ice it shouldn't cause any problems. + // + + // + // Reacquire the lock the same number of times. + // + for(int i = 0; i < lockCount; ++i) + { + _mutex.WaitOne(); + } + + _lockCount = lockCount; + + // + // In the case of a timeout, check the event one more time to work around the + // race condition described above. + // + if(!b) + { + b = e.WaitOne(0, false); + } + + // + // If our event was not signaled, we need to remove it from the wait queue. + // + if(!b) + { + Debug.Assert(node.List != null); // The node must still be in the wait queue. + _waitQueue.Remove(node); + } + + // + // It is safe to close the event now because no other thread will use it. + // + e.Close(); + + return b; + } + + public void Notify() + { + if(_waitQueue.Count > 0) + { + // + // Set the first event in the wait queue. + // + System.Threading.EventWaitHandle h = _waitQueue.First.Value; + _waitQueue.RemoveFirst(); + h.Set(); + } + } + + public void NotifyAll() + { + // + // Set all the events in the wait queue. + // + foreach(System.Threading.EventWaitHandle h in _waitQueue) + { + h.Set(); + } + _waitQueue.Clear(); + } + + private LinkedList<System.Threading.EventWaitHandle> _waitQueue; + private System.Threading.Mutex _mutex; + private int _lockCount; + } + +#else + + // + // This implementation is just a wrapper around System.Threading.Monitor. + // + public class Monitor + { + public void Lock() + { + System.Threading.Monitor.Enter(this); + } + + public void Unlock() + { + System.Threading.Monitor.Exit(this); + } + + public bool TryLock() + { + return System.Threading.Monitor.TryEnter(this); + } + + public void Wait() + { + System.Threading.Monitor.Wait(this); + } + + public bool TimedWait(int timeout) + { + return System.Threading.Monitor.Wait(this, timeout); + } + + public void Notify() + { + System.Threading.Monitor.Pulse(this); + } + + public void NotifyAll() + { + System.Threading.Monitor.PulseAll(this); + } + } + +#endif +} diff --git a/cs/src/Ice/Network.cs b/cs/src/Ice/Network.cs index 2c26552ba15..08c607926cb 100644 --- a/cs/src/Ice/Network.cs +++ b/cs/src/Ice/Network.cs @@ -15,7 +15,9 @@ namespace IceInternal using System.ComponentModel; using System.Diagnostics; using System.Net; +#if !COMPACT using System.Net.NetworkInformation; +#endif using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; @@ -97,7 +99,11 @@ namespace IceInternal { } +#if COMPACT + foreach(IPAddress a in Dns.GetHostEntry(host).AddressList) +#else foreach(IPAddress a in Dns.GetHostAddresses(host)) +#endif { if((a.AddressFamily == AddressFamily.InterNetwork && protocol != EnableIPv6) || (a.AddressFamily == AddressFamily.InterNetworkV6 && protocol != EnableIPv4)) @@ -270,7 +276,11 @@ namespace IceInternal public static bool isMulticast(IPEndPoint addr) { +#if COMPACT + string ip = addr.Address.ToString().ToUpper(); +#else string ip = addr.Address.ToString().ToUpperInvariant(); +#endif if(addr.AddressFamily == AddressFamily.InterNetwork) { char[] splitChars = { '.' }; @@ -816,7 +826,11 @@ namespace IceInternal } } +#if COMPACT + foreach(IPAddress a in Dns.GetHostEntry(host).AddressList) +#else foreach(IPAddress a in Dns.GetHostAddresses(host)) +#endif { if((a.AddressFamily == AddressFamily.InterNetwork && protocol != EnableIPv6) || (a.AddressFamily == AddressFamily.InterNetworkV6 && protocol != EnableIPv4)) @@ -866,6 +880,7 @@ namespace IceInternal try { addresses = new ArrayList(); +#if !COMPACT if(AssemblyUtil.runtime_ != AssemblyUtil.Runtime.Mono) { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); @@ -887,8 +902,13 @@ namespace IceInternal } } else +#endif { +#if COMPACT + foreach(IPAddress a in Dns.GetHostEntry(Dns.GetHostName()).AddressList) +#else foreach(IPAddress a in Dns.GetHostAddresses(Dns.GetHostName())) +#endif { if((a.AddressFamily == AddressFamily.InterNetwork && protocol != EnableIPv6) || (a.AddressFamily == AddressFamily.InterNetworkV6 && protocol != EnableIPv4)) @@ -989,7 +1009,11 @@ namespace IceInternal IPAddress[] addrs = getLocalAddresses(protocol); foreach(IPAddress a in addrs) { +#if COMPACT + if(!IPAddress.IsLoopback(a)) +#else if(!a.IsIPv6LinkLocal) +#endif { hosts.Add(a.ToString()); } @@ -1092,6 +1116,7 @@ namespace IceInternal private static int getInterfaceIndex(string name) { +#if !COMPACT NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach(NetworkInterface ni in nics) { @@ -1105,12 +1130,14 @@ namespace IceInternal } } } +#endif return 0; } private static IPAddress getInterfaceAddress(string name) { +#if !COMPACT NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach(NetworkInterface ni in nics) { @@ -1127,6 +1154,7 @@ namespace IceInternal } } } +#endif return IPAddress.Any; } } diff --git a/cs/src/Ice/ObjectAdapterFactory.cs b/cs/src/Ice/ObjectAdapterFactory.cs index 90a95d31d5b..d5776d74da7 100644 --- a/cs/src/Ice/ObjectAdapterFactory.cs +++ b/cs/src/Ice/ObjectAdapterFactory.cs @@ -19,7 +19,8 @@ namespace IceInternal public void shutdown() { List<Ice.ObjectAdapterI> adapters; - lock(this) + _m.Lock(); + try { // // Ignore shutdown requests if the object adapter factory has @@ -35,7 +36,11 @@ namespace IceInternal instance_ = null; _communicator = null; - System.Threading.Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } // @@ -51,18 +56,23 @@ namespace IceInternal public void waitForShutdown() { List<Ice.ObjectAdapterI> adapters; - lock(this) + _m.Lock(); + try { // // First we wait for the shutdown of the factory itself. // while(instance_ != null) { - System.Threading.Monitor.Wait(this); + _m.Wait(); } adapters = new List<Ice.ObjectAdapterI>(_adapters); } + finally + { + _m.Unlock(); + } // // Now we wait for deactivation of each object adapter. @@ -75,10 +85,15 @@ namespace IceInternal public bool isShutdown() { - lock(this) + _m.Lock(); + try { return instance_ == null; } + finally + { + _m.Unlock(); + } } public void destroy() @@ -89,25 +104,36 @@ namespace IceInternal waitForShutdown(); List<Ice.ObjectAdapterI> adapters; - lock(this) + _m.Lock(); + try { adapters = new List<Ice.ObjectAdapterI>(_adapters); } + finally + { + _m.Unlock(); + } foreach(Ice.ObjectAdapter adapter in adapters) { adapter.destroy(); } - lock(this) + _m.Lock(); + try { _adapters.Clear(); } + finally + { + _m.Unlock(); + } } public Ice.ObjectAdapter createObjectAdapter(string name, Ice.RouterPrx router) { - lock(this) + _m.Lock(); + try { if(instance_ == null) { @@ -135,12 +161,17 @@ namespace IceInternal _adapters.Add(adapter); return adapter; } + finally + { + _m.Unlock(); + } } public Ice.ObjectAdapter findObjectAdapter(Ice.ObjectPrx proxy) { List<Ice.ObjectAdapterI> adapters; - lock(this) + _m.Lock(); + try { if(instance_ == null) { @@ -149,6 +180,10 @@ namespace IceInternal adapters = new List<Ice.ObjectAdapterI>(_adapters); } + finally + { + _m.Unlock(); + } foreach(Ice.ObjectAdapterI adapter in adapters) { @@ -170,7 +205,8 @@ namespace IceInternal public void removeObjectAdapter(Ice.ObjectAdapterI adapter) { - lock(this) + _m.Lock(); + try { if(instance_ == null) { @@ -180,15 +216,24 @@ namespace IceInternal _adapters.Remove(adapter); _adapterNamesInUse.Remove(adapter.getName()); } + finally + { + _m.Unlock(); + } } public void flushAsyncBatchRequests(CommunicatorBatchOutgoingAsync outAsync) { List<Ice.ObjectAdapterI> adapters; - lock(this) + _m.Lock(); + try { adapters = new List<Ice.ObjectAdapterI>(_adapters); } + finally + { + _m.Unlock(); + } foreach(Ice.ObjectAdapterI adapter in adapters) { @@ -211,6 +256,8 @@ namespace IceInternal private Ice.Communicator _communicator; private HashSet<string> _adapterNamesInUse; private List<Ice.ObjectAdapterI> _adapters; + + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); } } diff --git a/cs/src/Ice/ObjectAdapterI.cs b/cs/src/Ice/ObjectAdapterI.cs index 7a280e9b9b9..49fd56c85ea 100644 --- a/cs/src/Ice/ObjectAdapterI.cs +++ b/cs/src/Ice/ObjectAdapterI.cs @@ -36,7 +36,8 @@ namespace Ice bool registerProcess = false; bool printAdapterReady = false; - lock(this) + _m.Lock(); + try { checkForDeactivation(); @@ -77,6 +78,10 @@ namespace Ice printAdapterReady = properties.getPropertyAsInt("Ice.PrintAdapterReady") > 0; } } + finally + { + _m.Unlock(); + } try { @@ -92,10 +97,15 @@ namespace Ice // allow to user code to retry activating the adapter // later. // - lock(this) + _m.Lock(); + try { _waitForActivate = false; - System.Threading.Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } throw; } @@ -105,7 +115,8 @@ namespace Ice System.Console.Out.WriteLine(_name + " ready"); } - lock(this) + _m.Lock(); + try { Debug.Assert(!_deactivated); // Not possible if _waitForActivate = true; @@ -113,7 +124,7 @@ namespace Ice // Signal threads waiting for the activation. // _waitForActivate = false; - System.Threading.Monitor.PulseAll(this); + _m.NotifyAll(); _activateOneOffDone = true; @@ -122,11 +133,16 @@ namespace Ice icf.activate(); } } + finally + { + _m.Unlock(); + } } public void hold() { - lock(this) + _m.Lock(); + try { checkForDeactivation(); @@ -135,6 +151,10 @@ namespace Ice factory.hold(); } } + finally + { + _m.Unlock(); + } } public void waitForHold() @@ -142,7 +162,8 @@ namespace Ice while(true) { List<IceInternal.IncomingConnectionFactory> incomingConnectionFactories; - lock(this) + _m.Lock(); + try { checkForDeactivation(); @@ -151,17 +172,22 @@ namespace Ice ++_waitForHold; } + finally + { + _m.Unlock(); + } foreach(IceInternal.IncomingConnectionFactory factory in incomingConnectionFactories) { factory.waitUntilHolding(); } - lock(this) + _m.Lock(); + try { if(--_waitForHold == 0) { - System.Threading.Monitor.PulseAll(this); + _m.NotifyAll(); } // @@ -181,11 +207,15 @@ namespace Ice while(_waitForHold > 0) { checkForDeactivation(); - System.Threading.Monitor.Wait(this); + _m.Wait(); } _waitForHoldRetry = false; } } + finally + { + _m.Unlock(); + } } } @@ -195,7 +225,8 @@ namespace Ice List<IceInternal.IncomingConnectionFactory> incomingConnectionFactories; IceInternal.LocatorInfo locatorInfo; - lock(this) + _m.Lock(); + try { // // Ignore deactivation requests if the object adapter has @@ -213,7 +244,7 @@ namespace Ice // while(_waitForActivate) { - System.Threading.Monitor.Wait(this); + _m.Wait(); } if(_routerInfo != null) @@ -235,7 +266,11 @@ namespace Ice locatorInfo = _locatorInfo; _deactivated = true; - System.Threading.Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } try @@ -271,7 +306,8 @@ namespace Ice public void waitForDeactivate() { IceInternal.IncomingConnectionFactory[] incomingConnectionFactories = null; - lock(this) + _m.Lock(); + try { if(_destroyed) { @@ -285,11 +321,15 @@ namespace Ice // while(!_deactivated || _directCount > 0) { - System.Threading.Monitor.Wait(this); + _m.Wait(); } incomingConnectionFactories = _incomingConnectionFactories.ToArray(); } + finally + { + _m.Unlock(); + } // // Now we wait for until all incoming connection factories are @@ -303,15 +343,21 @@ namespace Ice public bool isDeactivated() { - lock(this) + _m.Lock(); + try { return _deactivated; } + finally + { + _m.Unlock(); + } } public void destroy() { - lock(this) + _m.Lock(); + try { // // Another thread is in the process of destroying the object @@ -319,7 +365,7 @@ namespace Ice // while(_destroying) { - System.Threading.Monitor.Wait(this); + _m.Wait(); } // @@ -332,6 +378,10 @@ namespace Ice _destroying = true; } + finally + { + _m.Unlock(); + } // // Deactivate and wait for completion. @@ -356,14 +406,15 @@ namespace Ice IceInternal.ObjectAdapterFactory objectAdapterFactory; - lock(this) + _m.Lock(); + try { // // Signal that destroying is complete. // _destroying = false; _destroyed = true; - System.Threading.Monitor.PulseAll(this); + _m.NotifyAll(); // // We're done, now we can throw away all incoming connection @@ -385,6 +436,10 @@ namespace Ice objectAdapterFactory = _objectAdapterFactory; _objectAdapterFactory = null; } + finally + { + _m.Unlock(); + } if(objectAdapterFactory != null) { @@ -399,7 +454,8 @@ namespace Ice public ObjectPrx addFacet(Ice.Object obj, Identity ident, string facet) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); checkIdentity(ident); @@ -416,6 +472,10 @@ namespace Ice return newProxy(id, facet); } + finally + { + _m.Unlock(); + } } public ObjectPrx addWithUUID(Ice.Object obj) @@ -434,12 +494,17 @@ namespace Ice public void addDefaultServant(Ice.Object servant, string category) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); _servantManager.addDefaultServant(servant, category); } + finally + { + _m.Unlock(); + } } public Ice.Object remove(Identity ident) @@ -449,34 +514,49 @@ namespace Ice public Ice.Object removeFacet(Identity ident, string facet) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); checkIdentity(ident); return _servantManager.removeServant(ident, facet); } + finally + { + _m.Unlock(); + } } public Dictionary<string, Ice.Object> removeAllFacets(Identity ident) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); checkIdentity(ident); return _servantManager.removeAllFacets(ident); } + finally + { + _m.Unlock(); + } } public Ice.Object removeDefaultServant(string category) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); return _servantManager.removeDefaultServant(category); } + finally + { + _m.Unlock(); + } } public Ice.Object find(Identity ident) @@ -486,118 +566,173 @@ namespace Ice public Ice.Object findFacet(Identity ident, string facet) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); checkIdentity(ident); return _servantManager.findServant(ident, facet); } + finally + { + _m.Unlock(); + } } public Dictionary<string, Ice.Object> findAllFacets(Identity ident) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); checkIdentity(ident); return _servantManager.findAllFacets(ident); } + finally + { + _m.Unlock(); + } } public Ice.Object findByProxy(ObjectPrx proxy) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); IceInternal.Reference @ref = ((ObjectPrxHelperBase)proxy).reference__(); return findFacet(@ref.getIdentity(), @ref.getFacet()); } + finally + { + _m.Unlock(); + } } public Ice.Object findDefaultServant(string category) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); return _servantManager.findDefaultServant(category); } + finally + { + _m.Unlock(); + } } public void addServantLocator(ServantLocator locator, string prefix) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); _servantManager.addServantLocator(locator, prefix); } + finally + { + _m.Unlock(); + } } public ServantLocator removeServantLocator(string prefix) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); return _servantManager.removeServantLocator(prefix); } + finally + { + _m.Unlock(); + } } public ServantLocator findServantLocator(string prefix) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); return _servantManager.findServantLocator(prefix); } + finally + { + _m.Unlock(); + } } public ObjectPrx createProxy(Identity ident) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); checkIdentity(ident); return newProxy(ident, ""); } + finally + { + _m.Unlock(); + } } public ObjectPrx createDirectProxy(Identity ident) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); checkIdentity(ident); return newDirectProxy(ident, ""); } + finally + { + _m.Unlock(); + } } public ObjectPrx createIndirectProxy(Identity ident) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); checkIdentity(ident); return newIndirectProxy(ident, "", _id); } + finally + { + _m.Unlock(); + } } public void setLocator(LocatorPrx locator) { - lock(this) + _m.Lock(); + try { checkForDeactivation(); _locatorInfo = instance_.locatorManager().get(locator); } + finally + { + _m.Unlock(); + } } public void refreshPublishedEndpoints() @@ -606,7 +741,8 @@ namespace Ice bool registerProcess = false; List<IceInternal.EndpointI> oldPublishedEndpoints; - lock(this) + _m.Lock(); + try { checkForDeactivation(); @@ -620,6 +756,10 @@ namespace Ice instance_.initializationData().properties.getPropertyAsInt(_name + ".RegisterProcess") > 0; } } + finally + { + _m.Unlock(); + } try { @@ -629,7 +769,8 @@ namespace Ice } catch(Ice.LocalException) { - lock(this) + _m.Lock(); + try { // // Restore the old published endpoints. @@ -637,12 +778,17 @@ namespace Ice _publishedEndpoints = oldPublishedEndpoints; throw; } + finally + { + _m.Unlock(); + } } } public Endpoint[] getEndpoints() { - lock(this) + _m.Lock(); + try { List<Endpoint> endpoints = new List<Endpoint>(); foreach(IceInternal.IncomingConnectionFactory factory in _incomingConnectionFactories) @@ -651,14 +797,23 @@ namespace Ice } return endpoints.ToArray(); } + finally + { + _m.Unlock(); + } } public Endpoint[] getPublishedEndpoints() { - lock(this) + _m.Lock(); + try { return _publishedEndpoints.ToArray(); } + finally + { + _m.Unlock(); + } } public bool isLocal(ObjectPrx proxy) @@ -689,7 +844,8 @@ namespace Ice { IceInternal.EndpointI[] endpoints = r.getEndpoints(); - lock(this) + _m.Lock(); + try { checkForDeactivation(); @@ -737,16 +893,25 @@ namespace Ice return false; } + finally + { + _m.Unlock(); + } } } public void flushAsyncBatchRequests(IceInternal.CommunicatorBatchOutgoingAsync outAsync) { List<IceInternal.IncomingConnectionFactory> f; - lock(this) + _m.Lock(); + try { f = new List<IceInternal.IncomingConnectionFactory>(_incomingConnectionFactories); } + finally + { + _m.Unlock(); + } foreach(IceInternal.IncomingConnectionFactory factory in f) { @@ -756,18 +921,24 @@ namespace Ice public void incDirectCount() { - lock(this) + _m.Lock(); + try { checkForDeactivation(); Debug.Assert(_directCount >= 0); ++_directCount; } + finally + { + _m.Unlock(); + } } public void decDirectCount() { - lock(this) + _m.Lock(); + try { // Not check for deactivation here! @@ -776,9 +947,13 @@ namespace Ice Debug.Assert(_directCount > 0); if(--_directCount == 0) { - System.Threading.Monitor.PulseAll(this); + _m.NotifyAll(); } } + finally + { + _m.Unlock(); + } } public IceInternal.ThreadPool getThreadPool() @@ -1227,6 +1402,16 @@ namespace Ice IceInternal.EndpointI endp = instance_.endpointFactoryManager().create(s, oaEndpoints); if(endp == null) { +#if COMPACT + if(s.StartsWith("ssl", StringComparison.Ordinal)) + { + instance_.initializationData().logger.warning( + "SSL endpoint `" + s + + "' ignored: IceSSL is not supported with the .NET Compact Framework"); + ++end; + continue; + } +#else if(IceInternal.AssemblyUtil.runtime_ == IceInternal.AssemblyUtil.Runtime.Mono && s.StartsWith("ssl", StringComparison.Ordinal)) { @@ -1235,6 +1420,7 @@ namespace Ice ++end; continue; } +#endif Ice.EndpointParseException e2 = new Ice.EndpointParseException(); e2.str = "invalid object adapter endpoint `" + s + "'"; throw e2; @@ -1416,7 +1602,8 @@ namespace Ice if(registerProcess && serverId.Length > 0) { - lock(this) + _m.Lock(); + try { if(_processId == null) { @@ -1424,6 +1611,10 @@ namespace Ice _processId = addWithUUID(servant).ice_getIdentity(); } } + finally + { + _m.Unlock(); + } try { @@ -1566,5 +1757,7 @@ namespace Ice private bool _destroyed; private bool _noConfig; private Identity _processId; + + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); } } diff --git a/cs/src/Ice/Outgoing.cs b/cs/src/Ice/Outgoing.cs index f3db8430841..a6f94e77340 100644 --- a/cs/src/Ice/Outgoing.cs +++ b/cs/src/Ice/Outgoing.cs @@ -73,16 +73,16 @@ namespace IceInternal bool timedOut = false; - lock(this) + _m.Lock(); + try { - // // If the request is being sent in the background we first wait for the // sent notification. // while(_state != StateFailed && !_sent) { - Monitor.Wait(this); + _m.Wait(); } // @@ -94,7 +94,7 @@ namespace IceInternal { if(timeout >= 0) { - Monitor.Wait(this, timeout); + _m.TimedWait(timeout); if(_state == StateInProgress) { @@ -103,10 +103,14 @@ namespace IceInternal } else { - Monitor.Wait(this); + _m.Wait(); } } } + finally + { + _m.Unlock(); + } if(timedOut) { @@ -120,13 +124,18 @@ namespace IceInternal // We must wait until the exception set above has // propagated to this Outgoing object. // - lock(this) + _m.Lock(); + try { while(_state == StateInProgress) { - Monitor.Wait(this); + _m.Wait(); } } + finally + { + _m.Unlock(); + } } if(_exception != null) @@ -180,11 +189,12 @@ namespace IceInternal // // If the handler returns the connection, we must wait for the sent callback. // - lock(this) + _m.Lock(); + try { while(_state != StateFailed && !_sent) { - Monitor.Wait(this); + _m.Wait(); } if(_exception != null) @@ -193,6 +203,10 @@ namespace IceInternal throw _exception; } } + finally + { + _m.Unlock(); + } } return true; } @@ -237,10 +251,15 @@ namespace IceInternal { if(notify) { - lock(this) + _m.Lock(); + try { _sent = true; - Monitor.Pulse(this); + _m.Notify(); + } + finally + { + _m.Unlock(); } } else @@ -255,7 +274,8 @@ namespace IceInternal public void finished(BasicStream istr) { - lock(this) + _m.Lock(); + try { Debug.Assert(_handler.getReference().getMode() == Reference.Mode.ModeTwoway); // Only for twoways. @@ -384,19 +404,28 @@ namespace IceInternal } } - Monitor.Pulse(this); + _m.Notify(); + } + finally + { + _m.Unlock(); } } public void finished(Ice.LocalException ex, bool sent) { - lock(this) + _m.Lock(); + try { Debug.Assert(_state <= StateInProgress); _state = StateFailed; _exception = ex; _sent = sent; - Monitor.Pulse(this); + _m.Notify(); + } + finally + { + _m.Unlock(); } } @@ -519,6 +548,8 @@ namespace IceInternal private const int StateFailed = 5; private int _state; + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); + public Outgoing next; // For use by Ice.ObjectDelM_ } @@ -545,11 +576,12 @@ namespace IceInternal if(_handler != null && !_handler.flushBatchRequests(this) || _connection != null && !_connection.flushBatchRequests(this)) { - lock(this) + _m.Lock(); + try { while(_exception == null && !_sent) { - Monitor.Wait(this); + _m.Wait(); } if(_exception != null) @@ -557,6 +589,10 @@ namespace IceInternal throw _exception; } } + finally + { + _m.Unlock(); + } } } @@ -564,10 +600,15 @@ namespace IceInternal { if(notify) { - lock(this) + _m.Lock(); + try { _sent = true; - Monitor.Pulse(this); + _m.Notify(); + } + finally + { + _m.Unlock(); } } else @@ -578,10 +619,15 @@ namespace IceInternal public void finished(Ice.LocalException ex, bool sent) { - lock(this) + _m.Lock(); + try { _exception = ex; - Monitor.Pulse(this); + _m.Notify(); + } + finally + { + _m.Unlock(); } } @@ -595,6 +641,8 @@ namespace IceInternal private BasicStream _os; private bool _sent; private Ice.LocalException _exception; + + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); } } diff --git a/cs/src/Ice/OutgoingAsync.cs b/cs/src/Ice/OutgoingAsync.cs index bc78961ac4f..3a2ee65b206 100644 --- a/cs/src/Ice/OutgoingAsync.cs +++ b/cs/src/Ice/OutgoingAsync.cs @@ -137,40 +137,60 @@ namespace IceInternal public bool isCompleted_() { - lock(monitor_) + monitor_.Lock(); + try { return (state_ & Done) != 0; } + finally + { + monitor_.Unlock(); + } } public void waitForCompleted() { - lock(monitor_) + monitor_.Lock(); + try { while((state_ & Done) == 0) { - Monitor.Wait(monitor_); + monitor_.Wait(); } } + finally + { + monitor_.Unlock(); + } } public bool isSent() { - lock(monitor_) + monitor_.Lock(); + try { return (state_ & Sent) != 0; } + finally + { + monitor_.Unlock(); + } } public void waitForSent() { - lock(monitor_) + monitor_.Lock(); + try { while((state_ & (Sent | Done)) == 0) { - Monitor.Wait(monitor_); + monitor_.Wait(); } } + finally + { + monitor_.Unlock(); + } } public void throwLocalException() @@ -225,7 +245,8 @@ namespace IceInternal { get { - lock(monitor_) + monitor_.Lock(); + try { if(waitHandle_ == null) { @@ -237,12 +258,17 @@ namespace IceInternal } return waitHandle_; } + finally + { + monitor_.Unlock(); + } } } public Ice.AsyncResult whenSent(Ice.AsyncCallback cb) { - lock(monitor_) + monitor_.Lock(); + try { if(cb == null) { @@ -258,6 +284,10 @@ namespace IceInternal return this; } } + finally + { + monitor_.Unlock(); + } if(sentSynchronously_) { @@ -289,7 +319,8 @@ namespace IceInternal public Ice.AsyncResult whenSent(Ice.SentCallback cb) { - lock(monitor_) + monitor_.Lock(); + try { if(cb == null) { @@ -308,6 +339,10 @@ namespace IceInternal return this; } } + finally + { + monitor_.Unlock(); + } if(sentSynchronously_) { @@ -339,7 +374,8 @@ namespace IceInternal public Ice.AsyncResult whenCompletedWithAsyncCallback(Ice.AsyncCallback cb) { - lock(monitor_) + monitor_.Lock(); + try { setCompletedCallback(cb); if((state_ & Done) == 0) @@ -351,6 +387,10 @@ namespace IceInternal return this; } } + finally + { + monitor_.Unlock(); + } instance_.clientThreadPool().dispatch(delegate() { @@ -368,7 +408,8 @@ namespace IceInternal public Ice.AsyncResult whenCompleted(Ice.ExceptionCallback cb) { - lock(monitor_) + monitor_.Lock(); + try { if(cb == null) { @@ -385,6 +426,10 @@ namespace IceInternal return this; } } + finally + { + monitor_.Unlock(); + } instance_.clientThreadPool().dispatch(delegate() { @@ -423,7 +468,8 @@ namespace IceInternal public bool wait__() { - lock(monitor_) + monitor_.Lock(); + try { if((state_ & EndCalled) != 0) { @@ -432,7 +478,7 @@ namespace IceInternal state_ |= EndCalled; while((state_ & Done) == 0) { - Monitor.Wait(monitor_); + monitor_.Wait(); } if(exception_ != null) { @@ -440,6 +486,10 @@ namespace IceInternal } return (state_ & OK) != 0; } + finally + { + monitor_.Unlock(); + } } public void throwUserException__() @@ -611,17 +661,22 @@ namespace IceInternal protected void exception__(Ice.Exception ex) { Ice.AsyncCallback cb; - lock(monitor_) + monitor_.Lock(); + try { state_ |= Done; exception_ = ex; - Monitor.PulseAll(monitor_); + monitor_.NotifyAll(); if(waitHandle_ != null) { waitHandle_.Set(); } cb = completedCallback_; } + finally + { + monitor_.Unlock(); + } if(cb != null) { @@ -666,7 +721,7 @@ namespace IceInternal protected IceInternal.Instance instance_; protected string operation_; - protected object monitor_ = new object(); + protected readonly IceUtilInternal.Monitor monitor_ = new IceUtilInternal.Monitor(); protected IceInternal.BasicStream is_; protected IceInternal.BasicStream os_; @@ -775,7 +830,8 @@ namespace IceInternal public Ice.AsyncCallback sent__(Ice.ConnectionI connection) { - lock(monitor_) + monitor_.Lock(); + try { bool alreadySent = (state_ & Sent) != 0; state_ |= Sent; @@ -803,9 +859,13 @@ namespace IceInternal proxy_.reference__().getInstance().timer().schedule(_timerTask, connection.timeout()); } } - Monitor.PulseAll(monitor_); + monitor_.NotifyAll(); return alreadySent ? null : sentCallback_; // Don't call the sent call is already sent. } + finally + { + monitor_.Unlock(); + } } public new void sent__(Ice.AsyncCallback cb) @@ -815,7 +875,8 @@ namespace IceInternal public void finished__(Ice.LocalException exc, bool sent) { - lock(monitor_) + monitor_.Lock(); + try { Debug.Assert((state_ & Done) == 0); if(_timerTaskConnection != null) @@ -826,6 +887,10 @@ namespace IceInternal _timerTask = null; } } + finally + { + monitor_.Unlock(); + } // // NOTE: at this point, synchronization isn't needed, no other threads should be @@ -884,7 +949,8 @@ namespace IceInternal Ice.AsyncCallback cb = null; try { - lock(monitor_) + monitor_.Lock(); + try { Debug.Assert(exception_ == null && (state_ & Done) == 0); @@ -1018,7 +1084,11 @@ namespace IceInternal state_ |= OK; } cb = completedCallback_; - Monitor.PulseAll(monitor_); + monitor_.NotifyAll(); + } + finally + { + monitor_.Unlock(); } } catch(Ice.LocalException ex) @@ -1145,12 +1215,17 @@ namespace IceInternal private void runTimerTask__() { Ice.ConnectionI connection = null; - lock(monitor_) + monitor_.Lock(); + try { connection = _timerTaskConnection; _timerTaskConnection = null; _timerTask = null; } + finally + { + monitor_.Unlock(); + } if(connection != null) { @@ -1179,7 +1254,8 @@ namespace IceInternal new public Ice.AsyncResult<T> whenCompleted(Ice.ExceptionCallback excb) { - lock(monitor_) + monitor_.Lock(); + try { if(excb == null) { @@ -1196,6 +1272,10 @@ namespace IceInternal return this; } } + finally + { + monitor_.Unlock(); + } instance_.clientThreadPool().dispatch(delegate() { @@ -1213,7 +1293,8 @@ namespace IceInternal virtual public Ice.AsyncResult<T> whenCompleted(T cb, Ice.ExceptionCallback excb) { - lock(monitor_) + monitor_.Lock(); + try { if(cb == null && excb == null) { @@ -1231,6 +1312,10 @@ namespace IceInternal return this; } } + finally + { + monitor_.Unlock(); + } instance_.clientThreadPool().dispatch(delegate() { @@ -1321,17 +1406,22 @@ namespace IceInternal public Ice.AsyncCallback sent__(Ice.ConnectionI connection) { - lock(monitor_) + monitor_.Lock(); + try { Debug.Assert((state_ & (Done | OK | Sent)) == 0); state_ |= (Done | OK | Sent); - Monitor.PulseAll(monitor_); + monitor_.NotifyAll(); if(waitHandle_ != null) { waitHandle_.Set(); } return sentCallback_; } + finally + { + monitor_.Unlock(); + } } public new void sent__(Ice.AsyncCallback cb) @@ -1442,10 +1532,15 @@ namespace IceInternal public void flushConnection(Ice.Connection con) { - lock(monitor_) + monitor_.Lock(); + try { ++_useCount; } + finally + { + monitor_.Unlock(); + } Ice.AsyncResult r = con.begin_flushBatchRequests(completed, null); r.whenSent((Ice.AsyncCallback)sent); } @@ -1481,7 +1576,8 @@ namespace IceInternal bool done = false; Ice.AsyncCallback sentCallback = null; - lock(monitor_) + monitor_.Lock(); + try { Debug.Assert(_useCount > 0); --_useCount; @@ -1500,9 +1596,13 @@ namespace IceInternal done = true; state_ |= Done | OK | Sent; sentCallback = sentCallback_; - Monitor.PulseAll(monitor_); + monitor_.NotifyAll(); } } + finally + { + monitor_.Unlock(); + } if(done) { diff --git a/cs/src/Ice/PluginManagerI.cs b/cs/src/Ice/PluginManagerI.cs index 16eca7f40f5..a03377d230a 100644 --- a/cs/src/Ice/PluginManagerI.cs +++ b/cs/src/Ice/PluginManagerI.cs @@ -337,7 +337,7 @@ namespace Ice { entryPoint = pluginSpec.Substring(0, pos); char[] delims = { ' ', '\t', '\n' }; - args = pluginSpec.Substring(pos).Trim().Split(delims, pos); + args = pluginSpec.Substring(pos).Trim().Split(delims); } } @@ -401,6 +401,21 @@ namespace Ice } catch(System.Exception ex) { +#if COMPACT + // + // IceSSL is not supported with the Compact Framework. + // + if(name == "IceSSL") + { + if(!_sslWarnOnce) + { + _communicator.getLogger().warning( + "IceSSL plug-in not loaded: IceSSL is not supported with the .NET Compact Framework"); + _sslWarnOnce = true; + } + return; + } +#else // // IceSSL is not yet supported with Mono. We avoid throwing an exception in that case, // so the same configuration can be used with Mono or Visual C#. @@ -415,6 +430,7 @@ namespace Ice } return; } +#endif PluginInitializationException e = new PluginInitializationException(); e.reason = err + "unable to load assembly: '" + assemblyName + "': " + ex.ToString(); diff --git a/cs/src/Ice/PropertiesI.cs b/cs/src/Ice/PropertiesI.cs index cedf3f5ef97..feaed731be4 100644 --- a/cs/src/Ice/PropertiesI.cs +++ b/cs/src/Ice/PropertiesI.cs @@ -625,7 +625,8 @@ namespace Ice private void loadConfig() { string val = getProperty("Ice.Config"); - + +#if !COMPACT if(val.Length == 0 || val.Equals("1")) { string s = System.Environment.GetEnvironmentVariable("ICE_CONFIG"); @@ -634,6 +635,7 @@ namespace Ice val = s; } } +#endif if(val.Length > 0) { diff --git a/cs/src/Ice/PropertyNames.cs b/cs/src/Ice/PropertyNames.cs index f00d251fb25..2a0c854e04f 100644 --- a/cs/src/Ice/PropertyNames.cs +++ b/cs/src/Ice/PropertyNames.cs @@ -8,7 +8,7 @@ // ********************************************************************** // -// Generated by makeprops.py from file ./config/PropertyNames.xml, Mon Mar 7 23:28:12 2011 +// Generated by makeprops.py from file ..\config\PropertyNames.xml, Mon May 09 07:39:43 2011 // IMPORTANT: Do not edit this file -- any edits made here will be lost! @@ -75,6 +75,7 @@ namespace IceInternal new Property(@"^Ice\.IPv4$", false, null), new Property(@"^Ice\.IPv6$", false, null), new Property(@"^Ice\.EventLog\.Source$", false, null), + new Property(@"^Ice\.FactoryAssemblies$", false, null), new Property(@"^Ice\.GC\.Interval$", false, null), new Property(@"^Ice\.ImplicitContext$", false, null), new Property(@"^Ice\.InitPlugins$", false, null), diff --git a/cs/src/Ice/ProtocolPluginFacade.cs b/cs/src/Ice/ProtocolPluginFacade.cs index 201f0190ddb..ac38bedea58 100644 --- a/cs/src/Ice/ProtocolPluginFacade.cs +++ b/cs/src/Ice/ProtocolPluginFacade.cs @@ -47,12 +47,16 @@ namespace IceInternal // Get an EndpointFactory. // EndpointFactory getEndpointFactory(short type); + + // + // Obtain the type for a name. + // + System.Type findType(string name); } public sealed class ProtocolPluginFacadeI : ProtocolPluginFacade { - public - ProtocolPluginFacadeI(Ice.Communicator communicator) + public ProtocolPluginFacadeI(Ice.Communicator communicator) { _communicator = communicator; _instance = IceInternal.Util.getInstance(communicator); @@ -120,6 +124,14 @@ namespace IceInternal return _instance.endpointFactoryManager().get(type); } + // + // Obtain the type for a name. + // + public System.Type findType(string name) + { + return AssemblyUtil.findType(_instance, name); + } + private Instance _instance; private Ice.Communicator _communicator; } diff --git a/cs/src/Ice/Proxy.cs b/cs/src/Ice/Proxy.cs index 22b7f1fc6e4..16e58cf486e 100644 --- a/cs/src/Ice/Proxy.cs +++ b/cs/src/Ice/Proxy.cs @@ -1676,8 +1676,11 @@ namespace Ice } else { - ArrayList arr = ArrayList.Adapter(newEndpoints); - IceInternal.EndpointI[] endpts = (IceInternal.EndpointI[])arr.ToArray(typeof(IceInternal.EndpointI)); + IceInternal.EndpointI[] endpts = new IceInternal.EndpointI[newEndpoints.Length]; + for(int i = 0; i < newEndpoints.Length; ++i) + { + endpts[i] = (IceInternal.EndpointI)newEndpoints[i]; + } return newInstance(_reference.changeEndpoints(endpts)); } } diff --git a/cs/src/Ice/SliceChecksums.cs b/cs/src/Ice/SliceChecksums.cs index 178e3fc3d01..496c40d9762 100644 --- a/cs/src/Ice/SliceChecksums.cs +++ b/cs/src/Ice/SliceChecksums.cs @@ -19,6 +19,7 @@ namespace Ice { public static Dictionary<string, string> checksums = new Dictionary<string, string>(); +#if !COMPACT static SliceChecksums() { Type[] types = IceInternal.AssemblyUtil.findTypesWithPrefix("IceInternal.SliceChecksums"); @@ -32,6 +33,7 @@ namespace Ice } } } +#endif } } diff --git a/cs/src/Ice/StringUtil.cs b/cs/src/Ice/StringUtil.cs index e5adff61d0a..5528410d19b 100644 --- a/cs/src/Ice/StringUtil.cs +++ b/cs/src/Ice/StringUtil.cs @@ -353,7 +353,7 @@ namespace IceUtilInternal } UTF8Encoding utf8 = new UTF8Encoding(false, true); - return utf8.GetString(arr); // May raise ArgumentException. + return utf8.GetString(arr, 0, arr.Length); // May raise ArgumentException. } // @@ -453,13 +453,14 @@ namespace IceUtilInternal return 0; // Not quoted } - private class OrdinalStringComparerImpl : System.Collections.IComparer + private class OrdinalStringComparerImpl : System.Collections.Generic.IComparer<string> { - public int Compare(object l, object r) + public int Compare(string l, string r) { - return string.CompareOrdinal((string)l, (string)r); + return string.CompareOrdinal(l, r); } } - public static System.Collections.IComparer OrdinalStringComparer = new OrdinalStringComparerImpl(); + public static System.Collections.Generic.IComparer<string> OrdinalStringComparer = + new OrdinalStringComparerImpl(); } } diff --git a/cs/src/Ice/TcpAcceptor.cs b/cs/src/Ice/TcpAcceptor.cs index 354d2ba458e..9a6befcd8db 100644 --- a/cs/src/Ice/TcpAcceptor.cs +++ b/cs/src/Ice/TcpAcceptor.cs @@ -90,7 +90,9 @@ namespace IceInternal } Network.setBlock(_acceptFd, false); +#if !COMPACT Network.setTcpBufSize(_acceptFd, instance_.initializationData().properties, _logger); +#endif if(_traceLevels.network >= 1) { @@ -126,7 +128,9 @@ namespace IceInternal _addr = Network.getAddressForServer(host, port, instance_.protocolSupport()); _fd = Network.createSocket(false, _addr.AddressFamily); Network.setBlock(_fd, false); +#if !COMPACT Network.setTcpBufSize(_fd, instance_.initializationData().properties, _logger); +#endif if(AssemblyUtil.platform_ != AssemblyUtil.Platform.Windows) { // diff --git a/cs/src/Ice/TcpConnector.cs b/cs/src/Ice/TcpConnector.cs index d13494a8c60..0c67d6dce9f 100644 --- a/cs/src/Ice/TcpConnector.cs +++ b/cs/src/Ice/TcpConnector.cs @@ -30,7 +30,9 @@ namespace IceInternal { Socket fd = Network.createSocket(false, _addr.AddressFamily); Network.setBlock(fd, false); +#if !COMPACT Network.setTcpBufSize(fd, _instance.initializationData().properties, _logger); +#endif // // Nonblocking connect is handled by the transceiver. diff --git a/cs/src/Ice/TcpTransceiver.cs b/cs/src/Ice/TcpTransceiver.cs index 737347fd02d..0859b06cf04 100644 --- a/cs/src/Ice/TcpTransceiver.cs +++ b/cs/src/Ice/TcpTransceiver.cs @@ -83,6 +83,14 @@ namespace IceInternal public bool write(Buffer buf) { +#if COMPACT + // + // The Compact Framework does not support the use of synchronous socket + // operations on a non-blocking socket. Returning false here forces the + // caller to schedule an asynchronous operation. + // + return false; +#else int packetSize = buf.b.remaining(); if(AssemblyUtil.platform_ == AssemblyUtil.Platform.Windows) { @@ -155,10 +163,18 @@ namespace IceInternal } return true; // No more data to send. +#endif } public bool read(Buffer buf) { +#if COMPACT + // + // The .NET Compact Framework does not support the use of synchronous socket + // operations on a non-blocking socket. + // + return false; +#else // COMPILERFIX: Workaround for Mac OS X broken poll(), see Mono bug #470120 if(AssemblyUtil.osx_) { @@ -242,6 +258,7 @@ namespace IceInternal } return true; +#endif } public bool startRead(Buffer buf, AsyncCallback callback, object state) diff --git a/cs/src/Ice/ThreadPool.cs b/cs/src/Ice/ThreadPool.cs index 0f7bf4f9226..b2e5ae85fce 100644 --- a/cs/src/Ice/ThreadPool.cs +++ b/cs/src/Ice/ThreadPool.cs @@ -19,7 +19,7 @@ namespace IceInternal internal struct ThreadPoolMessage { - public ThreadPoolMessage(object mutex) + public ThreadPoolMessage(IceUtilInternal.Monitor mutex) { _mutex = mutex; _finish = false; @@ -66,15 +66,20 @@ namespace IceInternal // of the event handler. We need to lock the event handler here to call // finishMessage. // - lock(_mutex) + _mutex.Lock(); + try { current.finishMessage(false); Debug.Assert(!current.completedSynchronously); } + finally + { + _mutex.Unlock(); + } } } - private object _mutex; + private IceUtilInternal.Monitor _mutex; private bool _finish; private bool _finishWithIO; } @@ -241,11 +246,16 @@ namespace IceInternal public void destroy() { - lock(this) + _m.Lock(); + try { Debug.Assert(!_destroyed); _destroyed = true; - Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } } @@ -261,7 +271,8 @@ namespace IceInternal public void update(EventHandler handler, int remove, int add) { - lock(this) + _m.Lock(); + try { Debug.Assert(!_destroyed); handler._registered = handler._registered & ~remove; @@ -283,6 +294,10 @@ namespace IceInternal }); } } + finally + { + _m.Unlock(); + } } public void unregister(EventHandler handler, int op) @@ -292,7 +307,8 @@ namespace IceInternal public void finish(EventHandler handler) { - lock(this) + _m.Lock(); + try { Debug.Assert(!_destroyed); if(handler._pending == 0) @@ -310,10 +326,17 @@ namespace IceInternal handler._finish = true; } } + finally + { + _m.Unlock(); + } } - public void - dispatch(System.Action call) +#if COMPACT + public void dispatch(Ice.VoidAction call) +#else + public void dispatch(System.Action call) +#endif { if(_dispatcher != null) { @@ -339,12 +362,13 @@ namespace IceInternal public void execute(ThreadPoolWorkItem workItem) { - lock(this) + _m.Lock(); + try { Debug.Assert(!_destroyed); if(_workItems.Count == 0) { - Monitor.Pulse(this); + _m.Notify(); } _workItems.Enqueue(workItem); @@ -383,16 +407,25 @@ namespace IceInternal } } } + finally + { + _m.Unlock(); + } } public void executeNonBlocking(ThreadPoolWorkItem workItem) { - lock(this) + _m.Lock(); + try { Debug.Assert(!_destroyed); _instance.asyncIOThread().queue(workItem); } + finally + { + _m.Unlock(); + } } public void joinWithAllThreads() @@ -425,7 +458,8 @@ namespace IceInternal ThreadPoolWorkItem workItem = null; while(true) { - lock(this) + _m.Lock(); + try { if(workItem != null) { @@ -444,7 +478,7 @@ namespace IceInternal if(_threadIdleTime > 0) { - if(!Monitor.Wait(this, _threadIdleTime * 1000) && _workItems.Count == 0) // If timeout + if(!_m.TimedWait(_threadIdleTime * 1000) && _workItems.Count == 0) // If timeout { if(_destroyed) { @@ -476,7 +510,7 @@ namespace IceInternal else { Debug.Assert(_serverIdleTime > 0 && _inUse == 0 && _threads.Count == 1); - if(!Monitor.Wait(this, _serverIdleTime * 1000) && _workItems.Count == 0) + if(!_m.TimedWait(_serverIdleTime * 1000) && _workItems.Count == 0) { if(!_destroyed) { @@ -497,7 +531,7 @@ namespace IceInternal } else { - Monitor.Wait(this); + _m.Wait(); } } @@ -514,6 +548,10 @@ namespace IceInternal _instance.initializationData().logger.warning(s); } } + finally + { + _m.Unlock(); + } try { @@ -759,7 +797,6 @@ namespace IceInternal private Thread _thread; } - private readonly int _size; // Number of threads that are pre-created. private readonly int _sizeMax; // Maximum number of threads. private readonly int _sizeWarn; // If _inUse reaches _sizeWarn, a "low on threads" warning will be printed. @@ -775,6 +812,8 @@ namespace IceInternal private int _inUse; // Number of threads that are currently in use. private Queue<ThreadPoolWorkItem> _workItems; + + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); } } diff --git a/cs/src/Ice/Timer.cs b/cs/src/Ice/Timer.cs index bc536fa95f0..c6a3780a675 100644 --- a/cs/src/Ice/Timer.cs +++ b/cs/src/Ice/Timer.cs @@ -29,7 +29,8 @@ namespace IceInternal { public void destroy() { - lock(this) + _m.Lock(); + try { if(_instance == null) { @@ -37,18 +38,23 @@ namespace IceInternal } _instance = null; - Monitor.Pulse(this); + _m.Notify(); _tokens.Clear(); _tasks.Clear(); } + finally + { + _m.Unlock(); + } _thread.Join(); } public void schedule(TimerTask task, long delay) { - lock(this) + _m.Lock(); + try { if(_instance == null) { @@ -69,14 +75,19 @@ namespace IceInternal if(token.scheduledTime < _wakeUpTime) { - Monitor.Pulse(this); + _m.Notify(); } } + finally + { + _m.Unlock(); + } } public void scheduleRepeated(TimerTask task, long period) { - lock(this) + _m.Lock(); + try { if(_instance == null) { @@ -97,14 +108,19 @@ namespace IceInternal if(token.scheduledTime < _wakeUpTime) { - Monitor.Pulse(this); + _m.Notify(); } } + finally + { + _m.Unlock(); + } } public bool cancel(TimerTask task) { - lock(this) + _m.Lock(); + try { if(_instance == null) { @@ -120,6 +136,10 @@ namespace IceInternal _tokens.Remove(token); return true; } + finally + { + _m.Unlock(); + } } // @@ -160,7 +180,8 @@ namespace IceInternal Token token = null; while(true) { - lock(this) + _m.Lock(); + try { if(_instance != null) { @@ -187,7 +208,7 @@ namespace IceInternal if(_tokens.Count == 0) { _wakeUpTime = System.Int64.MaxValue; - Monitor.Wait(this); + _m.Wait(); } if(_instance == null) @@ -219,7 +240,7 @@ namespace IceInternal } _wakeUpTime = first.scheduledTime; - Monitor.Wait(this, (int)(first.scheduledTime - now)); + _m.TimedWait((int)(first.scheduledTime - now)); } if(_instance == null) @@ -227,6 +248,10 @@ namespace IceInternal break; } } + finally + { + _m.Unlock(); + } if(token != null) { @@ -236,7 +261,8 @@ namespace IceInternal } catch(System.Exception ex) { - lock(this) + _m.Lock(); + try { if(_instance != null) { @@ -244,6 +270,10 @@ namespace IceInternal _instance.initializationData().logger.error(s); } } + finally + { + _m.Unlock(); + } } } } @@ -319,11 +349,17 @@ namespace IceInternal public TimerTask task; } +#if COMPACT + private IDictionary<Token, object> _tokens = new SortedList<Token, object>(); +#else private IDictionary<Token, object> _tokens = new SortedDictionary<Token, object>(); +#endif private IDictionary<TimerTask, Token> _tasks = new Dictionary<TimerTask, Token>(); private Instance _instance; private long _wakeUpTime = System.Int64.MaxValue; private int _tokenId = 0; private Thread _thread; + + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); } } diff --git a/cs/src/Ice/UdpTransceiver.cs b/cs/src/Ice/UdpTransceiver.cs index 0776c99653e..e9d46bb6495 100644 --- a/cs/src/Ice/UdpTransceiver.cs +++ b/cs/src/Ice/UdpTransceiver.cs @@ -77,6 +77,14 @@ namespace IceInternal public bool write(Buffer buf) { +#if COMPACT + // + // The Compact Framework does not support the use of synchronous socket + // operations on a non-blocking socket. Returning false here forces the + // caller to schedule an asynchronous operation. + // + return false; +#else Debug.Assert(buf.b.position() == 0); Debug.Assert(_fd != null && _state >= StateConnected); @@ -145,10 +153,19 @@ namespace IceInternal Debug.Assert(ret == buf.b.limit()); return true; +#endif } public bool read(Buffer buf) { +#if COMPACT + // + // The Compact Framework does not support the use of synchronous socket + // operations on a non-blocking socket. Returning false here forces the + // caller to schedule an asynchronous operation. + // + return false; +#else Debug.Assert(buf.b.position() == 0); Debug.Assert(_fd != null); @@ -260,6 +277,7 @@ namespace IceInternal buf.b.position(ret); return true; +#endif } public bool startRead(Buffer buf, AsyncCallback callback, object state) diff --git a/cs/src/Ice/Util.cs b/cs/src/Ice/Util.cs index 49799ced937..d265d93e73a 100644 --- a/cs/src/Ice/Util.cs +++ b/cs/src/Ice/Util.cs @@ -34,11 +34,22 @@ namespace Ice void stop(); } +#if COMPACT + /// <summary> + /// A delegate for an action taking no parameters. + /// </summary> + public delegate void VoidAction(); +#endif + /// <summary> /// A delegate for the dispatcher. The dispatcher is called by the Ice /// runtime to dispatch servant calls and AMI callbacks. /// </summary> +#if COMPACT + public delegate void Dispatcher(VoidAction call, Connection con); +#else public delegate void Dispatcher(System.Action call, Connection con); +#endif /// <summary> /// A class that encpasulates data to initalize a communicator. diff --git a/cs/src/Ice/ValueWriter.cs b/cs/src/Ice/ValueWriter.cs index 56e2defb4d7..1238e2d06ce 100644 --- a/cs/src/Ice/ValueWriter.cs +++ b/cs/src/Ice/ValueWriter.cs @@ -57,9 +57,9 @@ namespace IceInternal writeValue(elem, i.Current, objectTable, output); } } - else if(val is DictionaryBase) + else if(val is IDictionary) { - foreach(DictionaryEntry entry in (Hashtable)val) + foreach(DictionaryEntry entry in (IDictionary)val) { string elem = name != null ? name + "." : ""; writeValue(elem + "key", entry.Key, objectTable, output); diff --git a/cs/src/IceBox/Server.cs b/cs/src/IceBox/Server.cs index 171af4f71d5..cd3fb780822 100644 --- a/cs/src/IceBox/Server.cs +++ b/cs/src/IceBox/Server.cs @@ -47,14 +47,14 @@ public class Server } } - public static void Main(string[] args) + public static int Main(string[] args) { Ice.InitializationData initData = new Ice.InitializationData(); initData.properties = Ice.Util.createProperties(); initData.properties.setProperty("Ice.Admin.DelayCreation", "1"); App server = new App(); - System.Environment.Exit(server.main(args, initData)); + return server.main(args, initData); } } } diff --git a/cs/src/IceBox/ServiceManagerI.cs b/cs/src/IceBox/ServiceManagerI.cs index 3a97ed060ce..5f49e8cbbfc 100644 --- a/cs/src/IceBox/ServiceManagerI.cs +++ b/cs/src/IceBox/ServiceManagerI.cs @@ -94,7 +94,8 @@ class ServiceManagerI : ServiceManagerDisp_ startService(string name, Ice.Current current) { ServiceInfo info = new ServiceInfo(); - lock(this) + _m.Lock(); + try { // // Search would be more efficient if services were contained in @@ -121,6 +122,10 @@ class ServiceManagerI : ServiceManagerDisp_ } _pendingStatusChanges = true; } + finally + { + _m.Unlock(); + } bool started = false; try @@ -134,7 +139,8 @@ class ServiceManagerI : ServiceManagerDisp_ _logger.warning("ServiceManager: exception in start for service " + info.name + "\n" + e.ToString()); } - lock(this) + _m.Lock(); + try { int i; for(i = 0; i < _services.Count; ++i) @@ -159,7 +165,11 @@ class ServiceManagerI : ServiceManagerDisp_ } } _pendingStatusChanges = false; - Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } } @@ -167,7 +177,8 @@ class ServiceManagerI : ServiceManagerDisp_ stopService(string name, Ice.Current current) { ServiceInfo info = new ServiceInfo(); - lock(this) + _m.Lock(); + try { // // Search would be more efficient if services were contained in @@ -194,6 +205,10 @@ class ServiceManagerI : ServiceManagerDisp_ } _pendingStatusChanges = true; } + finally + { + _m.Unlock(); + } bool stopped = false; try @@ -207,7 +222,8 @@ class ServiceManagerI : ServiceManagerDisp_ e.ToString()); } - lock(this) + _m.Lock(); + try { int i; for(i = 0; i < _services.Count; ++i) @@ -232,7 +248,11 @@ class ServiceManagerI : ServiceManagerDisp_ } } _pendingStatusChanges = false; - Monitor.PulseAll(this); + _m.NotifyAll(); + } + finally + { + _m.Unlock(); } } @@ -245,7 +265,8 @@ class ServiceManagerI : ServiceManagerDisp_ // Null observers and duplicate registrations are ignored // - lock(this) + _m.Lock(); + try { if(observer != null) { @@ -273,6 +294,10 @@ class ServiceManagerI : ServiceManagerDisp_ } } } + finally + { + _m.Unlock(); + } if(activeServices.Count > 0) { @@ -508,7 +533,8 @@ class ServiceManagerI : ServiceManagerDisp_ private void startService(string service, string entryPoint, string[] args) { - lock(this) + _m.Lock(); + try { // // Instantiate the class. @@ -764,19 +790,24 @@ class ServiceManagerI : ServiceManagerDisp_ throw e; } } + finally + { + _m.Unlock(); + } } private void stopAll() { - lock(this) + _m.Lock(); + try { // // First wait for any active startService/stopService calls to complete. // while(_pendingStatusChanges) { - Monitor.Wait(this); + _m.Wait(); } // @@ -859,6 +890,10 @@ class ServiceManagerI : ServiceManagerDisp_ _services.Clear(); servicesStopped(stoppedServices, _observers.Keys); } + finally + { + _m.Unlock(); + } } private void @@ -902,13 +937,18 @@ class ServiceManagerI : ServiceManagerDisp_ private void removeObserver(ServiceObserverPrx observer, Ice.Exception ex) { - lock(this) + _m.Lock(); + try { if(_observers.Remove(observer)) { observerRemoved(observer, ex); } } + finally + { + _m.Unlock(); + } } private void @@ -1068,6 +1108,7 @@ class ServiceManagerI : ServiceManagerDisp_ private bool _pendingStatusChanges = false; private Dictionary<ServiceObserverPrx, bool> _observers = new Dictionary<ServiceObserverPrx, bool>(); private int _traceServiceObserver = 0; + private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor(); } } diff --git a/cs/src/IceSSL/Instance.cs b/cs/src/IceSSL/Instance.cs index 9e331e02400..cd6f04bbf34 100644 --- a/cs/src/IceSSL/Instance.cs +++ b/cs/src/IceSSL/Instance.cs @@ -105,7 +105,7 @@ namespace IceSSL throw e; } - Type cls = IceInternal.AssemblyUtil.findType(certVerifierClass); + Type cls = _facade.findType(certVerifierClass); if(cls == null) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); @@ -145,7 +145,7 @@ namespace IceSSL throw e; } - Type cls = IceInternal.AssemblyUtil.findType(passwordCallbackClass); + Type cls = _facade.findType(passwordCallbackClass); if(cls == null) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); diff --git a/cs/src/IceSSL/TransceiverI.cs b/cs/src/IceSSL/TransceiverI.cs index 2f18b70afef..2f18b70afef 100755..100644 --- a/cs/src/IceSSL/TransceiverI.cs +++ b/cs/src/IceSSL/TransceiverI.cs diff --git a/cs/src/Makefile.mak b/cs/src/Makefile.mak index 6a43f4c570c..b46fca78665 100644 --- a/cs/src/Makefile.mak +++ b/cs/src/Makefile.mak @@ -12,7 +12,10 @@ top_srcdir = .. !include $(top_srcdir)\config\Make.rules.mak.cs
SUBDIRS = Ice IceStorm Glacier2 IcePatch2 IceGrid IceBox
+
+!if "$(COMPACT)" != "yes"
SUBDIRS = $(SUBDIRS) IceSSL
+!endif
$(EVERYTHING)::
@for %i in ( $(SUBDIRS) ) do \
|