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