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