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"
28 #include <sys/types.h>
29 #ifdef HAVE_SYS_TIMES_H
30 #include <sys/times.h>
43 #include "wine/winbase16.h"
44 #include "wine/exception.h"
45 #include "wine/library.h"
46 #include "wine/pthread.h"
47 #include "wine/server.h"
48 #include "wine/debug.h"
50 WINE_DEFAULT_DEBUG_CHANNEL(thread);
51 WINE_DECLARE_DEBUG_CHANNEL(relay);
54 /***********************************************************************
57 * Allocate the stack of a thread.
59 TEB *THREAD_InitStack( TEB *teb, DWORD stack_size )
62 DWORD page_size = getpagesize();
65 stack_size = (stack_size + (page_size - 1)) & ~(page_size - 1);
66 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
68 if (!(base = VirtualAlloc( NULL, stack_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE )))
71 teb->DeallocationStack = base;
72 teb->Tib.StackBase = (char *)base + stack_size;
73 teb->Tib.StackLimit = base; /* note: limit is lower than base since the stack grows down */
75 /* Setup guard pages */
77 VirtualProtect( base, 1, PAGE_EXECUTE_READWRITE | PAGE_GUARD, &old_prot );
82 struct new_thread_info
84 LPTHREAD_START_ROUTINE func;
88 /***********************************************************************
91 * Start execution of a newly created thread. Does not return.
93 static void CALLBACK THREAD_Start( void *ptr )
95 struct new_thread_info *info = ptr;
96 LPTHREAD_START_ROUTINE func = info->func;
97 void *arg = info->arg;
99 RtlFreeHeap( GetProcessHeap(), 0, info );
102 DPRINTF("%04lx:Starting thread (entryproc=%p)\n", GetCurrentThreadId(), func );
106 MODULE_DllThreadAttach( NULL );
107 ExitThread( func( arg ) );
109 __EXCEPT(UnhandledExceptionFilter)
111 TerminateThread( GetCurrentThread(), GetExceptionCode() );
117 /***********************************************************************
118 * CreateThread (KERNEL32.@)
120 HANDLE WINAPI CreateThread( SECURITY_ATTRIBUTES *sa, SIZE_T stack,
121 LPTHREAD_START_ROUTINE start, LPVOID param,
122 DWORD flags, LPDWORD id )
124 return CreateRemoteThread( GetCurrentProcess(),
125 sa, stack, start, param, flags, id );
129 /***************************************************************************
130 * CreateRemoteThread (KERNEL32.@)
132 * Creates a thread that runs in the address space of another process
137 * Success: Handle to the new thread.
138 * Failure: NULL. Use GetLastError() to find the error cause.
141 * Improper memory allocation: there's no ability to free new_thread_info
143 * Bad start address for RtlCreateUserThread because the library
144 * may be loaded at different address in other process.
146 HANDLE WINAPI CreateRemoteThread( HANDLE hProcess, SECURITY_ATTRIBUTES *sa, SIZE_T stack,
147 LPTHREAD_START_ROUTINE start, LPVOID param,
148 DWORD flags, LPDWORD id )
153 SIZE_T stack_reserve = 0, stack_commit = 0;
154 struct new_thread_info *info;
156 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
158 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
164 if (flags & STACK_SIZE_PARAM_IS_A_RESERVATION) stack_reserve = stack;
165 else stack_commit = stack;
167 status = RtlCreateUserThread( hProcess, NULL, TRUE,
168 NULL, stack_reserve, stack_commit,
169 THREAD_Start, info, &handle, &client_id );
170 if (status == STATUS_SUCCESS)
172 if (id) *id = (DWORD)client_id.UniqueThread;
173 if (sa && (sa->nLength >= sizeof(*sa)) && sa->bInheritHandle)
174 SetHandleInformation( handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT );
175 if (!(flags & CREATE_SUSPENDED))
178 if (NtResumeThread( handle, &ret ))
181 RtlFreeHeap( GetProcessHeap(), 0, info );
182 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
189 RtlFreeHeap( GetProcessHeap(), 0, info );
190 SetLastError( RtlNtStatusToDosError(status) );
197 /***********************************************************************
198 * OpenThread [KERNEL32.@] Retrieves a handle to a thread from its thread id
200 HANDLE WINAPI OpenThread( DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId )
203 SERVER_START_REQ( open_thread )
205 req->tid = dwThreadId;
206 req->access = dwDesiredAccess;
207 req->inherit = bInheritHandle;
208 if (!wine_server_call_err( req )) ret = reply->handle;
215 /***********************************************************************
216 * ExitThread [KERNEL32.@] Ends a thread
221 void WINAPI ExitThread( DWORD code ) /* [in] Exit code for this thread */
224 SERVER_START_REQ( terminate_thread )
226 /* send the exit code to the server */
227 req->handle = GetCurrentThread();
228 req->exit_code = code;
229 wine_server_call( req );
236 LdrShutdownProcess();
241 struct wine_pthread_thread_info info;
247 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
250 info.stack_base = NtCurrentTeb()->DeallocationStack;
251 info.teb_base = NtCurrentTeb();
252 info.teb_sel = wine_get_fs();
253 info.exit_status = code;
256 NtFreeVirtualMemory( GetCurrentProcess(), &info.stack_base, &size, MEM_RELEASE | MEM_SYSTEM );
257 info.stack_size = size;
260 NtFreeVirtualMemory( GetCurrentProcess(), &info.teb_base, &size, MEM_RELEASE | MEM_SYSTEM );
261 info.teb_size = size;
263 /* block the async signals */
264 sigemptyset( &block_set );
265 sigaddset( &block_set, SIGALRM );
266 sigaddset( &block_set, SIGIO );
267 sigaddset( &block_set, SIGINT );
268 sigaddset( &block_set, SIGHUP );
269 sigaddset( &block_set, SIGUSR1 );
270 sigaddset( &block_set, SIGUSR2 );
271 sigaddset( &block_set, SIGTERM );
272 sigprocmask( SIG_BLOCK, &block_set, NULL );
274 close( NtCurrentTeb()->wait_fd[0] );
275 close( NtCurrentTeb()->wait_fd[1] );
276 close( NtCurrentTeb()->reply_fd );
277 close( NtCurrentTeb()->request_fd );
279 wine_pthread_exit_thread( &info );
284 /**********************************************************************
285 * TerminateThread [KERNEL32.@] Terminates a thread
291 BOOL WINAPI TerminateThread( HANDLE handle, /* [in] Handle to thread */
292 DWORD exit_code) /* [in] Exit code for thread */
294 NTSTATUS status = NtTerminateThread( handle, exit_code );
295 if (status) SetLastError( RtlNtStatusToDosError(status) );
300 /***********************************************************************
301 * FreeLibraryAndExitThread (KERNEL32.@)
303 void WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
305 FreeLibrary(hLibModule);
306 ExitThread(dwExitCode);
310 /**********************************************************************
311 * GetExitCodeThread (KERNEL32.@)
313 * Gets termination status of thread.
319 BOOL WINAPI GetExitCodeThread(
320 HANDLE hthread, /* [in] Handle to thread */
321 LPDWORD exitcode) /* [out] Address to receive termination status */
323 THREAD_BASIC_INFORMATION info;
324 NTSTATUS status = NtQueryInformationThread( hthread, ThreadBasicInformation,
325 &info, sizeof(info), NULL );
329 SetLastError( RtlNtStatusToDosError(status) );
332 if (exitcode) *exitcode = info.ExitStatus;
337 /***********************************************************************
338 * SetThreadContext [KERNEL32.@] Sets context of thread.
344 BOOL WINAPI SetThreadContext( HANDLE handle, /* [in] Handle to thread with context */
345 const CONTEXT *context ) /* [in] Address of context structure */
347 NTSTATUS status = NtSetContextThread( handle, context );
348 if (status) SetLastError( RtlNtStatusToDosError(status) );
353 /***********************************************************************
354 * GetThreadContext [KERNEL32.@] Retrieves context of thread.
360 BOOL WINAPI GetThreadContext( HANDLE handle, /* [in] Handle to thread with context */
361 CONTEXT *context ) /* [out] Address of context structure */
363 NTSTATUS status = NtGetContextThread( handle, context );
364 if (status) SetLastError( RtlNtStatusToDosError(status) );
369 /**********************************************************************
370 * SuspendThread [KERNEL32.@] Suspends a thread.
373 * Success: Previous suspend count
374 * Failure: 0xFFFFFFFF
376 DWORD WINAPI SuspendThread( HANDLE hthread ) /* [in] Handle to the thread */
379 NTSTATUS status = NtSuspendThread( hthread, &ret );
384 SetLastError( RtlNtStatusToDosError(status) );
390 /**********************************************************************
391 * ResumeThread [KERNEL32.@] Resumes a thread.
393 * Decrements a thread's suspend count. When count is zero, the
394 * execution of the thread is resumed.
397 * Success: Previous suspend count
398 * Failure: 0xFFFFFFFF
401 DWORD WINAPI ResumeThread( HANDLE hthread ) /* [in] Identifies thread to restart */
404 NTSTATUS status = NtResumeThread( hthread, &ret );
409 SetLastError( RtlNtStatusToDosError(status) );
415 /**********************************************************************
416 * GetThreadPriority [KERNEL32.@] Returns priority for thread.
419 * Success: Thread's priority level.
420 * Failure: THREAD_PRIORITY_ERROR_RETURN
422 INT WINAPI GetThreadPriority(
423 HANDLE hthread) /* [in] Handle to thread */
425 THREAD_BASIC_INFORMATION info;
426 NTSTATUS status = NtQueryInformationThread( hthread, ThreadBasicInformation,
427 &info, sizeof(info), NULL );
431 SetLastError( RtlNtStatusToDosError(status) );
432 return THREAD_PRIORITY_ERROR_RETURN;
434 return info.Priority;
438 /**********************************************************************
439 * SetThreadPriority [KERNEL32.@] Sets priority for thread.
445 BOOL WINAPI SetThreadPriority(
446 HANDLE hthread, /* [in] Handle to thread */
447 INT priority) /* [in] Thread priority level */
450 SERVER_START_REQ( set_thread_info )
452 req->handle = hthread;
453 req->priority = priority;
454 req->mask = SET_THREAD_INFO_PRIORITY;
455 ret = !wine_server_call_err( req );
462 /**********************************************************************
463 * GetThreadPriorityBoost [KERNEL32.@] Returns priority boost for thread.
465 * Always reports that priority boost is disabled.
471 BOOL WINAPI GetThreadPriorityBoost(
472 HANDLE hthread, /* [in] Handle to thread */
473 PBOOL pstate) /* [out] pointer to var that receives the boost state */
475 if (pstate) *pstate = FALSE;
480 /**********************************************************************
481 * SetThreadPriorityBoost [KERNEL32.@] Sets priority boost for thread.
483 * Priority boost is not implemented. Thsi function always returns
484 * FALSE and sets last error to ERROR_CALL_NOT_IMPLEMENTED
487 * Always returns FALSE to indicate a failure
489 BOOL WINAPI SetThreadPriorityBoost(
490 HANDLE hthread, /* [in] Handle to thread */
491 BOOL disable) /* [in] TRUE to disable priority boost */
493 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
498 /**********************************************************************
499 * SetThreadAffinityMask (KERNEL32.@)
501 DWORD WINAPI SetThreadAffinityMask( HANDLE hThread, DWORD dwThreadAffinityMask )
504 SERVER_START_REQ( set_thread_info )
506 req->handle = hThread;
507 req->affinity = dwThreadAffinityMask;
508 req->mask = SET_THREAD_INFO_AFFINITY;
509 ret = !wine_server_call_err( req );
510 /* FIXME: should return previous value */
517 /**********************************************************************
518 * SetThreadIdealProcessor [KERNEL32.@] Obtains timing information.
521 * Success: Value of last call to SetThreadIdealProcessor
524 DWORD WINAPI SetThreadIdealProcessor(
525 HANDLE hThread, /* [in] Specifies the thread of interest */
526 DWORD dwIdealProcessor) /* [in] Specifies the new preferred processor */
528 FIXME("(%p): stub\n",hThread);
529 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
534 /* callback for QueueUserAPC */
535 static void CALLBACK call_user_apc( ULONG_PTR arg1, ULONG_PTR arg2, ULONG_PTR arg3 )
537 PAPCFUNC func = (PAPCFUNC)arg1;
541 /***********************************************************************
542 * QueueUserAPC (KERNEL32.@)
544 DWORD WINAPI QueueUserAPC( PAPCFUNC func, HANDLE hthread, ULONG_PTR data )
546 NTSTATUS status = NtQueueApcThread( hthread, call_user_apc, (ULONG_PTR)func, data, 0 );
548 if (status) SetLastError( RtlNtStatusToDosError(status) );
552 /***********************************************************************
553 * QueueUserWorkItem (KERNEL32.@)
555 BOOL WINAPI QueueUserWorkItem( LPTHREAD_START_ROUTINE Function, PVOID Context, ULONG Flags )
557 FIXME("(%p,%p,0x%08lx): stub\n", Function, Context, Flags);
561 /**********************************************************************
562 * GetThreadTimes [KERNEL32.@] Obtains timing information.
568 BOOL WINAPI GetThreadTimes(
569 HANDLE thread, /* [in] Specifies the thread of interest */
570 LPFILETIME creationtime, /* [out] When the thread was created */
571 LPFILETIME exittime, /* [out] When the thread was destroyed */
572 LPFILETIME kerneltime, /* [out] Time thread spent in kernel mode */
573 LPFILETIME usertime) /* [out] Time thread spent in user mode */
577 if (creationtime || exittime)
579 /* We need to do a server call to get the creation time or exit time */
580 /* This works on any thread */
582 SERVER_START_REQ( get_thread_info )
584 req->handle = thread;
586 if ((ret = !wine_server_call_err( req )))
589 RtlSecondsSince1970ToTime( reply->creation_time, (LARGE_INTEGER*)creationtime );
591 RtlSecondsSince1970ToTime( reply->exit_time, (LARGE_INTEGER*)exittime );
596 if (ret && (kerneltime || usertime))
598 /* We call times(2) for kernel time or user time */
599 /* We can only (portably) do this for the current thread */
600 if (thread == GetCurrentThread())
604 long clocks_per_sec = sysconf(_SC_CLK_TCK);
609 time = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
610 kerneltime->dwHighDateTime = time >> 32;
611 kerneltime->dwLowDateTime = (DWORD)time;
615 time = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
616 usertime->dwHighDateTime = time >> 32;
617 usertime->dwLowDateTime = (DWORD)time;
622 if (kerneltime) kerneltime->dwHighDateTime = kerneltime->dwLowDateTime = 0;
623 if (usertime) usertime->dwHighDateTime = usertime->dwLowDateTime = 0;
624 FIXME("Cannot get kerneltime or usertime of other threads\n");
631 /**********************************************************************
632 * VWin32_BoostThreadGroup [KERNEL.535]
634 VOID WINAPI VWin32_BoostThreadGroup( DWORD threadId, INT boost )
636 FIXME("(0x%08lx,%d): stub\n", threadId, boost);
640 /**********************************************************************
641 * VWin32_BoostThreadStatic [KERNEL.536]
643 VOID WINAPI VWin32_BoostThreadStatic( DWORD threadId, INT boost )
645 FIXME("(0x%08lx,%d): stub\n", threadId, boost);
649 /***********************************************************************
650 * GetCurrentThread [KERNEL32.@] Gets pseudohandle for current thread
653 * Pseudohandle for the current thread
655 #undef GetCurrentThread
656 HANDLE WINAPI GetCurrentThread(void)
658 return (HANDLE)0xfffffffe;
664 /***********************************************************************
665 * SetLastError (KERNEL.147)
666 * SetLastError (KERNEL32.@)
668 /* void WINAPI SetLastError( DWORD error ); */
669 __ASM_GLOBAL_FUNC( SetLastError,
670 "movl 4(%esp),%eax\n\t"
675 /***********************************************************************
676 * GetLastError (KERNEL.148)
677 * GetLastError (KERNEL32.@)
679 /* DWORD WINAPI GetLastError(void); */
680 __ASM_GLOBAL_FUNC( GetLastError, ".byte 0x64\n\tmovl 0x34,%eax\n\tret" )
682 /***********************************************************************
683 * GetCurrentProcessId (KERNEL.471)
684 * GetCurrentProcessId (KERNEL32.@)
686 /* DWORD WINAPI GetCurrentProcessId(void) */
687 __ASM_GLOBAL_FUNC( GetCurrentProcessId, ".byte 0x64\n\tmovl 0x20,%eax\n\tret" )
689 /***********************************************************************
690 * GetCurrentThreadId (KERNEL.462)
691 * GetCurrentThreadId (KERNEL32.@)
693 /* DWORD WINAPI GetCurrentThreadId(void) */
694 __ASM_GLOBAL_FUNC( GetCurrentThreadId, ".byte 0x64\n\tmovl 0x24,%eax\n\tret" )
698 /**********************************************************************
699 * SetLastError (KERNEL.147)
700 * SetLastError (KERNEL32.@)
702 * Sets the last-error code.
704 void WINAPI SetLastError( DWORD error ) /* [in] Per-thread error code */
706 NtCurrentTeb()->LastErrorValue = error;
709 /**********************************************************************
710 * GetLastError (KERNEL.148)
711 * GetLastError (KERNEL32.@)
713 * Returns last-error code.
715 DWORD WINAPI GetLastError(void)
717 return NtCurrentTeb()->LastErrorValue;
720 /***********************************************************************
721 * GetCurrentProcessId (KERNEL.471)
722 * GetCurrentProcessId (KERNEL32.@)
724 * Returns process identifier.
726 DWORD WINAPI GetCurrentProcessId(void)
728 return (DWORD)NtCurrentTeb()->ClientId.UniqueProcess;
731 /***********************************************************************
732 * GetCurrentThreadId (KERNEL.462)
733 * GetCurrentThreadId (KERNEL32.@)
735 * Returns thread identifier.
737 DWORD WINAPI GetCurrentThreadId(void)
739 return (DWORD)NtCurrentTeb()->ClientId.UniqueThread;
742 #endif /* __i386__ */