Thread.cs 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. //
  2. // System.Threading.Thread.cs
  3. //
  4. // Author:
  5. // Dick Porter ([email protected])
  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. using System.Runtime.Remoting.Contexts;
  30. using System.Runtime.Serialization;
  31. using System.Runtime.Serialization.Formatters.Binary;
  32. using System.Security.Permissions;
  33. using System.Security.Principal;
  34. using System.Globalization;
  35. using System.Runtime.CompilerServices;
  36. using System.Runtime.InteropServices;
  37. using System.IO;
  38. using System.Collections;
  39. using System.Reflection;
  40. using System.Security;
  41. using System.Runtime.ConstrainedExecution;
  42. namespace System.Threading {
  43. internal class InternalThread : CriticalFinalizerObject {
  44. #pragma warning disable 169, 414, 649
  45. #region Sync with metadata/object-internals.h
  46. int lock_thread_id;
  47. // stores a thread handle
  48. internal IntPtr system_thread_handle;
  49. /* Note this is an opaque object (an array), not a CultureInfo */
  50. private object cached_culture_info; /*FIXME remove this on the next corlib version bump*/
  51. private IntPtr unused0;
  52. internal bool threadpool_thread;
  53. /* accessed only from unmanaged code */
  54. private IntPtr name;
  55. private int name_len;
  56. private ThreadState state;
  57. private object abort_exc;
  58. private int abort_state_handle;
  59. /* thread_id is only accessed from unmanaged code */
  60. internal Int64 thread_id;
  61. /* start_notify is used by the runtime to signal that Start()
  62. * is ok to return
  63. */
  64. private IntPtr start_notify;
  65. private IntPtr stack_ptr;
  66. private UIntPtr static_data; /* GC-tracked */
  67. private IntPtr jit_data;
  68. private IntPtr lock_data;
  69. /* current System.Runtime.Remoting.Contexts.Context instance
  70. keep as an object to avoid triggering its class constructor when not needed */
  71. private object current_appcontext;
  72. internal int stack_size;
  73. private IntPtr appdomain_refs;
  74. private int interruption_requested;
  75. private IntPtr suspend_event;
  76. private IntPtr suspended_event;
  77. private IntPtr resume_event;
  78. private IntPtr synch_cs;
  79. private bool thread_dump_requested;
  80. private IntPtr end_stack;
  81. private bool thread_interrupt_requested;
  82. internal byte apartment_state;
  83. internal volatile int critical_region_level;
  84. private int small_id;
  85. private IntPtr manage_callback;
  86. private object pending_exception;
  87. /* This is the ExecutionContext that will be set by
  88. start_wrapper() in the runtime. */
  89. private ExecutionContext ec_to_set;
  90. private IntPtr interrupt_on_stop;
  91. /*
  92. * These fields are used to avoid having to increment corlib versions
  93. * when a new field is added to the unmanaged MonoThread structure.
  94. */
  95. private IntPtr unused3;
  96. private IntPtr unused4;
  97. private IntPtr unused5;
  98. private IntPtr unused6;
  99. #endregion
  100. #pragma warning restore 169, 414, 649
  101. internal int managed_id;
  102. internal byte[] _serialized_principal;
  103. internal int _serialized_principal_version;
  104. // Closes the system thread handle
  105. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  106. private extern void Thread_free_internal(IntPtr handle);
  107. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  108. ~InternalThread() {
  109. Thread_free_internal(system_thread_handle);
  110. }
  111. }
  112. [ClassInterface (ClassInterfaceType.None)]
  113. [ComVisible (true)]
  114. [ComDefaultInterface (typeof (_Thread))]
  115. public sealed class Thread : CriticalFinalizerObject, _Thread {
  116. #pragma warning disable 414
  117. #region Sync with metadata/object-internals.h
  118. private InternalThread internal_thread;
  119. object start_obj;
  120. private ExecutionContext ec_to_set;
  121. #endregion
  122. #pragma warning restore 414
  123. IPrincipal principal;
  124. int principal_version;
  125. CultureInfo current_culture;
  126. CultureInfo current_ui_culture;
  127. // the name of local_slots, current_thread and _ec is
  128. // important because they are used by the runtime.
  129. [ThreadStatic]
  130. static object[] local_slots;
  131. [ThreadStatic]
  132. static Thread current_thread;
  133. /* The actual ExecutionContext of the thread. It's
  134. ThreadStatic so that it's not shared between
  135. AppDomains. */
  136. [ThreadStatic]
  137. static ExecutionContext _ec;
  138. // can be both a ThreadStart and a ParameterizedThreadStart
  139. private MulticastDelegate threadstart;
  140. //private string thread_name=null;
  141. private static int _managed_id_counter;
  142. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  143. private extern void ConstructInternalThread ();
  144. private InternalThread Internal {
  145. get {
  146. if (internal_thread == null)
  147. ConstructInternalThread ();
  148. return internal_thread;
  149. }
  150. }
  151. public static Context CurrentContext {
  152. [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
  153. get {
  154. return(AppDomain.InternalGetContext ());
  155. }
  156. }
  157. /*
  158. * These two methods return an array in the target
  159. * domain with the same content as the argument. If
  160. * the argument is already in the target domain, then
  161. * the argument is returned, otherwise a copy.
  162. */
  163. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  164. private extern static byte[] ByteArrayToRootDomain (byte[] arr);
  165. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  166. private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
  167. #if !MOONLIGHT
  168. public static IPrincipal CurrentPrincipal {
  169. get {
  170. Thread th = CurrentThread;
  171. if (th.principal_version != th.Internal._serialized_principal_version)
  172. th.principal = null;
  173. if (th.principal != null)
  174. return th.principal;
  175. if (th.Internal._serialized_principal != null) {
  176. try {
  177. BinaryFormatter bf = new BinaryFormatter ();
  178. MemoryStream ms = new MemoryStream (ByteArrayToCurrentDomain (th.Internal._serialized_principal));
  179. th.principal = (IPrincipal) bf.Deserialize (ms);
  180. th.principal_version = th.Internal._serialized_principal_version;
  181. return th.principal;
  182. } catch (Exception) {
  183. }
  184. }
  185. th.principal = GetDomain ().DefaultPrincipal;
  186. th.principal_version = th.Internal._serialized_principal_version;
  187. return th.principal;
  188. }
  189. [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
  190. set {
  191. Thread th = CurrentThread;
  192. ++th.Internal._serialized_principal_version;
  193. try {
  194. BinaryFormatter bf = new BinaryFormatter ();
  195. MemoryStream ms = new MemoryStream ();
  196. bf.Serialize (ms, value);
  197. th.Internal._serialized_principal = ByteArrayToRootDomain (ms.ToArray ());
  198. } catch (Exception) {
  199. th.Internal._serialized_principal = null;
  200. }
  201. th.principal = value;
  202. th.principal_version = th.Internal._serialized_principal_version;
  203. }
  204. }
  205. #endif
  206. // Looks up the object associated with the current thread
  207. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  208. private extern static InternalThread CurrentInternalThread_internal();
  209. public static Thread CurrentThread {
  210. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  211. get {
  212. if (current_thread == null)
  213. current_thread = new Thread (CurrentInternalThread_internal ());
  214. return current_thread;
  215. }
  216. }
  217. internal static int CurrentThreadId {
  218. get {
  219. return (int)(CurrentThread.internal_thread.thread_id);
  220. }
  221. }
  222. #if !MOONLIGHT
  223. // Stores a hash keyed by strings of LocalDataStoreSlot objects
  224. static Hashtable datastorehash;
  225. private static object datastore_lock = new object ();
  226. private static void InitDataStoreHash () {
  227. lock (datastore_lock) {
  228. if (datastorehash == null) {
  229. datastorehash = Hashtable.Synchronized(new Hashtable());
  230. }
  231. }
  232. }
  233. public static LocalDataStoreSlot AllocateNamedDataSlot (string name) {
  234. lock (datastore_lock) {
  235. if (datastorehash == null)
  236. InitDataStoreHash ();
  237. LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash [name];
  238. if (slot != null) {
  239. // This exception isnt documented (of
  240. // course) but .net throws it
  241. throw new ArgumentException("Named data slot already added");
  242. }
  243. slot = AllocateDataSlot ();
  244. datastorehash.Add (name, slot);
  245. return slot;
  246. }
  247. }
  248. public static void FreeNamedDataSlot (string name) {
  249. lock (datastore_lock) {
  250. if (datastorehash == null)
  251. InitDataStoreHash ();
  252. LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash [name];
  253. if (slot != null) {
  254. datastorehash.Remove (slot);
  255. }
  256. }
  257. }
  258. public static LocalDataStoreSlot AllocateDataSlot () {
  259. return new LocalDataStoreSlot (true);
  260. }
  261. public static object GetData (LocalDataStoreSlot slot) {
  262. object[] slots = local_slots;
  263. if (slot == null)
  264. throw new ArgumentNullException ("slot");
  265. if (slots != null && slot.slot < slots.Length)
  266. return slots [slot.slot];
  267. return null;
  268. }
  269. public static void SetData (LocalDataStoreSlot slot, object data) {
  270. object[] slots = local_slots;
  271. if (slot == null)
  272. throw new ArgumentNullException ("slot");
  273. if (slots == null) {
  274. slots = new object [slot.slot + 2];
  275. local_slots = slots;
  276. } else if (slot.slot >= slots.Length) {
  277. object[] nslots = new object [slot.slot + 2];
  278. slots.CopyTo (nslots, 0);
  279. slots = nslots;
  280. local_slots = slots;
  281. }
  282. slots [slot.slot] = data;
  283. }
  284. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  285. internal extern static void FreeLocalSlotValues (int slot, bool thread_local);
  286. public static LocalDataStoreSlot GetNamedDataSlot(string name) {
  287. lock (datastore_lock) {
  288. if (datastorehash == null)
  289. InitDataStoreHash ();
  290. LocalDataStoreSlot slot=(LocalDataStoreSlot)datastorehash[name];
  291. if(slot==null) {
  292. slot=AllocateNamedDataSlot(name);
  293. }
  294. return(slot);
  295. }
  296. }
  297. #endif
  298. public static AppDomain GetDomain() {
  299. return AppDomain.CurrentDomain;
  300. }
  301. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  302. public extern static int GetDomainID();
  303. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  304. private extern static void ResetAbort_internal();
  305. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  306. public static void ResetAbort ()
  307. {
  308. ResetAbort_internal ();
  309. }
  310. #if NET_4_0
  311. [HostProtectionAttribute (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
  312. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  313. public extern static bool Yield ();
  314. #endif
  315. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  316. private extern static void Sleep_internal(int ms);
  317. public static void Sleep (int millisecondsTimeout)
  318. {
  319. if (millisecondsTimeout < Timeout.Infinite)
  320. throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Negative timeout");
  321. Sleep_internal (millisecondsTimeout);
  322. }
  323. public static void Sleep (TimeSpan timeout)
  324. {
  325. long ms = (long) timeout.TotalMilliseconds;
  326. if (ms < Timeout.Infinite || ms > Int32.MaxValue)
  327. throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
  328. Sleep_internal ((int) ms);
  329. }
  330. // Returns the system thread handle
  331. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  332. private extern IntPtr Thread_internal (MulticastDelegate start);
  333. public Thread(ThreadStart start) {
  334. if(start==null) {
  335. throw new ArgumentNullException("Null ThreadStart");
  336. }
  337. threadstart=start;
  338. }
  339. private Thread (InternalThread it) {
  340. internal_thread = it;
  341. }
  342. #if !MOONLIGHT
  343. [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
  344. public ApartmentState ApartmentState {
  345. get {
  346. if ((ThreadState & ThreadState.Stopped) != 0)
  347. throw new ThreadStateException ("Thread is dead; state can not be accessed.");
  348. return (ApartmentState)Internal.apartment_state;
  349. }
  350. set {
  351. TrySetApartmentState (value);
  352. }
  353. }
  354. #endif // !NET_2_1
  355. //[MethodImplAttribute (MethodImplOptions.InternalCall)]
  356. //private static extern int current_lcid ();
  357. public CultureInfo CurrentCulture {
  358. get {
  359. CultureInfo culture = current_culture;
  360. if (culture != null)
  361. return culture;
  362. current_culture = culture = CultureInfo.ConstructCurrentCulture ();
  363. NumberFormatter.SetThreadCurrentCulture (culture);
  364. return culture;
  365. }
  366. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  367. set {
  368. if (value == null)
  369. throw new ArgumentNullException ("value");
  370. value.CheckNeutral ();
  371. current_culture = value;
  372. NumberFormatter.SetThreadCurrentCulture (value);
  373. }
  374. }
  375. public CultureInfo CurrentUICulture {
  376. get {
  377. CultureInfo culture = current_ui_culture;
  378. if (culture != null)
  379. return culture;
  380. current_ui_culture = culture = CultureInfo.ConstructCurrentUICulture ();
  381. return culture;
  382. }
  383. set {
  384. if (value == null)
  385. throw new ArgumentNullException ("value");
  386. current_ui_culture = value;
  387. }
  388. }
  389. public bool IsThreadPoolThread {
  390. get {
  391. return IsThreadPoolThreadInternal;
  392. }
  393. }
  394. internal bool IsThreadPoolThreadInternal {
  395. get {
  396. return Internal.threadpool_thread;
  397. }
  398. set {
  399. Internal.threadpool_thread = value;
  400. }
  401. }
  402. public bool IsAlive {
  403. get {
  404. ThreadState curstate = GetState (Internal);
  405. if((curstate & ThreadState.Aborted) != 0 ||
  406. (curstate & ThreadState.Stopped) != 0 ||
  407. (curstate & ThreadState.Unstarted) != 0) {
  408. return(false);
  409. } else {
  410. return(true);
  411. }
  412. }
  413. }
  414. public bool IsBackground {
  415. get {
  416. ThreadState thread_state = GetState (Internal);
  417. if ((thread_state & ThreadState.Stopped) != 0)
  418. throw new ThreadStateException ("Thread is dead; state can not be accessed.");
  419. return (thread_state & ThreadState.Background) != 0;
  420. }
  421. set {
  422. if (value) {
  423. SetState (Internal, ThreadState.Background);
  424. } else {
  425. ClrState (Internal, ThreadState.Background);
  426. }
  427. }
  428. }
  429. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  430. private extern static string GetName_internal (InternalThread thread);
  431. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  432. private extern static void SetName_internal (InternalThread thread, String name);
  433. /*
  434. * The thread name must be shared by appdomains, so it is stored in
  435. * unmanaged code.
  436. */
  437. public string Name {
  438. get {
  439. return GetName_internal (Internal);
  440. }
  441. set {
  442. SetName_internal (Internal, value);
  443. }
  444. }
  445. #if !MOONLIGHT
  446. public ThreadPriority Priority {
  447. get {
  448. return(ThreadPriority.Lowest);
  449. }
  450. set {
  451. // FIXME: Implement setter.
  452. }
  453. }
  454. #endif
  455. public ThreadState ThreadState {
  456. get {
  457. return GetState (Internal);
  458. }
  459. }
  460. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  461. private extern static void Abort_internal (InternalThread thread, object stateInfo);
  462. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  463. public void Abort ()
  464. {
  465. Abort_internal (Internal, null);
  466. }
  467. #if !MOONLIGHT
  468. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  469. public void Abort (object stateInfo)
  470. {
  471. Abort_internal (Internal, stateInfo);
  472. }
  473. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  474. internal extern object GetAbortExceptionState ();
  475. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  476. private extern static void Interrupt_internal (InternalThread thread);
  477. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  478. public void Interrupt ()
  479. {
  480. Interrupt_internal (Internal);
  481. }
  482. #endif
  483. // The current thread joins with 'this'. Set ms to 0 to block
  484. // until this actually exits.
  485. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  486. private extern static bool Join_internal(InternalThread thread, int ms, IntPtr handle);
  487. public void Join()
  488. {
  489. Join_internal(Internal, Timeout.Infinite, Internal.system_thread_handle);
  490. }
  491. public bool Join(int millisecondsTimeout)
  492. {
  493. if (millisecondsTimeout < Timeout.Infinite)
  494. throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Timeout less than zero");
  495. return Join_internal (Internal, millisecondsTimeout, Internal.system_thread_handle);
  496. }
  497. #if !MOONLIGHT
  498. public bool Join(TimeSpan timeout)
  499. {
  500. long ms = (long) timeout.TotalMilliseconds;
  501. if (ms < Timeout.Infinite || ms > Int32.MaxValue)
  502. throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
  503. return Join_internal (Internal, (int) ms, Internal.system_thread_handle);
  504. }
  505. #endif
  506. #if NET_1_1
  507. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  508. public extern static void MemoryBarrier ();
  509. #endif
  510. #if !MOONLIGHT
  511. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  512. private extern void Resume_internal();
  513. [Obsolete ("")]
  514. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  515. public void Resume ()
  516. {
  517. Resume_internal ();
  518. }
  519. #endif // !NET_2_1
  520. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  521. private extern static void SpinWait_nop ();
  522. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  523. public static void SpinWait (int iterations)
  524. {
  525. if (iterations < 0)
  526. return;
  527. while (iterations-- > 0)
  528. {
  529. SpinWait_nop ();
  530. }
  531. }
  532. #if MOONLIGHT
  533. private void StartSafe ()
  534. {
  535. current_thread = this;
  536. try {
  537. if (threadstart is ThreadStart) {
  538. ((ThreadStart) threadstart) ();
  539. } else {
  540. ((ParameterizedThreadStart) threadstart) (start_obj);
  541. }
  542. } catch (ThreadAbortException) {
  543. // do nothing
  544. } catch (Exception ex) {
  545. MoonlightUnhandledException (ex);
  546. }
  547. }
  548. static MethodInfo moonlight_unhandled_exception = null;
  549. static internal void MoonlightUnhandledException (Exception e)
  550. {
  551. try {
  552. if (moonlight_unhandled_exception == null) {
  553. var assembly = System.Reflection.Assembly.Load ("System.Windows, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e");
  554. var application = assembly.GetType ("System.Windows.Application");
  555. moonlight_unhandled_exception = application.GetMethod ("OnUnhandledException",
  556. System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
  557. }
  558. moonlight_unhandled_exception.Invoke (null, new object [] { null, e });
  559. }
  560. catch {
  561. try {
  562. Console.WriteLine ("Unexpected exception while trying to report unhandled application exception: {0}", e);
  563. } catch {
  564. }
  565. }
  566. }
  567. #endif
  568. private void StartUnsafe ()
  569. {
  570. current_thread = this;
  571. if (threadstart is ThreadStart) {
  572. ((ThreadStart) threadstart) ();
  573. } else {
  574. ((ParameterizedThreadStart) threadstart) (start_obj);
  575. }
  576. }
  577. public void Start() {
  578. // propagate informations from the original thread to the new thread
  579. if (!ExecutionContext.IsFlowSuppressed ())
  580. ec_to_set = ExecutionContext.Capture ();
  581. Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
  582. // Thread_internal creates and starts the new thread,
  583. #if MOONLIGHT
  584. if (Thread_internal((ThreadStart) StartSafe) == (IntPtr) 0)
  585. #else
  586. if (Thread_internal((ThreadStart) StartUnsafe) == (IntPtr) 0)
  587. #endif
  588. throw new SystemException ("Thread creation failed.");
  589. }
  590. #if !MOONLIGHT
  591. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  592. private extern static void Suspend_internal(InternalThread thread);
  593. [Obsolete ("")]
  594. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  595. public void Suspend ()
  596. {
  597. Suspend_internal (Internal);
  598. }
  599. #endif // !NET_2_1
  600. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  601. extern private static void SetState (InternalThread thread, ThreadState set);
  602. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  603. extern private static void ClrState (InternalThread thread, ThreadState clr);
  604. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  605. extern private static ThreadState GetState (InternalThread thread);
  606. #if NET_1_1
  607. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  608. extern public static byte VolatileRead (ref byte address);
  609. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  610. extern public static double VolatileRead (ref double address);
  611. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  612. extern public static short VolatileRead (ref short address);
  613. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  614. extern public static int VolatileRead (ref int address);
  615. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  616. extern public static long VolatileRead (ref long address);
  617. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  618. extern public static IntPtr VolatileRead (ref IntPtr address);
  619. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  620. extern public static object VolatileRead (ref object address);
  621. [CLSCompliant(false)]
  622. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  623. extern public static sbyte VolatileRead (ref sbyte address);
  624. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  625. extern public static float VolatileRead (ref float address);
  626. [CLSCompliant (false)]
  627. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  628. extern public static ushort VolatileRead (ref ushort address);
  629. [CLSCompliant (false)]
  630. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  631. extern public static uint VolatileRead (ref uint address);
  632. [CLSCompliant (false)]
  633. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  634. extern public static ulong VolatileRead (ref ulong address);
  635. [CLSCompliant (false)]
  636. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  637. extern public static UIntPtr VolatileRead (ref UIntPtr address);
  638. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  639. extern public static void VolatileWrite (ref byte address, byte value);
  640. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  641. extern public static void VolatileWrite (ref double address, double value);
  642. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  643. extern public static void VolatileWrite (ref short address, short value);
  644. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  645. extern public static void VolatileWrite (ref int address, int value);
  646. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  647. extern public static void VolatileWrite (ref long address, long value);
  648. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  649. extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
  650. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  651. extern public static void VolatileWrite (ref object address, object value);
  652. [CLSCompliant(false)]
  653. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  654. extern public static void VolatileWrite (ref sbyte address, sbyte value);
  655. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  656. extern public static void VolatileWrite (ref float address, float value);
  657. [CLSCompliant (false)]
  658. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  659. extern public static void VolatileWrite (ref ushort address, ushort value);
  660. [CLSCompliant (false)]
  661. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  662. extern public static void VolatileWrite (ref uint address, uint value);
  663. [CLSCompliant (false)]
  664. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  665. extern public static void VolatileWrite (ref ulong address, ulong value);
  666. [CLSCompliant (false)]
  667. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  668. extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
  669. #endif
  670. private static int GetNewManagedId() {
  671. return Interlocked.Increment(ref _managed_id_counter);
  672. }
  673. public Thread (ThreadStart start, int maxStackSize)
  674. {
  675. if (start == null)
  676. throw new ArgumentNullException ("start");
  677. if (maxStackSize < 131072)
  678. throw new ArgumentException ("< 128 kb", "maxStackSize");
  679. threadstart = start;
  680. Internal.stack_size = maxStackSize;
  681. }
  682. public Thread (ParameterizedThreadStart start)
  683. {
  684. if (start == null)
  685. throw new ArgumentNullException ("start");
  686. threadstart = start;
  687. }
  688. public Thread (ParameterizedThreadStart start, int maxStackSize)
  689. {
  690. if (start == null)
  691. throw new ArgumentNullException ("start");
  692. if (maxStackSize < 131072)
  693. throw new ArgumentException ("< 128 kb", "maxStackSize");
  694. threadstart = start;
  695. Internal.stack_size = maxStackSize;
  696. }
  697. [MonoTODO ("limited to CompressedStack support")]
  698. public ExecutionContext ExecutionContext {
  699. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  700. get {
  701. if (_ec == null)
  702. _ec = new ExecutionContext ();
  703. return _ec;
  704. }
  705. }
  706. public int ManagedThreadId {
  707. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  708. get {
  709. // Fastpath
  710. if (internal_thread != null && internal_thread.managed_id != 0)
  711. return internal_thread.managed_id;
  712. if (Internal.managed_id == 0) {
  713. int new_managed_id = GetNewManagedId ();
  714. Interlocked.CompareExchange (ref Internal.managed_id, new_managed_id, 0);
  715. }
  716. return Internal.managed_id;
  717. }
  718. }
  719. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  720. public static void BeginCriticalRegion ()
  721. {
  722. CurrentThread.Internal.critical_region_level++;
  723. }
  724. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  725. public static void EndCriticalRegion ()
  726. {
  727. CurrentThread.Internal.critical_region_level--;
  728. }
  729. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  730. public static void BeginThreadAffinity ()
  731. {
  732. // Managed and native threads are currently bound together.
  733. }
  734. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  735. public static void EndThreadAffinity ()
  736. {
  737. // Managed and native threads are currently bound together.
  738. }
  739. #if !MOONLIGHT
  740. public ApartmentState GetApartmentState ()
  741. {
  742. return (ApartmentState)Internal.apartment_state;
  743. }
  744. public void SetApartmentState (ApartmentState state)
  745. {
  746. if (!TrySetApartmentState (state))
  747. throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
  748. }
  749. public bool TrySetApartmentState (ApartmentState state)
  750. {
  751. /* Only throw this exception when changing the
  752. * state of another thread. See bug 324338
  753. */
  754. if ((this != CurrentThread) &&
  755. (ThreadState & ThreadState.Unstarted) == 0)
  756. throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
  757. if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown)
  758. return false;
  759. Internal.apartment_state = (byte)state;
  760. return true;
  761. }
  762. #endif // !NET_2_1
  763. [ComVisible (false)]
  764. public override int GetHashCode ()
  765. {
  766. return ManagedThreadId;
  767. }
  768. public void Start (object parameter)
  769. {
  770. start_obj = parameter;
  771. Start ();
  772. }
  773. #if !MOONLIGHT
  774. // NOTE: This method doesn't show in the class library status page because
  775. // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
  776. // But it's there!
  777. [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
  778. [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
  779. [Obsolete ("see CompressedStack class")]
  780. #if NET_1_1
  781. public
  782. #else
  783. internal
  784. #endif
  785. CompressedStack GetCompressedStack ()
  786. {
  787. // Note: returns null if no CompressedStack has been set.
  788. // However CompressedStack.GetCompressedStack returns an
  789. // (empty?) CompressedStack instance.
  790. CompressedStack cs = ExecutionContext.SecurityContext.CompressedStack;
  791. return ((cs == null) || cs.IsEmpty ()) ? null : cs.CreateCopy ();
  792. }
  793. // NOTE: This method doesn't show in the class library status page because
  794. // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
  795. // But it's there!
  796. [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
  797. [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
  798. [Obsolete ("see CompressedStack class")]
  799. #if NET_1_1
  800. public
  801. #else
  802. internal
  803. #endif
  804. void SetCompressedStack (CompressedStack stack)
  805. {
  806. ExecutionContext.SecurityContext.CompressedStack = stack;
  807. }
  808. #endif
  809. #if NET_1_1
  810. void _Thread.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  811. {
  812. throw new NotImplementedException ();
  813. }
  814. void _Thread.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  815. {
  816. throw new NotImplementedException ();
  817. }
  818. void _Thread.GetTypeInfoCount (out uint pcTInfo)
  819. {
  820. throw new NotImplementedException ();
  821. }
  822. void _Thread.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
  823. IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  824. {
  825. throw new NotImplementedException ();
  826. }
  827. #endif
  828. }
  829. }