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 start_notify;
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 start_notify_refcount;
95 * These fields are used to avoid having to increment corlib versions
96 * when a new field is added to the unmanaged MonoThread structure.
98 private IntPtr unused2;
100 #pragma warning restore 169, 414, 649
102 // Closes the system thread handle
103 [MethodImplAttribute(MethodImplOptions.InternalCall)]
104 private extern void Thread_free_internal(IntPtr handle);
106 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
108 Thread_free_internal(system_thread_handle);
112 [StructLayout (LayoutKind.Sequential)]
113 public sealed partial class Thread {
114 #pragma warning disable 414
115 #region Sync with metadata/object-internals.h
116 private InternalThread internal_thread;
117 object m_ThreadStartArg;
118 object pending_exception;
119 int priority = (int) ThreadPriority.Normal;
121 #pragma warning restore 414
123 IPrincipal principal;
124 int principal_version;
126 // the name of current_thread is
127 // important because they are used by the runtime.
130 static Thread current_thread;
132 // can be both a ThreadStart and a ParameterizedThreadStart
133 private MulticastDelegate m_Delegate;
135 private ExecutionContext m_ExecutionContext; // this call context follows the logical thread
137 private bool m_ExecutionContextBelongsToOuterScope;
139 [MethodImplAttribute(MethodImplOptions.InternalCall)]
140 private extern void ConstructInternalThread ();
142 private InternalThread Internal {
144 if (internal_thread == null)
145 ConstructInternalThread ();
146 return internal_thread;
150 public static Context CurrentContext {
151 [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
153 return(AppDomain.InternalGetContext ());
158 * These two methods return an array in the target
159 * domain with the same content as the argument. If
160 * the argument is already in the target domain, then
161 * the argument is returned, otherwise a copy.
163 [MethodImplAttribute(MethodImplOptions.InternalCall)]
164 private extern static byte[] ByteArrayToRootDomain (byte[] arr);
166 [MethodImplAttribute(MethodImplOptions.InternalCall)]
167 private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
169 static void DeserializePrincipal (Thread th)
171 MemoryStream ms = new MemoryStream (ByteArrayToCurrentDomain (th.Internal._serialized_principal));
172 int type = ms.ReadByte ();
174 BinaryFormatter bf = new BinaryFormatter ();
175 th.principal = (IPrincipal) bf.Deserialize (ms);
176 th.principal_version = th.Internal._serialized_principal_version;
177 } else if (type == 1) {
178 BinaryReader reader = new BinaryReader (ms);
179 string name = reader.ReadString ();
180 string auth_type = reader.ReadString ();
181 int n_roles = reader.ReadInt32 ();
182 string [] roles = null;
184 roles = new string [n_roles];
185 for (int i = 0; i < n_roles; i++)
186 roles [i] = reader.ReadString ();
188 th.principal = new GenericPrincipal (new GenericIdentity (name, auth_type), roles);
189 } else if (type == 2 || type == 3) {
190 string [] roles = type == 2 ? null : new string [0];
191 th.principal = new GenericPrincipal (new GenericIdentity ("", ""), roles);
195 static void SerializePrincipal (Thread th, IPrincipal value)
197 MemoryStream ms = new MemoryStream ();
199 if (value.GetType () == typeof (GenericPrincipal)) {
200 GenericPrincipal gp = (GenericPrincipal) value;
201 if (gp.Identity != null && gp.Identity.GetType () == typeof (GenericIdentity)) {
202 GenericIdentity id = (GenericIdentity) gp.Identity;
203 if (id.Name == "" && id.AuthenticationType == "") {
204 if (gp.Roles == null) {
207 } else if (gp.Roles.Length == 0) {
213 BinaryWriter br = new BinaryWriter (ms);
214 br.Write (gp.Identity.Name);
215 br.Write (gp.Identity.AuthenticationType);
216 string [] roles = gp.Roles;
218 br.Write ((int) (-1));
220 br.Write (roles.Length);
221 foreach (string s in roles) {
232 BinaryFormatter bf = new BinaryFormatter ();
234 bf.Serialize (ms, value);
237 th.Internal._serialized_principal = ByteArrayToRootDomain (ms.ToArray ());
240 public static IPrincipal CurrentPrincipal {
242 Thread th = CurrentThread;
244 if (th.principal_version != th.Internal._serialized_principal_version)
247 if (th.principal != null)
250 if (th.Internal._serialized_principal != null) {
252 DeserializePrincipal (th);
257 th.principal = GetDomain ().DefaultPrincipal;
258 th.principal_version = th.Internal._serialized_principal_version;
261 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
263 Thread th = CurrentThread;
265 if (value != GetDomain ().DefaultPrincipal) {
266 ++th.Internal._serialized_principal_version;
268 SerializePrincipal (th, value);
269 } catch (Exception) {
270 th.Internal._serialized_principal = null;
272 th.principal_version = th.Internal._serialized_principal_version;
274 th.Internal._serialized_principal = null;
277 th.principal = value;
281 // Looks up the object associated with the current thread
282 // this is called by the JIT directly, too
283 [MethodImplAttribute(MethodImplOptions.InternalCall)]
284 private extern static InternalThread CurrentInternalThread_internal();
286 public static Thread CurrentThread {
287 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
289 if (current_thread == null)
290 current_thread = new Thread (CurrentInternalThread_internal ());
291 return current_thread;
295 internal static int CurrentThreadId {
297 return (int)(CurrentThread.internal_thread.thread_id);
301 public static AppDomain GetDomain() {
302 return AppDomain.CurrentDomain;
305 [MethodImplAttribute(MethodImplOptions.InternalCall)]
306 public extern static int GetDomainID();
308 // Returns the system thread handle
309 [MethodImplAttribute(MethodImplOptions.InternalCall)]
310 private extern IntPtr Thread_internal (MulticastDelegate start);
312 private Thread (InternalThread it) {
313 internal_thread = it;
316 // part of ".NETPortable,Version=v4.0,Profile=Profile3" i.e. FX4 and SL4
317 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
322 [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
323 public ApartmentState ApartmentState {
325 if ((ThreadState & ThreadState.Stopped) != 0)
326 throw new ThreadStateException ("Thread is dead; state can not be accessed.");
328 return (ApartmentState)Internal.apartment_state;
332 TrySetApartmentState (value);
336 public bool IsThreadPoolThread {
338 return IsThreadPoolThreadInternal;
342 internal bool IsThreadPoolThreadInternal {
344 return Internal.threadpool_thread;
347 Internal.threadpool_thread = value;
351 public bool IsAlive {
353 ThreadState curstate = GetState (Internal);
355 if((curstate & ThreadState.Aborted) != 0 ||
356 (curstate & ThreadState.Stopped) != 0 ||
357 (curstate & ThreadState.Unstarted) != 0) {
365 public bool IsBackground {
367 ThreadState thread_state = GetState (Internal);
368 if ((thread_state & ThreadState.Stopped) != 0)
369 throw new ThreadStateException ("Thread is dead; state can not be accessed.");
371 return (thread_state & ThreadState.Background) != 0;
376 SetState (Internal, ThreadState.Background);
378 ClrState (Internal, ThreadState.Background);
383 [MethodImplAttribute(MethodImplOptions.InternalCall)]
384 private extern static string GetName_internal (InternalThread thread);
386 [MethodImplAttribute(MethodImplOptions.InternalCall)]
387 private extern static void SetName_internal (InternalThread thread, String name);
390 * The thread name must be shared by appdomains, so it is stored in
396 return GetName_internal (Internal);
400 SetName_internal (Internal, value);
404 public ThreadState ThreadState {
406 return GetState (Internal);
410 #if MONO_FEATURE_THREAD_ABORT
411 [MethodImplAttribute(MethodImplOptions.InternalCall)]
412 private extern static void Abort_internal (InternalThread thread, object stateInfo);
414 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
417 Abort_internal (Internal, null);
420 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
421 public void Abort (object stateInfo)
423 Abort_internal (Internal, stateInfo);
426 [MethodImplAttribute(MethodImplOptions.InternalCall)]
427 extern object GetAbortExceptionState ();
429 internal object AbortReason {
431 return GetAbortExceptionState ();
435 void ClearAbortReason ()
439 [Obsolete ("Thread.Abort is not supported on the current platform.", true)]
442 throw new PlatformNotSupportedException ("Thread.Abort is not supported on the current platform.");
445 [Obsolete ("Thread.Abort is not supported on the current platform.", true)]
446 public void Abort (object stateInfo)
448 throw new PlatformNotSupportedException ("Thread.Abort is not supported on the current platform.");
451 [Obsolete ("Thread.ResetAbort is not supported on the current platform.", true)]
452 public static void ResetAbort ()
454 throw new PlatformNotSupportedException ("Thread.ResetAbort is not supported on the current platform.");
456 #endif // MONO_FEATURE_THREAD_ABORT
458 [MethodImplAttribute (MethodImplOptions.InternalCall)]
459 private extern static void SpinWait_nop ();
462 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
463 public static void SpinWait (int iterations)
467 while (iterations-- > 0)
473 void StartInternal (IPrincipal principal, ref StackCrawlMark stackMark)
475 #if FEATURE_ROLE_BASED_SECURITY
476 Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
479 // Thread_internal creates and starts the new thread,
480 if (Thread_internal(m_Delegate) == IntPtr.Zero)
481 throw new SystemException ("Thread creation failed.");
483 m_ThreadStartArg = null;
486 [MethodImplAttribute (MethodImplOptions.InternalCall)]
487 extern private static void SetState (InternalThread thread, ThreadState set);
489 [MethodImplAttribute (MethodImplOptions.InternalCall)]
490 extern private static void ClrState (InternalThread thread, ThreadState clr);
492 [MethodImplAttribute (MethodImplOptions.InternalCall)]
493 extern private static ThreadState GetState (InternalThread thread);
495 [MethodImplAttribute (MethodImplOptions.InternalCall)]
496 extern public static byte VolatileRead (ref byte address);
498 [MethodImplAttribute (MethodImplOptions.InternalCall)]
499 extern public static double VolatileRead (ref double address);
501 [MethodImplAttribute (MethodImplOptions.InternalCall)]
502 extern public static short VolatileRead (ref short address);
504 [MethodImplAttribute (MethodImplOptions.InternalCall)]
505 extern public static int VolatileRead (ref int address);
507 [MethodImplAttribute (MethodImplOptions.InternalCall)]
508 extern public static long VolatileRead (ref long address);
510 [MethodImplAttribute (MethodImplOptions.InternalCall)]
511 extern public static IntPtr VolatileRead (ref IntPtr address);
513 [MethodImplAttribute (MethodImplOptions.InternalCall)]
514 extern public static object VolatileRead (ref object address);
516 [CLSCompliant(false)]
517 [MethodImplAttribute (MethodImplOptions.InternalCall)]
518 extern public static sbyte VolatileRead (ref sbyte address);
520 [MethodImplAttribute (MethodImplOptions.InternalCall)]
521 extern public static float VolatileRead (ref float address);
523 [CLSCompliant (false)]
524 [MethodImplAttribute (MethodImplOptions.InternalCall)]
525 extern public static ushort VolatileRead (ref ushort address);
527 [CLSCompliant (false)]
528 [MethodImplAttribute (MethodImplOptions.InternalCall)]
529 extern public static uint VolatileRead (ref uint address);
531 [CLSCompliant (false)]
532 [MethodImplAttribute (MethodImplOptions.InternalCall)]
533 extern public static ulong VolatileRead (ref ulong address);
535 [CLSCompliant (false)]
536 [MethodImplAttribute (MethodImplOptions.InternalCall)]
537 extern public static UIntPtr VolatileRead (ref UIntPtr address);
539 [MethodImplAttribute (MethodImplOptions.InternalCall)]
540 extern public static void VolatileWrite (ref byte address, byte value);
542 [MethodImplAttribute (MethodImplOptions.InternalCall)]
543 extern public static void VolatileWrite (ref double address, double value);
545 [MethodImplAttribute (MethodImplOptions.InternalCall)]
546 extern public static void VolatileWrite (ref short address, short value);
548 [MethodImplAttribute (MethodImplOptions.InternalCall)]
549 extern public static void VolatileWrite (ref int address, int value);
551 [MethodImplAttribute (MethodImplOptions.InternalCall)]
552 extern public static void VolatileWrite (ref long address, long value);
554 [MethodImplAttribute (MethodImplOptions.InternalCall)]
555 extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
557 [MethodImplAttribute (MethodImplOptions.InternalCall)]
558 extern public static void VolatileWrite (ref object address, object value);
560 [CLSCompliant(false)]
561 [MethodImplAttribute (MethodImplOptions.InternalCall)]
562 extern public static void VolatileWrite (ref sbyte address, sbyte value);
564 [MethodImplAttribute (MethodImplOptions.InternalCall)]
565 extern public static void VolatileWrite (ref float address, float value);
567 [CLSCompliant (false)]
568 [MethodImplAttribute (MethodImplOptions.InternalCall)]
569 extern public static void VolatileWrite (ref ushort address, ushort value);
571 [CLSCompliant (false)]
572 [MethodImplAttribute (MethodImplOptions.InternalCall)]
573 extern public static void VolatileWrite (ref uint address, uint value);
575 [CLSCompliant (false)]
576 [MethodImplAttribute (MethodImplOptions.InternalCall)]
577 extern public static void VolatileWrite (ref ulong address, ulong value);
579 [CLSCompliant (false)]
580 [MethodImplAttribute (MethodImplOptions.InternalCall)]
581 extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
583 [MethodImplAttribute (MethodImplOptions.InternalCall)]
584 extern static int SystemMaxStackStize ();
586 static int GetProcessDefaultStackSize (int maxStackSize)
588 if (maxStackSize == 0)
591 if (maxStackSize < 131072) // make sure stack is at least 128k big
594 int page_size = Environment.GetPageSize ();
596 if ((maxStackSize % page_size) != 0) // round up to a divisible of page size
597 maxStackSize = (maxStackSize / (page_size - 1)) * page_size;
599 /* Respect the max stack size imposed by the system*/
600 return Math.Min (maxStackSize, SystemMaxStackStize ());
603 void SetStart (MulticastDelegate start, int maxStackSize)
606 Internal.stack_size = maxStackSize;
609 public int ManagedThreadId {
610 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
612 return Internal.managed_id;
616 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
617 public static void BeginCriticalRegion ()
619 CurrentThread.Internal.critical_region_level++;
622 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
623 public static void EndCriticalRegion ()
625 CurrentThread.Internal.critical_region_level--;
628 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
629 public static void BeginThreadAffinity ()
631 // Managed and native threads are currently bound together.
634 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
635 public static void EndThreadAffinity ()
637 // Managed and native threads are currently bound together.
640 public ApartmentState GetApartmentState ()
642 return (ApartmentState)Internal.apartment_state;
645 public void SetApartmentState (ApartmentState state)
647 if (!TrySetApartmentState (state))
648 throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
651 public bool TrySetApartmentState (ApartmentState state)
653 if ((ThreadState & ThreadState.Unstarted) == 0)
654 throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
656 if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown &&
657 (ApartmentState)Internal.apartment_state != state)
660 Internal.apartment_state = (byte)state;
666 public override int GetHashCode ()
668 return ManagedThreadId;
671 [MethodImplAttribute(MethodImplOptions.InternalCall)]
672 internal static extern void GetStackTraces (out Thread[] threads, out object[] stack_frames);
674 // This is a mono extension to gather the stack traces for all running threads
675 internal static Dictionary<Thread, StackTrace> Mono_GetStackTraces () {
677 object[] stack_frames;
679 GetStackTraces (out threads, out stack_frames);
681 var res = new Dictionary<Thread, StackTrace> ();
682 for (int i = 0; i < threads.Length; ++i)
683 res [threads [i]] = new StackTrace ((StackFrame[])stack_frames [i]);
687 #if !MONO_FEATURE_THREAD_SUSPEND_RESUME
688 [Obsolete ("Thread.Suspend is not supported on the current platform.", true)]
689 public void Suspend ()
691 throw new PlatformNotSupportedException ("Thread.Suspend is not supported on the current platform.");
694 [Obsolete ("Thread.Resume is not supported on the current platform.", true)]
695 public void Resume ()
697 throw new PlatformNotSupportedException ("Thread.Resume is not supported on the current platform.");