forked from chakra-core/ChakraCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpal_thread.cpp
More file actions
2894 lines (2382 loc) · 73.5 KB
/
pal_thread.cpp
File metadata and controls
2894 lines (2382 loc) · 73.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
#include "pal/corunix.hpp"
#include "pal/context.h"
#include "pal/thread.hpp"
#include "pal/mutex.hpp"
#include "pal/handlemgr.hpp"
#include "pal/cs.hpp"
#include "procprivate.hpp"
#include "pal/process.h"
#include "pal/module.h"
#include "pal/dbgmsg.h"
#include "pal/misc.h"
#include "pal/init.h"
#include <signal.h>
#include <pthread.h>
#if HAVE_PTHREAD_NP_H
#include <pthread_np.h>
#endif
#include <unistd.h>
#include <errno.h>
#include <stddef.h>
#include <sys/stat.h>
#if HAVE_MACH_THREADS
#include <mach/mach.h>
#endif // HAVE_MACH_THREADS
#if HAVE_POLL
#include <poll.h>
#else
#include "pal/fakepoll.h"
#endif // HAVE_POLL
#include <limits.h>
#if HAVE_SYS_LWP_H
#include <sys/lwp.h>
// If we don't have sys/lwp.h but do expect to use _lwp_self, declare it to silence compiler warnings
#elif HAVE__LWP_SELF
extern "C" int _lwp_self ();
#endif // HAVE_LWP_H
using namespace CorUnix;
#ifdef __APPLE__
#define EXPECTED_ALIGNMENT 16 * 1024
static void GetInternalStackLimit(pthread_t thread, ULONG_PTR *highLimit, ULONG_PTR *lowLimit)
{
size_t stack = pthread_get_stacksize_np(thread);
// osx 10.9(+ ?) pthread_get_stacksize_np bug
if (pthread_main_np())
{
#ifndef __IOS__
// https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html
stack = max(8 * 1024 * 1024, stack);
#else
pthread_attr_t pat;
pthread_attr_init(&pat);
size_t gs = 0;
pthread_attr_getguardsize(&pat, &gs);
stack = max((1024 * 1024) - gs, stack);
#endif
}
*highLimit = (ULONG_PTR)pthread_get_stackaddr_np(thread);
stack = *highLimit - stack;
*lowLimit = ((stack + (EXPECTED_ALIGNMENT - 1)) & ~(EXPECTED_ALIGNMENT - 1));
}
#undef EXPECTED_ALIGNMENT
#endif
/* ------------------- Definitions ------------------------------*/
SET_DEFAULT_DEBUG_CHANNEL(THREAD);
// The default stack size of a newly created thread (currently 256KB)
// when the dwStackSize parameter of PAL_CreateThread()
// is zero. This value can be set by setting the
// environment variable PAL_THREAD_DEFAULT_STACK_SIZE
// (the value should be in bytes and in hex).
DWORD CPalThread::s_dwDefaultThreadStackSize = 256*1024;
/* list of free CPalThread objects */
static Volatile<CPalThread*> free_threads_list PAL_GLOBAL = NULL;
/* lock to access list of free THREAD structures */
/* NOTE: can't use a CRITICAL_SECTION here (see comment in FreeTHREAD) */
int free_threads_spinlock = 0;
/* lock to access iEndingThreads counter, condition variable to signal shutdown
thread when any remaining threads have died, and count of exiting threads that
can't be suspended. */
pthread_mutex_t ptmEndThread PAL_GLOBAL;
pthread_cond_t ptcEndThread PAL_GLOBAL;
static int iEndingThreads = 0;
// Activation function that gets called when an activation is injected into a thread.
PAL_ActivationFunction g_activationFunction = NULL;
// Function to check if an activation can be safely injected at a specified context
PAL_SafeActivationCheckFunction g_safeActivationCheckFunction = NULL;
void
ThreadCleanupRoutine(
CPalThread *pThread,
IPalObject *pObjectToCleanup,
bool fShutdown,
bool fCleanupSharedState
);
PAL_ERROR
ThreadInitializationRoutine(
CPalThread *pThread,
CObjectType *pObjectType,
void *pImmutableData,
void *pSharedData,
void *pProcessLocalData
);
void
IncrementEndingThreadCount(
void
);
void
DecrementEndingThreadCount(
void
);
CObjectType CorUnix::otThread PAL_GLOBAL (
otiThread,
ThreadCleanupRoutine,
ThreadInitializationRoutine,
0, //sizeof(CThreadImmutableData),
sizeof(CThreadProcessLocalData),
0, //sizeof(CThreadSharedData),
0, // THREAD_ALL_ACCESS,
CObjectType::SecuritySupported,
CObjectType::SecurityInfoNotPersisted,
CObjectType::UnnamedObject,
CObjectType::LocalDuplicationOnly,
CObjectType::WaitableObject,
CObjectType::SingleTransitionObject,
CObjectType::ThreadReleaseHasNoSideEffects,
CObjectType::NoOwner
);
CAllowedObjectTypes aotThread PAL_GLOBAL (otiThread);
/*++
Function:
InternalEndCurrentThreadWrapper
Destructor for the thread-specific data representing the current PAL thread.
Called from pthread_exit. (pthread_exit is not called from the thread on which
main() was first invoked. This is not a problem, though, since when main()
returns, this results in an implicit call to exit().)
arg: the PAL thread
*/
static void InternalEndCurrentThreadWrapper(void *arg)
{
CPalThread *pThread = (CPalThread *) arg;
// When pthread_exit calls us, it has already removed the PAL thread
// from TLS. Since InternalEndCurrentThread calls functions that assert
// that the current thread is known to this PAL, and that pThread
// actually is the current PAL thread, put it back in TLS temporarily.
pthread_setspecific(thObjKey, pThread);
(void)PAL_Enter(PAL_BoundaryTop);
/* Call entry point functions of every attached modules to
indicate the thread is exiting */
/* note : no need to enter a critical section for serialization, the loader
will lock its own critical section */
LOADCallDllMain(DLL_THREAD_DETACH, NULL);
// PAL_Leave will be called just before we release the thread reference
// in InternalEndCurrentThread.
InternalEndCurrentThread(pThread);
pthread_setspecific(thObjKey, NULL);
}
/*++
Function:
TLSInitialize
Initialize the TLS subsystem
--*/
BOOL TLSInitialize()
{
/* Create the pthread key for thread objects, which we use
for fast access to the current thread object. */
if (pthread_key_create(&thObjKey, InternalEndCurrentThreadWrapper))
{
ERROR("Couldn't create the thread object key\n");
return FALSE;
}
SPINLOCKInit(&free_threads_spinlock);
return TRUE;
}
/*++
Function:
TLSCleanup
Shutdown the TLS subsystem
--*/
VOID TLSCleanup()
{
SPINLOCKDestroy(&free_threads_spinlock);
}
/*++
Function:
AllocTHREAD
Abstract:
Allocate CPalThread instance
Return:
The fresh thread structure, NULL otherwise
--*/
CPalThread* AllocTHREAD()
{
CPalThread* pThread = NULL;
/* Get the lock */
SPINLOCKAcquire(&free_threads_spinlock, 0);
pThread = free_threads_list;
if (pThread != NULL)
{
free_threads_list = pThread->GetNext();
}
/* Release the lock */
SPINLOCKRelease(&free_threads_spinlock);
if (pThread == NULL)
{
pThread = InternalNew<CPalThread>();
}
else
{
pThread = new (pThread) CPalThread;
}
return pThread;
}
/*++
Function:
FreeTHREAD
Abstract:
Free THREAD structure
--*/
static void FreeTHREAD(CPalThread *pThread)
{
//
// Run the destructors for this object
//
pThread->~CPalThread();
#ifdef _DEBUG
// Fill value so we can find code re-using threads after they're dead. We
// check against pThread->dwGuard when getting the current thread's data.
memset((void*)pThread, 0xcc, sizeof(*pThread));
#endif
// We SHOULD be doing the following, but it causes massive problems. See the
// comment below.
//pthread_setspecific(thObjKey, NULL); // Make sure any TLS entry is removed.
//
// Never actually free the THREAD structure to make the TLS lookaside cache work.
// THREAD* for terminated thread can be stuck in the lookaside cache code for an
// arbitrary amount of time. The unused THREAD* structures has to remain in a
// valid memory and thus can't be returned to the heap.
//
// TODO: is this really true? Why would the entry remain in the cache for
// an indefinite period of time after we've flushed it?
//
/* NOTE: can't use a CRITICAL_SECTION here: EnterCriticalSection(&cs,TRUE) and
LeaveCriticalSection(&cs,TRUE) need to access the thread private data
stored in the very THREAD structure that we just destroyed. Entering and
leaving the critical section with internal==FALSE leads to possible hangs
in the PROCSuspendOtherThreads logic, at shutdown time
Update: [TODO] PROCSuspendOtherThreads has been removed. Can this
code be changed?*/
/* Get the lock */
SPINLOCKAcquire(&free_threads_spinlock, 0);
pThread->SetNext(free_threads_list);
free_threads_list = pThread;
/* Release the lock */
SPINLOCKRelease(&free_threads_spinlock);
}
/*++
Function:
GetThreadId
See MSDN doc.
--*/
DWORD
PALAPI
GetThreadId(
HANDLE hThread
// UNIXTODO Should take pThread parameter here (modify callers)
)
{
DWORD dwThreadId = 0;
CPalThread *pThread;
PAL_ERROR palError = NO_ERROR;
IPalObject *pobjThread = 0;
// TODO: not sure if this could be done in a more efficient way.
PERF_ENTRY(GetThreadId);
ENTRY("GetThreadId()\n");
pThread = InternalGetCurrentThread();
palError = InternalGetThreadDataFromHandle(
pThread,
hThread,
0,
0,
&pobjThread
);
if (NO_ERROR != palError)
{
dwThreadId = (DWORD)pThread->GetThreadId();
}
if (NULL != pobjThread)
{
pobjThread->ReleaseReference(pThread);
}
LOGEXIT("GetThreadId returns DWORD %#x\n", dwThreadId);
PERF_EXIT(GetThreadId);
return dwThreadId;
}
static THREAD_LOCAL DWORD cachedCurrentThreadId = 0;
/*++
Function:
GetCurrentThreadId
See MSDN doc.
--*/
DWORD
PALAPI
GetCurrentThreadId(
VOID)
{
if (cachedCurrentThreadId != 0) return cachedCurrentThreadId;
DWORD dwThreadId;
PERF_ENTRY(GetCurrentThreadId);
ENTRY("GetCurrentThreadId()\n");
dwThreadId = (DWORD)THREADSilentGetCurrentThreadId();
LOGEXIT("GetCurrentThreadId returns DWORD %#x\n", dwThreadId);
PERF_EXIT(GetCurrentThreadId);
cachedCurrentThreadId = dwThreadId;
return dwThreadId;
}
/*++
Function:
GetCurrentThread
See MSDN doc.
--*/
HANDLE
PALAPI
PAL_GetCurrentThread(
VOID)
{
PERF_ENTRY(GetCurrentThread);
ENTRY("GetCurrentThread()\n");
LOGEXIT("GetCurrentThread returns HANDLE %p\n", hPseudoCurrentThread);
PERF_EXIT(GetCurrentThread);
/* return a pseudo handle */
return (HANDLE) hPseudoCurrentThread;
}
/*++
Function:
SwitchToThread
See MSDN doc.
--*/
BOOL
PALAPI
SwitchToThread(
VOID)
{
BOOL ret;
PERF_ENTRY(SwitchToThread);
ENTRY("SwitchToThread(VOID)\n");
/* sched_yield yields to another thread in the current process. This implementation
won't work well for cross-process synchronization. */
ret = (sched_yield() == 0);
LOGEXIT("SwitchToThread returns BOOL %d\n", ret);
PERF_EXIT(SwitchToThread);
return ret;
}
/*++
Function:
CreateThread
Note:
lpThreadAttributes could be ignored.
See MSDN doc.
--*/
HANDLE
PALAPI
CreateThread(
IN LPSECURITY_ATTRIBUTES lpThreadAttributes,
IN DWORD dwStackSize,
IN LPTHREAD_START_ROUTINE lpStartAddress,
IN LPVOID lpParameter,
IN DWORD dwCreationFlags,
OUT LPDWORD lpThreadId)
{
PAL_ERROR palError;
CPalThread *pThread;
HANDLE hNewThread = NULL;
PERF_ENTRY(CreateThread);
ENTRY("CreateThread(lpThreadAttr=%p, dwStackSize=%u, lpStartAddress=%p, "
"lpParameter=%p, dwFlags=%#x, lpThreadId=%#x)\n",
lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter,
dwCreationFlags, lpThreadId);
pThread = InternalGetCurrentThread();
palError = InternalCreateThread(
pThread,
lpThreadAttributes,
dwStackSize,
lpStartAddress,
lpParameter,
dwCreationFlags,
UserCreatedThread,
lpThreadId,
&hNewThread
);
if (NO_ERROR != palError)
{
pThread->SetLastError(palError);
}
LOGEXIT("CreateThread returns HANDLE %p\n", hNewThread);
PERF_EXIT(CreateThread);
return hNewThread;
}
PAL_ERROR
CorUnix::InternalCreateThread(
CPalThread *pThread,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
DWORD dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
DWORD dwCreationFlags,
PalThreadType eThreadType,
LPDWORD lpThreadId,
HANDLE *phThread
)
{
PAL_ERROR palError;
CPalThread *pNewThread = NULL;
CObjectAttributes oa;
bool fAttributesInitialized = FALSE;
bool fThreadDataAddedToProcessList = FALSE;
HANDLE hNewThread = NULL;
pthread_t pthread;
pthread_attr_t pthreadAttr;
size_t pthreadStackSize;
#if PTHREAD_CREATE_MODIFIES_ERRNO
int storedErrno;
#endif // PTHREAD_CREATE_MODIFIES_ERRNO
BOOL fHoldingProcessLock = FALSE;
int iError = 0;
if (0 != terminator)
{
//
// Since the PAL is in the middle of shutting down we don't want to
// create any new threads (since it's possible for that new thread
// to create another thread before the shutdown thread gets around
// to suspending it, and so on). We don't want to return an error
// here, though, as some programs (in particular, build) do not
// handle CreateThread errors properly -- instead, we just put
// the calling thread to sleep (unless it is the shutdown thread,
// which could occur if a DllMain PROCESS_DETACH handler tried to
// create a new thread for some odd reason).
//
ERROR("process is terminating, can't create new thread.\n");
if (pThread->GetThreadId() != static_cast<DWORD>(terminator))
{
while (true)
{
poll(NULL, 0, INFTIM);
sched_yield();
}
}
else
{
//
// This is the shutdown thread, so just return an error
//
palError = ERROR_PROCESS_ABORTED;
goto EXIT;
}
}
/* Validate parameters */
if (lpThreadAttributes != NULL)
{
ASSERT("lpThreadAttributes parameter must be NULL (%p)\n",
lpThreadAttributes);
palError = ERROR_INVALID_PARAMETER;
goto EXIT;
}
// Ignore the STACK_SIZE_PARAM_IS_A_RESERVATION flag
dwCreationFlags &= ~STACK_SIZE_PARAM_IS_A_RESERVATION;
if ((dwCreationFlags != 0) && (dwCreationFlags != CREATE_SUSPENDED))
{
ASSERT("dwCreationFlags parameter is invalid (%#x)\n", dwCreationFlags);
palError = ERROR_INVALID_PARAMETER;
goto EXIT;
}
//
// Create the CPalThread for the thread
//
pNewThread = AllocTHREAD();
if (NULL == pNewThread)
{
palError = ERROR_OUTOFMEMORY;
goto EXIT;
}
palError = pNewThread->RunPreCreateInitializers();
if (NO_ERROR != palError)
{
goto EXIT;
}
pNewThread->m_lpStartAddress = lpStartAddress;
pNewThread->m_lpStartParameter = lpParameter;
pNewThread->m_bCreateSuspended = (dwCreationFlags & CREATE_SUSPENDED) == CREATE_SUSPENDED;
pNewThread->m_eThreadType = eThreadType;
if (0 != pthread_attr_init(&pthreadAttr))
{
ERROR("couldn't initialize pthread attributes\n");
palError = ERROR_INTERNAL_ERROR;
goto EXIT;
}
fAttributesInitialized = TRUE;
/* adjust the stack size if necessary */
if (0 != pthread_attr_getstacksize(&pthreadAttr, &pthreadStackSize))
{
ERROR("couldn't set thread stack size\n");
palError = ERROR_INTERNAL_ERROR;
goto EXIT;
}
TRACE("default pthread stack size is %d, caller requested %d (default is %d)\n",
pthreadStackSize, dwStackSize, CPalThread::s_dwDefaultThreadStackSize);
if (0 == dwStackSize)
{
dwStackSize = CPalThread::s_dwDefaultThreadStackSize;
}
if (PTHREAD_STACK_MIN > pthreadStackSize)
{
WARN("default stack size is reported as %d, but PTHREAD_STACK_MIN is "
"%d\n", pthreadStackSize, PTHREAD_STACK_MIN);
}
if (pthreadStackSize < dwStackSize)
{
TRACE("setting thread stack size to %d\n", dwStackSize);
if (0 != pthread_attr_setstacksize(&pthreadAttr, dwStackSize))
{
ERROR("couldn't set pthread stack size to %d\n", dwStackSize);
palError = ERROR_INTERNAL_ERROR;
goto EXIT;
}
}
else
{
TRACE("using the system default thread stack size of %d\n", pthreadStackSize);
}
#if HAVE_THREAD_SELF || HAVE__LWP_SELF
/* Create new threads as "bound", so each pthread is permanently bound
to an LWP. Get/SetThreadContext() depend on this 1:1 mapping. */
pthread_attr_setscope(&pthreadAttr, PTHREAD_SCOPE_SYSTEM);
#endif // HAVE_THREAD_SELF || HAVE__LWP_SELF
//
// We never call pthread_join, so create the new thread as detached
//
iError = pthread_attr_setdetachstate(&pthreadAttr, PTHREAD_CREATE_DETACHED);
_ASSERTE(0 == iError);
//
// Create the IPalObject for the thread and store it in the object
//
palError = CreateThreadObject(
pThread,
pNewThread,
&hNewThread);
if (NO_ERROR != palError)
{
goto EXIT;
}
//
// Add the thread to the process list
//
//
// We use the process lock to ensure that we're not interrupted
// during the creation process. After adding the CPalThread reference
// to the process list, we want to make sure the actual thread has been
// started. Otherwise, there's a window where the thread can be found
// in the process list but doesn't yet exist in the system.
//
PROCProcessLock();
fHoldingProcessLock = TRUE;
PROCAddThread(pThread, pNewThread);
fThreadDataAddedToProcessList = TRUE;
//
// Spawn the new pthread
//
#if PTHREAD_CREATE_MODIFIES_ERRNO
storedErrno = errno;
#endif // PTHREAD_CREATE_MODIFIES_ERRNO
#ifdef FEATURE_PAL_SXS
_ASSERT_MSG(pNewThread->IsInPal(), "New threads we're about to spawn should always be in the PAL.\n");
#endif // FEATURE_PAL_SXS
iError = pthread_create(&pthread, &pthreadAttr, CPalThread::ThreadEntry, pNewThread);
#if PTHREAD_CREATE_MODIFIES_ERRNO
if (iError == 0)
{
// Restore errno if pthread_create succeeded.
errno = storedErrno;
}
#endif // PTHREAD_CREATE_MODIFIES_ERRNO
if (0 != iError)
{
ERROR("pthread_create failed, error is %d (%s)\n", iError, strerror(iError));
palError = ERROR_NOT_ENOUGH_MEMORY;
goto EXIT;
}
//
// Wait for the new thread to finish its initial startup tasks
// (i.e., the ones that might fail)
//
if (pNewThread->WaitForStartStatus())
{
//
// Everything succeeded. Store the handle for the new thread and
// the thread's ID in the out params
//
*phThread = hNewThread;
if (NULL != lpThreadId)
{
*lpThreadId = pNewThread->GetThreadId();
}
}
else
{
ERROR("error occurred in THREADEntry, thread creation failed.\n");
palError = ERROR_INTERNAL_ERROR;
goto EXIT;
}
//
// If we're here, then we've locked the process list and both pthread_create
// and WaitForStartStatus succeeded. Thus, we can now unlock the process list.
// Since palError == NO_ERROR, we won't call this again in the exit block.
//
PROCProcessUnlock();
fHoldingProcessLock = FALSE;
EXIT:
if (fAttributesInitialized)
{
if (0 != pthread_attr_destroy(&pthreadAttr))
{
WARN("pthread_attr_destroy() failed\n");
}
}
if (NO_ERROR != palError)
{
//
// We either were not able to create the new thread, or a failure
// occurred in the new thread's entry routine. Free up the associated
// resources here
//
if (fThreadDataAddedToProcessList)
{
PROCRemoveThread(pThread, pNewThread);
}
//
// Once we remove the thread from the process list, we can call
// PROCProcessUnlock.
//
if (fHoldingProcessLock)
{
PROCProcessUnlock();
}
fHoldingProcessLock = FALSE;
}
_ASSERT_MSG(!fHoldingProcessLock, "Exiting InternalCreateThread while still holding the process critical section.\n");
return palError;
}
/*++
Function:
ExitThread
See MSDN doc.
--*/
PAL_NORETURN
VOID
PALAPI
ExitThread(
IN DWORD dwExitCode)
{
CPalThread *pThread;
ENTRY("ExitThread(dwExitCode=%u)\n", dwExitCode);
PERF_ENTRY_ONLY(ExitThread);
pThread = InternalGetCurrentThread();
/* store the exit code */
pThread->SetExitCode(dwExitCode);
/* pthread_exit runs TLS destructors and cleanup routines,
possibly registered by foreign code. The right thing
to do here is to leave the PAL. Our own TLS destructor
re-enters us explicitly. */
PAL_Leave(PAL_BoundaryTop);
/* kill the thread (itself), resulting in a call to InternalEndCurrentThread */
pthread_exit(NULL);
ASSERT("pthread_exit should not return!\n");
for (;;);
}
/*++
Function:
GetExitCodeThread
See MSDN doc.
--*/
BOOL
PALAPI
GetExitCodeThread(
IN HANDLE hThread,
IN LPDWORD lpExitCode)
{
PAL_ERROR palError = NO_ERROR;
CPalThread *pthrCurrent = NULL;
CPalThread *pthrTarget = NULL;
IPalObject *pobjThread = NULL;
BOOL fExitCodeSet;
PERF_ENTRY(GetExitCodeThread);
ENTRY("GetExitCodeThread(hThread = %p, lpExitCode = %p)\n",
hThread, lpExitCode);
if (NULL == lpExitCode)
{
WARN("Got NULL lpExitCode\n");
palError = ERROR_INVALID_PARAMETER;
goto done;
}
pthrCurrent = InternalGetCurrentThread();
palError = InternalGetThreadDataFromHandle(
pthrCurrent,
hThread,
0,
&pthrTarget,
&pobjThread
);
pthrTarget->Lock(pthrCurrent);
fExitCodeSet = pthrTarget->GetExitCode(lpExitCode);
if (!fExitCodeSet)
{
if (TS_DONE == pthrTarget->synchronizationInfo.GetThreadState())
{
#ifdef FEATURE_PAL_SXS
// The thread exited without ever calling ExitThread.
// It must have wandered in.
*lpExitCode = 0;
#else // FEATURE_PAL_SXS
ASSERT("exit code not set but thread is dead\n");
#endif // FEATURE_PAL_SXS
}
else
{
*lpExitCode = STILL_ACTIVE;
}
}
pthrTarget->Unlock(pthrCurrent);
done:
if (NULL != pobjThread)
{
pobjThread->ReleaseReference(pthrCurrent);
}
LOGEXIT("GetExitCodeThread returns BOOL %d\n", NO_ERROR == palError);
PERF_EXIT(GetExitCodeThread);
return NO_ERROR == palError;
}
/*++
Function:
InternalEndCurrentThread
Does any necessary memory clean up, signals waiting threads, and then forces
the current thread to exit.
--*/
VOID
CorUnix::InternalEndCurrentThread(
CPalThread *pThread
)
{
PAL_ERROR palError = NO_ERROR;
ISynchStateController *pSynchStateController = NULL;
#ifdef PAL_PERF
PERFDisableThreadProfile(UserCreatedThread != pThread->GetThreadType());
#endif
//
// Abandon any objects owned by this thread
//
palError = g_pSynchronizationManager->AbandonObjectsOwnedByThread(
pThread,
pThread
);
if (NO_ERROR != palError)
{
ERROR("Failure abandoning owned objects");
}
//
// Need to synchronize setting the thread state to TS_DONE since
// this is checked for in InternalSuspendThreadFromData.
// TODO: Is this still needed after removing InternalSuspendThreadFromData?
//
pThread->suspensionInfo.AcquireSuspensionLock(pThread);
IncrementEndingThreadCount();
pThread->synchronizationInfo.SetThreadState(TS_DONE);
pThread->suspensionInfo.ReleaseSuspensionLock(pThread);
//
// Mark the thread object as signaled
//
palError = pThread->GetThreadObject()->GetSynchStateController(
pThread,
&pSynchStateController
);
if (NO_ERROR == palError)
{
palError = pSynchStateController->SetSignalCount(1);
if (NO_ERROR != palError)
{
ASSERT("Unable to mark thread object as signaled");
}
pSynchStateController->ReleaseController();
}
else
{
ASSERT("Unable to obtain state controller for thread");
}
#ifndef FEATURE_PAL_SXS
// If this is the last thread then delete the process' data,
// but don't exit because the application hosting the PAL
// might have its own threads.
if (PROCGetNumberOfThreads() == 1)
{
TRACE("Last thread is exiting\n");
DecrementEndingThreadCount();
TerminateCurrentProcessNoExit(FALSE);
}
else
#endif // !FEATURE_PAL_SXS
{
/* Do this ONLY if we aren't the last thread -> otherwise
it gets done by TerminateProcess->
PROCCleanupProcess->PALShutdown->PAL_Terminate */
//
// Add a reference to the thread data before releasing the
// thread object, so we can still use it
//
pThread->AddThreadReference();
//
// Release the reference to the IPalObject for this thread
//
pThread->GetThreadObject()->ReleaseReference(pThread);
/* Remove thread for the thread list of the process
(don't do if this is the last thread -> gets handled by
TerminateProcess->PROCCleanupProcess->PROCTerminateOtherThreads) */
PROCRemoveThread(pThread, pThread);