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
52 internal IntPtr system_thread_handle;
54 /* Note this is an opaque object (an array), not a CultureInfo */
55 private object cached_culture_info;
56 /* accessed only from unmanaged code */
59 private ThreadState state;
60 private object abort_exc;
61 private int abort_state_handle;
62 /* thread_id is only accessed from unmanaged code */
63 internal Int64 thread_id;
65 /* start_notify is used by the runtime to signal that Start()
68 private IntPtr stack_ptr;
69 private UIntPtr static_data; /* GC-tracked */
70 private IntPtr runtime_thread_info;
71 /* current System.Runtime.Remoting.Contexts.Context instance
72 keep as an object to avoid triggering its class constructor when not needed */
73 private object current_appcontext;
74 private object root_domain_thread;
75 internal byte[] _serialized_principal;
76 internal int _serialized_principal_version;
77 private IntPtr appdomain_refs;
78 private int interruption_requested;
79 private IntPtr synch_cs;
80 internal bool threadpool_thread;
81 private bool thread_interrupt_requested;
82 /* These are used from managed code */
83 internal int stack_size;
84 internal byte apartment_state;
85 internal volatile int critical_region_level;
86 internal int managed_id;
88 private IntPtr manage_callback;
89 private IntPtr interrupt_on_stop;
91 private IntPtr thread_pinning_ref;
92 private IntPtr abort_protected_block_count;
93 private int priority = (int) ThreadPriority.Normal;
94 private IntPtr owned_mutex;
96 * These fields are used to avoid having to increment corlib versions
97 * when a new field is added to the unmanaged MonoThread structure.
99 private IntPtr unused1;
100 private IntPtr unused2;
102 /* This is used only to check that we are in sync between the representation
103 * of MonoInternalThread in native and InternalThread in managed
105 * DO NOT RENAME! DO NOT ADD FIELDS AFTER! */
108 #pragma warning restore 169, 414, 649
110 // Closes the system thread handle
111 [MethodImplAttribute(MethodImplOptions.InternalCall)]
112 private extern void Thread_free_internal(IntPtr handle);
114 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
116 Thread_free_internal(system_thread_handle);
120 [StructLayout (LayoutKind.Sequential)]
121 public sealed partial class Thread {
122 #pragma warning disable 414
123 #region Sync with metadata/object-internals.h
124 private InternalThread internal_thread;
125 object m_ThreadStartArg;
126 object pending_exception;
128 #pragma warning restore 414
130 IPrincipal principal;
131 int principal_version;
133 // the name of current_thread is
134 // important because they are used by the runtime.
137 static Thread current_thread;
139 // can be both a ThreadStart and a ParameterizedThreadStart
140 private MulticastDelegate m_Delegate;
142 private ExecutionContext m_ExecutionContext; // this call context follows the logical thread
144 private bool m_ExecutionContextBelongsToOuterScope;
146 [MethodImplAttribute(MethodImplOptions.InternalCall)]
147 private extern void ConstructInternalThread ();
149 private InternalThread Internal {
151 if (internal_thread == null)
152 ConstructInternalThread ();
153 return internal_thread;
157 public static Context CurrentContext {
158 [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
160 return(AppDomain.InternalGetContext ());
165 * These two methods return an array in the target
166 * domain with the same content as the argument. If
167 * the argument is already in the target domain, then
168 * the argument is returned, otherwise a copy.
170 [MethodImplAttribute(MethodImplOptions.InternalCall)]
171 private extern static byte[] ByteArrayToRootDomain (byte[] arr);
173 [MethodImplAttribute(MethodImplOptions.InternalCall)]
174 private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
176 static void DeserializePrincipal (Thread th)
178 MemoryStream ms = new MemoryStream (ByteArrayToCurrentDomain (th.Internal._serialized_principal));
179 int type = ms.ReadByte ();
181 BinaryFormatter bf = new BinaryFormatter ();
182 th.principal = (IPrincipal) bf.Deserialize (ms);
183 th.principal_version = th.Internal._serialized_principal_version;
184 } else if (type == 1) {
185 BinaryReader reader = new BinaryReader (ms);
186 string name = reader.ReadString ();
187 string auth_type = reader.ReadString ();
188 int n_roles = reader.ReadInt32 ();
189 string [] roles = null;
191 roles = new string [n_roles];
192 for (int i = 0; i < n_roles; i++)
193 roles [i] = reader.ReadString ();
195 th.principal = new GenericPrincipal (new GenericIdentity (name, auth_type), roles);
196 } else if (type == 2 || type == 3) {
197 string [] roles = type == 2 ? null : new string [0];
198 th.principal = new GenericPrincipal (new GenericIdentity ("", ""), roles);
202 static void SerializePrincipal (Thread th, IPrincipal value)
204 MemoryStream ms = new MemoryStream ();
206 if (value.GetType () == typeof (GenericPrincipal)) {
207 GenericPrincipal gp = (GenericPrincipal) value;
208 if (gp.Identity != null && gp.Identity.GetType () == typeof (GenericIdentity)) {
209 GenericIdentity id = (GenericIdentity) gp.Identity;
210 if (id.Name == "" && id.AuthenticationType == "") {
211 if (gp.Roles == null) {
214 } else if (gp.Roles.Length == 0) {
220 BinaryWriter br = new BinaryWriter (ms);
221 br.Write (gp.Identity.Name);
222 br.Write (gp.Identity.AuthenticationType);
223 string [] roles = gp.Roles;
225 br.Write ((int) (-1));
227 br.Write (roles.Length);
228 foreach (string s in roles) {
239 BinaryFormatter bf = new BinaryFormatter ();
241 bf.Serialize (ms, value);
244 th.Internal._serialized_principal = ByteArrayToRootDomain (ms.ToArray ());
247 public static IPrincipal CurrentPrincipal {
249 Thread th = CurrentThread;
251 if (th.principal_version != th.Internal._serialized_principal_version)
254 if (th.principal != null)
257 if (th.Internal._serialized_principal != null) {
259 DeserializePrincipal (th);
264 th.principal = GetDomain ().DefaultPrincipal;
265 th.principal_version = th.Internal._serialized_principal_version;
268 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
270 Thread th = CurrentThread;
272 if (value != GetDomain ().DefaultPrincipal) {
273 ++th.Internal._serialized_principal_version;
275 SerializePrincipal (th, value);
276 } catch (Exception) {
277 th.Internal._serialized_principal = null;
279 th.principal_version = th.Internal._serialized_principal_version;
281 th.Internal._serialized_principal = null;
284 th.principal = value;
288 // Looks up the object associated with the current thread
289 // this is called by the JIT directly, too
290 [MethodImplAttribute(MethodImplOptions.InternalCall)]
291 private extern static InternalThread CurrentInternalThread_internal();
293 public static Thread CurrentThread {
294 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
296 if (current_thread == null)
297 current_thread = new Thread (CurrentInternalThread_internal ());
298 return current_thread;
302 internal static int CurrentThreadId {
304 return (int)(CurrentThread.internal_thread.thread_id);
308 public static AppDomain GetDomain() {
309 return AppDomain.CurrentDomain;
312 [MethodImplAttribute(MethodImplOptions.InternalCall)]
313 public extern static int GetDomainID();
315 // Returns the system thread handle
316 [MethodImplAttribute(MethodImplOptions.InternalCall)]
317 private extern IntPtr Thread_internal (MulticastDelegate start);
319 private Thread (InternalThread it) {
320 internal_thread = it;
323 // part of ".NETPortable,Version=v4.0,Profile=Profile3" i.e. FX4 and SL4
324 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
329 [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
330 public ApartmentState ApartmentState {
332 if ((ThreadState & ThreadState.Stopped) != 0)
333 throw new ThreadStateException ("Thread is dead; state can not be accessed.");
335 return (ApartmentState)Internal.apartment_state;
339 TrySetApartmentState (value);
343 public bool IsThreadPoolThread {
345 return IsThreadPoolThreadInternal;
349 internal bool IsThreadPoolThreadInternal {
351 return Internal.threadpool_thread;
354 Internal.threadpool_thread = value;
358 public bool IsAlive {
360 ThreadState curstate = GetState (Internal);
362 if((curstate & ThreadState.Aborted) != 0 ||
363 (curstate & ThreadState.Stopped) != 0 ||
364 (curstate & ThreadState.Unstarted) != 0) {
372 public bool IsBackground {
374 ThreadState thread_state = GetState (Internal);
375 if ((thread_state & ThreadState.Stopped) != 0)
376 throw new ThreadStateException ("Thread is dead; state can not be accessed.");
378 return (thread_state & ThreadState.Background) != 0;
383 SetState (Internal, ThreadState.Background);
385 ClrState (Internal, ThreadState.Background);
390 [MethodImplAttribute(MethodImplOptions.InternalCall)]
391 private extern static string GetName_internal (InternalThread thread);
393 [MethodImplAttribute(MethodImplOptions.InternalCall)]
394 private extern static void SetName_internal (InternalThread thread, String name);
397 * The thread name must be shared by appdomains, so it is stored in
403 return GetName_internal (Internal);
407 SetName_internal (Internal, value);
411 public ThreadState ThreadState {
413 return GetState (Internal);
417 #if MONO_FEATURE_THREAD_ABORT
418 [MethodImplAttribute(MethodImplOptions.InternalCall)]
419 private extern static void Abort_internal (InternalThread thread, object stateInfo);
421 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
424 Abort_internal (Internal, null);
427 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
428 public void Abort (object stateInfo)
430 Abort_internal (Internal, stateInfo);
433 [MethodImplAttribute(MethodImplOptions.InternalCall)]
434 extern object GetAbortExceptionState ();
436 internal object AbortReason {
438 return GetAbortExceptionState ();
442 void ClearAbortReason ()
446 [Obsolete ("Thread.Abort is not supported on the current platform.", true)]
449 throw new PlatformNotSupportedException ("Thread.Abort is not supported on the current platform.");
452 [Obsolete ("Thread.Abort is not supported on the current platform.", true)]
453 public void Abort (object stateInfo)
455 throw new PlatformNotSupportedException ("Thread.Abort is not supported on the current platform.");
458 [Obsolete ("Thread.ResetAbort is not supported on the current platform.", true)]
459 public static void ResetAbort ()
461 throw new PlatformNotSupportedException ("Thread.ResetAbort is not supported on the current platform.");
464 internal object AbortReason {
466 throw new PlatformNotSupportedException ("Thread.ResetAbort is not supported on the current platform.");
469 #endif // MONO_FEATURE_THREAD_ABORT
471 [MethodImplAttribute (MethodImplOptions.InternalCall)]
472 private extern static void SpinWait_nop ();
475 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
476 public static void SpinWait (int iterations)
480 while (iterations-- > 0)
486 void StartInternal (IPrincipal principal, ref StackCrawlMark stackMark)
488 #if FEATURE_ROLE_BASED_SECURITY
489 Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
492 // Thread_internal creates and starts the new thread,
493 if (Thread_internal(m_Delegate) == IntPtr.Zero)
494 throw new SystemException ("Thread creation failed.");
496 m_ThreadStartArg = null;
499 [MethodImplAttribute (MethodImplOptions.InternalCall)]
500 extern private static void SetState (InternalThread thread, ThreadState set);
502 [MethodImplAttribute (MethodImplOptions.InternalCall)]
503 extern private static void ClrState (InternalThread thread, ThreadState clr);
505 [MethodImplAttribute (MethodImplOptions.InternalCall)]
506 extern private static ThreadState GetState (InternalThread thread);
508 [MethodImplAttribute (MethodImplOptions.InternalCall)]
509 extern public static byte VolatileRead (ref byte address);
511 [MethodImplAttribute (MethodImplOptions.InternalCall)]
512 extern public static double VolatileRead (ref double address);
514 [MethodImplAttribute (MethodImplOptions.InternalCall)]
515 extern public static short VolatileRead (ref short address);
517 [MethodImplAttribute (MethodImplOptions.InternalCall)]
518 extern public static int VolatileRead (ref int address);
520 [MethodImplAttribute (MethodImplOptions.InternalCall)]
521 extern public static long VolatileRead (ref long address);
523 [MethodImplAttribute (MethodImplOptions.InternalCall)]
524 extern public static IntPtr VolatileRead (ref IntPtr address);
526 [MethodImplAttribute (MethodImplOptions.InternalCall)]
527 extern public static object VolatileRead (ref object address);
529 [CLSCompliant(false)]
530 [MethodImplAttribute (MethodImplOptions.InternalCall)]
531 extern public static sbyte VolatileRead (ref sbyte address);
533 [MethodImplAttribute (MethodImplOptions.InternalCall)]
534 extern public static float VolatileRead (ref float address);
536 [CLSCompliant (false)]
537 [MethodImplAttribute (MethodImplOptions.InternalCall)]
538 extern public static ushort VolatileRead (ref ushort address);
540 [CLSCompliant (false)]
541 [MethodImplAttribute (MethodImplOptions.InternalCall)]
542 extern public static uint VolatileRead (ref uint address);
544 [CLSCompliant (false)]
545 [MethodImplAttribute (MethodImplOptions.InternalCall)]
546 extern public static ulong VolatileRead (ref ulong address);
548 [CLSCompliant (false)]
549 [MethodImplAttribute (MethodImplOptions.InternalCall)]
550 extern public static UIntPtr VolatileRead (ref UIntPtr address);
552 [MethodImplAttribute (MethodImplOptions.InternalCall)]
553 extern public static void VolatileWrite (ref byte address, byte value);
555 [MethodImplAttribute (MethodImplOptions.InternalCall)]
556 extern public static void VolatileWrite (ref double address, double value);
558 [MethodImplAttribute (MethodImplOptions.InternalCall)]
559 extern public static void VolatileWrite (ref short address, short value);
561 [MethodImplAttribute (MethodImplOptions.InternalCall)]
562 extern public static void VolatileWrite (ref int address, int value);
564 [MethodImplAttribute (MethodImplOptions.InternalCall)]
565 extern public static void VolatileWrite (ref long address, long value);
567 [MethodImplAttribute (MethodImplOptions.InternalCall)]
568 extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
570 [MethodImplAttribute (MethodImplOptions.InternalCall)]
571 extern public static void VolatileWrite (ref object address, object value);
573 [CLSCompliant(false)]
574 [MethodImplAttribute (MethodImplOptions.InternalCall)]
575 extern public static void VolatileWrite (ref sbyte address, sbyte value);
577 [MethodImplAttribute (MethodImplOptions.InternalCall)]
578 extern public static void VolatileWrite (ref float address, float value);
580 [CLSCompliant (false)]
581 [MethodImplAttribute (MethodImplOptions.InternalCall)]
582 extern public static void VolatileWrite (ref ushort address, ushort value);
584 [CLSCompliant (false)]
585 [MethodImplAttribute (MethodImplOptions.InternalCall)]
586 extern public static void VolatileWrite (ref uint address, uint value);
588 [CLSCompliant (false)]
589 [MethodImplAttribute (MethodImplOptions.InternalCall)]
590 extern public static void VolatileWrite (ref ulong address, ulong value);
592 [CLSCompliant (false)]
593 [MethodImplAttribute (MethodImplOptions.InternalCall)]
594 extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
596 [MethodImplAttribute (MethodImplOptions.InternalCall)]
597 extern static int SystemMaxStackStize ();
599 static int GetProcessDefaultStackSize (int maxStackSize)
601 if (maxStackSize == 0)
604 if (maxStackSize < 131072) // make sure stack is at least 128k big
607 int page_size = Environment.GetPageSize ();
609 if ((maxStackSize % page_size) != 0) // round up to a divisible of page size
610 maxStackSize = (maxStackSize / (page_size - 1)) * page_size;
612 /* Respect the max stack size imposed by the system*/
613 return Math.Min (maxStackSize, SystemMaxStackStize ());
616 void SetStart (MulticastDelegate start, int maxStackSize)
619 Internal.stack_size = maxStackSize;
622 public int ManagedThreadId {
623 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
625 return Internal.managed_id;
629 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
630 public static void BeginCriticalRegion ()
632 CurrentThread.Internal.critical_region_level++;
635 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
636 public static void EndCriticalRegion ()
638 CurrentThread.Internal.critical_region_level--;
641 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
642 public static void BeginThreadAffinity ()
644 // Managed and native threads are currently bound together.
647 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
648 public static void EndThreadAffinity ()
650 // Managed and native threads are currently bound together.
653 public ApartmentState GetApartmentState ()
655 return (ApartmentState)Internal.apartment_state;
658 public void SetApartmentState (ApartmentState state)
660 if (!TrySetApartmentState (state))
661 throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
664 public bool TrySetApartmentState (ApartmentState state)
666 if ((ThreadState & ThreadState.Unstarted) == 0)
667 throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
669 if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown &&
670 (ApartmentState)Internal.apartment_state != state)
673 Internal.apartment_state = (byte)state;
679 public override int GetHashCode ()
681 return ManagedThreadId;
684 [MethodImplAttribute(MethodImplOptions.InternalCall)]
685 internal static extern void GetStackTraces (out Thread[] threads, out object[] stack_frames);
687 // This is a mono extension to gather the stack traces for all running threads
688 internal static Dictionary<Thread, StackTrace> Mono_GetStackTraces () {
690 object[] stack_frames;
692 GetStackTraces (out threads, out stack_frames);
694 var res = new Dictionary<Thread, StackTrace> ();
695 for (int i = 0; i < threads.Length; ++i)
696 res [threads [i]] = new StackTrace ((StackFrame[])stack_frames [i]);
700 #if !MONO_FEATURE_THREAD_SUSPEND_RESUME
701 [Obsolete ("Thread.Suspend is not supported on the current platform.", true)]
702 public void Suspend ()
704 throw new PlatformNotSupportedException ("Thread.Suspend is not supported on the current platform.");
707 [Obsolete ("Thread.Resume is not supported on the current platform.", true)]
708 public void Resume ()
710 throw new PlatformNotSupportedException ("Thread.Resume is not supported on the current platform.");
714 public void DisableComObjectEagerCleanup ()
716 throw new PlatformNotSupportedException ();