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"
22 #include "selectors.h"
24 #include "wine/server.h"
26 #include "stackframe.h"
27 #include "builtin16.h"
28 #include "debugtools.h"
31 DEFAULT_DEBUG_CHANNEL(thread
);
32 DECLARE_DEBUG_CHANNEL(relay
);
34 /* TEB of the initial thread */
35 static TEB initial_teb
;
37 extern struct _PDB current_process
;
39 /***********************************************************************
42 * Convert a thread id to a TEB, making sure it is valid.
44 TEB
*THREAD_IdToTEB( DWORD id
)
48 if (!id
|| id
== GetCurrentThreadId()) return NtCurrentTeb();
50 SERVER_START_REQ( get_thread_info
)
53 req
->tid_in
= (void *)id
;
54 if (!SERVER_CALL()) ret
= req
->teb
;
60 /* Allow task handles to be used; convert to main thread */
63 TDB
*pTask
= TASK_GetPtr( id
);
64 if (pTask
) return pTask
->teb
;
66 SetLastError( ERROR_INVALID_PARAMETER
);
72 /***********************************************************************
75 * Initialization of a newly created TEB.
77 static BOOL
THREAD_InitTEB( TEB
*teb
)
79 teb
->except
= (void *)~0UL;
81 teb
->tibflags
= TEBF_WIN32
;
82 teb
->tls_ptr
= teb
->tls_array
;
83 teb
->exit_code
= STILL_ACTIVE
;
88 teb
->stack_top
= (void *)~0UL;
89 teb
->StaticUnicodeString
.MaximumLength
= sizeof(teb
->StaticUnicodeBuffer
);
90 teb
->StaticUnicodeString
.Buffer
= (PWSTR
)teb
->StaticUnicodeBuffer
;
91 teb
->teb_sel
= SELECTOR_AllocBlock( teb
, 0x1000, WINE_LDT_FLAGS_DATA
|WINE_LDT_FLAGS_32BIT
);
92 return (teb
->teb_sel
!= 0);
96 /***********************************************************************
99 * Free data structures associated with a thread.
100 * Must be called from the context of another thread.
102 static void CALLBACK
THREAD_FreeTEB( TEB
*teb
)
104 TRACE("(%p) called\n", teb
);
105 if (teb
->cleanup
) SERVICE_Delete( teb
->cleanup
);
107 /* Free the associated memory */
109 close( teb
->request_fd
);
110 close( teb
->reply_fd
);
111 close( teb
->wait_fd
[0] );
112 close( teb
->wait_fd
[1] );
113 if (teb
->stack_sel
) FreeSelector16( teb
->stack_sel
);
114 FreeSelector16( teb
->teb_sel
);
115 if (teb
->buffer
) munmap( (void *)teb
->buffer
, teb
->buffer_size
);
116 if (teb
->debug_info
) HeapFree( GetProcessHeap(), 0, teb
->debug_info
);
117 VirtualFree( teb
->stack_base
, 0, MEM_RELEASE
);
121 /***********************************************************************
124 * Allocate the stack of a thread.
126 TEB
*THREAD_InitStack( TEB
*teb
, DWORD stack_size
)
128 DWORD old_prot
, total_size
;
129 DWORD page_size
= getpagesize();
132 /* Allocate the stack */
134 if (stack_size
>= 16*1024*1024)
135 WARN("Thread stack size is %ld MB.\n",stack_size
/1024/1024);
137 /* if size is smaller than default, get stack size from parent */
138 if (stack_size
< 1024 * 1024)
141 stack_size
= 1024 * 1024; /* no parent */
143 stack_size
= ((char *)NtCurrentTeb()->stack_top
- (char *)NtCurrentTeb()->stack_base
144 - SIGNAL_STACK_SIZE
- 3 * page_size
);
147 /* FIXME: some Wine functions use a lot of stack, so we add 64Kb here */
148 stack_size
+= 64 * 1024;
150 /* Memory layout in allocated block:
153 * 1 page NOACCESS guard page
154 * SIGNAL_STACK_SIZE signal stack
155 * 1 page NOACCESS guard page
156 * 1 page PAGE_GUARD guard page
157 * stack_size normal stack
158 * 64Kb 16-bit stack (optional)
159 * 1 page TEB (except for initial thread)
162 stack_size
= (stack_size
+ (page_size
- 1)) & ~(page_size
- 1);
163 total_size
= stack_size
+ SIGNAL_STACK_SIZE
+ 3 * page_size
;
164 total_size
+= 0x10000; /* 16-bit stack */
165 if (!teb
) total_size
+= page_size
;
167 if (!(base
= VirtualAlloc( NULL
, total_size
, MEM_COMMIT
, PAGE_EXECUTE_READWRITE
)))
172 teb
= (TEB
*)((char *)base
+ total_size
- page_size
);
173 if (!THREAD_InitTEB( teb
))
175 VirtualFree( base
, 0, MEM_RELEASE
);
180 teb
->stack_low
= base
;
181 teb
->stack_base
= base
;
182 teb
->signal_stack
= (char *)base
+ page_size
;
183 teb
->stack_top
= (char *)base
+ 3 * page_size
+ SIGNAL_STACK_SIZE
+ stack_size
;
185 /* Setup guard pages */
187 VirtualProtect( base
, 1, PAGE_NOACCESS
, &old_prot
);
188 VirtualProtect( (char *)teb
->signal_stack
+ SIGNAL_STACK_SIZE
, 1, PAGE_NOACCESS
, &old_prot
);
189 VirtualProtect( (char *)teb
->signal_stack
+ SIGNAL_STACK_SIZE
+ page_size
, 1,
190 PAGE_EXECUTE_READWRITE
| PAGE_GUARD
, &old_prot
);
192 /* Allocate the 16-bit stack selector */
194 teb
->stack_sel
= SELECTOR_AllocBlock( teb
->stack_top
, 0x10000, WINE_LDT_FLAGS_DATA
);
195 if (!teb
->stack_sel
) goto error
;
196 teb
->cur_stack
= MAKESEGPTR( teb
->stack_sel
, 0x10000 - sizeof(STACK16FRAME
) );
201 THREAD_FreeTEB( teb
);
206 /***********************************************************************
207 * thread_errno_location
209 * Get the per-thread errno location.
211 static int *thread_errno_location(void)
213 return &NtCurrentTeb()->thread_errno
;
216 /***********************************************************************
217 * thread_h_errno_location
219 * Get the per-thread h_errno location.
221 static int *thread_h_errno_location(void)
223 return &NtCurrentTeb()->thread_h_errno
;
226 /***********************************************************************
229 * Setup the initial thread.
231 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
233 void THREAD_Init(void)
235 if (!initial_teb
.self
) /* do it only once */
237 THREAD_InitTEB( &initial_teb
);
238 assert( initial_teb
.teb_sel
);
239 initial_teb
.process
= ¤t_process
;
240 SYSDEPS_SetCurThread( &initial_teb
);
241 wine_errno_location
= thread_errno_location
;
242 wine_h_errno_location
= thread_h_errno_location
;
246 DECL_GLOBAL_CONSTRUCTOR(thread_init
) { THREAD_Init(); }
249 /***********************************************************************
252 * Start execution of a newly created thread. Does not return.
254 static void THREAD_Start(void)
256 HANDLE cleanup_object
;
257 LPTHREAD_START_ROUTINE func
= (LPTHREAD_START_ROUTINE
)NtCurrentTeb()->entry_point
;
259 /* install cleanup handler */
260 if (DuplicateHandle( GetCurrentProcess(), GetCurrentThread(),
261 GetCurrentProcess(), &cleanup_object
,
262 0, FALSE
, DUPLICATE_SAME_ACCESS
))
263 NtCurrentTeb()->cleanup
= SERVICE_AddObject( cleanup_object
, (PAPCFUNC
)THREAD_FreeTEB
,
264 (ULONG_PTR
)NtCurrentTeb() );
267 DPRINTF("%08lx:Starting thread (entryproc=%p)\n", GetCurrentThreadId(), func
);
269 PROCESS_CallUserSignalProc( USIG_THREAD_INIT
, 0 );
271 MODULE_DllThreadAttach( NULL
);
272 ExitThread( func( NtCurrentTeb()->entry_arg
) );
276 /***********************************************************************
277 * CreateThread (KERNEL32.@)
279 HANDLE WINAPI
CreateThread( SECURITY_ATTRIBUTES
*sa
, DWORD stack
,
280 LPTHREAD_START_ROUTINE start
, LPVOID param
,
281 DWORD flags
, LPDWORD id
)
288 if (pipe( request_pipe
) == -1)
290 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
293 fcntl( request_pipe
[1], F_SETFD
, 1 ); /* set close on exec flag */
294 wine_server_send_fd( request_pipe
[0] );
296 SERVER_START_REQ( new_thread
)
298 req
->suspend
= ((flags
& CREATE_SUSPENDED
) != 0);
299 req
->inherit
= (sa
&& (sa
->nLength
>=sizeof(*sa
)) && sa
->bInheritHandle
);
300 req
->request_fd
= request_pipe
[0];
301 if (!SERVER_CALL_ERR())
303 handle
= req
->handle
;
306 close( request_pipe
[0] );
310 if (!handle
|| !(teb
= THREAD_InitStack( NULL
, stack
)))
312 close( request_pipe
[1] );
316 teb
->process
= NtCurrentTeb()->process
;
318 teb
->request_fd
= request_pipe
[1];
319 teb
->entry_point
= start
;
320 teb
->entry_arg
= param
;
321 teb
->startup
= THREAD_Start
;
322 teb
->htask16
= GetCurrentTask();
324 if (id
) *id
= (DWORD
)tid
;
325 if (SYSDEPS_SpawnThread( teb
) == -1)
327 CloseHandle( handle
);
328 THREAD_FreeTEB( teb
);
334 /***********************************************************************
335 * CreateThread16 (KERNEL.441)
337 static DWORD CALLBACK
THREAD_StartThread16( LPVOID threadArgs
)
339 FARPROC16 start
= ((FARPROC16
*)threadArgs
)[0];
340 DWORD param
= ((DWORD
*)threadArgs
)[1];
341 HeapFree( GetProcessHeap(), 0, threadArgs
);
343 ((LPDWORD
)CURRENT_STACK16
)[-1] = param
;
344 return wine_call_to_16_long( start
, sizeof(DWORD
) );
346 HANDLE WINAPI
CreateThread16( SECURITY_ATTRIBUTES
*sa
, DWORD stack
,
347 FARPROC16 start
, SEGPTR param
,
348 DWORD flags
, LPDWORD id
)
350 DWORD
*threadArgs
= HeapAlloc( GetProcessHeap(), 0, 2*sizeof(DWORD
) );
351 if (!threadArgs
) return INVALID_HANDLE_VALUE
;
352 threadArgs
[0] = (DWORD
)start
;
353 threadArgs
[1] = (DWORD
)param
;
355 return CreateThread( sa
, stack
, THREAD_StartThread16
, threadArgs
, flags
, id
);
359 /***********************************************************************
360 * ExitThread [KERNEL32.@] Ends a thread
365 void WINAPI
ExitThread( DWORD code
) /* [in] Exit code for this thread */
368 SERVER_START_REQ( terminate_thread
)
370 /* send the exit code to the server */
371 req
->handle
= GetCurrentThread();
372 req
->exit_code
= code
;
380 MODULE_DllProcessDetach( TRUE
, (LPVOID
)1 );
385 MODULE_DllThreadDetach( NULL
);
386 if (!(NtCurrentTeb()->tibflags
& TEBF_WIN32
)) TASK_ExitTask();
387 SYSDEPS_ExitThread( code
);
392 /***********************************************************************
393 * SetThreadContext [KERNEL32.@] Sets context of thread.
399 BOOL WINAPI
SetThreadContext( HANDLE handle
, /* [in] Handle to thread with context */
400 const CONTEXT
*context
) /* [in] Address of context structure */
403 SERVER_START_VAR_REQ( set_thread_context
, sizeof(*context
) )
405 req
->handle
= handle
;
406 req
->flags
= context
->ContextFlags
;
407 memcpy( server_data_ptr(req
), context
, sizeof(*context
) );
408 ret
= !SERVER_CALL_ERR();
415 /***********************************************************************
416 * GetThreadContext [KERNEL32.@] Retrieves context of thread.
422 BOOL WINAPI
GetThreadContext( HANDLE handle
, /* [in] Handle to thread with context */
423 CONTEXT
*context
) /* [out] Address of context structure */
426 SERVER_START_VAR_REQ( get_thread_context
, sizeof(*context
) )
428 req
->handle
= handle
;
429 req
->flags
= context
->ContextFlags
;
430 memcpy( server_data_ptr(req
), context
, sizeof(*context
) );
431 if ((ret
= !SERVER_CALL_ERR()))
432 memcpy( context
, server_data_ptr(req
), sizeof(*context
) );
439 /**********************************************************************
440 * GetThreadPriority [KERNEL32.@] Returns priority for thread.
443 * Success: Thread's priority level.
444 * Failure: THREAD_PRIORITY_ERROR_RETURN
446 INT WINAPI
GetThreadPriority(
447 HANDLE hthread
) /* [in] Handle to thread */
449 INT ret
= THREAD_PRIORITY_ERROR_RETURN
;
450 SERVER_START_REQ( get_thread_info
)
452 req
->handle
= hthread
;
454 if (!SERVER_CALL_ERR()) ret
= req
->priority
;
461 /**********************************************************************
462 * SetThreadPriority [KERNEL32.@] Sets priority for thread.
468 BOOL WINAPI
SetThreadPriority(
469 HANDLE hthread
, /* [in] Handle to thread */
470 INT priority
) /* [in] Thread priority level */
473 SERVER_START_REQ( set_thread_info
)
475 req
->handle
= hthread
;
476 req
->priority
= priority
;
477 req
->mask
= SET_THREAD_INFO_PRIORITY
;
478 ret
= !SERVER_CALL_ERR();
485 /**********************************************************************
486 * GetThreadPriorityBoost [KERNEL32.@] Returns priority boost for thread.
488 * Always reports that priority boost is disabled.
494 BOOL WINAPI
GetThreadPriorityBoost(
495 HANDLE hthread
, /* [in] Handle to thread */
496 PBOOL pstate
) /* [out] pointer to var that receives the boost state */
498 if (pstate
) *pstate
= FALSE
;
503 /**********************************************************************
504 * SetThreadPriorityBoost [KERNEL32.@] Sets priority boost for thread.
506 * Priority boost is not implemented. Thsi function always returns
507 * FALSE and sets last error to ERROR_CALL_NOT_IMPLEMENTED
510 * Always returns FALSE to indicate a failure
512 BOOL WINAPI
SetThreadPriorityBoost(
513 HANDLE hthread
, /* [in] Handle to thread */
514 BOOL disable
) /* [in] TRUE to disable priority boost */
516 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
521 /**********************************************************************
522 * SetThreadAffinityMask (KERNEL32.@)
524 DWORD WINAPI
SetThreadAffinityMask( HANDLE hThread
, DWORD dwThreadAffinityMask
)
527 SERVER_START_REQ( set_thread_info
)
529 req
->handle
= hThread
;
530 req
->affinity
= dwThreadAffinityMask
;
531 req
->mask
= SET_THREAD_INFO_AFFINITY
;
532 ret
= !SERVER_CALL_ERR();
533 /* FIXME: should return previous value */
540 /**********************************************************************
541 * TerminateThread [KERNEL32.@] Terminates a thread
547 BOOL WINAPI
TerminateThread( HANDLE handle
, /* [in] Handle to thread */
548 DWORD exit_code
) /* [in] Exit code for thread */
550 NTSTATUS status
= NtTerminateThread( handle
, exit_code
);
551 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
556 /**********************************************************************
557 * GetExitCodeThread (KERNEL32.@)
559 * Gets termination status of thread.
565 BOOL WINAPI
GetExitCodeThread(
566 HANDLE hthread
, /* [in] Handle to thread */
567 LPDWORD exitcode
) /* [out] Address to receive termination status */
570 SERVER_START_REQ( get_thread_info
)
572 req
->handle
= hthread
;
574 ret
= !SERVER_CALL_ERR();
575 if (ret
&& exitcode
) *exitcode
= req
->exit_code
;
582 /**********************************************************************
583 * ResumeThread [KERNEL32.@] Resumes a thread.
585 * Decrements a thread's suspend count. When count is zero, the
586 * execution of the thread is resumed.
589 * Success: Previous suspend count
590 * Failure: 0xFFFFFFFF
593 DWORD WINAPI
ResumeThread(
594 HANDLE hthread
) /* [in] Identifies thread to restart */
596 DWORD ret
= 0xffffffff;
597 SERVER_START_REQ( resume_thread
)
599 req
->handle
= hthread
;
600 if (!SERVER_CALL_ERR()) ret
= req
->count
;
607 /**********************************************************************
608 * SuspendThread [KERNEL32.@] Suspends a thread.
611 * Success: Previous suspend count
612 * Failure: 0xFFFFFFFF
614 DWORD WINAPI
SuspendThread(
615 HANDLE hthread
) /* [in] Handle to the thread */
617 DWORD ret
= 0xffffffff;
618 SERVER_START_REQ( suspend_thread
)
620 req
->handle
= hthread
;
621 if (!SERVER_CALL_ERR()) ret
= req
->count
;
628 /***********************************************************************
629 * QueueUserAPC (KERNEL32.@)
631 DWORD WINAPI
QueueUserAPC( PAPCFUNC func
, HANDLE hthread
, ULONG_PTR data
)
634 SERVER_START_REQ( queue_apc
)
636 req
->handle
= hthread
;
639 req
->param
= (void *)data
;
640 ret
= !SERVER_CALL_ERR();
647 /**********************************************************************
648 * GetThreadTimes [KERNEL32.@] Obtains timing information.
651 * What are the fields where these values are stored?
657 BOOL WINAPI
GetThreadTimes(
658 HANDLE thread
, /* [in] Specifies the thread of interest */
659 LPFILETIME creationtime
, /* [out] When the thread was created */
660 LPFILETIME exittime
, /* [out] When the thread was destroyed */
661 LPFILETIME kerneltime
, /* [out] Time thread spent in kernel mode */
662 LPFILETIME usertime
) /* [out] Time thread spent in user mode */
664 FIXME("(0x%08x): stub\n",thread
);
665 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
670 /**********************************************************************
671 * VWin32_BoostThreadGroup [KERNEL.535]
673 VOID WINAPI
VWin32_BoostThreadGroup( DWORD threadId
, INT boost
)
675 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
678 /**********************************************************************
679 * VWin32_BoostThreadStatic [KERNEL.536]
681 VOID WINAPI
VWin32_BoostThreadStatic( DWORD threadId
, INT boost
)
683 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
687 /***********************************************************************
688 * GetThreadLocale (KERNEL32.@)
690 LCID WINAPI
GetThreadLocale(void)
692 LCID ret
= NtCurrentTeb()->CurrentLocale
;
693 if (!ret
) NtCurrentTeb()->CurrentLocale
= ret
= GetUserDefaultLCID();
698 /**********************************************************************
699 * SetThreadLocale [KERNEL32.@] Sets the calling threads current locale.
706 * check if lcid is a valid cp
708 BOOL WINAPI
SetThreadLocale(
709 LCID lcid
) /* [in] Locale identifier */
713 case LOCALE_SYSTEM_DEFAULT
:
714 lcid
= GetSystemDefaultLCID();
716 case LOCALE_USER_DEFAULT
:
718 lcid
= GetUserDefaultLCID();
721 NtCurrentTeb()->CurrentLocale
= lcid
;
726 /***********************************************************************
727 * GetCurrentThread [KERNEL32.@] Gets pseudohandle for current thread
730 * Pseudohandle for the current thread
732 #undef GetCurrentThread
733 HANDLE WINAPI
GetCurrentThread(void)
739 /***********************************************************************
740 * ProcessIdToSessionId (KERNEL32.@)
741 * This function is available on Terminal Server 4SP4 and Windows 2000
743 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
745 /* According to MSDN, if the calling process is not in a terminal
746 * services environment, then the sessionid returned is zero.
752 /***********************************************************************
753 * SetThreadExecutionState (KERNEL32.@)
755 * Informs the system that activity is taking place for
756 * power management purposes.
758 EXECUTION_STATE WINAPI
SetThreadExecutionState(EXECUTION_STATE flags
)
760 FIXME("(0x%lx): stub\n", flags
);
761 return ES_SYSTEM_REQUIRED
|ES_DISPLAY_REQUIRED
|ES_USER_PRESENT
;
767 /***********************************************************************
768 * SetLastError (KERNEL.147)
769 * SetLastError (KERNEL32.@)
771 /* void WINAPI SetLastError( DWORD error ); */
772 __ASM_GLOBAL_FUNC( SetLastError
,
773 "movl 4(%esp),%eax\n\t"
778 /***********************************************************************
779 * GetLastError (KERNEL.148)
780 * GetLastError (KERNEL32.@)
782 /* DWORD WINAPI GetLastError(void); */
783 __ASM_GLOBAL_FUNC( GetLastError
, ".byte 0x64\n\tmovl 0x60,%eax\n\tret" );
785 /***********************************************************************
786 * GetCurrentProcessId (KERNEL.471)
787 * GetCurrentProcessId (KERNEL32.@)
789 /* DWORD WINAPI GetCurrentProcessId(void) */
790 __ASM_GLOBAL_FUNC( GetCurrentProcessId
, ".byte 0x64\n\tmovl 0x20,%eax\n\tret" );
792 /***********************************************************************
793 * GetCurrentThreadId (KERNEL.462)
794 * GetCurrentThreadId (KERNEL32.@)
796 /* DWORD WINAPI GetCurrentThreadId(void) */
797 __ASM_GLOBAL_FUNC( GetCurrentThreadId
, ".byte 0x64\n\tmovl 0x24,%eax\n\tret" );
801 /**********************************************************************
802 * SetLastError (KERNEL.147)
803 * SetLastError (KERNEL32.@)
805 * Sets the last-error code.
807 void WINAPI
SetLastError( DWORD error
) /* [in] Per-thread error code */
809 NtCurrentTeb()->last_error
= error
;
812 /**********************************************************************
813 * GetLastError (KERNEL.148)
814 * GetLastError (KERNEL32.@)
816 * Returns last-error code.
818 DWORD WINAPI
GetLastError(void)
820 return NtCurrentTeb()->last_error
;
823 /***********************************************************************
824 * GetCurrentProcessId (KERNEL.471)
825 * GetCurrentProcessId (KERNEL32.@)
827 * Returns process identifier.
829 DWORD WINAPI
GetCurrentProcessId(void)
831 return (DWORD
)NtCurrentTeb()->pid
;
834 /***********************************************************************
835 * GetCurrentThreadId (KERNEL.462)
836 * GetCurrentThreadId (KERNEL32.@)
838 * Returns thread identifier.
840 DWORD WINAPI
GetCurrentThreadId(void)
842 return (DWORD
)NtCurrentTeb()->tid
;
845 #endif /* __i386__ */