4 * Copyright 1996 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "wine/port.h"
26 #include <sys/types.h>
27 #ifdef HAVE_SYS_MMAN_H
30 #ifdef HAVE_SYS_TIMES_H
31 #include <sys/times.h>
36 #include "wine/winbase16.h"
41 #include "selectors.h"
43 #include "wine/server.h"
44 #include "stackframe.h"
45 #include "wine/debug.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(thread
);
49 WINE_DECLARE_DEBUG_CHANNEL(relay
);
51 /* TEB of the initial thread */
52 static TEB initial_teb
;
54 extern struct _PDB current_process
;
56 /***********************************************************************
59 * Convert a thread id to a TEB, making sure it is valid.
61 TEB
*THREAD_IdToTEB( DWORD id
)
65 if (!id
|| id
== GetCurrentThreadId()) return NtCurrentTeb();
67 SERVER_START_REQ( get_thread_info
)
71 if (!wine_server_call( req
)) ret
= reply
->teb
;
77 /* Allow task handles to be used; convert to main thread */
80 TDB
*pTask
= TASK_GetPtr( id
);
81 if (pTask
) return pTask
->teb
;
83 SetLastError( ERROR_INVALID_PARAMETER
);
89 /***********************************************************************
92 * Initialization of a newly created TEB.
94 static BOOL
THREAD_InitTEB( TEB
*teb
)
96 teb
->except
= (void *)~0UL;
98 teb
->tibflags
= TEBF_WIN32
;
99 teb
->tls_ptr
= teb
->tls_array
;
100 teb
->exit_code
= STILL_ACTIVE
;
101 teb
->request_fd
= -1;
103 teb
->wait_fd
[0] = -1;
104 teb
->wait_fd
[1] = -1;
105 teb
->stack_top
= (void *)~0UL;
106 teb
->StaticUnicodeString
.MaximumLength
= sizeof(teb
->StaticUnicodeBuffer
);
107 teb
->StaticUnicodeString
.Buffer
= (PWSTR
)teb
->StaticUnicodeBuffer
;
108 teb
->teb_sel
= wine_ldt_alloc_fs();
109 return (teb
->teb_sel
!= 0);
113 /***********************************************************************
116 * Free data structures associated with a thread.
117 * Must be called from the context of another thread.
119 static void THREAD_FreeTEB( TEB
*teb
)
121 TRACE("(%p) called\n", teb
);
122 /* Free the associated memory */
123 wine_ldt_free_fs( teb
->teb_sel
);
124 VirtualFree( teb
->stack_base
, 0, MEM_RELEASE
);
128 /***********************************************************************
131 * Allocate the stack of a thread.
133 TEB
*THREAD_InitStack( TEB
*teb
, DWORD stack_size
)
135 DWORD old_prot
, total_size
;
136 DWORD page_size
= getpagesize();
139 /* Allocate the stack */
141 if (stack_size
>= 16*1024*1024)
142 WARN("Thread stack size is %ld MB.\n",stack_size
/1024/1024);
144 /* if size is smaller than default, get stack size from parent */
145 if (stack_size
< 1024 * 1024)
148 stack_size
= 1024 * 1024; /* no parent */
150 stack_size
= ((char *)NtCurrentTeb()->stack_top
- (char *)NtCurrentTeb()->stack_base
151 - SIGNAL_STACK_SIZE
- 3 * page_size
);
154 /* FIXME: some Wine functions use a lot of stack, so we add 64Kb here */
155 stack_size
+= 64 * 1024;
157 /* Memory layout in allocated block:
160 * 1 page NOACCESS guard page
161 * SIGNAL_STACK_SIZE signal stack
162 * 1 page NOACCESS guard page
163 * 1 page PAGE_GUARD guard page
164 * stack_size normal stack
165 * 1 page TEB (except for initial thread)
166 * 1 page debug info (except for initial thread)
169 stack_size
= (stack_size
+ (page_size
- 1)) & ~(page_size
- 1);
170 total_size
= stack_size
+ SIGNAL_STACK_SIZE
+ 3 * page_size
;
171 if (!teb
) total_size
+= 2 * page_size
;
173 if (!(base
= VirtualAlloc( NULL
, total_size
, MEM_COMMIT
, PAGE_EXECUTE_READWRITE
)))
178 teb
= (TEB
*)((char *)base
+ total_size
- 2 * page_size
);
179 if (!THREAD_InitTEB( teb
))
181 VirtualFree( base
, 0, MEM_RELEASE
);
184 teb
->debug_info
= (char *)teb
+ page_size
;
187 teb
->stack_low
= base
;
188 teb
->stack_base
= base
;
189 teb
->signal_stack
= (char *)base
+ page_size
;
190 teb
->stack_top
= (char *)base
+ 3 * page_size
+ SIGNAL_STACK_SIZE
+ stack_size
;
192 /* Setup guard pages */
194 VirtualProtect( base
, 1, PAGE_NOACCESS
, &old_prot
);
195 VirtualProtect( (char *)teb
->signal_stack
+ SIGNAL_STACK_SIZE
, 1, PAGE_NOACCESS
, &old_prot
);
196 VirtualProtect( (char *)teb
->signal_stack
+ SIGNAL_STACK_SIZE
+ page_size
, 1,
197 PAGE_EXECUTE_READWRITE
| PAGE_GUARD
, &old_prot
);
202 /***********************************************************************
205 * Setup the initial thread.
207 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
209 void THREAD_Init(void)
211 if (!initial_teb
.self
) /* do it only once */
213 THREAD_InitTEB( &initial_teb
);
214 assert( initial_teb
.teb_sel
);
215 initial_teb
.process
= ¤t_process
;
216 SYSDEPS_SetCurThread( &initial_teb
);
221 DECL_GLOBAL_CONSTRUCTOR(thread_init
) { THREAD_Init(); }
224 /***********************************************************************
227 * Start execution of a newly created thread. Does not return.
229 static void THREAD_Start(void)
231 LPTHREAD_START_ROUTINE func
= (LPTHREAD_START_ROUTINE
)NtCurrentTeb()->entry_point
;
234 DPRINTF("%04lx:Starting thread (entryproc=%p)\n", GetCurrentThreadId(), func
);
236 PROCESS_CallUserSignalProc( USIG_THREAD_INIT
, 0 );
237 MODULE_DllThreadAttach( NULL
);
238 ExitThread( func( NtCurrentTeb()->entry_arg
) );
242 /***********************************************************************
243 * CreateThread (KERNEL32.@)
245 HANDLE WINAPI
CreateThread( SECURITY_ATTRIBUTES
*sa
, SIZE_T stack
,
246 LPTHREAD_START_ROUTINE start
, LPVOID param
,
247 DWORD flags
, LPDWORD id
)
254 if (pipe( request_pipe
) == -1)
256 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
259 fcntl( request_pipe
[1], F_SETFD
, 1 ); /* set close on exec flag */
260 wine_server_send_fd( request_pipe
[0] );
262 SERVER_START_REQ( new_thread
)
264 req
->suspend
= ((flags
& CREATE_SUSPENDED
) != 0);
265 req
->inherit
= (sa
&& (sa
->nLength
>=sizeof(*sa
)) && sa
->bInheritHandle
);
266 req
->request_fd
= request_pipe
[0];
267 if (!wine_server_call_err( req
))
269 handle
= reply
->handle
;
272 close( request_pipe
[0] );
276 if (!handle
|| !(teb
= THREAD_InitStack( NULL
, stack
)))
278 close( request_pipe
[1] );
282 teb
->process
= NtCurrentTeb()->process
;
284 teb
->request_fd
= request_pipe
[1];
285 teb
->entry_point
= start
;
286 teb
->entry_arg
= param
;
287 teb
->startup
= THREAD_Start
;
288 teb
->htask16
= GetCurrentTask();
291 if (SYSDEPS_SpawnThread( teb
) == -1)
293 CloseHandle( handle
);
294 close( request_pipe
[1] );
295 THREAD_FreeTEB( teb
);
301 /***********************************************************************
302 * ExitThread [KERNEL32.@] Ends a thread
307 void WINAPI
ExitThread( DWORD code
) /* [in] Exit code for this thread */
310 SERVER_START_REQ( terminate_thread
)
312 /* send the exit code to the server */
313 req
->handle
= GetCurrentThread();
314 req
->exit_code
= code
;
315 wine_server_call( req
);
322 LdrShutdownProcess();
328 if (!(NtCurrentTeb()->tibflags
& TEBF_WIN32
)) TASK_ExitTask();
329 SYSDEPS_ExitThread( code
);
333 /***********************************************************************
334 * OpenThread Retrieves a handle to a thread from its thread id
339 HANDLE WINAPI
OpenThread( DWORD dwDesiredAccess
, BOOL bInheritHandle
, DWORD dwThreadId
)
342 SERVER_START_REQ( open_thread
)
344 req
->tid
= dwThreadId
;
345 req
->access
= dwDesiredAccess
;
346 req
->inherit
= bInheritHandle
;
347 if (!wine_server_call_err( req
)) ret
= reply
->handle
;
353 /***********************************************************************
354 * SetThreadContext [KERNEL32.@] Sets context of thread.
360 BOOL WINAPI
SetThreadContext( HANDLE handle
, /* [in] Handle to thread with context */
361 const CONTEXT
*context
) /* [in] Address of context structure */
363 NTSTATUS status
= NtSetContextThread( handle
, context
);
364 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
369 /***********************************************************************
370 * GetThreadContext [KERNEL32.@] Retrieves context of thread.
376 BOOL WINAPI
GetThreadContext( HANDLE handle
, /* [in] Handle to thread with context */
377 CONTEXT
*context
) /* [out] Address of context structure */
379 NTSTATUS status
= NtGetContextThread( handle
, context
);
380 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
385 /**********************************************************************
386 * GetThreadPriority [KERNEL32.@] Returns priority for thread.
389 * Success: Thread's priority level.
390 * Failure: THREAD_PRIORITY_ERROR_RETURN
392 INT WINAPI
GetThreadPriority(
393 HANDLE hthread
) /* [in] Handle to thread */
395 INT ret
= THREAD_PRIORITY_ERROR_RETURN
;
396 SERVER_START_REQ( get_thread_info
)
398 req
->handle
= hthread
;
400 if (!wine_server_call_err( req
)) ret
= reply
->priority
;
407 /**********************************************************************
408 * SetThreadPriority [KERNEL32.@] Sets priority for thread.
414 BOOL WINAPI
SetThreadPriority(
415 HANDLE hthread
, /* [in] Handle to thread */
416 INT priority
) /* [in] Thread priority level */
419 SERVER_START_REQ( set_thread_info
)
421 req
->handle
= hthread
;
422 req
->priority
= priority
;
423 req
->mask
= SET_THREAD_INFO_PRIORITY
;
424 ret
= !wine_server_call_err( req
);
431 /**********************************************************************
432 * GetThreadPriorityBoost [KERNEL32.@] Returns priority boost for thread.
434 * Always reports that priority boost is disabled.
440 BOOL WINAPI
GetThreadPriorityBoost(
441 HANDLE hthread
, /* [in] Handle to thread */
442 PBOOL pstate
) /* [out] pointer to var that receives the boost state */
444 if (pstate
) *pstate
= FALSE
;
449 /**********************************************************************
450 * SetThreadPriorityBoost [KERNEL32.@] Sets priority boost for thread.
452 * Priority boost is not implemented. Thsi function always returns
453 * FALSE and sets last error to ERROR_CALL_NOT_IMPLEMENTED
456 * Always returns FALSE to indicate a failure
458 BOOL WINAPI
SetThreadPriorityBoost(
459 HANDLE hthread
, /* [in] Handle to thread */
460 BOOL disable
) /* [in] TRUE to disable priority boost */
462 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
467 /**********************************************************************
468 * SetThreadAffinityMask (KERNEL32.@)
470 DWORD WINAPI
SetThreadAffinityMask( HANDLE hThread
, DWORD dwThreadAffinityMask
)
473 SERVER_START_REQ( set_thread_info
)
475 req
->handle
= hThread
;
476 req
->affinity
= dwThreadAffinityMask
;
477 req
->mask
= SET_THREAD_INFO_AFFINITY
;
478 ret
= !wine_server_call_err( req
);
479 /* FIXME: should return previous value */
485 /**********************************************************************
486 * SetThreadIdealProcessor [KERNEL32.@] Obtains timing information.
489 * Success: Value of last call to SetThreadIdealProcessor
492 DWORD WINAPI
SetThreadIdealProcessor(
493 HANDLE hThread
, /* [in] Specifies the thread of interest */
494 DWORD dwIdealProcessor
) /* [in] Specifies the new preferred processor */
496 FIXME("(%p): stub\n",hThread
);
497 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
501 /**********************************************************************
502 * TerminateThread [KERNEL32.@] Terminates a thread
508 BOOL WINAPI
TerminateThread( HANDLE handle
, /* [in] Handle to thread */
509 DWORD exit_code
) /* [in] Exit code for thread */
511 NTSTATUS status
= NtTerminateThread( handle
, exit_code
);
512 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
517 /**********************************************************************
518 * GetExitCodeThread (KERNEL32.@)
520 * Gets termination status of thread.
526 BOOL WINAPI
GetExitCodeThread(
527 HANDLE hthread
, /* [in] Handle to thread */
528 LPDWORD exitcode
) /* [out] Address to receive termination status */
531 SERVER_START_REQ( get_thread_info
)
533 req
->handle
= hthread
;
535 ret
= !wine_server_call_err( req
);
536 if (ret
&& exitcode
) *exitcode
= reply
->exit_code
;
543 /**********************************************************************
544 * ResumeThread [KERNEL32.@] Resumes a thread.
546 * Decrements a thread's suspend count. When count is zero, the
547 * execution of the thread is resumed.
550 * Success: Previous suspend count
551 * Failure: 0xFFFFFFFF
554 DWORD WINAPI
ResumeThread( HANDLE hthread
) /* [in] Identifies thread to restart */
557 NTSTATUS status
= NtResumeThread( hthread
, &ret
);
562 SetLastError( RtlNtStatusToDosError(status
) );
568 /**********************************************************************
569 * SuspendThread [KERNEL32.@] Suspends a thread.
572 * Success: Previous suspend count
573 * Failure: 0xFFFFFFFF
575 DWORD WINAPI
SuspendThread( HANDLE hthread
) /* [in] Handle to the thread */
578 NTSTATUS status
= NtSuspendThread( hthread
, &ret
);
583 SetLastError( RtlNtStatusToDosError(status
) );
589 /* callback for QueueUserAPC */
590 static void CALLBACK
call_user_apc( ULONG_PTR arg1
, ULONG_PTR arg2
, ULONG_PTR arg3
)
592 PAPCFUNC func
= (PAPCFUNC
)arg1
;
596 /***********************************************************************
597 * QueueUserAPC (KERNEL32.@)
599 DWORD WINAPI
QueueUserAPC( PAPCFUNC func
, HANDLE hthread
, ULONG_PTR data
)
601 NTSTATUS status
= NtQueueApcThread( hthread
, call_user_apc
, (ULONG_PTR
)func
, data
, 0 );
603 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
608 /**********************************************************************
609 * GetThreadTimes [KERNEL32.@] Obtains timing information.
615 BOOL WINAPI
GetThreadTimes(
616 HANDLE thread
, /* [in] Specifies the thread of interest */
617 LPFILETIME creationtime
, /* [out] When the thread was created */
618 LPFILETIME exittime
, /* [out] When the thread was destroyed */
619 LPFILETIME kerneltime
, /* [out] Time thread spent in kernel mode */
620 LPFILETIME usertime
) /* [out] Time thread spent in user mode */
624 if (creationtime
|| exittime
)
626 /* We need to do a server call to get the creation time or exit time */
627 /* This works on any thread */
629 SERVER_START_REQ( get_thread_info
)
631 req
->handle
= thread
;
633 if ((ret
= !wine_server_call_err( req
)))
636 RtlSecondsSince1970ToTime( reply
->creation_time
, (LARGE_INTEGER
*)creationtime
);
638 RtlSecondsSince1970ToTime( reply
->exit_time
, (LARGE_INTEGER
*)exittime
);
643 if (ret
&& (kerneltime
|| usertime
))
645 /* We call times(2) for kernel time or user time */
646 /* We can only (portably) do this for the current thread */
647 if (thread
== GetCurrentThread())
651 long clocks_per_sec
= sysconf(_SC_CLK_TCK
);
656 time
= (ULONGLONG
)time_buf
.tms_stime
* 10000000 / clocks_per_sec
;
657 kerneltime
->dwHighDateTime
= time
>> 32;
658 kerneltime
->dwLowDateTime
= (DWORD
)time
;
662 time
= (ULONGLONG
)time_buf
.tms_utime
* 10000000 / clocks_per_sec
;
663 usertime
->dwHighDateTime
= time
>> 32;
664 usertime
->dwLowDateTime
= (DWORD
)time
;
669 if (kerneltime
) kerneltime
->dwHighDateTime
= kerneltime
->dwLowDateTime
= 0;
670 if (usertime
) usertime
->dwHighDateTime
= usertime
->dwLowDateTime
= 0;
671 FIXME("Cannot get kerneltime or usertime of other threads\n");
678 /**********************************************************************
679 * VWin32_BoostThreadGroup [KERNEL.535]
681 VOID WINAPI
VWin32_BoostThreadGroup( DWORD threadId
, INT boost
)
683 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
686 /**********************************************************************
687 * VWin32_BoostThreadStatic [KERNEL.536]
689 VOID WINAPI
VWin32_BoostThreadStatic( DWORD threadId
, INT boost
)
691 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
695 /***********************************************************************
696 * GetCurrentThread [KERNEL32.@] Gets pseudohandle for current thread
699 * Pseudohandle for the current thread
701 #undef GetCurrentThread
702 HANDLE WINAPI
GetCurrentThread(void)
704 return (HANDLE
)0xfffffffe;
708 /***********************************************************************
709 * ProcessIdToSessionId (KERNEL32.@)
710 * This function is available on Terminal Server 4SP4 and Windows 2000
712 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
714 /* According to MSDN, if the calling process is not in a terminal
715 * services environment, then the sessionid returned is zero.
721 /***********************************************************************
722 * SetThreadExecutionState (KERNEL32.@)
724 * Informs the system that activity is taking place for
725 * power management purposes.
727 EXECUTION_STATE WINAPI
SetThreadExecutionState(EXECUTION_STATE flags
)
729 static EXECUTION_STATE current
=
730 ES_SYSTEM_REQUIRED
|ES_DISPLAY_REQUIRED
|ES_USER_PRESENT
;
731 EXECUTION_STATE old
= current
;
733 if (!(current
& ES_CONTINUOUS
) || (flags
& ES_CONTINUOUS
))
735 FIXME("(0x%lx): stub, harmless (power management).\n", flags
);
742 /***********************************************************************
743 * SetLastError (KERNEL.147)
744 * SetLastError (KERNEL32.@)
746 /* void WINAPI SetLastError( DWORD error ); */
747 __ASM_GLOBAL_FUNC( SetLastError
,
748 "movl 4(%esp),%eax\n\t"
753 /***********************************************************************
754 * GetLastError (KERNEL.148)
755 * GetLastError (KERNEL32.@)
757 /* DWORD WINAPI GetLastError(void); */
758 __ASM_GLOBAL_FUNC( GetLastError
, ".byte 0x64\n\tmovl 0x60,%eax\n\tret" );
760 /***********************************************************************
761 * GetCurrentProcessId (KERNEL.471)
762 * GetCurrentProcessId (KERNEL32.@)
764 /* DWORD WINAPI GetCurrentProcessId(void) */
765 __ASM_GLOBAL_FUNC( GetCurrentProcessId
, ".byte 0x64\n\tmovl 0x20,%eax\n\tret" );
767 /***********************************************************************
768 * GetCurrentThreadId (KERNEL.462)
769 * GetCurrentThreadId (KERNEL32.@)
771 /* DWORD WINAPI GetCurrentThreadId(void) */
772 __ASM_GLOBAL_FUNC( GetCurrentThreadId
, ".byte 0x64\n\tmovl 0x24,%eax\n\tret" );
776 /**********************************************************************
777 * SetLastError (KERNEL.147)
778 * SetLastError (KERNEL32.@)
780 * Sets the last-error code.
782 void WINAPI
SetLastError( DWORD error
) /* [in] Per-thread error code */
784 NtCurrentTeb()->last_error
= error
;
787 /**********************************************************************
788 * GetLastError (KERNEL.148)
789 * GetLastError (KERNEL32.@)
791 * Returns last-error code.
793 DWORD WINAPI
GetLastError(void)
795 return NtCurrentTeb()->last_error
;
798 /***********************************************************************
799 * GetCurrentProcessId (KERNEL.471)
800 * GetCurrentProcessId (KERNEL32.@)
802 * Returns process identifier.
804 DWORD WINAPI
GetCurrentProcessId(void)
806 return (DWORD
)NtCurrentTeb()->pid
;
809 /***********************************************************************
810 * GetCurrentThreadId (KERNEL.462)
811 * GetCurrentThreadId (KERNEL32.@)
813 * Returns thread identifier.
815 DWORD WINAPI
GetCurrentThreadId(void)
817 return NtCurrentTeb()->tid
;
820 #endif /* __i386__ */