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