4 * Copyright 1996 Alexandre Julliard
11 #include <sys/types.h>
12 #ifdef HAVE_SYS_MMAN_H
16 #include "wine/winbase16.h"
17 #include "wine/port.h"
23 #include "selectors.h"
27 #include "stackframe.h"
28 #include "builtin16.h"
29 #include "debugtools.h"
32 DEFAULT_DEBUG_CHANNEL(thread
);
34 /* TEB of the initial thread */
35 static TEB initial_teb
;
37 extern struct _PDB current_process
;
39 /***********************************************************************
42 BOOL
THREAD_IsWin16( TEB
*teb
)
44 return !teb
|| !(teb
->tibflags
& TEBF_WIN32
);
47 /***********************************************************************
50 * Convert a thread id to a TEB, making sure it is valid.
52 TEB
*THREAD_IdToTEB( DWORD id
)
56 if (!id
|| id
== GetCurrentThreadId()) return NtCurrentTeb();
60 struct get_thread_info_request
*req
= server_alloc_req( sizeof(*req
), 0 );
62 req
->tid_in
= (void *)id
;
63 if (!server_call_noerr( REQ_GET_THREAD_INFO
)) ret
= req
->teb
;
69 /* Allow task handles to be used; convert to main thread */
72 TDB
*pTask
= (TDB
*)GlobalLock16( id
);
73 if (pTask
) return pTask
->teb
;
75 SetLastError( ERROR_INVALID_PARAMETER
);
81 /***********************************************************************
84 * Initialization of a newly created TEB.
86 static BOOL
THREAD_InitTEB( TEB
*teb
)
88 teb
->except
= (void *)~0UL;
90 teb
->tibflags
= TEBF_WIN32
;
91 teb
->tls_ptr
= teb
->tls_array
;
92 teb
->exit_code
= STILL_ACTIVE
;
97 teb
->stack_top
= (void *)~0UL;
98 teb
->StaticUnicodeString
.MaximumLength
= sizeof(teb
->StaticUnicodeBuffer
);
99 teb
->StaticUnicodeString
.Buffer
= (PWSTR
)teb
->StaticUnicodeBuffer
;
100 teb
->teb_sel
= SELECTOR_AllocBlock( teb
, 0x1000, WINE_LDT_FLAGS_DATA
|WINE_LDT_FLAGS_32BIT
);
101 return (teb
->teb_sel
!= 0);
105 /***********************************************************************
108 * Free data structures associated with a thread.
109 * Must be called from the context of another thread.
111 static void CALLBACK
THREAD_FreeTEB( TEB
*teb
)
113 TRACE("(%p) called\n", teb
);
114 if (teb
->cleanup
) SERVICE_Delete( teb
->cleanup
);
116 /* Free the associated memory */
118 if (teb
->socket
!= -1) close( teb
->socket
);
119 close( teb
->request_fd
);
120 close( teb
->reply_fd
);
121 close( teb
->wait_fd
);
122 if (teb
->stack_sel
) FreeSelector16( teb
->stack_sel
);
123 FreeSelector16( teb
->teb_sel
);
124 if (teb
->buffer
) munmap( (void *)teb
->buffer
,
125 (char *)(teb
->buffer_info
+1) - (char *)teb
->buffer
);
126 if (teb
->debug_info
) HeapFree( GetProcessHeap(), 0, teb
->debug_info
);
127 VirtualFree( teb
->stack_base
, 0, MEM_RELEASE
);
131 /***********************************************************************
134 * Allocate the stack of a thread.
136 TEB
*THREAD_InitStack( TEB
*teb
, DWORD stack_size
, BOOL alloc_stack16
)
138 DWORD old_prot
, total_size
;
139 DWORD page_size
= getpagesize();
142 /* Allocate the stack */
144 if (stack_size
>= 16*1024*1024)
145 WARN("Thread stack size is %ld MB.\n",stack_size
/1024/1024);
147 /* if size is smaller than default, get stack size from parent */
148 if (stack_size
< 1024 * 1024)
151 stack_size
= 1024 * 1024; /* no parent */
153 stack_size
= ((char *)NtCurrentTeb()->stack_top
- (char *)NtCurrentTeb()->stack_base
154 - SIGNAL_STACK_SIZE
- 3 * page_size
);
157 /* FIXME: some Wine functions use a lot of stack, so we add 64Kb here */
158 stack_size
+= 64 * 1024;
160 /* Memory layout in allocated block:
163 * 1 page NOACCESS guard page
164 * SIGNAL_STACK_SIZE signal stack
165 * 1 page NOACCESS guard page
166 * 1 page PAGE_GUARD guard page
167 * stack_size normal stack
168 * 64Kb 16-bit stack (optional)
169 * 1 page TEB (except for initial thread)
172 stack_size
= (stack_size
+ (page_size
- 1)) & ~(page_size
- 1);
173 total_size
= stack_size
+ SIGNAL_STACK_SIZE
+ 3 * page_size
;
174 if (alloc_stack16
) total_size
+= 0x10000;
175 if (!teb
) total_size
+= page_size
;
177 if (!(base
= VirtualAlloc( NULL
, total_size
, MEM_COMMIT
, PAGE_EXECUTE_READWRITE
)))
182 teb
= (TEB
*)((char *)base
+ total_size
- page_size
);
183 if (!THREAD_InitTEB( teb
))
185 VirtualFree( base
, 0, MEM_RELEASE
);
190 teb
->stack_low
= base
;
191 teb
->stack_base
= base
;
192 teb
->signal_stack
= (char *)base
+ page_size
;
193 teb
->stack_top
= (char *)base
+ 3 * page_size
+ SIGNAL_STACK_SIZE
+ stack_size
;
195 /* Setup guard pages */
197 VirtualProtect( base
, 1, PAGE_NOACCESS
, &old_prot
);
198 VirtualProtect( (char *)teb
->signal_stack
+ SIGNAL_STACK_SIZE
, 1, PAGE_NOACCESS
, &old_prot
);
199 VirtualProtect( (char *)teb
->signal_stack
+ SIGNAL_STACK_SIZE
+ page_size
, 1,
200 PAGE_EXECUTE_READWRITE
| PAGE_GUARD
, &old_prot
);
202 /* Allocate the 16-bit stack selector */
206 teb
->stack_sel
= SELECTOR_AllocBlock( teb
->stack_top
, 0x10000, WINE_LDT_FLAGS_DATA
);
207 if (!teb
->stack_sel
) goto error
;
208 teb
->cur_stack
= MAKESEGPTR( teb
->stack_sel
, 0x10000 - sizeof(STACK16FRAME
) );
213 THREAD_FreeTEB( teb
);
218 /***********************************************************************
219 * thread_errno_location
221 * Get the per-thread errno location.
223 static int *thread_errno_location(void)
225 return &NtCurrentTeb()->thread_errno
;
228 /***********************************************************************
229 * thread_h_errno_location
231 * Get the per-thread h_errno location.
233 static int *thread_h_errno_location(void)
235 return &NtCurrentTeb()->thread_h_errno
;
238 /***********************************************************************
241 * Setup the initial thread.
243 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
245 void THREAD_Init(void)
247 if (!initial_teb
.self
) /* do it only once */
249 THREAD_InitTEB( &initial_teb
);
250 assert( initial_teb
.teb_sel
);
251 initial_teb
.process
= ¤t_process
;
252 SYSDEPS_SetCurThread( &initial_teb
);
253 wine_errno_location
= thread_errno_location
;
254 wine_h_errno_location
= thread_h_errno_location
;
258 DECL_GLOBAL_CONSTRUCTOR(thread_init
) { THREAD_Init(); }
260 /***********************************************************************
264 TEB
*THREAD_Create( int fd
, DWORD stack_size
, BOOL alloc_stack16
)
268 if ((teb
= THREAD_InitStack( NULL
, stack_size
, alloc_stack16
)))
270 teb
->tibflags
= TEBF_WIN32
;
271 teb
->process
= NtCurrentTeb()->process
;
273 fcntl( fd
, F_SETFD
, 1 ); /* set close on exec flag */
274 TRACE("(%p) succeeded\n", teb
);
280 /***********************************************************************
283 * Start execution of a newly created thread. Does not return.
285 static void THREAD_Start(void)
287 HANDLE cleanup_object
;
288 LPTHREAD_START_ROUTINE func
= (LPTHREAD_START_ROUTINE
)NtCurrentTeb()->entry_point
;
290 /* install cleanup handler */
291 if (DuplicateHandle( GetCurrentProcess(), GetCurrentThread(),
292 GetCurrentProcess(), &cleanup_object
,
293 0, FALSE
, DUPLICATE_SAME_ACCESS
))
294 NtCurrentTeb()->cleanup
= SERVICE_AddObject( cleanup_object
, (PAPCFUNC
)THREAD_FreeTEB
,
295 (ULONG_PTR
)NtCurrentTeb() );
297 PROCESS_CallUserSignalProc( USIG_THREAD_INIT
, 0 );
299 MODULE_DllThreadAttach( NULL
);
300 ExitThread( func( NtCurrentTeb()->entry_arg
) );
304 /***********************************************************************
305 * CreateThread (KERNEL32.@)
307 HANDLE WINAPI
CreateThread( SECURITY_ATTRIBUTES
*sa
, DWORD stack
,
308 LPTHREAD_START_ROUTINE start
, LPVOID param
,
309 DWORD flags
, LPDWORD id
)
318 struct new_thread_request
*req
= server_alloc_req( sizeof(*req
), 0 );
320 req
->suspend
= ((flags
& CREATE_SUSPENDED
) != 0);
321 req
->inherit
= (sa
&& (sa
->nLength
>=sizeof(*sa
)) && sa
->bInheritHandle
);
322 if (!server_call( REQ_NEW_THREAD
))
324 handle
= req
->handle
;
326 socket
= wine_server_recv_fd( handle
, 0 );
330 if (!handle
) return 0;
332 if (!(teb
= THREAD_Create( socket
, stack
, TRUE
)))
337 teb
->entry_point
= start
;
338 teb
->entry_arg
= param
;
339 teb
->startup
= THREAD_Start
;
340 teb
->htask16
= GetCurrentTask();
341 if (id
) *id
= (DWORD
)tid
;
342 if (SYSDEPS_SpawnThread( teb
) == -1)
344 CloseHandle( handle
);
345 THREAD_FreeTEB( teb
);
351 /***********************************************************************
352 * CreateThread16 (KERNEL.441)
354 static DWORD CALLBACK
THREAD_StartThread16( LPVOID threadArgs
)
356 FARPROC16 start
= ((FARPROC16
*)threadArgs
)[0];
357 DWORD param
= ((DWORD
*)threadArgs
)[1];
358 HeapFree( GetProcessHeap(), 0, threadArgs
);
360 ((LPDWORD
)CURRENT_STACK16
)[-1] = param
;
361 return wine_call_to_16_long( start
, sizeof(DWORD
) );
363 HANDLE WINAPI
CreateThread16( SECURITY_ATTRIBUTES
*sa
, DWORD stack
,
364 FARPROC16 start
, SEGPTR param
,
365 DWORD flags
, LPDWORD id
)
367 DWORD
*threadArgs
= HeapAlloc( GetProcessHeap(), 0, 2*sizeof(DWORD
) );
368 if (!threadArgs
) return INVALID_HANDLE_VALUE
;
369 threadArgs
[0] = (DWORD
)start
;
370 threadArgs
[1] = (DWORD
)param
;
372 return CreateThread( sa
, stack
, THREAD_StartThread16
, threadArgs
, flags
, id
);
376 /***********************************************************************
377 * ExitThread [KERNEL32.215] Ends a thread
382 void WINAPI
ExitThread( DWORD code
) /* [in] Exit code for this thread */
387 struct terminate_thread_request
*req
= server_alloc_req( sizeof(*req
), 0 );
389 /* send the exit code to the server */
390 req
->handle
= GetCurrentThread();
391 req
->exit_code
= code
;
392 server_call( REQ_TERMINATE_THREAD
);
399 MODULE_DllProcessDetach( TRUE
, (LPVOID
)1 );
404 MODULE_DllThreadDetach( NULL
);
405 if (!(NtCurrentTeb()->tibflags
& TEBF_WIN32
)) TASK_ExitTask();
406 SYSDEPS_ExitThread( code
);
411 /***********************************************************************
412 * SetThreadContext [KERNEL32.670] Sets context of thread.
418 BOOL WINAPI
SetThreadContext( HANDLE handle
, /* [in] Handle to thread with context */
419 const CONTEXT
*context
) /* [in] Address of context structure */
424 struct set_thread_context_request
*req
= server_alloc_req( sizeof(*req
),
426 req
->handle
= handle
;
427 req
->flags
= context
->ContextFlags
;
428 memcpy( server_data_ptr(req
), context
, sizeof(*context
) );
429 ret
= !server_call( REQ_SET_THREAD_CONTEXT
);
436 /***********************************************************************
437 * GetThreadContext [KERNEL32.@] Retrieves context of thread.
443 BOOL WINAPI
GetThreadContext( HANDLE handle
, /* [in] Handle to thread with context */
444 CONTEXT
*context
) /* [out] Address of context structure */
449 struct get_thread_context_request
*req
= server_alloc_req( sizeof(*req
),
451 req
->handle
= handle
;
452 req
->flags
= context
->ContextFlags
;
453 memcpy( server_data_ptr(req
), context
, sizeof(*context
) );
454 if ((ret
= !server_call( REQ_GET_THREAD_CONTEXT
)))
455 memcpy( context
, server_data_ptr(req
), sizeof(*context
) );
462 /**********************************************************************
463 * GetThreadPriority [KERNEL32.@] Returns priority for thread.
466 * Success: Thread's priority level.
467 * Failure: THREAD_PRIORITY_ERROR_RETURN
469 INT WINAPI
GetThreadPriority(
470 HANDLE hthread
) /* [in] Handle to thread */
472 INT ret
= THREAD_PRIORITY_ERROR_RETURN
;
475 struct get_thread_info_request
*req
= server_alloc_req( sizeof(*req
), 0 );
476 req
->handle
= hthread
;
478 if (!server_call( REQ_GET_THREAD_INFO
)) ret
= req
->priority
;
485 /**********************************************************************
486 * SetThreadPriority [KERNEL32.@] Sets priority for thread.
492 BOOL WINAPI
SetThreadPriority(
493 HANDLE hthread
, /* [in] Handle to thread */
494 INT priority
) /* [in] Thread priority level */
499 struct set_thread_info_request
*req
= server_alloc_req( sizeof(*req
), 0 );
500 req
->handle
= hthread
;
501 req
->priority
= priority
;
502 req
->mask
= SET_THREAD_INFO_PRIORITY
;
503 ret
= !server_call( REQ_SET_THREAD_INFO
);
510 /**********************************************************************
511 * GetThreadPriorityBoost [KERNEL32.877] Returns priority boost for thread.
513 * Always reports that priority boost is disabled.
519 BOOL WINAPI
GetThreadPriorityBoost(
520 HANDLE hthread
, /* [in] Handle to thread */
521 PBOOL pstate
) /* [out] pointer to var that receives the boost state */
523 if (pstate
) *pstate
= FALSE
;
528 /**********************************************************************
529 * SetThreadPriorityBoost [KERNEL32.893] Sets priority boost for thread.
531 * Priority boost is not implemented. Thsi function always returns
532 * FALSE and sets last error to ERROR_CALL_NOT_IMPLEMENTED
535 * Always returns FALSE to indicate a failure
537 BOOL WINAPI
SetThreadPriorityBoost(
538 HANDLE hthread
, /* [in] Handle to thread */
539 BOOL disable
) /* [in] TRUE to disable priority boost */
541 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
546 /**********************************************************************
547 * SetThreadAffinityMask (KERNEL32.669)
549 DWORD WINAPI
SetThreadAffinityMask( HANDLE hThread
, DWORD dwThreadAffinityMask
)
554 struct set_thread_info_request
*req
= server_alloc_req( sizeof(*req
), 0 );
555 req
->handle
= hThread
;
556 req
->affinity
= dwThreadAffinityMask
;
557 req
->mask
= SET_THREAD_INFO_AFFINITY
;
558 ret
= !server_call( REQ_SET_THREAD_INFO
);
559 /* FIXME: should return previous value */
566 /**********************************************************************
567 * TerminateThread [KERNEL32.685] Terminates a thread
573 BOOL WINAPI
TerminateThread( HANDLE handle
, /* [in] Handle to thread */
574 DWORD exit_code
) /* [in] Exit code for thread */
576 NTSTATUS status
= NtTerminateThread( handle
, exit_code
);
577 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
582 /**********************************************************************
583 * GetExitCodeThread (KERNEL32.@)
584 * GetExitCodeThread (WIN32S16.13)
586 * Gets termination status of thread.
592 BOOL WINAPI
GetExitCodeThread(
593 HANDLE hthread
, /* [in] Handle to thread */
594 LPDWORD exitcode
) /* [out] Address to receive termination status */
599 struct get_thread_info_request
*req
= server_alloc_req( sizeof(*req
), 0 );
600 req
->handle
= hthread
;
602 ret
= !server_call( REQ_GET_THREAD_INFO
);
603 if (ret
&& exitcode
) *exitcode
= req
->exit_code
;
610 /**********************************************************************
611 * ResumeThread [KERNEL32.587] Resumes a thread.
613 * Decrements a thread's suspend count. When count is zero, the
614 * execution of the thread is resumed.
617 * Success: Previous suspend count
618 * Failure: 0xFFFFFFFF
621 DWORD WINAPI
ResumeThread(
622 HANDLE hthread
) /* [in] Identifies thread to restart */
624 DWORD ret
= 0xffffffff;
627 struct resume_thread_request
*req
= server_alloc_req( sizeof(*req
), 0 );
628 req
->handle
= hthread
;
629 if (!server_call( REQ_RESUME_THREAD
)) ret
= req
->count
;
636 /**********************************************************************
637 * SuspendThread [KERNEL32.681] Suspends a thread.
640 * Success: Previous suspend count
641 * Failure: 0xFFFFFFFF
643 DWORD WINAPI
SuspendThread(
644 HANDLE hthread
) /* [in] Handle to the thread */
646 DWORD ret
= 0xffffffff;
649 struct suspend_thread_request
*req
= server_alloc_req( sizeof(*req
), 0 );
650 req
->handle
= hthread
;
651 if (!server_call( REQ_SUSPEND_THREAD
)) ret
= req
->count
;
658 /***********************************************************************
659 * QueueUserAPC (KERNEL32.566)
661 DWORD WINAPI
QueueUserAPC( PAPCFUNC func
, HANDLE hthread
, ULONG_PTR data
)
666 struct queue_apc_request
*req
= server_alloc_req( sizeof(*req
), 0 );
667 req
->handle
= hthread
;
670 req
->param
= (void *)data
;
671 ret
= !server_call( REQ_QUEUE_APC
);
678 /**********************************************************************
679 * GetThreadTimes [KERNEL32.@] Obtains timing information.
682 * What are the fields where these values are stored?
688 BOOL WINAPI
GetThreadTimes(
689 HANDLE thread
, /* [in] Specifies the thread of interest */
690 LPFILETIME creationtime
, /* [out] When the thread was created */
691 LPFILETIME exittime
, /* [out] When the thread was destroyed */
692 LPFILETIME kerneltime
, /* [out] Time thread spent in kernel mode */
693 LPFILETIME usertime
) /* [out] Time thread spent in user mode */
695 FIXME("(0x%08x): stub\n",thread
);
696 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
701 /**********************************************************************
702 * VWin32_BoostThreadGroup [KERNEL.535]
704 VOID WINAPI
VWin32_BoostThreadGroup( DWORD threadId
, INT boost
)
706 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
709 /**********************************************************************
710 * VWin32_BoostThreadStatic [KERNEL.536]
712 VOID WINAPI
VWin32_BoostThreadStatic( DWORD threadId
, INT boost
)
714 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
718 /***********************************************************************
719 * GetThreadLocale (KERNEL32.@)
721 LCID WINAPI
GetThreadLocale(void)
723 LCID ret
= NtCurrentTeb()->CurrentLocale
;
724 if (!ret
) NtCurrentTeb()->CurrentLocale
= ret
= GetUserDefaultLCID();
729 /**********************************************************************
730 * SetThreadLocale [KERNEL32.671] Sets the calling threads current locale.
737 * check if lcid is a valid cp
739 BOOL WINAPI
SetThreadLocale(
740 LCID lcid
) /* [in] Locale identifier */
744 case LOCALE_SYSTEM_DEFAULT
:
745 lcid
= GetSystemDefaultLCID();
747 case LOCALE_USER_DEFAULT
:
749 lcid
= GetUserDefaultLCID();
752 NtCurrentTeb()->CurrentLocale
= lcid
;
757 /***********************************************************************
758 * GetCurrentThread [KERNEL32.@] Gets pseudohandle for current thread
761 * Pseudohandle for the current thread
763 #undef GetCurrentThread
764 HANDLE WINAPI
GetCurrentThread(void)
770 /***********************************************************************
771 * ProcessIdToSessionId (KERNEL32.@)
772 * This function is available on Terminal Server 4SP4 and Windows 2000
774 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
776 /* According to MSDN, if the calling process is not in a terminal
777 * services environment, then the sessionid returned is zero.
786 /* void WINAPI SetLastError( DWORD error ); */
787 __ASM_GLOBAL_FUNC( SetLastError
,
788 "movl 4(%esp),%eax\n\t"
793 /* DWORD WINAPI GetLastError(void); */
794 __ASM_GLOBAL_FUNC( GetLastError
, ".byte 0x64\n\tmovl 0x60,%eax\n\tret" );
796 /* DWORD WINAPI GetCurrentProcessId(void) */
797 __ASM_GLOBAL_FUNC( GetCurrentProcessId
, ".byte 0x64\n\tmovl 0x20,%eax\n\tret" );
799 /* DWORD WINAPI GetCurrentThreadId(void) */
800 __ASM_GLOBAL_FUNC( GetCurrentThreadId
, ".byte 0x64\n\tmovl 0x24,%eax\n\tret" );
804 /**********************************************************************
805 * SetLastError (KERNEL.147)
806 * SetLastError (KERNEL32.@)
808 * Sets the last-error code.
810 void WINAPI
SetLastError( DWORD error
) /* [in] Per-thread error code */
812 NtCurrentTeb()->last_error
= error
;
815 /**********************************************************************
816 * GetLastError (KERNEL.10)
817 * GetLastError (KERNEL32.@)
818 * GetLastError (WIN32S16.10)
820 * Returns last-error code.
822 DWORD WINAPI
GetLastError(void)
824 return NtCurrentTeb()->last_error
;
827 /***********************************************************************
828 * GetCurrentProcessId (KERNEL.471)
829 * GetCurrentProcessId (KERNEL32.@)
831 * Returns process identifier.
833 DWORD WINAPI
GetCurrentProcessId(void)
835 return (DWORD
)NtCurrentTeb()->pid
;
838 /***********************************************************************
839 * GetCurrentThreadId (KERNEL.462)
840 * GetCurrentThreadId (KERNEL32.@)
842 * Returns thread identifier.
844 DWORD WINAPI
GetCurrentThreadId(void)
846 return (DWORD
)NtCurrentTeb()->tid
;
849 #endif /* __i386__ */