4 * Copyright 1996 Alexandre Julliard
11 #include <sys/types.h>
12 #ifdef HAVE_SYS_MMAN_H
16 #include "wine/winbase16.h"
21 #include "selectors.h"
23 #include "wine/server.h"
25 #include "stackframe.h"
26 #include "builtin16.h"
27 #include "debugtools.h"
30 DEFAULT_DEBUG_CHANNEL(thread
);
31 DECLARE_DEBUG_CHANNEL(relay
);
33 /* TEB of the initial thread */
34 static TEB initial_teb
;
36 extern struct _PDB current_process
;
38 /***********************************************************************
41 * Convert a thread id to a TEB, making sure it is valid.
43 TEB
*THREAD_IdToTEB( DWORD id
)
47 if (!id
|| id
== GetCurrentThreadId()) return NtCurrentTeb();
49 SERVER_START_REQ( get_thread_info
)
52 req
->tid_in
= (void *)id
;
53 if (!SERVER_CALL()) ret
= req
->teb
;
59 /* Allow task handles to be used; convert to main thread */
62 TDB
*pTask
= TASK_GetPtr( id
);
63 if (pTask
) return pTask
->teb
;
65 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
;
87 teb
->stack_top
= (void *)~0UL;
88 teb
->StaticUnicodeString
.MaximumLength
= sizeof(teb
->StaticUnicodeBuffer
);
89 teb
->StaticUnicodeString
.Buffer
= (PWSTR
)teb
->StaticUnicodeBuffer
;
90 teb
->teb_sel
= SELECTOR_AllocBlock( teb
, 0x1000, WINE_LDT_FLAGS_DATA
|WINE_LDT_FLAGS_32BIT
);
91 return (teb
->teb_sel
!= 0);
95 /***********************************************************************
98 * Free data structures associated with a thread.
99 * Must be called from the context of another thread.
101 static void CALLBACK
THREAD_FreeTEB( TEB
*teb
)
103 TRACE("(%p) called\n", teb
);
104 if (teb
->cleanup
) SERVICE_Delete( teb
->cleanup
);
106 /* Free the associated memory */
108 close( teb
->request_fd
);
109 close( teb
->reply_fd
);
110 close( teb
->wait_fd
[0] );
111 close( teb
->wait_fd
[1] );
112 if (teb
->stack_sel
) FreeSelector16( teb
->stack_sel
);
113 FreeSelector16( teb
->teb_sel
);
114 if (teb
->buffer
) munmap( (void *)teb
->buffer
, teb
->buffer_size
);
115 if (teb
->debug_info
) HeapFree( GetProcessHeap(), 0, teb
->debug_info
);
116 VirtualFree( teb
->stack_base
, 0, MEM_RELEASE
);
120 /***********************************************************************
123 * Allocate the stack of a thread.
125 TEB
*THREAD_InitStack( TEB
*teb
, DWORD stack_size
)
127 DWORD old_prot
, total_size
;
128 DWORD page_size
= getpagesize();
131 /* Allocate the stack */
133 if (stack_size
>= 16*1024*1024)
134 WARN("Thread stack size is %ld MB.\n",stack_size
/1024/1024);
136 /* if size is smaller than default, get stack size from parent */
137 if (stack_size
< 1024 * 1024)
140 stack_size
= 1024 * 1024; /* no parent */
142 stack_size
= ((char *)NtCurrentTeb()->stack_top
- (char *)NtCurrentTeb()->stack_base
143 - SIGNAL_STACK_SIZE
- 3 * page_size
);
146 /* FIXME: some Wine functions use a lot of stack, so we add 64Kb here */
147 stack_size
+= 64 * 1024;
149 /* Memory layout in allocated block:
152 * 1 page NOACCESS guard page
153 * SIGNAL_STACK_SIZE signal stack
154 * 1 page NOACCESS guard page
155 * 1 page PAGE_GUARD guard page
156 * stack_size normal stack
157 * 64Kb 16-bit stack (optional)
158 * 1 page TEB (except for initial thread)
161 stack_size
= (stack_size
+ (page_size
- 1)) & ~(page_size
- 1);
162 total_size
= stack_size
+ SIGNAL_STACK_SIZE
+ 3 * page_size
;
163 total_size
+= 0x10000; /* 16-bit stack */
164 if (!teb
) total_size
+= page_size
;
166 if (!(base
= VirtualAlloc( NULL
, total_size
, MEM_COMMIT
, PAGE_EXECUTE_READWRITE
)))
171 teb
= (TEB
*)((char *)base
+ total_size
- page_size
);
172 if (!THREAD_InitTEB( teb
))
174 VirtualFree( base
, 0, MEM_RELEASE
);
179 teb
->stack_low
= base
;
180 teb
->stack_base
= base
;
181 teb
->signal_stack
= (char *)base
+ page_size
;
182 teb
->stack_top
= (char *)base
+ 3 * page_size
+ SIGNAL_STACK_SIZE
+ stack_size
;
184 /* Setup guard pages */
186 VirtualProtect( base
, 1, PAGE_NOACCESS
, &old_prot
);
187 VirtualProtect( (char *)teb
->signal_stack
+ SIGNAL_STACK_SIZE
, 1, PAGE_NOACCESS
, &old_prot
);
188 VirtualProtect( (char *)teb
->signal_stack
+ SIGNAL_STACK_SIZE
+ page_size
, 1,
189 PAGE_EXECUTE_READWRITE
| PAGE_GUARD
, &old_prot
);
191 /* Allocate the 16-bit stack selector */
193 teb
->stack_sel
= SELECTOR_AllocBlock( teb
->stack_top
, 0x10000, WINE_LDT_FLAGS_DATA
);
194 if (!teb
->stack_sel
) goto error
;
195 teb
->cur_stack
= MAKESEGPTR( teb
->stack_sel
, 0x10000 - sizeof(STACK16FRAME
) );
200 THREAD_FreeTEB( teb
);
205 /***********************************************************************
206 * thread_errno_location
208 * Get the per-thread errno location.
210 static int *thread_errno_location(void)
212 return &NtCurrentTeb()->thread_errno
;
215 /***********************************************************************
216 * thread_h_errno_location
218 * Get the per-thread h_errno location.
220 static int *thread_h_errno_location(void)
222 return &NtCurrentTeb()->thread_h_errno
;
225 /***********************************************************************
228 * Setup the initial thread.
230 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
232 void THREAD_Init(void)
234 if (!initial_teb
.self
) /* do it only once */
236 THREAD_InitTEB( &initial_teb
);
237 assert( initial_teb
.teb_sel
);
238 initial_teb
.process
= ¤t_process
;
239 SYSDEPS_SetCurThread( &initial_teb
);
240 wine_errno_location
= thread_errno_location
;
241 wine_h_errno_location
= thread_h_errno_location
;
245 DECL_GLOBAL_CONSTRUCTOR(thread_init
) { THREAD_Init(); }
248 /***********************************************************************
251 * Start execution of a newly created thread. Does not return.
253 static void THREAD_Start(void)
255 HANDLE cleanup_object
;
256 LPTHREAD_START_ROUTINE func
= (LPTHREAD_START_ROUTINE
)NtCurrentTeb()->entry_point
;
258 /* install cleanup handler */
259 if (DuplicateHandle( GetCurrentProcess(), GetCurrentThread(),
260 GetCurrentProcess(), &cleanup_object
,
261 0, FALSE
, DUPLICATE_SAME_ACCESS
))
262 NtCurrentTeb()->cleanup
= SERVICE_AddObject( cleanup_object
, (PAPCFUNC
)THREAD_FreeTEB
,
263 (ULONG_PTR
)NtCurrentTeb() );
266 DPRINTF("%08lx:Starting thread (entryproc=%p)\n", GetCurrentThreadId(), func
);
268 PROCESS_CallUserSignalProc( USIG_THREAD_INIT
, 0 );
270 MODULE_DllThreadAttach( NULL
);
271 ExitThread( func( NtCurrentTeb()->entry_arg
) );
275 /***********************************************************************
276 * CreateThread (KERNEL32.@)
278 HANDLE WINAPI
CreateThread( SECURITY_ATTRIBUTES
*sa
, DWORD stack
,
279 LPTHREAD_START_ROUTINE start
, LPVOID param
,
280 DWORD flags
, LPDWORD id
)
287 if (pipe( request_pipe
) == -1)
289 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
292 fcntl( request_pipe
[1], F_SETFD
, 1 ); /* set close on exec flag */
293 wine_server_send_fd( request_pipe
[0] );
295 SERVER_START_REQ( new_thread
)
297 req
->suspend
= ((flags
& CREATE_SUSPENDED
) != 0);
298 req
->inherit
= (sa
&& (sa
->nLength
>=sizeof(*sa
)) && sa
->bInheritHandle
);
299 req
->request_fd
= request_pipe
[0];
300 if (!SERVER_CALL_ERR())
302 handle
= req
->handle
;
305 close( request_pipe
[0] );
309 if (!handle
|| !(teb
= THREAD_InitStack( NULL
, stack
)))
311 close( request_pipe
[1] );
315 teb
->process
= NtCurrentTeb()->process
;
317 teb
->request_fd
= request_pipe
[1];
318 teb
->entry_point
= start
;
319 teb
->entry_arg
= param
;
320 teb
->startup
= THREAD_Start
;
321 teb
->htask16
= GetCurrentTask();
323 if (id
) *id
= (DWORD
)tid
;
324 if (SYSDEPS_SpawnThread( teb
) == -1)
326 CloseHandle( handle
);
327 THREAD_FreeTEB( teb
);
333 /***********************************************************************
334 * CreateThread16 (KERNEL.441)
336 static DWORD CALLBACK
THREAD_StartThread16( LPVOID threadArgs
)
338 FARPROC16 start
= ((FARPROC16
*)threadArgs
)[0];
339 DWORD param
= ((DWORD
*)threadArgs
)[1];
340 HeapFree( GetProcessHeap(), 0, threadArgs
);
342 ((LPDWORD
)CURRENT_STACK16
)[-1] = param
;
343 return wine_call_to_16_long( start
, sizeof(DWORD
) );
345 HANDLE WINAPI
CreateThread16( SECURITY_ATTRIBUTES
*sa
, DWORD stack
,
346 FARPROC16 start
, SEGPTR param
,
347 DWORD flags
, LPDWORD id
)
349 DWORD
*threadArgs
= HeapAlloc( GetProcessHeap(), 0, 2*sizeof(DWORD
) );
350 if (!threadArgs
) return INVALID_HANDLE_VALUE
;
351 threadArgs
[0] = (DWORD
)start
;
352 threadArgs
[1] = (DWORD
)param
;
354 return CreateThread( sa
, stack
, THREAD_StartThread16
, threadArgs
, flags
, id
);
358 /***********************************************************************
359 * ExitThread [KERNEL32.@] Ends a thread
364 void WINAPI
ExitThread( DWORD code
) /* [in] Exit code for this thread */
367 SERVER_START_REQ( terminate_thread
)
369 /* send the exit code to the server */
370 req
->handle
= GetCurrentThread();
371 req
->exit_code
= code
;
379 MODULE_DllProcessDetach( TRUE
, (LPVOID
)1 );
384 MODULE_DllThreadDetach( NULL
);
385 if (!(NtCurrentTeb()->tibflags
& TEBF_WIN32
)) TASK_ExitTask();
386 SYSDEPS_ExitThread( code
);
391 /***********************************************************************
392 * SetThreadContext [KERNEL32.@] Sets context of thread.
398 BOOL WINAPI
SetThreadContext( HANDLE handle
, /* [in] Handle to thread with context */
399 const CONTEXT
*context
) /* [in] Address of context structure */
402 SERVER_START_VAR_REQ( set_thread_context
, sizeof(*context
) )
404 req
->handle
= handle
;
405 req
->flags
= context
->ContextFlags
;
406 memcpy( server_data_ptr(req
), context
, sizeof(*context
) );
407 ret
= !SERVER_CALL_ERR();
414 /***********************************************************************
415 * GetThreadContext [KERNEL32.@] Retrieves context of thread.
421 BOOL WINAPI
GetThreadContext( HANDLE handle
, /* [in] Handle to thread with context */
422 CONTEXT
*context
) /* [out] Address of context structure */
425 SERVER_START_VAR_REQ( get_thread_context
, sizeof(*context
) )
427 req
->handle
= handle
;
428 req
->flags
= context
->ContextFlags
;
429 memcpy( server_data_ptr(req
), context
, sizeof(*context
) );
430 if ((ret
= !SERVER_CALL_ERR()))
431 memcpy( context
, server_data_ptr(req
), sizeof(*context
) );
438 /**********************************************************************
439 * GetThreadPriority [KERNEL32.@] Returns priority for thread.
442 * Success: Thread's priority level.
443 * Failure: THREAD_PRIORITY_ERROR_RETURN
445 INT WINAPI
GetThreadPriority(
446 HANDLE hthread
) /* [in] Handle to thread */
448 INT ret
= THREAD_PRIORITY_ERROR_RETURN
;
449 SERVER_START_REQ( get_thread_info
)
451 req
->handle
= hthread
;
453 if (!SERVER_CALL_ERR()) ret
= req
->priority
;
460 /**********************************************************************
461 * SetThreadPriority [KERNEL32.@] Sets priority for thread.
467 BOOL WINAPI
SetThreadPriority(
468 HANDLE hthread
, /* [in] Handle to thread */
469 INT priority
) /* [in] Thread priority level */
472 SERVER_START_REQ( set_thread_info
)
474 req
->handle
= hthread
;
475 req
->priority
= priority
;
476 req
->mask
= SET_THREAD_INFO_PRIORITY
;
477 ret
= !SERVER_CALL_ERR();
484 /**********************************************************************
485 * GetThreadPriorityBoost [KERNEL32.@] Returns priority boost for thread.
487 * Always reports that priority boost is disabled.
493 BOOL WINAPI
GetThreadPriorityBoost(
494 HANDLE hthread
, /* [in] Handle to thread */
495 PBOOL pstate
) /* [out] pointer to var that receives the boost state */
497 if (pstate
) *pstate
= FALSE
;
502 /**********************************************************************
503 * SetThreadPriorityBoost [KERNEL32.@] Sets priority boost for thread.
505 * Priority boost is not implemented. Thsi function always returns
506 * FALSE and sets last error to ERROR_CALL_NOT_IMPLEMENTED
509 * Always returns FALSE to indicate a failure
511 BOOL WINAPI
SetThreadPriorityBoost(
512 HANDLE hthread
, /* [in] Handle to thread */
513 BOOL disable
) /* [in] TRUE to disable priority boost */
515 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
520 /**********************************************************************
521 * SetThreadAffinityMask (KERNEL32.@)
523 DWORD WINAPI
SetThreadAffinityMask( HANDLE hThread
, DWORD dwThreadAffinityMask
)
526 SERVER_START_REQ( set_thread_info
)
528 req
->handle
= hThread
;
529 req
->affinity
= dwThreadAffinityMask
;
530 req
->mask
= SET_THREAD_INFO_AFFINITY
;
531 ret
= !SERVER_CALL_ERR();
532 /* FIXME: should return previous value */
539 /**********************************************************************
540 * TerminateThread [KERNEL32.@] Terminates a thread
546 BOOL WINAPI
TerminateThread( HANDLE handle
, /* [in] Handle to thread */
547 DWORD exit_code
) /* [in] Exit code for thread */
549 NTSTATUS status
= NtTerminateThread( handle
, exit_code
);
550 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
555 /**********************************************************************
556 * GetExitCodeThread (KERNEL32.@)
558 * Gets termination status of thread.
564 BOOL WINAPI
GetExitCodeThread(
565 HANDLE hthread
, /* [in] Handle to thread */
566 LPDWORD exitcode
) /* [out] Address to receive termination status */
569 SERVER_START_REQ( get_thread_info
)
571 req
->handle
= hthread
;
573 ret
= !SERVER_CALL_ERR();
574 if (ret
&& exitcode
) *exitcode
= req
->exit_code
;
581 /**********************************************************************
582 * ResumeThread [KERNEL32.@] Resumes a thread.
584 * Decrements a thread's suspend count. When count is zero, the
585 * execution of the thread is resumed.
588 * Success: Previous suspend count
589 * Failure: 0xFFFFFFFF
592 DWORD WINAPI
ResumeThread(
593 HANDLE hthread
) /* [in] Identifies thread to restart */
595 DWORD ret
= 0xffffffff;
596 SERVER_START_REQ( resume_thread
)
598 req
->handle
= hthread
;
599 if (!SERVER_CALL_ERR()) ret
= req
->count
;
606 /**********************************************************************
607 * SuspendThread [KERNEL32.@] Suspends a thread.
610 * Success: Previous suspend count
611 * Failure: 0xFFFFFFFF
613 DWORD WINAPI
SuspendThread(
614 HANDLE hthread
) /* [in] Handle to the thread */
616 DWORD ret
= 0xffffffff;
617 SERVER_START_REQ( suspend_thread
)
619 req
->handle
= hthread
;
620 if (!SERVER_CALL_ERR()) ret
= req
->count
;
627 /***********************************************************************
628 * QueueUserAPC (KERNEL32.@)
630 DWORD WINAPI
QueueUserAPC( PAPCFUNC func
, HANDLE hthread
, ULONG_PTR data
)
633 SERVER_START_REQ( queue_apc
)
635 req
->handle
= hthread
;
638 req
->param
= (void *)data
;
639 ret
= !SERVER_CALL_ERR();
646 /**********************************************************************
647 * GetThreadTimes [KERNEL32.@] Obtains timing information.
650 * What are the fields where these values are stored?
656 BOOL WINAPI
GetThreadTimes(
657 HANDLE thread
, /* [in] Specifies the thread of interest */
658 LPFILETIME creationtime
, /* [out] When the thread was created */
659 LPFILETIME exittime
, /* [out] When the thread was destroyed */
660 LPFILETIME kerneltime
, /* [out] Time thread spent in kernel mode */
661 LPFILETIME usertime
) /* [out] Time thread spent in user mode */
663 FIXME("(0x%08x): stub\n",thread
);
664 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
669 /**********************************************************************
670 * VWin32_BoostThreadGroup [KERNEL.535]
672 VOID WINAPI
VWin32_BoostThreadGroup( DWORD threadId
, INT boost
)
674 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
677 /**********************************************************************
678 * VWin32_BoostThreadStatic [KERNEL.536]
680 VOID WINAPI
VWin32_BoostThreadStatic( DWORD threadId
, INT boost
)
682 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
686 /***********************************************************************
687 * GetThreadLocale (KERNEL32.@)
689 LCID WINAPI
GetThreadLocale(void)
691 LCID ret
= NtCurrentTeb()->CurrentLocale
;
692 if (!ret
) NtCurrentTeb()->CurrentLocale
= ret
= GetUserDefaultLCID();
697 /**********************************************************************
698 * SetThreadLocale [KERNEL32.@] Sets the calling threads current locale.
705 * check if lcid is a valid cp
707 BOOL WINAPI
SetThreadLocale(
708 LCID lcid
) /* [in] Locale identifier */
712 case LOCALE_SYSTEM_DEFAULT
:
713 lcid
= GetSystemDefaultLCID();
715 case LOCALE_USER_DEFAULT
:
717 lcid
= GetUserDefaultLCID();
720 NtCurrentTeb()->CurrentLocale
= lcid
;
725 /***********************************************************************
726 * GetCurrentThread [KERNEL32.@] Gets pseudohandle for current thread
729 * Pseudohandle for the current thread
731 #undef GetCurrentThread
732 HANDLE WINAPI
GetCurrentThread(void)
738 /***********************************************************************
739 * ProcessIdToSessionId (KERNEL32.@)
740 * This function is available on Terminal Server 4SP4 and Windows 2000
742 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
744 /* According to MSDN, if the calling process is not in a terminal
745 * services environment, then the sessionid returned is zero.
751 /***********************************************************************
752 * SetThreadExecutionState (KERNEL32.@)
754 * Informs the system that activity is taking place for
755 * power management purposes.
757 EXECUTION_STATE WINAPI
SetThreadExecutionState(EXECUTION_STATE flags
)
759 static EXECUTION_STATE current
=
760 ES_SYSTEM_REQUIRED
|ES_DISPLAY_REQUIRED
|ES_USER_PRESENT
;
761 EXECUTION_STATE old
= current
;
763 if (!(current
& ES_CONTINUOUS
) || (flags
& ES_CONTINUOUS
))
765 FIXME("(0x%lx): stub, harmless (power management).\n", flags
);
772 /***********************************************************************
773 * SetLastError (KERNEL.147)
774 * SetLastError (KERNEL32.@)
776 /* void WINAPI SetLastError( DWORD error ); */
777 __ASM_GLOBAL_FUNC( SetLastError
,
778 "movl 4(%esp),%eax\n\t"
783 /***********************************************************************
784 * GetLastError (KERNEL.148)
785 * GetLastError (KERNEL32.@)
787 /* DWORD WINAPI GetLastError(void); */
788 __ASM_GLOBAL_FUNC( GetLastError
, ".byte 0x64\n\tmovl 0x60,%eax\n\tret" );
790 /***********************************************************************
791 * GetCurrentProcessId (KERNEL.471)
792 * GetCurrentProcessId (KERNEL32.@)
794 /* DWORD WINAPI GetCurrentProcessId(void) */
795 __ASM_GLOBAL_FUNC( GetCurrentProcessId
, ".byte 0x64\n\tmovl 0x20,%eax\n\tret" );
797 /***********************************************************************
798 * GetCurrentThreadId (KERNEL.462)
799 * GetCurrentThreadId (KERNEL32.@)
801 /* DWORD WINAPI GetCurrentThreadId(void) */
802 __ASM_GLOBAL_FUNC( GetCurrentThreadId
, ".byte 0x64\n\tmovl 0x24,%eax\n\tret" );
806 /**********************************************************************
807 * SetLastError (KERNEL.147)
808 * SetLastError (KERNEL32.@)
810 * Sets the last-error code.
812 void WINAPI
SetLastError( DWORD error
) /* [in] Per-thread error code */
814 NtCurrentTeb()->last_error
= error
;
817 /**********************************************************************
818 * GetLastError (KERNEL.148)
819 * GetLastError (KERNEL32.@)
821 * Returns last-error code.
823 DWORD WINAPI
GetLastError(void)
825 return NtCurrentTeb()->last_error
;
828 /***********************************************************************
829 * GetCurrentProcessId (KERNEL.471)
830 * GetCurrentProcessId (KERNEL32.@)
832 * Returns process identifier.
834 DWORD WINAPI
GetCurrentProcessId(void)
836 return (DWORD
)NtCurrentTeb()->pid
;
839 /***********************************************************************
840 * GetCurrentThreadId (KERNEL.462)
841 * GetCurrentThreadId (KERNEL32.@)
843 * Returns thread identifier.
845 DWORD WINAPI
GetCurrentThreadId(void)
847 return (DWORD
)NtCurrentTeb()->tid
;
850 #endif /* __i386__ */