4 * Copyright 1996 Alexandre Julliard
11 #include <sys/types.h>
12 #ifdef HAVE_SYS_MMAN_H
16 #include "wine/winbase16.h"
24 #include "selectors.h"
28 #include "stackframe.h"
29 #include "builtin16.h"
30 #include "debugtools.h"
33 DEFAULT_DEBUG_CHANNEL(thread
);
35 /* TEB of the initial thread */
36 static TEB initial_teb
;
38 /***********************************************************************
41 BOOL
THREAD_IsWin16( TEB
*teb
)
43 return !teb
|| !(teb
->tibflags
& TEBF_WIN32
);
46 /***********************************************************************
49 * Convert a thread id to a TEB, making sure it is valid.
51 TEB
*THREAD_IdToTEB( DWORD id
)
53 struct get_thread_info_request
*req
= get_req_buffer();
55 if (!id
|| id
== GetCurrentThreadId()) return NtCurrentTeb();
57 req
->tid_in
= (void *)id
;
58 if (!server_call_noerr( REQ_GET_THREAD_INFO
)) return req
->teb
;
60 /* Allow task handles to be used; convert to main thread */
63 TDB
*pTask
= (TDB
*)GlobalLock16( id
);
64 if (pTask
) return pTask
->teb
;
66 SetLastError( ERROR_INVALID_PARAMETER
);
71 /***********************************************************************
74 * Initialization of a newly created TEB.
76 static BOOL
THREAD_InitTEB( TEB
*teb
)
78 teb
->except
= (void *)~0UL;
80 teb
->tibflags
= TEBF_WIN32
;
81 teb
->tls_ptr
= teb
->tls_array
;
82 teb
->exit_code
= STILL_ACTIVE
;
84 teb
->stack_top
= (void *)~0UL;
85 teb
->StaticUnicodeString
.MaximumLength
= sizeof(teb
->StaticUnicodeBuffer
);
86 teb
->StaticUnicodeString
.Buffer
= (PWSTR
)teb
->StaticUnicodeBuffer
;
87 teb
->teb_sel
= SELECTOR_AllocBlock( teb
, 0x1000, SEGMENT_DATA
, TRUE
, FALSE
);
88 return (teb
->teb_sel
!= 0);
92 /***********************************************************************
95 * Free data structures associated with a thread.
96 * Must be called from the context of another thread.
98 static void CALLBACK
THREAD_FreeTEB( TEB
*teb
)
100 TRACE("(%p) called\n", teb
);
101 if (teb
->cleanup
) SERVICE_Delete( teb
->cleanup
);
103 /* Free the associated memory */
105 if (teb
->socket
!= -1) close( teb
->socket
);
106 if (teb
->stack_sel
) SELECTOR_FreeBlock( teb
->stack_sel
, 1 );
107 SELECTOR_FreeBlock( teb
->teb_sel
, 1 );
108 if (teb
->buffer
) munmap( teb
->buffer
, teb
->buffer_size
);
109 if (teb
->debug_info
) HeapFree( GetProcessHeap(), 0, teb
->debug_info
);
110 VirtualFree( teb
->stack_base
, 0, MEM_RELEASE
);
114 /***********************************************************************
117 * Allocate the stack of a thread.
119 TEB
*THREAD_InitStack( TEB
*teb
, DWORD stack_size
, BOOL alloc_stack16
)
121 DWORD old_prot
, total_size
;
122 DWORD page_size
= VIRTUAL_GetPageSize();
125 /* Allocate the stack */
127 if (stack_size
>= 16*1024*1024)
128 WARN("Thread stack size is %ld MB.\n",stack_size
/1024/1024);
130 /* if size is smaller than default, get stack size from parent */
131 if (stack_size
< 1024 * 1024)
134 stack_size
= 1024 * 1024; /* no parent */
136 stack_size
= ((char *)NtCurrentTeb()->stack_top
- (char *)NtCurrentTeb()->stack_base
137 - SIGNAL_STACK_SIZE
- 3 * page_size
);
140 /* FIXME: some Wine functions use a lot of stack, so we add 64Kb here */
141 stack_size
+= 64 * 1024;
143 /* Memory layout in allocated block:
146 * 1 page NOACCESS guard page
147 * SIGNAL_STACK_SIZE signal stack
148 * 1 page NOACCESS guard page
149 * 1 page PAGE_GUARD guard page
150 * stack_size normal stack
151 * 64Kb 16-bit stack (optional)
152 * 1 page TEB (except for initial thread)
155 stack_size
= (stack_size
+ (page_size
- 1)) & ~(page_size
- 1);
156 total_size
= stack_size
+ SIGNAL_STACK_SIZE
+ 3 * page_size
;
157 if (alloc_stack16
) total_size
+= 0x10000;
158 if (!teb
) total_size
+= page_size
;
160 if (!(base
= VirtualAlloc( NULL
, total_size
, MEM_COMMIT
, PAGE_EXECUTE_READWRITE
)))
165 teb
= (TEB
*)((char *)base
+ total_size
- page_size
);
166 if (!THREAD_InitTEB( teb
))
168 VirtualFree( base
, 0, MEM_RELEASE
);
173 teb
->stack_low
= base
;
174 teb
->stack_base
= base
;
175 teb
->signal_stack
= (char *)base
+ page_size
;
176 teb
->stack_top
= (char *)base
+ 3 * page_size
+ SIGNAL_STACK_SIZE
+ stack_size
;
178 /* Setup guard pages */
180 VirtualProtect( base
, 1, PAGE_NOACCESS
, &old_prot
);
181 VirtualProtect( (char *)teb
->signal_stack
+ SIGNAL_STACK_SIZE
, 1, PAGE_NOACCESS
, &old_prot
);
182 VirtualProtect( (char *)teb
->signal_stack
+ SIGNAL_STACK_SIZE
+ page_size
, 1,
183 PAGE_EXECUTE_READWRITE
| PAGE_GUARD
, &old_prot
);
185 /* Allocate the 16-bit stack selector */
189 teb
->stack_sel
= SELECTOR_AllocBlock( teb
->stack_top
, 0x10000, SEGMENT_DATA
,
191 if (!teb
->stack_sel
) goto error
;
192 teb
->cur_stack
= PTR_SEG_OFF_TO_SEGPTR( teb
->stack_sel
,
193 0x10000 - sizeof(STACK16FRAME
) );
198 THREAD_FreeTEB( teb
);
203 /***********************************************************************
206 * Setup the initial thread.
208 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
210 void THREAD_Init(void)
212 if (!initial_teb
.self
) /* do it only once */
214 THREAD_InitTEB( &initial_teb
);
215 assert( initial_teb
.teb_sel
);
216 initial_teb
.process
= ¤t_process
;
217 SYSDEPS_SetCurThread( &initial_teb
);
221 DECL_GLOBAL_CONSTRUCTOR(thread_init
) { THREAD_Init(); }
223 /***********************************************************************
227 TEB
*THREAD_Create( int fd
, DWORD stack_size
, BOOL alloc_stack16
)
231 if ((teb
= THREAD_InitStack( NULL
, stack_size
, alloc_stack16
)))
233 teb
->tibflags
= (current_process
.flags
& PDB32_WIN16_PROC
) ? 0 : TEBF_WIN32
;
234 teb
->process
= ¤t_process
;
236 fcntl( fd
, F_SETFD
, 1 ); /* set close on exec flag */
237 TRACE("(%p) succeeded\n", teb
);
243 /***********************************************************************
246 * Start execution of a newly created thread. Does not return.
248 static void THREAD_Start(void)
250 HANDLE cleanup_object
;
251 LPTHREAD_START_ROUTINE func
= (LPTHREAD_START_ROUTINE
)NtCurrentTeb()->entry_point
;
253 /* install cleanup handler */
254 if (DuplicateHandle( GetCurrentProcess(), GetCurrentThread(),
255 GetCurrentProcess(), &cleanup_object
,
256 0, FALSE
, DUPLICATE_SAME_ACCESS
))
257 NtCurrentTeb()->cleanup
= SERVICE_AddObject( cleanup_object
, (PAPCFUNC
)THREAD_FreeTEB
,
258 (ULONG_PTR
)NtCurrentTeb() );
260 PROCESS_CallUserSignalProc( USIG_THREAD_INIT
, 0 );
262 MODULE_DllThreadAttach( NULL
);
263 ExitThread( func( NtCurrentTeb()->entry_arg
) );
267 /***********************************************************************
268 * CreateThread (KERNEL32.63)
270 HANDLE WINAPI
CreateThread( SECURITY_ATTRIBUTES
*sa
, DWORD stack
,
271 LPTHREAD_START_ROUTINE start
, LPVOID param
,
272 DWORD flags
, LPDWORD id
)
274 struct new_thread_request
*req
= get_req_buffer();
275 int socket
, handle
= -1;
279 req
->suspend
= ((flags
& CREATE_SUSPENDED
) != 0);
280 req
->inherit
= (sa
&& (sa
->nLength
>=sizeof(*sa
)) && sa
->bInheritHandle
);
281 if (server_call_fd( REQ_NEW_THREAD
, -1, &socket
)) return 0;
282 handle
= req
->handle
;
285 if (!(teb
= THREAD_Create( socket
, stack
, TRUE
)))
290 teb
->tibflags
|= TEBF_WIN32
;
291 teb
->entry_point
= start
;
292 teb
->entry_arg
= param
;
293 teb
->startup
= THREAD_Start
;
294 teb
->htask16
= GetCurrentTask();
295 if (id
) *id
= (DWORD
)tid
;
296 if (SYSDEPS_SpawnThread( teb
) == -1)
298 CloseHandle( handle
);
304 /***********************************************************************
305 * CreateThread16 (KERNEL.441)
307 static DWORD CALLBACK
THREAD_StartThread16( LPVOID threadArgs
)
309 FARPROC16 start
= ((FARPROC16
*)threadArgs
)[0];
310 DWORD param
= ((DWORD
*)threadArgs
)[1];
311 HeapFree( GetProcessHeap(), 0, threadArgs
);
313 ((LPDWORD
)CURRENT_STACK16
)[-1] = param
;
314 return CallTo16Long( start
, sizeof(DWORD
) );
316 HANDLE WINAPI
CreateThread16( SECURITY_ATTRIBUTES
*sa
, DWORD stack
,
317 FARPROC16 start
, SEGPTR param
,
318 DWORD flags
, LPDWORD id
)
320 DWORD
*threadArgs
= HeapAlloc( GetProcessHeap(), 0, 2*sizeof(DWORD
) );
321 if (!threadArgs
) return INVALID_HANDLE_VALUE
;
322 threadArgs
[0] = (DWORD
)start
;
323 threadArgs
[1] = (DWORD
)param
;
325 return CreateThread( sa
, stack
, THREAD_StartThread16
, threadArgs
, flags
, id
);
329 /***********************************************************************
330 * ExitThread [KERNEL32.215] Ends a thread
335 void WINAPI
ExitThread( DWORD code
) /* [in] Exit code for this thread */
337 struct terminate_thread_request
*req
= get_req_buffer();
339 /* send the exit code to the server */
340 req
->handle
= GetCurrentThread();
341 req
->exit_code
= code
;
342 server_call( REQ_TERMINATE_THREAD
);
345 MODULE_DllProcessDetach( TRUE
, (LPVOID
)1 );
350 MODULE_DllThreadDetach( NULL
);
351 if (!(NtCurrentTeb()->tibflags
& TEBF_WIN32
)) TASK_KillTask( 0 );
352 SYSDEPS_ExitThread( code
);
357 /**********************************************************************
358 * TlsAlloc [KERNEL32.530] Allocates a TLS index.
360 * Allocates a thread local storage index
364 * Failure: 0xFFFFFFFF
366 DWORD WINAPI
TlsAlloc( void )
368 DWORD i
, mask
, ret
= 0;
369 DWORD
*bits
= current_process
.tls_bits
;
370 EnterCriticalSection( ¤t_process
.crit_section
);
371 if (*bits
== 0xffffffff)
375 if (*bits
== 0xffffffff)
377 LeaveCriticalSection( ¤t_process
.crit_section
);
378 SetLastError( ERROR_NO_MORE_ITEMS
);
382 for (i
= 0, mask
= 1; i
< 32; i
++, mask
<<= 1) if (!(*bits
& mask
)) break;
384 LeaveCriticalSection( ¤t_process
.crit_section
);
389 /**********************************************************************
390 * TlsFree [KERNEL32.531] Releases a TLS index.
392 * Releases a thread local storage index, making it available for reuse
399 DWORD index
) /* [in] TLS Index to free */
402 DWORD
*bits
= current_process
.tls_bits
;
405 SetLastError( ERROR_INVALID_PARAMETER
);
408 EnterCriticalSection( ¤t_process
.crit_section
);
409 if (index
>= 32) bits
++;
410 mask
= (1 << (index
& 31));
411 if (!(*bits
& mask
)) /* already free? */
413 LeaveCriticalSection( ¤t_process
.crit_section
);
414 SetLastError( ERROR_INVALID_PARAMETER
);
418 NtCurrentTeb()->tls_array
[index
] = 0;
419 /* FIXME: should zero all other thread values */
420 LeaveCriticalSection( ¤t_process
.crit_section
);
425 /**********************************************************************
426 * TlsGetValue [KERNEL32.532] Gets value in a thread's TLS slot
429 * Success: Value stored in calling thread's TLS slot for index
430 * Failure: 0 and GetLastError returns NO_ERROR
432 LPVOID WINAPI
TlsGetValue(
433 DWORD index
) /* [in] TLS index to retrieve value for */
437 SetLastError( ERROR_INVALID_PARAMETER
);
440 SetLastError( ERROR_SUCCESS
);
441 return NtCurrentTeb()->tls_array
[index
];
445 /**********************************************************************
446 * TlsSetValue [KERNEL32.533] Stores a value in the thread's TLS slot.
452 BOOL WINAPI
TlsSetValue(
453 DWORD index
, /* [in] TLS index to set value for */
454 LPVOID value
) /* [in] Value to be stored */
458 SetLastError( ERROR_INVALID_PARAMETER
);
461 NtCurrentTeb()->tls_array
[index
] = value
;
466 /***********************************************************************
467 * SetThreadContext [KERNEL32.670] Sets context of thread.
473 BOOL WINAPI
SetThreadContext( HANDLE handle
, /* [in] Handle to thread with context */
474 const CONTEXT
*context
) /* [in] Address of context structure */
476 struct set_thread_context_request
*req
= get_req_buffer();
477 req
->handle
= handle
;
478 req
->flags
= context
->ContextFlags
;
479 memcpy( &req
->context
, context
, sizeof(*context
) );
480 return !server_call( REQ_SET_THREAD_CONTEXT
);
484 /***********************************************************************
485 * GetThreadContext [KERNEL32.294] Retrieves context of thread.
491 BOOL WINAPI
GetThreadContext( HANDLE handle
, /* [in] Handle to thread with context */
492 CONTEXT
*context
) /* [out] Address of context structure */
494 struct get_thread_context_request
*req
= get_req_buffer();
495 req
->handle
= handle
;
496 req
->flags
= context
->ContextFlags
;
497 memcpy( &req
->context
, context
, sizeof(*context
) );
498 if (server_call( REQ_GET_THREAD_CONTEXT
)) return FALSE
;
499 memcpy( context
, &req
->context
, sizeof(*context
) );
504 /**********************************************************************
505 * GetThreadPriority [KERNEL32.296] Returns priority for thread.
508 * Success: Thread's priority level.
509 * Failure: THREAD_PRIORITY_ERROR_RETURN
511 INT WINAPI
GetThreadPriority(
512 HANDLE hthread
) /* [in] Handle to thread */
514 INT ret
= THREAD_PRIORITY_ERROR_RETURN
;
515 struct get_thread_info_request
*req
= get_req_buffer();
516 req
->handle
= hthread
;
518 if (!server_call( REQ_GET_THREAD_INFO
)) ret
= req
->priority
;
523 /**********************************************************************
524 * SetThreadPriority [KERNEL32.514] Sets priority for thread.
530 BOOL WINAPI
SetThreadPriority(
531 HANDLE hthread
, /* [in] Handle to thread */
532 INT priority
) /* [in] Thread priority level */
534 struct set_thread_info_request
*req
= get_req_buffer();
535 req
->handle
= hthread
;
536 req
->priority
= priority
;
537 req
->mask
= SET_THREAD_INFO_PRIORITY
;
538 return !server_call( REQ_SET_THREAD_INFO
);
542 /**********************************************************************
543 * GetThreadPriorityBoost [KERNEL32.877] Returns priority boost for thread.
545 * Always reports that priority boost is disabled.
551 BOOL WINAPI
GetThreadPriorityBoost(
552 HANDLE hthread
, /* [in] Handle to thread */
553 PBOOL pstate
) /* [out] pointer to var that receives the boost state */
555 if (pstate
) *pstate
= FALSE
;
560 /**********************************************************************
561 * SetThreadPriorityBoost [KERNEL32.893] Sets priority boost for thread.
563 * Priority boost is not implemented. Thsi function always returns
564 * FALSE and sets last error to ERROR_CALL_NOT_IMPLEMENTED
567 * Always returns FALSE to indicate a failure
569 BOOL WINAPI
SetThreadPriorityBoost(
570 HANDLE hthread
, /* [in] Handle to thread */
571 BOOL disable
) /* [in] TRUE to disable priority boost */
573 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
578 /**********************************************************************
579 * SetThreadAffinityMask (KERNEL32.669)
581 DWORD WINAPI
SetThreadAffinityMask( HANDLE hThread
, DWORD dwThreadAffinityMask
)
583 struct set_thread_info_request
*req
= get_req_buffer();
584 req
->handle
= hThread
;
585 req
->affinity
= dwThreadAffinityMask
;
586 req
->mask
= SET_THREAD_INFO_AFFINITY
;
587 if (server_call( REQ_SET_THREAD_INFO
)) return 0;
588 return 1; /* FIXME: should return previous value */
592 /**********************************************************************
593 * TerminateThread [KERNEL32.685] Terminates a thread
599 BOOL WINAPI
TerminateThread(
600 HANDLE handle
, /* [in] Handle to thread */
601 DWORD exitcode
) /* [in] Exit code for thread */
604 struct terminate_thread_request
*req
= get_req_buffer();
605 req
->handle
= handle
;
606 req
->exit_code
= exitcode
;
607 if ((ret
= !server_call( REQ_TERMINATE_THREAD
)) && req
->self
)
609 PROCESS_CallUserSignalProc( USIG_THREAD_EXIT
, 0 );
610 if (req
->last
) exit( exitcode
);
611 else SYSDEPS_ExitThread( exitcode
);
617 /**********************************************************************
618 * GetExitCodeThread [KERNEL32.???] Gets termination status of thread.
624 BOOL WINAPI
GetExitCodeThread(
625 HANDLE hthread
, /* [in] Handle to thread */
626 LPDWORD exitcode
) /* [out] Address to receive termination status */
629 struct get_thread_info_request
*req
= get_req_buffer();
630 req
->handle
= hthread
;
632 if (!server_call( REQ_GET_THREAD_INFO
))
634 if (exitcode
) *exitcode
= req
->exit_code
;
641 /**********************************************************************
642 * ResumeThread [KERNEL32.587] Resumes a thread.
644 * Decrements a thread's suspend count. When count is zero, the
645 * execution of the thread is resumed.
648 * Success: Previous suspend count
649 * Failure: 0xFFFFFFFF
652 DWORD WINAPI
ResumeThread(
653 HANDLE hthread
) /* [in] Identifies thread to restart */
655 DWORD ret
= 0xffffffff;
656 struct resume_thread_request
*req
= get_req_buffer();
657 req
->handle
= hthread
;
658 if (!server_call( REQ_RESUME_THREAD
)) ret
= req
->count
;
663 /**********************************************************************
664 * SuspendThread [KERNEL32.681] Suspends a thread.
667 * Success: Previous suspend count
668 * Failure: 0xFFFFFFFF
670 DWORD WINAPI
SuspendThread(
671 HANDLE hthread
) /* [in] Handle to the thread */
673 DWORD ret
= 0xffffffff;
674 struct suspend_thread_request
*req
= get_req_buffer();
675 req
->handle
= hthread
;
676 if (!server_call( REQ_SUSPEND_THREAD
)) ret
= req
->count
;
681 /***********************************************************************
682 * QueueUserAPC (KERNEL32.566)
684 DWORD WINAPI
QueueUserAPC( PAPCFUNC func
, HANDLE hthread
, ULONG_PTR data
)
686 struct queue_apc_request
*req
= get_req_buffer();
687 req
->handle
= hthread
;
689 req
->param
= (void *)data
;
690 return !server_call( REQ_QUEUE_APC
);
694 /**********************************************************************
695 * GetThreadTimes [KERNEL32.???] Obtains timing information.
698 * What are the fields where these values are stored?
704 BOOL WINAPI
GetThreadTimes(
705 HANDLE thread
, /* [in] Specifies the thread of interest */
706 LPFILETIME creationtime
, /* [out] When the thread was created */
707 LPFILETIME exittime
, /* [out] When the thread was destroyed */
708 LPFILETIME kerneltime
, /* [out] Time thread spent in kernel mode */
709 LPFILETIME usertime
) /* [out] Time thread spent in user mode */
711 FIXME("(0x%08x): stub\n",thread
);
712 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
717 /**********************************************************************
718 * VWin32_BoostThreadGroup [KERNEL.535]
720 VOID WINAPI
VWin32_BoostThreadGroup( DWORD threadId
, INT boost
)
722 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
725 /**********************************************************************
726 * VWin32_BoostThreadStatic [KERNEL.536]
728 VOID WINAPI
VWin32_BoostThreadStatic( DWORD threadId
, INT boost
)
730 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
734 /***********************************************************************
735 * GetThreadLocale (KERNEL32.295)
737 LCID WINAPI
GetThreadLocale(void)
739 LCID ret
= NtCurrentTeb()->CurrentLocale
;
740 if (!ret
) NtCurrentTeb()->CurrentLocale
= ret
= GetUserDefaultLCID();
745 /**********************************************************************
746 * SetThreadLocale [KERNEL32.671] Sets the calling threads current locale.
753 * check if lcid is a valid cp
755 BOOL WINAPI
SetThreadLocale(
756 LCID lcid
) /* [in] Locale identifier */
760 case LOCALE_SYSTEM_DEFAULT
:
761 lcid
= GetSystemDefaultLCID();
763 case LOCALE_USER_DEFAULT
:
765 lcid
= GetUserDefaultLCID();
768 NtCurrentTeb()->CurrentLocale
= lcid
;
773 /***********************************************************************
774 * GetCurrentThread [KERNEL32.200] Gets pseudohandle for current thread
777 * Pseudohandle for the current thread
779 #undef GetCurrentThread
780 HANDLE WINAPI
GetCurrentThread(void)
788 /* void WINAPI SetLastError( DWORD error ); */
789 __ASM_GLOBAL_FUNC( SetLastError
,
790 "movl 4(%esp),%eax\n\t"
795 /* DWORD WINAPI GetLastError(void); */
796 __ASM_GLOBAL_FUNC( GetLastError
, ".byte 0x64\n\tmovl 0x60,%eax\n\tret" );
798 /* DWORD WINAPI GetCurrentProcessId(void) */
799 __ASM_GLOBAL_FUNC( GetCurrentProcessId
, ".byte 0x64\n\tmovl 0x20,%eax\n\tret" );
801 /* DWORD WINAPI GetCurrentThreadId(void) */
802 __ASM_GLOBAL_FUNC( GetCurrentThreadId
, ".byte 0x64\n\tmovl 0x24,%eax\n\tret" );
806 /**********************************************************************
807 * SetLastError [KERNEL.147] [KERNEL32.497] Sets the last-error code.
809 void WINAPI
SetLastError( DWORD error
) /* [in] Per-thread error code */
811 NtCurrentTeb()->last_error
= error
;
814 /**********************************************************************
815 * GetLastError [KERNEL.148] [KERNEL32.227] Returns last-error code.
817 DWORD WINAPI
GetLastError(void)
819 return NtCurrentTeb()->last_error
;
822 /***********************************************************************
823 * GetCurrentProcessId [KERNEL32.199] Returns process identifier.
825 DWORD WINAPI
GetCurrentProcessId(void)
827 return (DWORD
)NtCurrentTeb()->pid
;
830 /***********************************************************************
831 * GetCurrentThreadId [KERNEL32.201] Returns thread identifier.
833 DWORD WINAPI
GetCurrentThreadId(void)
835 return (DWORD
)NtCurrentTeb()->tid
;
838 #endif /* __i386__ */