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
);
33 DECLARE_DEBUG_CHANNEL(relay
);
35 /* TEB of the initial thread */
36 static TEB initial_teb
;
38 extern struct _PDB current_process
;
40 /***********************************************************************
43 BOOL
THREAD_IsWin16( TEB
*teb
)
45 return !teb
|| !(teb
->tibflags
& TEBF_WIN32
);
48 /***********************************************************************
51 * Convert a thread id to a TEB, making sure it is valid.
53 TEB
*THREAD_IdToTEB( DWORD id
)
57 if (!id
|| id
== GetCurrentThreadId()) return NtCurrentTeb();
59 SERVER_START_REQ( get_thread_info
)
62 req
->tid_in
= (void *)id
;
63 if (!SERVER_CALL()) ret
= req
->teb
;
69 /* Allow task handles to be used; convert to main thread */
72 TDB
*pTask
= TASK_GetPtr( 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 close( teb
->request_fd
);
119 close( teb
->reply_fd
);
120 close( teb
->wait_fd
[0] );
121 close( teb
->wait_fd
[1] );
122 if (teb
->stack_sel
) FreeSelector16( teb
->stack_sel
);
123 FreeSelector16( teb
->teb_sel
);
124 if (teb
->buffer
) munmap( (void *)teb
->buffer
, teb
->buffer_size
);
125 if (teb
->debug_info
) HeapFree( GetProcessHeap(), 0, teb
->debug_info
);
126 VirtualFree( teb
->stack_base
, 0, MEM_RELEASE
);
130 /***********************************************************************
133 * Allocate the stack of a thread.
135 TEB
*THREAD_InitStack( TEB
*teb
, DWORD stack_size
)
137 DWORD old_prot
, total_size
;
138 DWORD page_size
= getpagesize();
141 /* Allocate the stack */
143 if (stack_size
>= 16*1024*1024)
144 WARN("Thread stack size is %ld MB.\n",stack_size
/1024/1024);
146 /* if size is smaller than default, get stack size from parent */
147 if (stack_size
< 1024 * 1024)
150 stack_size
= 1024 * 1024; /* no parent */
152 stack_size
= ((char *)NtCurrentTeb()->stack_top
- (char *)NtCurrentTeb()->stack_base
153 - SIGNAL_STACK_SIZE
- 3 * page_size
);
156 /* FIXME: some Wine functions use a lot of stack, so we add 64Kb here */
157 stack_size
+= 64 * 1024;
159 /* Memory layout in allocated block:
162 * 1 page NOACCESS guard page
163 * SIGNAL_STACK_SIZE signal stack
164 * 1 page NOACCESS guard page
165 * 1 page PAGE_GUARD guard page
166 * stack_size normal stack
167 * 64Kb 16-bit stack (optional)
168 * 1 page TEB (except for initial thread)
171 stack_size
= (stack_size
+ (page_size
- 1)) & ~(page_size
- 1);
172 total_size
= stack_size
+ SIGNAL_STACK_SIZE
+ 3 * page_size
;
173 total_size
+= 0x10000; /* 16-bit stack */
174 if (!teb
) total_size
+= page_size
;
176 if (!(base
= VirtualAlloc( NULL
, total_size
, MEM_COMMIT
, PAGE_EXECUTE_READWRITE
)))
181 teb
= (TEB
*)((char *)base
+ total_size
- page_size
);
182 if (!THREAD_InitTEB( teb
))
184 VirtualFree( base
, 0, MEM_RELEASE
);
189 teb
->stack_low
= base
;
190 teb
->stack_base
= base
;
191 teb
->signal_stack
= (char *)base
+ page_size
;
192 teb
->stack_top
= (char *)base
+ 3 * page_size
+ SIGNAL_STACK_SIZE
+ stack_size
;
194 /* Setup guard pages */
196 VirtualProtect( base
, 1, PAGE_NOACCESS
, &old_prot
);
197 VirtualProtect( (char *)teb
->signal_stack
+ SIGNAL_STACK_SIZE
, 1, PAGE_NOACCESS
, &old_prot
);
198 VirtualProtect( (char *)teb
->signal_stack
+ SIGNAL_STACK_SIZE
+ page_size
, 1,
199 PAGE_EXECUTE_READWRITE
| PAGE_GUARD
, &old_prot
);
201 /* Allocate the 16-bit stack selector */
203 teb
->stack_sel
= SELECTOR_AllocBlock( teb
->stack_top
, 0x10000, WINE_LDT_FLAGS_DATA
);
204 if (!teb
->stack_sel
) goto error
;
205 teb
->cur_stack
= MAKESEGPTR( teb
->stack_sel
, 0x10000 - sizeof(STACK16FRAME
) );
210 THREAD_FreeTEB( teb
);
215 /***********************************************************************
216 * thread_errno_location
218 * Get the per-thread errno location.
220 static int *thread_errno_location(void)
222 return &NtCurrentTeb()->thread_errno
;
225 /***********************************************************************
226 * thread_h_errno_location
228 * Get the per-thread h_errno location.
230 static int *thread_h_errno_location(void)
232 return &NtCurrentTeb()->thread_h_errno
;
235 /***********************************************************************
238 * Setup the initial thread.
240 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
242 void THREAD_Init(void)
244 if (!initial_teb
.self
) /* do it only once */
246 THREAD_InitTEB( &initial_teb
);
247 assert( initial_teb
.teb_sel
);
248 initial_teb
.process
= ¤t_process
;
249 SYSDEPS_SetCurThread( &initial_teb
);
250 wine_errno_location
= thread_errno_location
;
251 wine_h_errno_location
= thread_h_errno_location
;
255 DECL_GLOBAL_CONSTRUCTOR(thread_init
) { THREAD_Init(); }
258 /***********************************************************************
261 * Start execution of a newly created thread. Does not return.
263 static void THREAD_Start(void)
265 HANDLE cleanup_object
;
266 LPTHREAD_START_ROUTINE func
= (LPTHREAD_START_ROUTINE
)NtCurrentTeb()->entry_point
;
268 /* install cleanup handler */
269 if (DuplicateHandle( GetCurrentProcess(), GetCurrentThread(),
270 GetCurrentProcess(), &cleanup_object
,
271 0, FALSE
, DUPLICATE_SAME_ACCESS
))
272 NtCurrentTeb()->cleanup
= SERVICE_AddObject( cleanup_object
, (PAPCFUNC
)THREAD_FreeTEB
,
273 (ULONG_PTR
)NtCurrentTeb() );
275 TRACE_(relay
)("Starting thread %08lx\n", GetCurrentThreadId());
277 PROCESS_CallUserSignalProc( USIG_THREAD_INIT
, 0 );
279 MODULE_DllThreadAttach( NULL
);
280 ExitThread( func( NtCurrentTeb()->entry_arg
) );
284 /***********************************************************************
285 * CreateThread (KERNEL32.@)
287 HANDLE WINAPI
CreateThread( SECURITY_ATTRIBUTES
*sa
, DWORD stack
,
288 LPTHREAD_START_ROUTINE start
, LPVOID param
,
289 DWORD flags
, LPDWORD id
)
296 if (pipe( request_pipe
) == -1)
298 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
301 fcntl( request_pipe
[1], F_SETFD
, 1 ); /* set close on exec flag */
302 wine_server_send_fd( request_pipe
[0] );
304 SERVER_START_REQ( new_thread
)
306 req
->suspend
= ((flags
& CREATE_SUSPENDED
) != 0);
307 req
->inherit
= (sa
&& (sa
->nLength
>=sizeof(*sa
)) && sa
->bInheritHandle
);
308 req
->request_fd
= request_pipe
[0];
309 if (!SERVER_CALL_ERR())
311 handle
= req
->handle
;
314 close( request_pipe
[0] );
318 if (!handle
|| !(teb
= THREAD_InitStack( NULL
, stack
)))
320 close( request_pipe
[1] );
324 teb
->process
= NtCurrentTeb()->process
;
326 teb
->request_fd
= request_pipe
[1];
327 teb
->entry_point
= start
;
328 teb
->entry_arg
= param
;
329 teb
->startup
= THREAD_Start
;
330 teb
->htask16
= GetCurrentTask();
332 if (id
) *id
= (DWORD
)tid
;
333 if (SYSDEPS_SpawnThread( teb
) == -1)
335 CloseHandle( handle
);
336 THREAD_FreeTEB( teb
);
342 /***********************************************************************
343 * CreateThread16 (KERNEL.441)
345 static DWORD CALLBACK
THREAD_StartThread16( LPVOID threadArgs
)
347 FARPROC16 start
= ((FARPROC16
*)threadArgs
)[0];
348 DWORD param
= ((DWORD
*)threadArgs
)[1];
349 HeapFree( GetProcessHeap(), 0, threadArgs
);
351 ((LPDWORD
)CURRENT_STACK16
)[-1] = param
;
352 return wine_call_to_16_long( start
, sizeof(DWORD
) );
354 HANDLE WINAPI
CreateThread16( SECURITY_ATTRIBUTES
*sa
, DWORD stack
,
355 FARPROC16 start
, SEGPTR param
,
356 DWORD flags
, LPDWORD id
)
358 DWORD
*threadArgs
= HeapAlloc( GetProcessHeap(), 0, 2*sizeof(DWORD
) );
359 if (!threadArgs
) return INVALID_HANDLE_VALUE
;
360 threadArgs
[0] = (DWORD
)start
;
361 threadArgs
[1] = (DWORD
)param
;
363 return CreateThread( sa
, stack
, THREAD_StartThread16
, threadArgs
, flags
, id
);
367 /***********************************************************************
368 * ExitThread [KERNEL32.215] Ends a thread
373 void WINAPI
ExitThread( DWORD code
) /* [in] Exit code for this thread */
376 SERVER_START_REQ( terminate_thread
)
378 /* send the exit code to the server */
379 req
->handle
= GetCurrentThread();
380 req
->exit_code
= code
;
388 MODULE_DllProcessDetach( TRUE
, (LPVOID
)1 );
393 MODULE_DllThreadDetach( NULL
);
394 if (!(NtCurrentTeb()->tibflags
& TEBF_WIN32
)) TASK_ExitTask();
395 SYSDEPS_ExitThread( code
);
400 /***********************************************************************
401 * SetThreadContext [KERNEL32.670] Sets context of thread.
407 BOOL WINAPI
SetThreadContext( HANDLE handle
, /* [in] Handle to thread with context */
408 const CONTEXT
*context
) /* [in] Address of context structure */
411 SERVER_START_VAR_REQ( set_thread_context
, sizeof(*context
) )
413 req
->handle
= handle
;
414 req
->flags
= context
->ContextFlags
;
415 memcpy( server_data_ptr(req
), context
, sizeof(*context
) );
416 ret
= !SERVER_CALL_ERR();
423 /***********************************************************************
424 * GetThreadContext [KERNEL32.@] Retrieves context of thread.
430 BOOL WINAPI
GetThreadContext( HANDLE handle
, /* [in] Handle to thread with context */
431 CONTEXT
*context
) /* [out] Address of context structure */
434 SERVER_START_VAR_REQ( get_thread_context
, sizeof(*context
) )
436 req
->handle
= handle
;
437 req
->flags
= context
->ContextFlags
;
438 memcpy( server_data_ptr(req
), context
, sizeof(*context
) );
439 if ((ret
= !SERVER_CALL_ERR()))
440 memcpy( context
, server_data_ptr(req
), sizeof(*context
) );
447 /**********************************************************************
448 * GetThreadPriority [KERNEL32.@] Returns priority for thread.
451 * Success: Thread's priority level.
452 * Failure: THREAD_PRIORITY_ERROR_RETURN
454 INT WINAPI
GetThreadPriority(
455 HANDLE hthread
) /* [in] Handle to thread */
457 INT ret
= THREAD_PRIORITY_ERROR_RETURN
;
458 SERVER_START_REQ( get_thread_info
)
460 req
->handle
= hthread
;
462 if (!SERVER_CALL_ERR()) ret
= req
->priority
;
469 /**********************************************************************
470 * SetThreadPriority [KERNEL32.@] Sets priority for thread.
476 BOOL WINAPI
SetThreadPriority(
477 HANDLE hthread
, /* [in] Handle to thread */
478 INT priority
) /* [in] Thread priority level */
481 SERVER_START_REQ( set_thread_info
)
483 req
->handle
= hthread
;
484 req
->priority
= priority
;
485 req
->mask
= SET_THREAD_INFO_PRIORITY
;
486 ret
= !SERVER_CALL_ERR();
493 /**********************************************************************
494 * GetThreadPriorityBoost [KERNEL32.877] Returns priority boost for thread.
496 * Always reports that priority boost is disabled.
502 BOOL WINAPI
GetThreadPriorityBoost(
503 HANDLE hthread
, /* [in] Handle to thread */
504 PBOOL pstate
) /* [out] pointer to var that receives the boost state */
506 if (pstate
) *pstate
= FALSE
;
511 /**********************************************************************
512 * SetThreadPriorityBoost [KERNEL32.893] Sets priority boost for thread.
514 * Priority boost is not implemented. Thsi function always returns
515 * FALSE and sets last error to ERROR_CALL_NOT_IMPLEMENTED
518 * Always returns FALSE to indicate a failure
520 BOOL WINAPI
SetThreadPriorityBoost(
521 HANDLE hthread
, /* [in] Handle to thread */
522 BOOL disable
) /* [in] TRUE to disable priority boost */
524 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
529 /**********************************************************************
530 * SetThreadAffinityMask (KERNEL32.669)
532 DWORD WINAPI
SetThreadAffinityMask( HANDLE hThread
, DWORD dwThreadAffinityMask
)
535 SERVER_START_REQ( set_thread_info
)
537 req
->handle
= hThread
;
538 req
->affinity
= dwThreadAffinityMask
;
539 req
->mask
= SET_THREAD_INFO_AFFINITY
;
540 ret
= !SERVER_CALL_ERR();
541 /* FIXME: should return previous value */
548 /**********************************************************************
549 * TerminateThread [KERNEL32.685] Terminates a thread
555 BOOL WINAPI
TerminateThread( HANDLE handle
, /* [in] Handle to thread */
556 DWORD exit_code
) /* [in] Exit code for thread */
558 NTSTATUS status
= NtTerminateThread( handle
, exit_code
);
559 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
564 /**********************************************************************
565 * GetExitCodeThread (KERNEL32.@)
566 * GetExitCodeThread (WIN32S16.13)
568 * Gets termination status of thread.
574 BOOL WINAPI
GetExitCodeThread(
575 HANDLE hthread
, /* [in] Handle to thread */
576 LPDWORD exitcode
) /* [out] Address to receive termination status */
579 SERVER_START_REQ( get_thread_info
)
581 req
->handle
= hthread
;
583 ret
= !SERVER_CALL_ERR();
584 if (ret
&& exitcode
) *exitcode
= req
->exit_code
;
591 /**********************************************************************
592 * ResumeThread [KERNEL32.587] Resumes a thread.
594 * Decrements a thread's suspend count. When count is zero, the
595 * execution of the thread is resumed.
598 * Success: Previous suspend count
599 * Failure: 0xFFFFFFFF
602 DWORD WINAPI
ResumeThread(
603 HANDLE hthread
) /* [in] Identifies thread to restart */
605 DWORD ret
= 0xffffffff;
606 SERVER_START_REQ( resume_thread
)
608 req
->handle
= hthread
;
609 if (!SERVER_CALL_ERR()) ret
= req
->count
;
616 /**********************************************************************
617 * SuspendThread [KERNEL32.681] Suspends a thread.
620 * Success: Previous suspend count
621 * Failure: 0xFFFFFFFF
623 DWORD WINAPI
SuspendThread(
624 HANDLE hthread
) /* [in] Handle to the thread */
626 DWORD ret
= 0xffffffff;
627 SERVER_START_REQ( suspend_thread
)
629 req
->handle
= hthread
;
630 if (!SERVER_CALL_ERR()) ret
= req
->count
;
637 /***********************************************************************
638 * QueueUserAPC (KERNEL32.566)
640 DWORD WINAPI
QueueUserAPC( PAPCFUNC func
, HANDLE hthread
, ULONG_PTR data
)
643 SERVER_START_REQ( queue_apc
)
645 req
->handle
= hthread
;
648 req
->param
= (void *)data
;
649 ret
= !SERVER_CALL_ERR();
656 /**********************************************************************
657 * GetThreadTimes [KERNEL32.@] Obtains timing information.
660 * What are the fields where these values are stored?
666 BOOL WINAPI
GetThreadTimes(
667 HANDLE thread
, /* [in] Specifies the thread of interest */
668 LPFILETIME creationtime
, /* [out] When the thread was created */
669 LPFILETIME exittime
, /* [out] When the thread was destroyed */
670 LPFILETIME kerneltime
, /* [out] Time thread spent in kernel mode */
671 LPFILETIME usertime
) /* [out] Time thread spent in user mode */
673 FIXME("(0x%08x): stub\n",thread
);
674 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
679 /**********************************************************************
680 * VWin32_BoostThreadGroup [KERNEL.535]
682 VOID WINAPI
VWin32_BoostThreadGroup( DWORD threadId
, INT boost
)
684 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
687 /**********************************************************************
688 * VWin32_BoostThreadStatic [KERNEL.536]
690 VOID WINAPI
VWin32_BoostThreadStatic( DWORD threadId
, INT boost
)
692 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
696 /***********************************************************************
697 * GetThreadLocale (KERNEL32.@)
699 LCID WINAPI
GetThreadLocale(void)
701 LCID ret
= NtCurrentTeb()->CurrentLocale
;
702 if (!ret
) NtCurrentTeb()->CurrentLocale
= ret
= GetUserDefaultLCID();
707 /**********************************************************************
708 * SetThreadLocale [KERNEL32.671] Sets the calling threads current locale.
715 * check if lcid is a valid cp
717 BOOL WINAPI
SetThreadLocale(
718 LCID lcid
) /* [in] Locale identifier */
722 case LOCALE_SYSTEM_DEFAULT
:
723 lcid
= GetSystemDefaultLCID();
725 case LOCALE_USER_DEFAULT
:
727 lcid
= GetUserDefaultLCID();
730 NtCurrentTeb()->CurrentLocale
= lcid
;
735 /***********************************************************************
736 * GetCurrentThread [KERNEL32.@] Gets pseudohandle for current thread
739 * Pseudohandle for the current thread
741 #undef GetCurrentThread
742 HANDLE WINAPI
GetCurrentThread(void)
748 /***********************************************************************
749 * ProcessIdToSessionId (KERNEL32.@)
750 * This function is available on Terminal Server 4SP4 and Windows 2000
752 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
754 /* According to MSDN, if the calling process is not in a terminal
755 * services environment, then the sessionid returned is zero.
761 /***********************************************************************
762 * SetThreadExecutionState (KERNEL32.@)
764 * Informs the system that activity is taking place for
765 * power management purposes.
767 EXECUTION_STATE WINAPI
SetThreadExecutionState(EXECUTION_STATE flags
)
769 FIXME("(%ld): stub\n", flags
);
776 /* void WINAPI SetLastError( DWORD error ); */
777 __ASM_GLOBAL_FUNC( SetLastError
,
778 "movl 4(%esp),%eax\n\t"
783 /* DWORD WINAPI GetLastError(void); */
784 __ASM_GLOBAL_FUNC( GetLastError
, ".byte 0x64\n\tmovl 0x60,%eax\n\tret" );
786 /* DWORD WINAPI GetCurrentProcessId(void) */
787 __ASM_GLOBAL_FUNC( GetCurrentProcessId
, ".byte 0x64\n\tmovl 0x20,%eax\n\tret" );
789 /* DWORD WINAPI GetCurrentThreadId(void) */
790 __ASM_GLOBAL_FUNC( GetCurrentThreadId
, ".byte 0x64\n\tmovl 0x24,%eax\n\tret" );
794 /**********************************************************************
795 * SetLastError (KERNEL.147)
796 * SetLastError (KERNEL32.@)
798 * Sets the last-error code.
800 void WINAPI
SetLastError( DWORD error
) /* [in] Per-thread error code */
802 NtCurrentTeb()->last_error
= error
;
805 /**********************************************************************
806 * GetLastError (KERNEL.10)
807 * GetLastError (KERNEL32.@)
808 * GetLastError (WIN32S16.10)
810 * Returns last-error code.
812 DWORD WINAPI
GetLastError(void)
814 return NtCurrentTeb()->last_error
;
817 /***********************************************************************
818 * GetCurrentProcessId (KERNEL.471)
819 * GetCurrentProcessId (KERNEL32.@)
821 * Returns process identifier.
823 DWORD WINAPI
GetCurrentProcessId(void)
825 return (DWORD
)NtCurrentTeb()->pid
;
828 /***********************************************************************
829 * GetCurrentThreadId (KERNEL.462)
830 * GetCurrentThreadId (KERNEL32.@)
832 * Returns thread identifier.
834 DWORD WINAPI
GetCurrentThreadId(void)
836 return (DWORD
)NtCurrentTeb()->tid
;
839 #endif /* __i386__ */