Merge pull request #1322 from StephenMcConnel/bug23532
[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         sealed 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                         ec_to_set = ExecutionContext.Capture (false, true);
700                         Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
701
702                         // Thread_internal creates and starts the new thread, 
703                         if (Thread_internal((ThreadStart) StartInternal) == (IntPtr) 0)
704                                 throw new SystemException ("Thread creation failed.");
705                 }
706
707                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
708                 private extern static void Suspend_internal(InternalThread thread);
709
710                 [Obsolete ("")]
711                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
712                 public void Suspend ()
713                 {
714                         Suspend_internal (Internal);
715                 }
716
717                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
718                 extern private static void SetState (InternalThread thread, ThreadState set);
719
720                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
721                 extern private static void ClrState (InternalThread thread, ThreadState clr);
722
723                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
724                 extern private static ThreadState GetState (InternalThread thread);
725
726                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
727                 extern public static byte VolatileRead (ref byte address);
728                 
729                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
730                 extern public static double VolatileRead (ref double address);
731                 
732                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
733                 extern public static short VolatileRead (ref short address);
734                 
735                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
736                 extern public static int VolatileRead (ref int address);
737                 
738                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
739                 extern public static long VolatileRead (ref long address);
740                 
741                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
742                 extern public static IntPtr VolatileRead (ref IntPtr address);
743                 
744                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
745                 extern public static object VolatileRead (ref object address);
746
747                 [CLSCompliant(false)]
748                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
749                 extern public static sbyte VolatileRead (ref sbyte address);
750                 
751                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
752                 extern public static float VolatileRead (ref float address);
753
754                 [CLSCompliant (false)]
755                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
756                 extern public static ushort VolatileRead (ref ushort address);
757
758                 [CLSCompliant (false)]
759                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
760                 extern public static uint VolatileRead (ref uint address);
761
762                 [CLSCompliant (false)]
763                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
764                 extern public static ulong VolatileRead (ref ulong address);
765
766                 [CLSCompliant (false)]
767                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
768                 extern public static UIntPtr VolatileRead (ref UIntPtr address);
769
770                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
771                 extern public static void VolatileWrite (ref byte address, byte value);
772                 
773                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
774                 extern public static void VolatileWrite (ref double address, double value);
775                 
776                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
777                 extern public static void VolatileWrite (ref short address, short value);
778                 
779                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
780                 extern public static void VolatileWrite (ref int address, int value);
781                 
782                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
783                 extern public static void VolatileWrite (ref long address, long value);
784                 
785                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
786                 extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
787                 
788                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
789                 extern public static void VolatileWrite (ref object address, object value);
790
791                 [CLSCompliant(false)]
792                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
793                 extern public static void VolatileWrite (ref sbyte address, sbyte value);
794                 
795                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
796                 extern public static void VolatileWrite (ref float address, float value);
797
798                 [CLSCompliant (false)]
799                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
800                 extern public static void VolatileWrite (ref ushort address, ushort value);
801
802                 [CLSCompliant (false)]
803                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
804                 extern public static void VolatileWrite (ref uint address, uint value);
805
806                 [CLSCompliant (false)]
807                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
808                 extern public static void VolatileWrite (ref ulong address, ulong value);
809
810                 [CLSCompliant (false)]
811                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
812                 extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
813                 
814                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
815                 extern static int SystemMaxStackStize ();
816
817                 static int CheckStackSize (int maxStackSize)
818                 {
819                         if (maxStackSize < 0)
820                                 throw new ArgumentOutOfRangeException ("less than zero", "maxStackSize");
821
822                         if (maxStackSize < 131072) // make sure stack is at least 128k big
823                                 return 131072;
824
825                         int page_size = Environment.GetPageSize ();
826
827                         if ((maxStackSize % page_size) != 0) // round up to a divisible of page size
828                                 maxStackSize = (maxStackSize / (page_size - 1)) * page_size;
829
830                         /* Respect the max stack size imposed by the system*/
831                         return Math.Min (maxStackSize, SystemMaxStackStize ());
832                 }
833
834                 public Thread (ThreadStart start, int maxStackSize)
835                 {
836                         if (start == null)
837                                 throw new ArgumentNullException ("start");
838
839                         threadstart = start;
840                         Internal.stack_size = CheckStackSize (maxStackSize);;
841                 }
842
843                 public Thread (ParameterizedThreadStart start)
844                 {
845                         if (start == null)
846                                 throw new ArgumentNullException ("start");
847
848                         threadstart = start;
849                 }
850
851                 public Thread (ParameterizedThreadStart start, int maxStackSize)
852                 {
853                         if (start == null)
854                                 throw new ArgumentNullException ("start");
855
856                         threadstart = start;
857                         Internal.stack_size = CheckStackSize (maxStackSize);
858                 }
859
860                 public ExecutionContext ExecutionContext {
861                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
862                         get {
863                                 if (_ec == null)
864                                         _ec = new ExecutionContext ();
865                                 return _ec;
866                         }
867                         internal set {
868                                 _ec = value;
869                         }
870                 }
871
872                 internal bool HasExecutionContext {
873                         get {
874                                 return _ec != null;
875                         }
876                 }
877
878                 internal void BranchExecutionContext (out ExecutionContext.Switcher switcher)
879                 {
880                         if (_ec == null) {
881                                 switcher =  new ExecutionContext.Switcher ();
882                         } else {
883                                 switcher = new ExecutionContext.Switcher (_ec);
884                                 _ec.CopyOnWrite = true;
885                         }
886                 }
887
888                 internal void RestoreExecutionContext (ref ExecutionContext.Switcher switcher)
889                 {
890                         if (switcher.IsEmpty) {
891                                 _ec = null;
892                                 return;
893                         }
894
895                         switcher.Restore (_ec);
896                 }
897
898                 public int ManagedThreadId {
899                         [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
900                         get {
901                                 return Internal.managed_id;
902                         }
903                 }
904
905                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
906                 public static void BeginCriticalRegion ()
907                 {
908                         CurrentThread.Internal.critical_region_level++;
909                 }
910
911                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
912                 public static void EndCriticalRegion ()
913                 {
914                         CurrentThread.Internal.critical_region_level--;
915                 }
916
917                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
918                 public static void BeginThreadAffinity ()
919                 {
920                         // Managed and native threads are currently bound together.
921                 }
922
923                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
924                 public static void EndThreadAffinity ()
925                 {
926                         // Managed and native threads are currently bound together.
927                 }
928
929                 public ApartmentState GetApartmentState ()
930                 {
931                         return (ApartmentState)Internal.apartment_state;
932                 }
933
934                 public void SetApartmentState (ApartmentState state)
935                 {
936                         if (!TrySetApartmentState (state))
937                                 throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
938                 }
939
940                 public bool TrySetApartmentState (ApartmentState state) 
941                 {
942                         if ((ThreadState & ThreadState.Unstarted) == 0)
943                                 throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
944
945                         if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown && 
946                             (ApartmentState)Internal.apartment_state != state)
947                                 return false;
948
949                         Internal.apartment_state = (byte)state;
950
951                         return true;
952                 }
953                 
954                 [ComVisible (false)]
955                 public override int GetHashCode ()
956                 {
957                         return ManagedThreadId;
958                 }
959
960                 public void Start (object parameter)
961                 {
962                         start_obj = parameter;
963                         Start ();
964                 }
965
966                 // NOTE: This method doesn't show in the class library status page because
967                 // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
968                 // But it's there!
969                 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
970                 [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
971                 [Obsolete ("see CompressedStack class")]
972                 public CompressedStack GetCompressedStack ()
973                 {
974 #if MOBILE
975                         throw new NotSupportedException ();
976 #else                   
977                         // Note: returns null if no CompressedStack has been set.
978                         // However CompressedStack.GetCompressedStack returns an 
979                         // (empty?) CompressedStack instance.
980                         CompressedStack cs = ExecutionContext.SecurityContext.CompressedStack;
981                         return ((cs == null) || cs.IsEmpty ()) ? null : cs.CreateCopy ();
982 #endif
983                 }
984
985                 // NOTE: This method doesn't show in the class library status page because
986                 // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
987                 // But it's there!
988                 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
989                 [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
990                 [Obsolete ("see CompressedStack class")]
991                 public void SetCompressedStack (CompressedStack stack)
992                 {
993 #if MOBILE
994                         throw new NotSupportedException ();
995 #else
996                         ExecutionContext.SecurityContext.CompressedStack = stack;
997 #endif
998                 }
999
1000 #if !MOBILE
1001                 void _Thread.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1002                 {
1003                         throw new NotImplementedException ();
1004                 }
1005
1006                 void _Thread.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1007                 {
1008                         throw new NotImplementedException ();
1009                 }
1010
1011                 void _Thread.GetTypeInfoCount (out uint pcTInfo)
1012                 {
1013                         throw new NotImplementedException ();
1014                 }
1015
1016                 void _Thread.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1017                         IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1018                 {
1019                         throw new NotImplementedException ();
1020                 }
1021 #endif
1022         }
1023 }