2 // System.Threading.Thread.cs
5 // Dick Porter (dick@ximian.com)
7 // (C) Ximian, Inc. http://www.ximian.com
8 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 using System.Runtime.Remoting.Contexts;
31 using System.Runtime.Serialization;
32 using System.Runtime.Serialization.Formatters.Binary;
33 using System.Security.Permissions;
34 using System.Security.Principal;
35 using System.Globalization;
36 using System.Runtime.CompilerServices;
37 using System.Runtime.InteropServices;
39 using System.Collections.Generic;
40 using System.Reflection;
41 using System.Security;
42 using System.Diagnostics;
43 using System.Runtime.ConstrainedExecution;
45 namespace System.Threading {
46 [StructLayout (LayoutKind.Sequential)]
47 sealed class InternalThread : CriticalFinalizerObject {
48 #pragma warning disable 169, 414, 649
49 #region Sync with metadata/object-internals.h
51 // stores a thread handle
53 IntPtr native_handle; // used only on Win32
55 /* Note this is an opaque object (an array), not a CultureInfo */
56 private object cached_culture_info;
57 /* accessed only from unmanaged code */
60 private ThreadState state;
61 private object abort_exc;
62 private int abort_state_handle;
63 /* thread_id is only accessed from unmanaged code */
64 internal Int64 thread_id;
66 /* start_notify is used by the runtime to signal that Start()
69 private IntPtr stack_ptr;
70 private UIntPtr static_data; /* GC-tracked */
71 private IntPtr runtime_thread_info;
72 /* current System.Runtime.Remoting.Contexts.Context instance
73 keep as an object to avoid triggering its class constructor when not needed */
74 private object current_appcontext;
75 private object root_domain_thread;
76 internal byte[] _serialized_principal;
77 internal int _serialized_principal_version;
78 private IntPtr appdomain_refs;
79 private int interruption_requested;
80 private IntPtr synch_cs;
81 internal bool threadpool_thread;
82 private bool thread_interrupt_requested;
83 /* These are used from managed code */
84 internal int stack_size;
85 internal byte apartment_state;
86 internal volatile int critical_region_level;
87 internal int managed_id;
89 private IntPtr manage_callback;
90 private IntPtr interrupt_on_stop;
92 private IntPtr thread_pinning_ref;
93 private IntPtr abort_protected_block_count;
94 private int priority = (int) ThreadPriority.Normal;
95 private IntPtr owned_mutex;
96 private IntPtr suspended_event;
98 * These fields are used to avoid having to increment corlib versions
99 * when a new field is added to the unmanaged MonoThread structure.
101 private IntPtr unused1;
102 private IntPtr unused2;
104 /* This is used only to check that we are in sync between the representation
105 * of MonoInternalThread in native and InternalThread in managed
107 * DO NOT RENAME! DO NOT ADD FIELDS AFTER! */
110 #pragma warning restore 169, 414, 649
112 // Closes the system thread handle
113 [MethodImplAttribute(MethodImplOptions.InternalCall)]
114 private extern void Thread_free_internal();
116 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
118 Thread_free_internal();
122 [StructLayout (LayoutKind.Sequential)]
123 public sealed partial class Thread {
124 #pragma warning disable 414
125 #region Sync with metadata/object-internals.h
126 private InternalThread internal_thread;
127 object m_ThreadStartArg;
128 object pending_exception;
130 #pragma warning restore 414
132 IPrincipal principal;
133 int principal_version;
135 // the name of current_thread is
136 // important because they are used by the runtime.
139 static Thread current_thread;
141 // can be both a ThreadStart and a ParameterizedThreadStart
142 private MulticastDelegate m_Delegate;
144 private ExecutionContext m_ExecutionContext; // this call context follows the logical thread
146 private bool m_ExecutionContextBelongsToOuterScope;
148 [MethodImplAttribute(MethodImplOptions.InternalCall)]
149 private extern void ConstructInternalThread ();
151 private InternalThread Internal {
153 if (internal_thread == null)
154 ConstructInternalThread ();
155 return internal_thread;
159 public static Context CurrentContext {
160 [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
162 return(AppDomain.InternalGetContext ());
167 * These two methods return an array in the target
168 * domain with the same content as the argument. If
169 * the argument is already in the target domain, then
170 * the argument is returned, otherwise a copy.
172 [MethodImplAttribute(MethodImplOptions.InternalCall)]
173 private extern static byte[] ByteArrayToRootDomain (byte[] arr);
175 [MethodImplAttribute(MethodImplOptions.InternalCall)]
176 private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
178 static void DeserializePrincipal (Thread th)
180 MemoryStream ms = new MemoryStream (ByteArrayToCurrentDomain (th.Internal._serialized_principal));
181 int type = ms.ReadByte ();
183 BinaryFormatter bf = new BinaryFormatter ();
184 th.principal = (IPrincipal) bf.Deserialize (ms);
185 th.principal_version = th.Internal._serialized_principal_version;
186 } else if (type == 1) {
187 BinaryReader reader = new BinaryReader (ms);
188 string name = reader.ReadString ();
189 string auth_type = reader.ReadString ();
190 int n_roles = reader.ReadInt32 ();
191 string [] roles = null;
193 roles = new string [n_roles];
194 for (int i = 0; i < n_roles; i++)
195 roles [i] = reader.ReadString ();
197 th.principal = new GenericPrincipal (new GenericIdentity (name, auth_type), roles);
198 } else if (type == 2 || type == 3) {
199 string [] roles = type == 2 ? null : new string [0];
200 th.principal = new GenericPrincipal (new GenericIdentity ("", ""), roles);
204 static void SerializePrincipal (Thread th, IPrincipal value)
206 MemoryStream ms = new MemoryStream ();
208 if (value.GetType () == typeof (GenericPrincipal)) {
209 GenericPrincipal gp = (GenericPrincipal) value;
210 if (gp.Identity != null && gp.Identity.GetType () == typeof (GenericIdentity)) {
211 GenericIdentity id = (GenericIdentity) gp.Identity;
212 if (id.Name == "" && id.AuthenticationType == "") {
213 if (gp.Roles == null) {
216 } else if (gp.Roles.Length == 0) {
222 BinaryWriter br = new BinaryWriter (ms);
223 br.Write (gp.Identity.Name);
224 br.Write (gp.Identity.AuthenticationType);
225 string [] roles = gp.Roles;
227 br.Write ((int) (-1));
229 br.Write (roles.Length);
230 foreach (string s in roles) {
241 BinaryFormatter bf = new BinaryFormatter ();
243 bf.Serialize (ms, value);
246 th.Internal._serialized_principal = ByteArrayToRootDomain (ms.ToArray ());
249 public static IPrincipal CurrentPrincipal {
251 Thread th = CurrentThread;
253 if (th.principal_version != th.Internal._serialized_principal_version)
256 if (th.principal != null)
259 if (th.Internal._serialized_principal != null) {
261 DeserializePrincipal (th);
266 th.principal = GetDomain ().DefaultPrincipal;
267 th.principal_version = th.Internal._serialized_principal_version;
270 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
272 Thread th = CurrentThread;
274 if (value != GetDomain ().DefaultPrincipal) {
275 ++th.Internal._serialized_principal_version;
277 SerializePrincipal (th, value);
278 } catch (Exception) {
279 th.Internal._serialized_principal = null;
281 th.principal_version = th.Internal._serialized_principal_version;
283 th.Internal._serialized_principal = null;
286 th.principal = value;
290 // Looks up the object associated with the current thread
291 // this is called by the JIT directly, too
292 [MethodImplAttribute(MethodImplOptions.InternalCall)]
293 private extern static InternalThread CurrentInternalThread_internal();
295 public static Thread CurrentThread {
296 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
298 if (current_thread == null)
299 current_thread = new Thread (CurrentInternalThread_internal ());
300 return current_thread;
304 internal static int CurrentThreadId {
306 return (int)(CurrentThread.internal_thread.thread_id);
310 public static AppDomain GetDomain() {
311 return AppDomain.CurrentDomain;
314 [MethodImplAttribute(MethodImplOptions.InternalCall)]
315 public extern static int GetDomainID();
317 // Returns the system thread handle
318 [MethodImplAttribute(MethodImplOptions.InternalCall)]
319 private extern IntPtr Thread_internal (MulticastDelegate start);
321 private Thread (InternalThread it) {
322 internal_thread = it;
325 // part of ".NETPortable,Version=v4.0,Profile=Profile3" i.e. FX4 and SL4
326 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
331 [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
332 public ApartmentState ApartmentState {
334 if ((ThreadState & ThreadState.Stopped) != 0)
335 throw new ThreadStateException ("Thread is dead; state can not be accessed.");
337 return (ApartmentState)Internal.apartment_state;
341 TrySetApartmentState (value);
345 public bool IsThreadPoolThread {
347 return IsThreadPoolThreadInternal;
351 internal bool IsThreadPoolThreadInternal {
353 return Internal.threadpool_thread;
356 Internal.threadpool_thread = value;
360 public bool IsAlive {
362 ThreadState curstate = GetState (Internal);
364 if((curstate & ThreadState.Aborted) != 0 ||
365 (curstate & ThreadState.Stopped) != 0 ||
366 (curstate & ThreadState.Unstarted) != 0) {
374 public bool IsBackground {
376 ThreadState thread_state = GetState (Internal);
377 if ((thread_state & ThreadState.Stopped) != 0)
378 throw new ThreadStateException ("Thread is dead; state can not be accessed.");
380 return (thread_state & ThreadState.Background) != 0;
385 SetState (Internal, ThreadState.Background);
387 ClrState (Internal, ThreadState.Background);
392 [MethodImplAttribute(MethodImplOptions.InternalCall)]
393 private extern static string GetName_internal (InternalThread thread);
395 [MethodImplAttribute(MethodImplOptions.InternalCall)]
396 private extern static void SetName_internal (InternalThread thread, String name);
399 * The thread name must be shared by appdomains, so it is stored in
405 return GetName_internal (Internal);
409 SetName_internal (Internal, value);
413 public ThreadState ThreadState {
415 return GetState (Internal);
419 #if MONO_FEATURE_THREAD_ABORT
420 [MethodImplAttribute(MethodImplOptions.InternalCall)]
421 private extern static void Abort_internal (InternalThread thread, object stateInfo);
423 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
426 Abort_internal (Internal, null);
429 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
430 public void Abort (object stateInfo)
432 Abort_internal (Internal, stateInfo);
435 [MethodImplAttribute(MethodImplOptions.InternalCall)]
436 extern object GetAbortExceptionState ();
438 internal object AbortReason {
440 return GetAbortExceptionState ();
444 void ClearAbortReason ()
448 [Obsolete ("Thread.Abort is not supported on the current platform.", true)]
451 throw new PlatformNotSupportedException ("Thread.Abort is not supported on the current platform.");
454 [Obsolete ("Thread.Abort is not supported on the current platform.", true)]
455 public void Abort (object stateInfo)
457 throw new PlatformNotSupportedException ("Thread.Abort is not supported on the current platform.");
460 [Obsolete ("Thread.ResetAbort is not supported on the current platform.", true)]
461 public static void ResetAbort ()
463 throw new PlatformNotSupportedException ("Thread.ResetAbort is not supported on the current platform.");
466 internal object AbortReason {
468 throw new PlatformNotSupportedException ("Thread.ResetAbort is not supported on the current platform.");
471 #endif // MONO_FEATURE_THREAD_ABORT
473 [MethodImplAttribute (MethodImplOptions.InternalCall)]
474 private extern static void SpinWait_nop ();
477 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
478 public static void SpinWait (int iterations)
482 while (iterations-- > 0)
488 void StartInternal (IPrincipal principal, ref StackCrawlMark stackMark)
490 #if FEATURE_ROLE_BASED_SECURITY
491 Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
494 // Thread_internal creates and starts the new thread,
495 if (Thread_internal(m_Delegate) == IntPtr.Zero)
496 throw new SystemException ("Thread creation failed.");
498 m_ThreadStartArg = null;
501 [MethodImplAttribute (MethodImplOptions.InternalCall)]
502 extern private static void SetState (InternalThread thread, ThreadState set);
504 [MethodImplAttribute (MethodImplOptions.InternalCall)]
505 extern private static void ClrState (InternalThread thread, ThreadState clr);
507 [MethodImplAttribute (MethodImplOptions.InternalCall)]
508 extern private static ThreadState GetState (InternalThread thread);
510 [MethodImplAttribute (MethodImplOptions.InternalCall)]
511 extern public static byte VolatileRead (ref byte address);
513 [MethodImplAttribute (MethodImplOptions.InternalCall)]
514 extern public static double VolatileRead (ref double address);
516 [MethodImplAttribute (MethodImplOptions.InternalCall)]
517 extern public static short VolatileRead (ref short address);
519 [MethodImplAttribute (MethodImplOptions.InternalCall)]
520 extern public static int VolatileRead (ref int address);
522 [MethodImplAttribute (MethodImplOptions.InternalCall)]
523 extern public static long VolatileRead (ref long address);
525 [MethodImplAttribute (MethodImplOptions.InternalCall)]
526 extern public static IntPtr VolatileRead (ref IntPtr address);
528 [MethodImplAttribute (MethodImplOptions.InternalCall)]
529 extern public static object VolatileRead (ref object address);
531 [CLSCompliant(false)]
532 [MethodImplAttribute (MethodImplOptions.InternalCall)]
533 extern public static sbyte VolatileRead (ref sbyte address);
535 [MethodImplAttribute (MethodImplOptions.InternalCall)]
536 extern public static float VolatileRead (ref float address);
538 [CLSCompliant (false)]
539 [MethodImplAttribute (MethodImplOptions.InternalCall)]
540 extern public static ushort VolatileRead (ref ushort address);
542 [CLSCompliant (false)]
543 [MethodImplAttribute (MethodImplOptions.InternalCall)]
544 extern public static uint VolatileRead (ref uint address);
546 [CLSCompliant (false)]
547 [MethodImplAttribute (MethodImplOptions.InternalCall)]
548 extern public static ulong VolatileRead (ref ulong address);
550 [CLSCompliant (false)]
551 [MethodImplAttribute (MethodImplOptions.InternalCall)]
552 extern public static UIntPtr VolatileRead (ref UIntPtr address);
554 [MethodImplAttribute (MethodImplOptions.InternalCall)]
555 extern public static void VolatileWrite (ref byte address, byte value);
557 [MethodImplAttribute (MethodImplOptions.InternalCall)]
558 extern public static void VolatileWrite (ref double address, double value);
560 [MethodImplAttribute (MethodImplOptions.InternalCall)]
561 extern public static void VolatileWrite (ref short address, short value);
563 [MethodImplAttribute (MethodImplOptions.InternalCall)]
564 extern public static void VolatileWrite (ref int address, int value);
566 [MethodImplAttribute (MethodImplOptions.InternalCall)]
567 extern public static void VolatileWrite (ref long address, long value);
569 [MethodImplAttribute (MethodImplOptions.InternalCall)]
570 extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
572 [MethodImplAttribute (MethodImplOptions.InternalCall)]
573 extern public static void VolatileWrite (ref object address, object value);
575 [CLSCompliant(false)]
576 [MethodImplAttribute (MethodImplOptions.InternalCall)]
577 extern public static void VolatileWrite (ref sbyte address, sbyte value);
579 [MethodImplAttribute (MethodImplOptions.InternalCall)]
580 extern public static void VolatileWrite (ref float address, float value);
582 [CLSCompliant (false)]
583 [MethodImplAttribute (MethodImplOptions.InternalCall)]
584 extern public static void VolatileWrite (ref ushort address, ushort value);
586 [CLSCompliant (false)]
587 [MethodImplAttribute (MethodImplOptions.InternalCall)]
588 extern public static void VolatileWrite (ref uint address, uint value);
590 [CLSCompliant (false)]
591 [MethodImplAttribute (MethodImplOptions.InternalCall)]
592 extern public static void VolatileWrite (ref ulong address, ulong value);
594 [CLSCompliant (false)]
595 [MethodImplAttribute (MethodImplOptions.InternalCall)]
596 extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
598 [MethodImplAttribute (MethodImplOptions.InternalCall)]
599 extern static int SystemMaxStackStize ();
601 static int GetProcessDefaultStackSize (int maxStackSize)
603 if (maxStackSize == 0)
606 if (maxStackSize < 131072) // make sure stack is at least 128k big
609 int page_size = Environment.GetPageSize ();
611 if ((maxStackSize % page_size) != 0) // round up to a divisible of page size
612 maxStackSize = (maxStackSize / (page_size - 1)) * page_size;
614 /* Respect the max stack size imposed by the system*/
615 return Math.Min (maxStackSize, SystemMaxStackStize ());
618 void SetStart (MulticastDelegate start, int maxStackSize)
621 Internal.stack_size = maxStackSize;
624 public int ManagedThreadId {
625 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
627 return Internal.managed_id;
631 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
632 public static void BeginCriticalRegion ()
634 CurrentThread.Internal.critical_region_level++;
637 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
638 public static void EndCriticalRegion ()
640 CurrentThread.Internal.critical_region_level--;
643 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
644 public static void BeginThreadAffinity ()
646 // Managed and native threads are currently bound together.
649 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
650 public static void EndThreadAffinity ()
652 // Managed and native threads are currently bound together.
655 public ApartmentState GetApartmentState ()
657 return (ApartmentState)Internal.apartment_state;
660 public void SetApartmentState (ApartmentState state)
662 if (!TrySetApartmentState (state))
663 throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
666 public bool TrySetApartmentState (ApartmentState state)
668 if ((ThreadState & ThreadState.Unstarted) == 0)
669 throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
671 if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown &&
672 (ApartmentState)Internal.apartment_state != state)
675 Internal.apartment_state = (byte)state;
681 public override int GetHashCode ()
683 return ManagedThreadId;
686 [MethodImplAttribute(MethodImplOptions.InternalCall)]
687 internal static extern void GetStackTraces (out Thread[] threads, out object[] stack_frames);
689 // This is a mono extension to gather the stack traces for all running threads
690 internal static Dictionary<Thread, StackTrace> Mono_GetStackTraces () {
692 object[] stack_frames;
694 GetStackTraces (out threads, out stack_frames);
696 var res = new Dictionary<Thread, StackTrace> ();
697 for (int i = 0; i < threads.Length; ++i)
698 res [threads [i]] = new StackTrace ((StackFrame[])stack_frames [i]);
702 #if !MONO_FEATURE_THREAD_SUSPEND_RESUME
703 [Obsolete ("Thread.Suspend is not supported on the current platform.", true)]
704 public void Suspend ()
706 throw new PlatformNotSupportedException ("Thread.Suspend is not supported on the current platform.");
709 [Obsolete ("Thread.Resume is not supported on the current platform.", true)]
710 public void Resume ()
712 throw new PlatformNotSupportedException ("Thread.Resume is not supported on the current platform.");
716 public void DisableComObjectEagerCleanup ()
718 throw new PlatformNotSupportedException ();