4 * Copyright 1996 Alexandre Julliard
10 #include <sys/socket.h>
11 #ifdef HAVE_SYS_MMAN_H
15 #include "wine/winbase16.h"
23 #include "selectors.h"
27 #include "stackframe.h"
28 #include "debugtools.h"
32 DEFAULT_DEBUG_CHANNEL(thread
)
34 /* TEB of the initial thread */
35 static TEB initial_teb
;
37 /* Global thread list (FIXME: not thread-safe) */
38 TEB
*THREAD_First
= &initial_teb
;
40 /***********************************************************************
43 BOOL
THREAD_IsWin16( TEB
*teb
)
45 return !teb
|| !(teb
->flags
& TEBF_WIN32
);
48 /***********************************************************************
51 * Convert a thread id to a TEB, making sure it is valid.
53 TEB
*THREAD_IdToTEB( DWORD id
)
55 TEB
*teb
= THREAD_First
;
57 if (!id
) return NtCurrentTeb();
60 if ((DWORD
)teb
->tid
== id
) return teb
;
63 /* Allow task handles to be used; convert to main thread */
66 TDB
*pTask
= (TDB
*)GlobalLock16( id
);
67 if (pTask
) return pTask
->teb
;
69 SetLastError( ERROR_INVALID_PARAMETER
);
74 /***********************************************************************
77 * Initialization of a newly created TEB.
79 static BOOL
THREAD_InitTEB( TEB
*teb
, DWORD stack_size
, BOOL alloc_stack16
,
80 LPSECURITY_ATTRIBUTES sa
)
84 /* Allocate the stack */
87 * If stacksize smaller than 1 MB, allocate 1MB
88 * (one program wanted only 10 kB, which is recommendable, but some WINE
89 * functions, noteably in the files subdir, push HUGE structures and
90 * arrays on the stack. They probably shouldn't.)
91 * If stacksize larger than 16 MB, warn the user. (We could shrink the stack
92 * but this could give more or less unexplainable crashes.)
94 if (stack_size
<1024*1024)
95 stack_size
= 1024 * 1024;
96 if (stack_size
>= 16*1024*1024)
97 WARN("Thread stack size is %ld MB.\n",stack_size
/1024/1024);
98 teb
->stack_base
= VirtualAlloc(NULL
, stack_size
+ SIGNAL_STACK_SIZE
+
99 (alloc_stack16
? 0x10000 : 0),
100 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
);
101 if (!teb
->stack_base
) goto error
;
102 /* Set a guard page at the bottom of the stack */
103 VirtualProtect( teb
->stack_base
, 1, PAGE_EXECUTE_READWRITE
| PAGE_GUARD
, &old_prot
);
104 teb
->stack_top
= (char *)teb
->stack_base
+ stack_size
;
105 teb
->stack_low
= teb
->stack_base
;
106 teb
->signal_stack
= teb
->stack_top
; /* start of signal stack */
108 /* Allocate the 16-bit stack selector */
112 teb
->stack_sel
= SELECTOR_AllocBlock( teb
->stack_top
, 0x10000, SEGMENT_DATA
,
114 if (!teb
->stack_sel
) goto error
;
115 teb
->cur_stack
= PTR_SEG_OFF_TO_SEGPTR( teb
->stack_sel
,
116 0x10000 - sizeof(STACK16FRAME
) );
117 teb
->signal_stack
= (char *)teb
->signal_stack
+ 0x10000;
120 /* Create the thread event */
122 if (!(teb
->event
= CreateEventA( NULL
, FALSE
, FALSE
, NULL
))) goto error
;
123 teb
->event
= ConvertToGlobalHandle( teb
->event
);
127 if (teb
->event
) CloseHandle( teb
->event
);
128 if (teb
->stack_sel
) SELECTOR_FreeBlock( teb
->stack_sel
, 1 );
129 if (teb
->stack_base
) VirtualFree( teb
->stack_base
, 0, MEM_RELEASE
);
134 /***********************************************************************
137 * Free data structures associated with a thread.
138 * Must be called from the context of another thread.
140 void CALLBACK
THREAD_FreeTEB( ULONG_PTR arg
)
142 TEB
*teb
= (TEB
*)arg
;
143 TEB
**pptr
= &THREAD_First
;
145 TRACE("(%p) called\n", teb
);
146 SERVICE_Delete( teb
->cleanup
);
148 PROCESS_CallUserSignalProc( USIG_THREAD_EXIT
, 0 );
150 CloseHandle( teb
->event
);
151 while (*pptr
&& (*pptr
!= teb
)) pptr
= &(*pptr
)->next
;
152 if (*pptr
) *pptr
= teb
->next
;
154 /* Free the associated memory */
156 if (teb
->stack_sel
) SELECTOR_FreeBlock( teb
->stack_sel
, 1 );
157 SELECTOR_FreeBlock( teb
->teb_sel
, 1 );
158 close( teb
->socket
);
159 if (teb
->buffer
) munmap( teb
->buffer
, teb
->buffer_size
);
160 VirtualFree( teb
->stack_base
, 0, MEM_RELEASE
);
161 HeapFree( SystemHeap
, 0, teb
);
165 /***********************************************************************
166 * THREAD_CreateInitialThread
168 * Create the initial thread.
170 TEB
*THREAD_CreateInitialThread( PDB
*pdb
, int server_fd
)
172 initial_teb
.except
= (void *)-1;
173 initial_teb
.self
= &initial_teb
;
174 initial_teb
.flags
= /* TEBF_WIN32 */ 0;
175 initial_teb
.tls_ptr
= initial_teb
.tls_array
;
176 initial_teb
.process
= pdb
;
177 initial_teb
.exit_code
= 0x103; /* STILL_ACTIVE */
178 initial_teb
.socket
= server_fd
;
180 /* Allocate the TEB selector (%fs register) */
182 if (!(initial_teb
.teb_sel
= SELECTOR_AllocBlock( &initial_teb
, 0x1000,
183 SEGMENT_DATA
, TRUE
, FALSE
)))
185 MESSAGE("Could not allocate fs register for initial thread\n" );
188 SYSDEPS_SetCurThread( &initial_teb
);
190 /* Now proceed with normal initialization */
192 if (CLIENT_InitThread()) return NULL
;
193 if (!THREAD_InitTEB( &initial_teb
, 0, TRUE
, NULL
)) return NULL
;
198 /***********************************************************************
201 TEB
*THREAD_Create( PDB
*pdb
, DWORD flags
, DWORD stack_size
, BOOL alloc_stack16
,
202 LPSECURITY_ATTRIBUTES sa
, int *server_handle
)
204 struct new_thread_request
*req
= get_req_buffer();
206 HANDLE cleanup_object
;
208 TEB
*teb
= HeapAlloc( SystemHeap
, HEAP_ZERO_MEMORY
, sizeof(TEB
) );
209 if (!teb
) return NULL
;
210 teb
->except
= (void *)-1;
211 teb
->htask16
= pdb
->task
;
213 teb
->flags
= (pdb
->flags
& PDB32_WIN16_PROC
)? 0 : TEBF_WIN32
;
214 teb
->tls_ptr
= teb
->tls_array
;
216 teb
->exit_code
= 0x103; /* STILL_ACTIVE */
219 /* Allocate the TEB selector (%fs register) */
222 teb
->teb_sel
= SELECTOR_AllocBlock( teb
, 0x1000, SEGMENT_DATA
, TRUE
, FALSE
);
223 if (!teb
->teb_sel
) goto error
;
225 /* Create the socket pair for server communication */
227 if (socketpair( AF_UNIX
, SOCK_STREAM
, 0, fd
) == -1)
229 SetLastError( ERROR_TOO_MANY_OPEN_FILES
); /* FIXME */
233 fcntl( fd
[0], F_SETFD
, 1 ); /* set close on exec flag */
235 /* Create the thread on the server side */
237 req
->pid
= teb
->process
->server_pid
;
238 req
->suspend
= ((flags
& CREATE_SUSPENDED
) != 0);
239 req
->inherit
= (sa
&& (sa
->nLength
>=sizeof(*sa
)) && sa
->bInheritHandle
);
240 if (server_call_fd( REQ_NEW_THREAD
, fd
[1], NULL
)) goto error
;
242 *server_handle
= req
->handle
;
244 /* Do the rest of the initialization */
246 if (!THREAD_InitTEB( teb
, stack_size
, alloc_stack16
, sa
)) goto error
;
247 teb
->next
= THREAD_First
;
250 /* Install cleanup handler */
251 if ( !DuplicateHandle( GetCurrentProcess(), *server_handle
,
252 GetCurrentProcess(), &cleanup_object
,
253 0, FALSE
, DUPLICATE_SAME_ACCESS
) ) goto error
;
254 teb
->cleanup
= SERVICE_AddObject( cleanup_object
, THREAD_FreeTEB
, (ULONG_PTR
)teb
);
259 if (*server_handle
!= -1) CloseHandle( *server_handle
);
260 if (teb
->teb_sel
) SELECTOR_FreeBlock( teb
->teb_sel
, 1 );
261 if (teb
->socket
!= -1) close( teb
->socket
);
262 HeapFree( SystemHeap
, 0, teb
);
267 /***********************************************************************
270 * Start execution of a newly created thread. Does not return.
272 static void THREAD_Start(void)
274 LPTHREAD_START_ROUTINE func
= (LPTHREAD_START_ROUTINE
)NtCurrentTeb()->entry_point
;
275 PROCESS_CallUserSignalProc( USIG_THREAD_INIT
, 0 );
277 MODULE_DllThreadAttach( NULL
);
279 if (NtCurrentTeb()->process
->flags
& PDB32_DEBUGGED
) DEBUG_SendCreateThreadEvent( func
);
281 ExitThread( func( NtCurrentTeb()->entry_arg
) );
285 /***********************************************************************
286 * CreateThread (KERNEL32.63)
288 HANDLE WINAPI
CreateThread( SECURITY_ATTRIBUTES
*sa
, DWORD stack
,
289 LPTHREAD_START_ROUTINE start
, LPVOID param
,
290 DWORD flags
, LPDWORD id
)
293 TEB
*teb
= THREAD_Create( PROCESS_Current(), flags
, stack
, TRUE
, sa
, &handle
);
295 teb
->flags
|= TEBF_WIN32
;
296 teb
->entry_point
= start
;
297 teb
->entry_arg
= param
;
298 teb
->startup
= THREAD_Start
;
299 if (SYSDEPS_SpawnThread( teb
) == -1)
301 CloseHandle( handle
);
304 if (id
) *id
= (DWORD
)teb
->tid
;
309 /***********************************************************************
310 * ExitThread [KERNEL32.215] Ends a thread
315 void WINAPI
ExitThread( DWORD code
) /* [in] Exit code for this thread */
317 MODULE_DllThreadDetach( NULL
);
318 TerminateThread( GetCurrentThread(), code
);
322 /***********************************************************************
323 * GetCurrentThread [KERNEL32.200] Gets pseudohandle for current thread
326 * Pseudohandle for the current thread
328 HANDLE WINAPI
GetCurrentThread(void)
330 return CURRENT_THREAD_PSEUDOHANDLE
;
334 /**********************************************************************
335 * GetLastError [KERNEL.148] [KERNEL32.227] Returns last-error code.
338 * Calling thread's last error code value.
340 DWORD WINAPI
GetLastError(void)
342 return NtCurrentTeb()->last_error
;
346 /**********************************************************************
347 * SetLastErrorEx [USER32.485] Sets the last-error code.
352 void WINAPI
SetLastErrorEx(
353 DWORD error
, /* [in] Per-thread error code */
354 DWORD type
) /* [in] Error type */
356 TRACE("(0x%08lx, 0x%08lx)\n", error
,type
);
363 /* Fall through for now */
365 FIXME("(error=%08lx, type=%08lx): Unhandled type\n", error
,type
);
368 SetLastError( error
);
372 /**********************************************************************
373 * TlsAlloc [KERNEL32.530] Allocates a TLS index.
375 * Allocates a thread local storage index
379 * Failure: 0xFFFFFFFF
381 DWORD WINAPI
TlsAlloc( void )
383 PDB
*process
= PROCESS_Current();
384 DWORD i
, mask
, ret
= 0;
385 DWORD
*bits
= process
->tls_bits
;
386 EnterCriticalSection( &process
->crit_section
);
387 if (*bits
== 0xffffffff)
391 if (*bits
== 0xffffffff)
393 LeaveCriticalSection( &process
->crit_section
);
394 SetLastError( ERROR_NO_MORE_ITEMS
);
398 for (i
= 0, mask
= 1; i
< 32; i
++, mask
<<= 1) if (!(*bits
& mask
)) break;
400 LeaveCriticalSection( &process
->crit_section
);
405 /**********************************************************************
406 * TlsFree [KERNEL32.531] Releases a TLS index.
408 * Releases a thread local storage index, making it available for reuse
415 DWORD index
) /* [in] TLS Index to free */
417 PDB
*process
= PROCESS_Current();
419 DWORD
*bits
= process
->tls_bits
;
422 SetLastError( ERROR_INVALID_PARAMETER
);
425 EnterCriticalSection( &process
->crit_section
);
426 if (index
>= 32) bits
++;
427 mask
= (1 << (index
& 31));
428 if (!(*bits
& mask
)) /* already free? */
430 LeaveCriticalSection( &process
->crit_section
);
431 SetLastError( ERROR_INVALID_PARAMETER
);
435 NtCurrentTeb()->tls_array
[index
] = 0;
436 /* FIXME: should zero all other thread values */
437 LeaveCriticalSection( &process
->crit_section
);
442 /**********************************************************************
443 * TlsGetValue [KERNEL32.532] Gets value in a thread's TLS slot
446 * Success: Value stored in calling thread's TLS slot for index
447 * Failure: 0 and GetLastError returns NO_ERROR
449 LPVOID WINAPI
TlsGetValue(
450 DWORD index
) /* [in] TLS index to retrieve value for */
454 SetLastError( ERROR_INVALID_PARAMETER
);
457 SetLastError( ERROR_SUCCESS
);
458 return NtCurrentTeb()->tls_array
[index
];
462 /**********************************************************************
463 * TlsSetValue [KERNEL32.533] Stores a value in the thread's TLS slot.
469 BOOL WINAPI
TlsSetValue(
470 DWORD index
, /* [in] TLS index to set value for */
471 LPVOID value
) /* [in] Value to be stored */
475 SetLastError( ERROR_INVALID_PARAMETER
);
478 NtCurrentTeb()->tls_array
[index
] = value
;
483 /***********************************************************************
484 * SetThreadContext [KERNEL32.670] Sets context of thread.
490 BOOL WINAPI
SetThreadContext(
491 HANDLE handle
, /* [in] Handle to thread with context */
492 CONTEXT
*context
) /* [out] Address of context structure */
494 FIXME("not implemented\n" );
498 /***********************************************************************
499 * GetThreadContext [KERNEL32.294] Retrieves context of thread.
505 BOOL WINAPI
GetThreadContext(
506 HANDLE handle
, /* [in] Handle to thread with context */
507 CONTEXT
*context
) /* [out] Address of context structure */
512 FIXME("returning dummy info\n" );
514 /* make up some plausible values for segment registers */
528 /**********************************************************************
529 * GetThreadPriority [KERNEL32.296] Returns priority for thread.
532 * Success: Thread's priority level.
533 * Failure: THREAD_PRIORITY_ERROR_RETURN
535 INT WINAPI
GetThreadPriority(
536 HANDLE hthread
) /* [in] Handle to thread */
538 INT ret
= THREAD_PRIORITY_ERROR_RETURN
;
539 struct get_thread_info_request
*req
= get_req_buffer();
540 req
->handle
= hthread
;
541 if (!server_call( REQ_GET_THREAD_INFO
)) ret
= req
->priority
;
546 /**********************************************************************
547 * SetThreadPriority [KERNEL32.514] Sets priority for thread.
553 BOOL WINAPI
SetThreadPriority(
554 HANDLE hthread
, /* [in] Handle to thread */
555 INT priority
) /* [in] Thread priority level */
557 struct set_thread_info_request
*req
= get_req_buffer();
558 req
->handle
= hthread
;
559 req
->priority
= priority
;
560 req
->mask
= SET_THREAD_INFO_PRIORITY
;
561 return !server_call( REQ_SET_THREAD_INFO
);
565 /**********************************************************************
566 * SetThreadAffinityMask (KERNEL32.669)
568 DWORD WINAPI
SetThreadAffinityMask( HANDLE hThread
, DWORD dwThreadAffinityMask
)
570 struct set_thread_info_request
*req
= get_req_buffer();
571 req
->handle
= hThread
;
572 req
->affinity
= dwThreadAffinityMask
;
573 req
->mask
= SET_THREAD_INFO_AFFINITY
;
574 if (server_call( REQ_SET_THREAD_INFO
)) return 0;
575 return 1; /* FIXME: should return previous value */
579 /**********************************************************************
580 * TerminateThread [KERNEL32.685] Terminates a thread
586 BOOL WINAPI
TerminateThread(
587 HANDLE handle
, /* [in] Handle to thread */
588 DWORD exitcode
) /* [in] Exit code for thread */
590 struct terminate_thread_request
*req
= get_req_buffer();
591 req
->handle
= handle
;
592 req
->exit_code
= exitcode
;
593 return !server_call( REQ_TERMINATE_THREAD
);
597 /**********************************************************************
598 * GetExitCodeThread [KERNEL32.???] Gets termination status of thread.
604 BOOL WINAPI
GetExitCodeThread(
605 HANDLE hthread
, /* [in] Handle to thread */
606 LPDWORD exitcode
) /* [out] Address to receive termination status */
609 struct get_thread_info_request
*req
= get_req_buffer();
610 req
->handle
= hthread
;
611 if (!server_call( REQ_GET_THREAD_INFO
))
613 if (exitcode
) *exitcode
= req
->exit_code
;
620 /**********************************************************************
621 * ResumeThread [KERNEL32.587] Resumes a thread.
623 * Decrements a thread's suspend count. When count is zero, the
624 * execution of the thread is resumed.
627 * Success: Previous suspend count
628 * Failure: 0xFFFFFFFF
631 DWORD WINAPI
ResumeThread(
632 HANDLE hthread
) /* [in] Identifies thread to restart */
634 DWORD ret
= 0xffffffff;
635 struct resume_thread_request
*req
= get_req_buffer();
636 req
->handle
= hthread
;
637 if (!server_call( REQ_RESUME_THREAD
)) ret
= req
->count
;
642 /**********************************************************************
643 * SuspendThread [KERNEL32.681] Suspends a thread.
646 * Success: Previous suspend count
647 * Failure: 0xFFFFFFFF
649 DWORD WINAPI
SuspendThread(
650 HANDLE hthread
) /* [in] Handle to the thread */
652 DWORD ret
= 0xffffffff;
653 struct suspend_thread_request
*req
= get_req_buffer();
654 req
->handle
= hthread
;
655 if (!server_call( REQ_SUSPEND_THREAD
)) ret
= req
->count
;
660 /***********************************************************************
661 * QueueUserAPC (KERNEL32.566)
663 DWORD WINAPI
QueueUserAPC( PAPCFUNC func
, HANDLE hthread
, ULONG_PTR data
)
665 struct queue_apc_request
*req
= get_req_buffer();
666 req
->handle
= hthread
;
668 req
->param
= (void *)data
;
669 return !server_call( REQ_QUEUE_APC
);
673 /**********************************************************************
674 * GetThreadTimes [KERNEL32.???] Obtains timing information.
677 * What are the fields where these values are stored?
683 BOOL WINAPI
GetThreadTimes(
684 HANDLE thread
, /* [in] Specifies the thread of interest */
685 LPFILETIME creationtime
, /* [out] When the thread was created */
686 LPFILETIME exittime
, /* [out] When the thread was destroyed */
687 LPFILETIME kerneltime
, /* [out] Time thread spent in kernel mode */
688 LPFILETIME usertime
) /* [out] Time thread spent in user mode */
690 FIXME("(0x%08x): stub\n",thread
);
691 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
696 /**********************************************************************
697 * AttachThreadInput [KERNEL32.8] Attaches input of 1 thread to other
699 * Attaches the input processing mechanism of one thread to that of
707 * 1. Reset the Key State (currenly per thread key state is not maintained)
709 BOOL WINAPI
AttachThreadInput(
710 DWORD idAttach
, /* [in] Thread to attach */
711 DWORD idAttachTo
, /* [in] Thread to attach to */
712 BOOL fAttach
) /* [in] Attach or detach */
714 MESSAGEQUEUE
*pSrcMsgQ
= 0, *pTgtMsgQ
= 0;
717 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
719 /* A thread cannot attach to itself */
720 if ( idAttach
== idAttachTo
)
723 /* According to the docs this method should fail if a
724 * "Journal record" hook is installed. (attaches all input queues together)
726 if ( HOOK_IsHooked( WH_JOURNALRECORD
) )
729 /* Retrieve message queues corresponding to the thread id's */
730 pTgtMsgQ
= (MESSAGEQUEUE
*)QUEUE_Lock( GetThreadQueue16( idAttach
) );
731 pSrcMsgQ
= (MESSAGEQUEUE
*)QUEUE_Lock( GetThreadQueue16( idAttachTo
) );
733 /* Ensure we have message queues and that Src and Tgt threads
734 * are not system threads.
736 if ( !pSrcMsgQ
|| !pTgtMsgQ
|| !pSrcMsgQ
->pQData
|| !pTgtMsgQ
->pQData
)
739 if (fAttach
) /* Attach threads */
741 /* Only attach if currently detached */
742 if ( pTgtMsgQ
->pQData
!= pSrcMsgQ
->pQData
)
744 /* First release the target threads perQData */
745 PERQDATA_Release( pTgtMsgQ
->pQData
);
747 /* Share a reference to the source threads perQDATA */
748 PERQDATA_Addref( pSrcMsgQ
->pQData
);
749 pTgtMsgQ
->pQData
= pSrcMsgQ
->pQData
;
752 else /* Detach threads */
754 /* Only detach if currently attached */
755 if ( pTgtMsgQ
->pQData
== pSrcMsgQ
->pQData
)
757 /* First release the target threads perQData */
758 PERQDATA_Release( pTgtMsgQ
->pQData
);
760 /* Give the target thread its own private perQDATA once more */
761 pTgtMsgQ
->pQData
= PERQDATA_CreateInstance();
765 /* TODO: Reset the Key State */
767 bRet
= 1; /* Success */
771 /* Unlock the queues before returning */
773 QUEUE_Unlock( pSrcMsgQ
);
775 QUEUE_Unlock( pTgtMsgQ
);
780 /**********************************************************************
781 * VWin32_BoostThreadGroup [KERNEL.535]
783 VOID WINAPI
VWin32_BoostThreadGroup( DWORD threadId
, INT boost
)
785 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
788 /**********************************************************************
789 * VWin32_BoostThreadStatic [KERNEL.536]
791 VOID WINAPI
VWin32_BoostThreadStatic( DWORD threadId
, INT boost
)
793 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
796 /**********************************************************************
797 * SetThreadLocale [KERNEL32.671] Sets the calling threads current locale.
804 * Implemented in NT only (3.1 and above according to MS
806 BOOL WINAPI
SetThreadLocale(
807 LCID lcid
) /* [in] Locale identifier */
809 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
814 /**********************************************************************
815 * SetLastError [KERNEL.147] [KERNEL32.497] Sets the last-error code.
821 void WINAPI
SetLastError( DWORD error
) /* [in] Per-thread error code */
823 NtCurrentTeb()->last_error
= error
;
827 /***********************************************************************
828 * GetCurrentThreadId [KERNEL32.201] Returns thread identifier.
831 * Thread identifier of calling thread
833 #undef GetCurrentThreadId
834 DWORD WINAPI
GetCurrentThreadId(void)
836 return (DWORD
)NtCurrentTeb()->tid
;