Wrap always_inline and noinline attributes in compiler checks and use MSVC equivalent.
[mono.git] / mcs / class / corlib / System.Threading / Thread.cs
1 //
2 // System.Threading.Thread.cs
3 //
4 // Author:
5 //   Dick Porter (dick@ximian.com)
6 //
7 // (C) Ximian, Inc.  http://www.ximian.com
8 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
9 //
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:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
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.
28 //
29
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;
38 using System.IO;
39 using System.Collections;
40 using System.Reflection;
41 using System.Security;
42 using System.Runtime.ConstrainedExecution;
43
44 namespace System.Threading {
45         [StructLayout (LayoutKind.Sequential)]
46         internal class InternalThread : CriticalFinalizerObject {
47 #pragma warning disable 169, 414, 649
48                 #region Sync with metadata/object-internals.h
49                 int lock_thread_id;
50                 // stores a thread handle
51                 internal IntPtr system_thread_handle;
52
53                 /* Note this is an opaque object (an array), not a CultureInfo */
54                 private object cached_culture_info; /*FIXME remove this on the next corlib version bump*/
55                 private IntPtr unused0;
56                 internal bool threadpool_thread;
57                 /* accessed only from unmanaged code */
58                 private IntPtr name;
59                 private int name_len; 
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;
65                 
66                 /* start_notify is used by the runtime to signal that Start()
67                  * is ok to return
68                  */
69                 private IntPtr start_notify;
70                 private IntPtr stack_ptr;
71                 private UIntPtr static_data; /* GC-tracked */
72                 private IntPtr jit_data;
73                 private IntPtr runtime_thread_info;
74                 /* current System.Runtime.Remoting.Contexts.Context instance
75                    keep as an object to avoid triggering its class constructor when not needed */
76                 private object current_appcontext;
77                 internal int stack_size;
78                 private IntPtr appdomain_refs;
79                 private int interruption_requested;
80                 private IntPtr suspend_event;
81                 private IntPtr suspended_event;
82                 private IntPtr resume_event;
83                 private IntPtr synch_cs;
84                 private bool thread_dump_requested;
85                 private IntPtr end_stack;
86                 private bool thread_interrupt_requested;
87                 internal byte apartment_state;
88                 internal volatile int critical_region_level;
89                 private int small_id;
90                 private IntPtr manage_callback;
91                 private object pending_exception;
92                 /* This is the ExecutionContext that will be set by
93                    start_wrapper() in the runtime. */
94                 private ExecutionContext ec_to_set;
95
96                 private IntPtr interrupt_on_stop;
97
98                 /* 
99                  * These fields are used to avoid having to increment corlib versions
100                  * when a new field is added to the unmanaged MonoThread structure.
101                  */
102                 private IntPtr unused3;
103                 private IntPtr unused4;
104                 private IntPtr unused5;
105                 internal int managed_id;
106                 int ignore_next_signal;
107                 #endregion
108 #pragma warning restore 169, 414, 649
109
110                 internal byte[] _serialized_principal;
111                 internal int _serialized_principal_version;
112
113                 // Closes the system thread handle
114                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
115                 private extern void Thread_free_internal(IntPtr handle);
116
117                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
118                 ~InternalThread() {
119                         Thread_free_internal(system_thread_handle);
120                 }
121         }
122
123         [ClassInterface (ClassInterfaceType.None)]
124         [ComVisible (true)]
125         [ComDefaultInterface (typeof (_Thread))]
126         [StructLayout (LayoutKind.Sequential)]
127         public sealed class Thread : CriticalFinalizerObject, _Thread {
128 #pragma warning disable 414             
129                 #region Sync with metadata/object-internals.h
130                 private InternalThread internal_thread;
131                 object start_obj;
132                 private ExecutionContext ec_to_set;
133                 #endregion
134 #pragma warning restore 414
135
136                 IPrincipal principal;
137                 int principal_version;
138                 CultureInfo current_culture;
139                 CultureInfo current_ui_culture;
140
141                 // the name of local_slots, current_thread and _ec is
142                 // important because they are used by the runtime.
143                 [ThreadStatic]
144                 static object[] local_slots;
145
146                 [ThreadStatic]
147                 static Thread current_thread;
148
149                 /* The actual ExecutionContext of the thread.  It's
150                    ThreadStatic so that it's not shared between
151                    AppDomains. */
152                 [ThreadStatic]
153                 static ExecutionContext _ec;
154
155                 // can be both a ThreadStart and a ParameterizedThreadStart
156                 private MulticastDelegate threadstart;
157                 //private string thread_name=null;
158
159                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
160                 private extern void ConstructInternalThread ();
161
162                 private InternalThread Internal {
163                         get {
164                                 if (internal_thread == null)
165                                         ConstructInternalThread ();
166                                 return internal_thread;
167                         }
168                 }
169
170                 public static Context CurrentContext {
171                         [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
172                         get {
173                                 return(AppDomain.InternalGetContext ());
174                         }
175                 }
176
177                 /*
178                  * These two methods return an array in the target
179                  * domain with the same content as the argument.  If
180                  * the argument is already in the target domain, then
181                  * the argument is returned, otherwise a copy.
182                  */
183                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
184                 private extern static byte[] ByteArrayToRootDomain (byte[] arr);
185
186                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
187                 private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
188
189 #if !MOONLIGHT
190                 static void DeserializePrincipal (Thread th)
191                 {
192                         MemoryStream ms = new MemoryStream (ByteArrayToCurrentDomain (th.Internal._serialized_principal));
193                         int type = ms.ReadByte ();
194                         if (type == 0) {
195                                 BinaryFormatter bf = new BinaryFormatter ();
196                                 th.principal = (IPrincipal) bf.Deserialize (ms);
197                                 th.principal_version = th.Internal._serialized_principal_version;
198                         } else if (type == 1) {
199                                 BinaryReader reader = new BinaryReader (ms);
200                                 string name = reader.ReadString ();
201                                 string auth_type = reader.ReadString ();
202                                 int n_roles = reader.ReadInt32 ();
203                                 string [] roles = null;
204                                 if (n_roles >= 0) {
205                                         roles = new string [n_roles];
206                                         for (int i = 0; i < n_roles; i++)
207                                                 roles [i] = reader.ReadString ();
208                                 }
209                                 th.principal = new GenericPrincipal (new GenericIdentity (name, auth_type), roles);
210                         } else if (type == 2 || type == 3) {
211                                 string [] roles = type == 2 ? null : new string [0];
212                                 th.principal = new GenericPrincipal (new GenericIdentity ("", ""), roles);
213                         }
214                 }
215
216                 static void SerializePrincipal (Thread th, IPrincipal value)
217                 {
218                         MemoryStream ms = new MemoryStream ();
219                         bool done = false;
220                         if (value.GetType () == typeof (GenericPrincipal)) {
221                                 GenericPrincipal gp = (GenericPrincipal) value;
222                                 if (gp.Identity != null && gp.Identity.GetType () == typeof (GenericIdentity)) {
223                                         GenericIdentity id = (GenericIdentity) gp.Identity;
224                                         if (id.Name == "" && id.AuthenticationType == "") {
225                                                 if (gp.Roles == null) {
226                                                         ms.WriteByte (2);
227                                                         done = true;
228                                                 } else if (gp.Roles.Length == 0) {
229                                                         ms.WriteByte (3);
230                                                         done = true;
231                                                 }
232                                         } else {
233                                                 ms.WriteByte (1);
234                                                 BinaryWriter br = new BinaryWriter (ms);
235                                                 br.Write (gp.Identity.Name);
236                                                 br.Write (gp.Identity.AuthenticationType);
237                                                 string [] roles = gp.Roles;
238                                                 if  (roles == null) {
239                                                         br.Write ((int) (-1));
240                                                 } else {
241                                                         br.Write (roles.Length);
242                                                         foreach (string s in roles) {
243                                                                 br.Write (s);
244                                                         }
245                                                 }
246                                                 br.Flush ();
247                                                 done = true;
248                                         }
249                                 }
250                         }
251                         if (!done) {
252                                 ms.WriteByte (0);
253                                 BinaryFormatter bf = new BinaryFormatter ();
254                                 try {
255                                         bf.Serialize (ms, value);
256                                 } catch {}
257                         }
258                         th.Internal._serialized_principal = ByteArrayToRootDomain (ms.ToArray ());
259                 }
260
261                 public static IPrincipal CurrentPrincipal {
262                         get {
263                                 Thread th = CurrentThread;
264
265                                 if (th.principal_version != th.Internal._serialized_principal_version)
266                                         th.principal = null;
267
268                                 if (th.principal != null)
269                                         return th.principal;
270
271                                 if (th.Internal._serialized_principal != null) {
272                                         try {
273                                                 DeserializePrincipal (th);
274                                                 return th.principal;
275                                         } catch {}
276                                 }
277
278                                 th.principal = GetDomain ().DefaultPrincipal;
279                                 th.principal_version = th.Internal._serialized_principal_version;
280                                 return th.principal;
281                         }
282                         [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
283                         set {
284                                 Thread th = CurrentThread;
285
286                                 if (value != GetDomain ().DefaultPrincipal) {
287                                         ++th.Internal._serialized_principal_version;
288                                         try {
289                                                 SerializePrincipal (th, value);
290                                         } catch (Exception) {
291                                                 th.Internal._serialized_principal = null;
292                                         }
293                                         th.principal_version = th.Internal._serialized_principal_version;
294                                 } else {
295                                         th.Internal._serialized_principal = null;
296                                 }
297
298                                 th.principal = value;
299                         }
300                 }
301 #endif
302
303                 // Looks up the object associated with the current thread
304                 // this is called by the JIT directly, too
305                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
306                 private extern static InternalThread CurrentInternalThread_internal();
307
308                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
309                 internal extern static uint AllocTlsData (Type type);
310
311                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
312                 internal extern static void DestroyTlsData (uint offset);
313
314                 public static Thread CurrentThread {
315                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
316                         get {
317                                 if (current_thread == null)
318                                         current_thread = new Thread (CurrentInternalThread_internal ());
319                                 return current_thread;
320                         }
321                 }
322
323                 internal static int CurrentThreadId {
324                         get {
325                                 return (int)(CurrentThread.internal_thread.thread_id);
326                         }
327                 }
328
329 #if !MOONLIGHT
330                 // Stores a hash keyed by strings of LocalDataStoreSlot objects
331                 static Hashtable datastorehash;
332                 private static object datastore_lock = new object ();
333                 
334                 private static void InitDataStoreHash () {
335                         lock (datastore_lock) {
336                                 if (datastorehash == null) {
337                                         datastorehash = Hashtable.Synchronized(new Hashtable());
338                                 }
339                         }
340                 }
341                 
342                 public static LocalDataStoreSlot AllocateNamedDataSlot (string name) {
343                         lock (datastore_lock) {
344                                 if (datastorehash == null)
345                                         InitDataStoreHash ();
346                                 LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash [name];
347                                 if (slot != null) {
348                                         // This exception isnt documented (of
349                                         // course) but .net throws it
350                                         throw new ArgumentException("Named data slot already added");
351                                 }
352                         
353                                 slot = AllocateDataSlot ();
354
355                                 datastorehash.Add (name, slot);
356
357                                 return slot;
358                         }
359                 }
360
361                 public static void FreeNamedDataSlot (string name) {
362                         lock (datastore_lock) {
363                                 if (datastorehash == null)
364                                         InitDataStoreHash ();
365                                 LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash [name];
366
367                                 if (slot != null) {
368                                         datastorehash.Remove (slot);
369                                 }
370                         }
371                 }
372
373                 public static LocalDataStoreSlot AllocateDataSlot () {
374                         return new LocalDataStoreSlot (true);
375                 }
376
377                 public static object GetData (LocalDataStoreSlot slot) {
378                         object[] slots = local_slots;
379                         if (slot == null)
380                                 throw new ArgumentNullException ("slot");
381                         if (slots != null && slot.slot < slots.Length)
382                                 return slots [slot.slot];
383                         return null;
384                 }
385
386                 public static void SetData (LocalDataStoreSlot slot, object data) {
387                         object[] slots = local_slots;
388                         if (slot == null)
389                                 throw new ArgumentNullException ("slot");
390                         if (slots == null) {
391                                 slots = new object [slot.slot + 2];
392                                 local_slots = slots;
393                         } else if (slot.slot >= slots.Length) {
394                                 object[] nslots = new object [slot.slot + 2];
395                                 slots.CopyTo (nslots, 0);
396                                 slots = nslots;
397                                 local_slots = slots;
398                         }
399                         slots [slot.slot] = data;
400                 }
401
402                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
403                 internal extern static void FreeLocalSlotValues (int slot, bool thread_local);
404
405                 public static LocalDataStoreSlot GetNamedDataSlot(string name) {
406                         lock (datastore_lock) {
407                                 if (datastorehash == null)
408                                         InitDataStoreHash ();
409                                 LocalDataStoreSlot slot=(LocalDataStoreSlot)datastorehash[name];
410
411                                 if(slot==null) {
412                                         slot=AllocateNamedDataSlot(name);
413                                 }
414                         
415                                 return(slot);
416                         }
417                 }
418 #endif
419                 
420                 public static AppDomain GetDomain() {
421                         return AppDomain.CurrentDomain;
422                 }
423
424                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
425                 public extern static int GetDomainID();
426
427                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
428                 private extern static void ResetAbort_internal();
429
430                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
431                 public static void ResetAbort ()
432                 {
433                         ResetAbort_internal ();
434                 }
435
436 #if NET_4_0 || MOBILE
437                 [HostProtectionAttribute (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
438                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
439                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
440                 public extern static bool Yield ();
441 #endif
442
443
444                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
445                 private extern static void Sleep_internal(int ms);
446
447                 public static void Sleep (int millisecondsTimeout)
448                 {
449                         if (millisecondsTimeout < Timeout.Infinite)
450                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Negative timeout");
451
452                         Sleep_internal (millisecondsTimeout);
453                 }
454
455                 public static void Sleep (TimeSpan timeout)
456                 {
457                         long ms = (long) timeout.TotalMilliseconds;
458                         if (ms < Timeout.Infinite || ms > Int32.MaxValue)
459                                 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
460
461                         Sleep_internal ((int) ms);
462                 }
463
464                 // Returns the system thread handle
465                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
466                 private extern IntPtr Thread_internal (MulticastDelegate start);
467
468                 public Thread(ThreadStart start) {
469                         if(start==null) {
470                                 throw new ArgumentNullException("Null ThreadStart");
471                         }
472                         threadstart=start;
473                 }
474
475                 private Thread (InternalThread it) {
476                         internal_thread = it;
477                 }
478                 
479                 // part of ".NETPortable,Version=v4.0,Profile=Profile3" i.e. FX4 and SL4
480                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
481                 ~Thread ()
482                 {
483                 }
484
485 #if !MOONLIGHT
486                 [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
487                 public ApartmentState ApartmentState {
488                         get {
489                                 if ((ThreadState & ThreadState.Stopped) != 0)
490                                         throw new ThreadStateException ("Thread is dead; state can not be accessed.");
491
492                                 return (ApartmentState)Internal.apartment_state;
493                         }
494
495                         set {
496                                 TrySetApartmentState (value);
497                         }
498                 }
499 #endif // !NET_2_1
500
501                 //[MethodImplAttribute (MethodImplOptions.InternalCall)]
502                 //private static extern int current_lcid ();
503
504                 public CultureInfo CurrentCulture {
505                         get {
506                                 CultureInfo culture = current_culture;
507                                 if (culture != null)
508                                         return culture;
509
510                                 current_culture = culture = CultureInfo.ConstructCurrentCulture ();
511                                 NumberFormatter.SetThreadCurrentCulture (culture);
512                                 return culture;
513                         }
514                         
515                         [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
516                         set {
517                                 if (value == null)
518                                         throw new ArgumentNullException ("value");
519
520                                 value.CheckNeutral ();
521                                 current_culture = value;
522                                 NumberFormatter.SetThreadCurrentCulture (value);
523                         }
524                 }
525
526                 public CultureInfo CurrentUICulture {
527                         get {
528                                 CultureInfo culture = current_ui_culture;
529                                 if (culture != null)
530                                         return culture;
531
532                                 current_ui_culture = culture = CultureInfo.ConstructCurrentUICulture ();
533                                 return culture;
534                         }
535                         
536                         set {
537                                 if (value == null)
538                                         throw new ArgumentNullException ("value");
539                                 current_ui_culture = value;
540                         }
541                 }
542
543                 public bool IsThreadPoolThread {
544                         get {
545                                 return IsThreadPoolThreadInternal;
546                         }
547                 }
548
549                 internal bool IsThreadPoolThreadInternal {
550                         get {
551                                 return Internal.threadpool_thread;
552                         }
553                         set {
554                                 Internal.threadpool_thread = value;
555                         }
556                 }
557
558                 public bool IsAlive {
559                         get {
560                                 ThreadState curstate = GetState (Internal);
561                                 
562                                 if((curstate & ThreadState.Aborted) != 0 ||
563                                    (curstate & ThreadState.Stopped) != 0 ||
564                                    (curstate & ThreadState.Unstarted) != 0) {
565                                         return(false);
566                                 } else {
567                                         return(true);
568                                 }
569                         }
570                 }
571
572                 public bool IsBackground {
573                         get {
574                                 ThreadState thread_state = GetState (Internal);
575                                 if ((thread_state & ThreadState.Stopped) != 0)
576                                         throw new ThreadStateException ("Thread is dead; state can not be accessed.");
577
578                                 return (thread_state & ThreadState.Background) != 0;
579                         }
580                         
581                         set {
582                                 if (value) {
583                                         SetState (Internal, ThreadState.Background);
584                                 } else {
585                                         ClrState (Internal, ThreadState.Background);
586                                 }
587                         }
588                 }
589
590                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
591                 private extern static string GetName_internal (InternalThread thread);
592
593                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
594                 private extern static void SetName_internal (InternalThread thread, String name);
595
596                 /* 
597                  * The thread name must be shared by appdomains, so it is stored in
598                  * unmanaged code.
599                  */
600
601                 public string Name {
602                         get {
603                                 return GetName_internal (Internal);
604                         }
605                         
606                         set {
607                                 SetName_internal (Internal, value);
608                         }
609                 }
610
611 #if !MOONLIGHT
612                 public ThreadPriority Priority {
613                         get {
614                                 return(ThreadPriority.Lowest);
615                         }
616                         
617                         set {
618                                 // FIXME: Implement setter.
619                         }
620                 }
621 #endif
622
623                 public ThreadState ThreadState {
624                         get {
625                                 return GetState (Internal);
626                         }
627                 }
628
629                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
630                 private extern static void Abort_internal (InternalThread thread, object stateInfo);
631
632                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
633                 public void Abort () 
634                 {
635                         Abort_internal (Internal, null);
636                 }
637
638 #if !MOONLIGHT
639                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
640                 public void Abort (object stateInfo) 
641                 {
642                         Abort_internal (Internal, stateInfo);
643                 }
644
645                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
646                 internal extern object GetAbortExceptionState ();
647
648                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
649                 private extern static void Interrupt_internal (InternalThread thread);
650                 
651                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
652                 public void Interrupt ()
653                 {
654                         Interrupt_internal (Internal);
655                 }
656 #endif
657
658                 // The current thread joins with 'this'. Set ms to 0 to block
659                 // until this actually exits.
660                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
661                 private extern static bool Join_internal(InternalThread thread, int ms, IntPtr handle);
662                 
663                 public void Join()
664                 {
665                         Join_internal(Internal, Timeout.Infinite, Internal.system_thread_handle);
666                 }
667
668                 public bool Join(int millisecondsTimeout)
669                 {
670                         if (millisecondsTimeout < Timeout.Infinite)
671                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Timeout less than zero");
672
673                         return Join_internal (Internal, millisecondsTimeout, Internal.system_thread_handle);
674                 }
675
676 #if !MOONLIGHT
677                 public bool Join(TimeSpan timeout)
678                 {
679                         long ms = (long) timeout.TotalMilliseconds;
680                         if (ms < Timeout.Infinite || ms > Int32.MaxValue)
681                                 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
682
683                         return Join_internal (Internal, (int) ms, Internal.system_thread_handle);
684                 }
685 #endif
686
687                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
688                 public extern static void MemoryBarrier ();
689
690 #if !MOONLIGHT
691                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
692                 private extern void Resume_internal();
693
694                 [Obsolete ("")]
695                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
696                 public void Resume () 
697                 {
698                         Resume_internal ();
699                 }
700 #endif // !NET_2_1
701
702                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
703                 private extern static void SpinWait_nop ();
704
705
706                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
707                 public static void SpinWait (int iterations) 
708                 {
709                         if (iterations < 0)
710                                 return;
711                         while (iterations-- > 0)
712                         {
713                                 SpinWait_nop ();
714                         }
715                 }
716
717 #if MOONLIGHT
718                 private void StartInternal ()
719                 {
720                         current_thread = this;
721
722                         try {
723                                 if (threadstart is ThreadStart) {
724                                         ((ThreadStart) threadstart) ();
725                                 } else {
726                                         ((ParameterizedThreadStart) threadstart) (start_obj);
727                                 }
728                         } catch (ThreadAbortException) {
729                                 // do nothing
730                         } catch (Exception ex) {
731                                 MoonlightUnhandledException (ex);
732                         }
733                 }
734
735                 static MethodInfo moonlight_unhandled_exception = null;
736
737                 static internal void MoonlightUnhandledException (Exception e)
738                 {
739                         try {
740                                 if (moonlight_unhandled_exception == null) {
741                                         var assembly = System.Reflection.Assembly.Load ("System.Windows, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e");
742                                         var application = assembly.GetType ("System.Windows.Application");
743                                         moonlight_unhandled_exception = application.GetMethod ("OnUnhandledException", 
744                                                 System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
745                                 }
746                                 moonlight_unhandled_exception.Invoke (null, new object [] { null, e });
747                         }
748                         catch {
749                                 try {
750                                         Console.WriteLine ("Unexpected exception while trying to report unhandled application exception: {0}", e);
751                                 } catch {
752                                 }
753                         }
754                 }
755 #elif MONOTOUCH
756                 static ConstructorInfo nsautoreleasepool_ctor;
757                 
758                 IDisposable GetNSAutoreleasePool ()
759                 {
760                         if (nsautoreleasepool_ctor == null) {
761                                 Type t = Type.GetType ("MonoTouch.Foundation.NSAutoreleasePool, monotouch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
762                                 nsautoreleasepool_ctor = t.GetConstructor (Type.EmptyTypes);
763                         }
764                         return (IDisposable) nsautoreleasepool_ctor.Invoke (null);
765                 }
766                 
767                 private void StartInternal ()
768                 {
769                         using (var pool = GetNSAutoreleasePool ()) {
770                                 current_thread = this;
771                         
772                                 if (threadstart is ThreadStart) {
773                                         ((ThreadStart) threadstart) ();
774                                 } else {
775                                         ((ParameterizedThreadStart) threadstart) (start_obj);
776                                 }
777                         }
778                 }
779 #else
780                 private void StartInternal ()
781                 {
782                         current_thread = this;
783
784                         if (threadstart is ThreadStart) {
785                                 ((ThreadStart) threadstart) ();
786                         } else {
787                                 ((ParameterizedThreadStart) threadstart) (start_obj);
788                         }
789                 }
790 #endif
791                 public void Start() {
792                         // propagate informations from the original thread to the new thread
793                         if (!ExecutionContext.IsFlowSuppressed ())
794                                 ec_to_set = ExecutionContext.Capture ();
795                         Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
796
797                         // Thread_internal creates and starts the new thread, 
798                         if (Thread_internal((ThreadStart) StartInternal) == (IntPtr) 0)
799                                 throw new SystemException ("Thread creation failed.");
800                 }
801
802 #if !MOONLIGHT
803                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
804                 private extern static void Suspend_internal(InternalThread thread);
805
806                 [Obsolete ("")]
807                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
808                 public void Suspend ()
809                 {
810                         Suspend_internal (Internal);
811                 }
812 #endif // !NET_2_1
813
814                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
815                 extern private static void SetState (InternalThread thread, ThreadState set);
816
817                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
818                 extern private static void ClrState (InternalThread thread, ThreadState clr);
819
820                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
821                 extern private static ThreadState GetState (InternalThread thread);
822
823                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
824                 extern public static byte VolatileRead (ref byte address);
825                 
826                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
827                 extern public static double VolatileRead (ref double address);
828                 
829                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
830                 extern public static short VolatileRead (ref short address);
831                 
832                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
833                 extern public static int VolatileRead (ref int address);
834                 
835                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
836                 extern public static long VolatileRead (ref long address);
837                 
838                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
839                 extern public static IntPtr VolatileRead (ref IntPtr address);
840                 
841                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
842                 extern public static object VolatileRead (ref object address);
843
844                 [CLSCompliant(false)]
845                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
846                 extern public static sbyte VolatileRead (ref sbyte address);
847                 
848                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
849                 extern public static float VolatileRead (ref float address);
850
851                 [CLSCompliant (false)]
852                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
853                 extern public static ushort VolatileRead (ref ushort address);
854
855                 [CLSCompliant (false)]
856                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
857                 extern public static uint VolatileRead (ref uint address);
858
859                 [CLSCompliant (false)]
860                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
861                 extern public static ulong VolatileRead (ref ulong address);
862
863                 [CLSCompliant (false)]
864                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
865                 extern public static UIntPtr VolatileRead (ref UIntPtr address);
866
867                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
868                 extern public static void VolatileWrite (ref byte address, byte value);
869                 
870                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
871                 extern public static void VolatileWrite (ref double address, double value);
872                 
873                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
874                 extern public static void VolatileWrite (ref short address, short value);
875                 
876                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
877                 extern public static void VolatileWrite (ref int address, int value);
878                 
879                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
880                 extern public static void VolatileWrite (ref long address, long value);
881                 
882                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
883                 extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
884                 
885                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
886                 extern public static void VolatileWrite (ref object address, object value);
887
888                 [CLSCompliant(false)]
889                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
890                 extern public static void VolatileWrite (ref sbyte address, sbyte value);
891                 
892                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
893                 extern public static void VolatileWrite (ref float address, float value);
894
895                 [CLSCompliant (false)]
896                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
897                 extern public static void VolatileWrite (ref ushort address, ushort value);
898
899                 [CLSCompliant (false)]
900                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
901                 extern public static void VolatileWrite (ref uint address, uint value);
902
903                 [CLSCompliant (false)]
904                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
905                 extern public static void VolatileWrite (ref ulong address, ulong value);
906
907                 [CLSCompliant (false)]
908                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
909                 extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
910                 
911
912                 static int CheckStackSize (int maxStackSize)
913                 {
914                         if (maxStackSize < 0)
915                                 throw new ArgumentOutOfRangeException ("less than zero", "maxStackSize");
916
917                         if (maxStackSize < 131072) // make sure stack is at least 128k big
918                                 return 131072;
919
920                         int page_size = Environment.GetPageSize ();
921
922                         if ((maxStackSize % page_size) != 0) // round up to a divisible of page size
923                                 maxStackSize = (maxStackSize / (page_size - 1)) * page_size;
924
925                         int default_stack_size = (IntPtr.Size / 4) * 1024 * 1024; // from wthreads.c
926
927                         if (maxStackSize > default_stack_size)
928                                 return default_stack_size;
929
930                         return maxStackSize; 
931                 }
932
933                 public Thread (ThreadStart start, int maxStackSize)
934                 {
935                         if (start == null)
936                                 throw new ArgumentNullException ("start");
937
938                         threadstart = start;
939                         Internal.stack_size = CheckStackSize (maxStackSize);;
940                 }
941
942                 public Thread (ParameterizedThreadStart start)
943                 {
944                         if (start == null)
945                                 throw new ArgumentNullException ("start");
946
947                         threadstart = start;
948                 }
949
950                 public Thread (ParameterizedThreadStart start, int maxStackSize)
951                 {
952                         if (start == null)
953                                 throw new ArgumentNullException ("start");
954
955                         threadstart = start;
956                         Internal.stack_size = CheckStackSize (maxStackSize);
957                 }
958
959                 [MonoTODO ("limited to CompressedStack support")]
960                 public ExecutionContext ExecutionContext {
961                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
962                         get {
963                                 if (_ec == null)
964                                         _ec = new ExecutionContext ();
965                                 return _ec;
966                         }
967                 }
968
969                 public int ManagedThreadId {
970                         [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
971                         get {
972                                 return Internal.managed_id;
973                         }
974                 }
975
976                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
977                 public static void BeginCriticalRegion ()
978                 {
979                         CurrentThread.Internal.critical_region_level++;
980                 }
981
982                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
983                 public static void EndCriticalRegion ()
984                 {
985                         CurrentThread.Internal.critical_region_level--;
986                 }
987
988                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
989                 public static void BeginThreadAffinity ()
990                 {
991                         // Managed and native threads are currently bound together.
992                 }
993
994                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
995                 public static void EndThreadAffinity ()
996                 {
997                         // Managed and native threads are currently bound together.
998                 }
999
1000 #if !MOONLIGHT
1001                 public ApartmentState GetApartmentState ()
1002                 {
1003                         return (ApartmentState)Internal.apartment_state;
1004                 }
1005
1006                 public void SetApartmentState (ApartmentState state)
1007                 {
1008                         if (!TrySetApartmentState (state))
1009                                 throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
1010                 }
1011
1012                 public bool TrySetApartmentState (ApartmentState state) 
1013                 {
1014                         /* Only throw this exception when changing the
1015                          * state of another thread.  See bug 324338
1016                          */
1017                         if ((this != CurrentThread) &&
1018                             (ThreadState & ThreadState.Unstarted) == 0)
1019                                 throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
1020
1021                         if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown)
1022                                 return false;
1023
1024                         Internal.apartment_state = (byte)state;
1025
1026                         return true;
1027                 }
1028 #endif // !NET_2_1
1029                 
1030                 [ComVisible (false)]
1031                 public override int GetHashCode ()
1032                 {
1033                         return ManagedThreadId;
1034                 }
1035
1036                 public void Start (object parameter)
1037                 {
1038                         start_obj = parameter;
1039                         Start ();
1040                 }
1041
1042 #if !MOONLIGHT
1043                 // NOTE: This method doesn't show in the class library status page because
1044                 // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
1045                 // But it's there!
1046                 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
1047                 [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
1048                 [Obsolete ("see CompressedStack class")]
1049                 public
1050                 CompressedStack GetCompressedStack ()
1051                 {
1052                         // Note: returns null if no CompressedStack has been set.
1053                         // However CompressedStack.GetCompressedStack returns an 
1054                         // (empty?) CompressedStack instance.
1055                         CompressedStack cs = ExecutionContext.SecurityContext.CompressedStack;
1056                         return ((cs == null) || cs.IsEmpty ()) ? null : cs.CreateCopy ();
1057                 }
1058
1059                 // NOTE: This method doesn't show in the class library status page because
1060                 // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
1061                 // But it's there!
1062                 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
1063                 [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
1064                 [Obsolete ("see CompressedStack class")]
1065                 public
1066                 void SetCompressedStack (CompressedStack stack)
1067                 {
1068                         ExecutionContext.SecurityContext.CompressedStack = stack;
1069                 }
1070
1071 #endif
1072
1073                 void _Thread.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1074                 {
1075                         throw new NotImplementedException ();
1076                 }
1077
1078                 void _Thread.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1079                 {
1080                         throw new NotImplementedException ();
1081                 }
1082
1083                 void _Thread.GetTypeInfoCount (out uint pcTInfo)
1084                 {
1085                         throw new NotImplementedException ();
1086                 }
1087
1088                 void _Thread.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1089                         IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1090                 {
1091                         throw new NotImplementedException ();
1092                 }
1093         }
1094 }