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"
27 #include <sys/types.h>
28 #ifdef HAVE_SYS_TIMES_H
29 #include <sys/times.h>
42 #include "wine/winbase16.h"
43 #include "wine/exception.h"
44 #include "wine/library.h"
45 #include "wine/pthread.h"
46 #include "wine/server.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(thread);
50 WINE_DECLARE_DEBUG_CHANNEL(relay);
53 /***********************************************************************
56 * Allocate the stack of a thread.
58 TEB *THREAD_InitStack( TEB *teb, DWORD stack_size )
61 DWORD page_size = getpagesize();
64 stack_size = (stack_size + (page_size - 1)) & ~(page_size - 1);
65 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
67 if (!(base = VirtualAlloc( NULL, stack_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE )))
70 teb->DeallocationStack = base;
71 teb->Tib.StackBase = (char *)base + stack_size;
72 teb->Tib.StackLimit = base; /* note: limit is lower than base since the stack grows down */
74 /* Setup guard pages */
76 VirtualProtect( base, 1, PAGE_EXECUTE_READWRITE | PAGE_GUARD, &old_prot );
81 struct new_thread_info
83 LPTHREAD_START_ROUTINE func;
87 /***********************************************************************
90 * Start execution of a newly created thread. Does not return.
92 static void CALLBACK THREAD_Start( void *ptr )
94 struct new_thread_info *info = ptr;
95 LPTHREAD_START_ROUTINE func = info->func;
96 void *arg = info->arg;
98 RtlFreeHeap( GetProcessHeap(), 0, info );
101 DPRINTF("%04lx:Starting thread (entryproc=%p)\n", GetCurrentThreadId(), func );
105 MODULE_DllThreadAttach( NULL );
106 ExitThread( func( arg ) );
108 __EXCEPT(UnhandledExceptionFilter)
110 TerminateThread( GetCurrentThread(), GetExceptionCode() );
116 /***********************************************************************
117 * CreateThread (KERNEL32.@)
119 HANDLE WINAPI CreateThread( SECURITY_ATTRIBUTES *sa, SIZE_T stack,
120 LPTHREAD_START_ROUTINE start, LPVOID param,
121 DWORD flags, LPDWORD id )
123 return CreateRemoteThread( GetCurrentProcess(),
124 sa, stack, start, param, flags, id );
128 /***************************************************************************
129 * CreateRemoteThread (KERNEL32.@)
131 * Creates a thread that runs in the address space of another process
136 * Success: Handle to the new thread.
137 * Failure: NULL. Use GetLastError() to find the error cause.
140 * Improper memory allocation: there's no ability to free new_thread_info
142 * Bad start address for RtlCreateUserThread because the library
143 * may be loaded at different address in other process.
145 HANDLE WINAPI CreateRemoteThread( HANDLE hProcess, SECURITY_ATTRIBUTES *sa, SIZE_T stack,
146 LPTHREAD_START_ROUTINE start, LPVOID param,
147 DWORD flags, LPDWORD id )
152 SIZE_T stack_reserve = 0, stack_commit = 0;
153 struct new_thread_info *info;
155 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
157 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
163 if (flags & STACK_SIZE_PARAM_IS_A_RESERVATION) stack_reserve = stack;
164 else stack_commit = stack;
166 status = RtlCreateUserThread( hProcess, NULL, TRUE,
167 NULL, stack_reserve, stack_commit,
168 THREAD_Start, info, &handle, &client_id );
169 if (status == STATUS_SUCCESS)
171 if (id) *id = (DWORD)client_id.UniqueThread;
172 if (sa && (sa->nLength >= sizeof(*sa)) && sa->bInheritHandle)
173 SetHandleInformation( handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT );
174 if (!(flags & CREATE_SUSPENDED))
177 if (NtResumeThread( handle, &ret ))
180 RtlFreeHeap( GetProcessHeap(), 0, info );
181 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
188 RtlFreeHeap( GetProcessHeap(), 0, info );
189 SetLastError( RtlNtStatusToDosError(status) );
196 /***********************************************************************
197 * OpenThread [KERNEL32.@] Retrieves a handle to a thread from its thread id
199 HANDLE WINAPI OpenThread( DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId )
202 SERVER_START_REQ( open_thread )
204 req->tid = dwThreadId;
205 req->access = dwDesiredAccess;
206 req->inherit = bInheritHandle;
207 if (!wine_server_call_err( req )) ret = reply->handle;
214 /***********************************************************************
215 * ExitThread [KERNEL32.@] Ends a thread
220 void WINAPI ExitThread( DWORD code ) /* [in] Exit code for this thread */
223 SERVER_START_REQ( terminate_thread )
225 /* send the exit code to the server */
226 req->handle = GetCurrentThread();
227 req->exit_code = code;
228 wine_server_call( req );
235 LdrShutdownProcess();
241 wine_server_exit_thread( code );
246 /**********************************************************************
247 * TerminateThread [KERNEL32.@] Terminates a thread
253 BOOL WINAPI TerminateThread( HANDLE handle, /* [in] Handle to thread */
254 DWORD exit_code) /* [in] Exit code for thread */
256 NTSTATUS status = NtTerminateThread( handle, exit_code );
257 if (status) SetLastError( RtlNtStatusToDosError(status) );
262 /***********************************************************************
263 * FreeLibraryAndExitThread (KERNEL32.@)
265 void WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
267 FreeLibrary(hLibModule);
268 ExitThread(dwExitCode);
272 /**********************************************************************
273 * GetExitCodeThread (KERNEL32.@)
275 * Gets termination status of thread.
281 BOOL WINAPI GetExitCodeThread(
282 HANDLE hthread, /* [in] Handle to thread */
283 LPDWORD exitcode) /* [out] Address to receive termination status */
285 THREAD_BASIC_INFORMATION info;
286 NTSTATUS status = NtQueryInformationThread( hthread, ThreadBasicInformation,
287 &info, sizeof(info), NULL );
291 SetLastError( RtlNtStatusToDosError(status) );
294 if (exitcode) *exitcode = info.ExitStatus;
299 /***********************************************************************
300 * SetThreadContext [KERNEL32.@] Sets context of thread.
306 BOOL WINAPI SetThreadContext( HANDLE handle, /* [in] Handle to thread with context */
307 const CONTEXT *context ) /* [in] Address of context structure */
309 NTSTATUS status = NtSetContextThread( handle, context );
310 if (status) SetLastError( RtlNtStatusToDosError(status) );
315 /***********************************************************************
316 * GetThreadContext [KERNEL32.@] Retrieves context of thread.
322 BOOL WINAPI GetThreadContext( HANDLE handle, /* [in] Handle to thread with context */
323 CONTEXT *context ) /* [out] Address of context structure */
325 NTSTATUS status = NtGetContextThread( handle, context );
326 if (status) SetLastError( RtlNtStatusToDosError(status) );
331 /**********************************************************************
332 * SuspendThread [KERNEL32.@] Suspends a thread.
335 * Success: Previous suspend count
336 * Failure: 0xFFFFFFFF
338 DWORD WINAPI SuspendThread( HANDLE hthread ) /* [in] Handle to the thread */
341 NTSTATUS status = NtSuspendThread( hthread, &ret );
346 SetLastError( RtlNtStatusToDosError(status) );
352 /**********************************************************************
353 * ResumeThread [KERNEL32.@] Resumes a thread.
355 * Decrements a thread's suspend count. When count is zero, the
356 * execution of the thread is resumed.
359 * Success: Previous suspend count
360 * Failure: 0xFFFFFFFF
363 DWORD WINAPI ResumeThread( HANDLE hthread ) /* [in] Identifies thread to restart */
366 NTSTATUS status = NtResumeThread( hthread, &ret );
371 SetLastError( RtlNtStatusToDosError(status) );
377 /**********************************************************************
378 * GetThreadPriority [KERNEL32.@] Returns priority for thread.
381 * Success: Thread's priority level.
382 * Failure: THREAD_PRIORITY_ERROR_RETURN
384 INT WINAPI GetThreadPriority(
385 HANDLE hthread) /* [in] Handle to thread */
387 THREAD_BASIC_INFORMATION info;
388 NTSTATUS status = NtQueryInformationThread( hthread, ThreadBasicInformation,
389 &info, sizeof(info), NULL );
393 SetLastError( RtlNtStatusToDosError(status) );
394 return THREAD_PRIORITY_ERROR_RETURN;
396 return info.Priority;
400 /**********************************************************************
401 * SetThreadPriority [KERNEL32.@] Sets priority for thread.
407 BOOL WINAPI SetThreadPriority(
408 HANDLE hthread, /* [in] Handle to thread */
409 INT priority) /* [in] Thread priority level */
412 SERVER_START_REQ( set_thread_info )
414 req->handle = hthread;
415 req->priority = priority;
416 req->mask = SET_THREAD_INFO_PRIORITY;
417 ret = !wine_server_call_err( req );
424 /**********************************************************************
425 * GetThreadPriorityBoost [KERNEL32.@] Returns priority boost for thread.
427 * Always reports that priority boost is disabled.
433 BOOL WINAPI GetThreadPriorityBoost(
434 HANDLE hthread, /* [in] Handle to thread */
435 PBOOL pstate) /* [out] pointer to var that receives the boost state */
437 if (pstate) *pstate = FALSE;
442 /**********************************************************************
443 * SetThreadPriorityBoost [KERNEL32.@] Sets priority boost for thread.
445 * Priority boost is not implemented. Thsi function always returns
446 * FALSE and sets last error to ERROR_CALL_NOT_IMPLEMENTED
449 * Always returns FALSE to indicate a failure
451 BOOL WINAPI SetThreadPriorityBoost(
452 HANDLE hthread, /* [in] Handle to thread */
453 BOOL disable) /* [in] TRUE to disable priority boost */
455 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
460 /**********************************************************************
461 * SetThreadAffinityMask (KERNEL32.@)
463 DWORD WINAPI SetThreadAffinityMask( HANDLE hThread, DWORD dwThreadAffinityMask )
466 SERVER_START_REQ( set_thread_info )
468 req->handle = hThread;
469 req->affinity = dwThreadAffinityMask;
470 req->mask = SET_THREAD_INFO_AFFINITY;
471 ret = !wine_server_call_err( req );
472 /* FIXME: should return previous value */
479 /**********************************************************************
480 * SetThreadIdealProcessor [KERNEL32.@] Obtains timing information.
483 * Success: Value of last call to SetThreadIdealProcessor
486 DWORD WINAPI SetThreadIdealProcessor(
487 HANDLE hThread, /* [in] Specifies the thread of interest */
488 DWORD dwIdealProcessor) /* [in] Specifies the new preferred processor */
490 FIXME("(%p): stub\n",hThread);
491 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
496 /* callback for QueueUserAPC */
497 static void CALLBACK call_user_apc( ULONG_PTR arg1, ULONG_PTR arg2, ULONG_PTR arg3 )
499 PAPCFUNC func = (PAPCFUNC)arg1;
503 /***********************************************************************
504 * QueueUserAPC (KERNEL32.@)
506 DWORD WINAPI QueueUserAPC( PAPCFUNC func, HANDLE hthread, ULONG_PTR data )
508 NTSTATUS status = NtQueueApcThread( hthread, call_user_apc, (ULONG_PTR)func, data, 0 );
510 if (status) SetLastError( RtlNtStatusToDosError(status) );
514 /***********************************************************************
515 * QueueUserWorkItem (KERNEL32.@)
517 BOOL WINAPI QueueUserWorkItem( LPTHREAD_START_ROUTINE Function, PVOID Context, ULONG Flags )
519 FIXME("(%p,%p,0x%08lx): stub\n", Function, Context, Flags);
523 /**********************************************************************
524 * GetThreadTimes [KERNEL32.@] Obtains timing information.
530 BOOL WINAPI GetThreadTimes(
531 HANDLE thread, /* [in] Specifies the thread of interest */
532 LPFILETIME creationtime, /* [out] When the thread was created */
533 LPFILETIME exittime, /* [out] When the thread was destroyed */
534 LPFILETIME kerneltime, /* [out] Time thread spent in kernel mode */
535 LPFILETIME usertime) /* [out] Time thread spent in user mode */
539 if (creationtime || exittime)
541 /* We need to do a server call to get the creation time or exit time */
542 /* This works on any thread */
544 SERVER_START_REQ( get_thread_info )
546 req->handle = thread;
548 if ((ret = !wine_server_call_err( req )))
551 RtlSecondsSince1970ToTime( reply->creation_time, (LARGE_INTEGER*)creationtime );
553 RtlSecondsSince1970ToTime( reply->exit_time, (LARGE_INTEGER*)exittime );
558 if (ret && (kerneltime || usertime))
560 /* We call times(2) for kernel time or user time */
561 /* We can only (portably) do this for the current thread */
562 if (thread == GetCurrentThread())
566 long clocks_per_sec = sysconf(_SC_CLK_TCK);
571 time = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
572 kerneltime->dwHighDateTime = time >> 32;
573 kerneltime->dwLowDateTime = (DWORD)time;
577 time = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
578 usertime->dwHighDateTime = time >> 32;
579 usertime->dwLowDateTime = (DWORD)time;
584 if (kerneltime) kerneltime->dwHighDateTime = kerneltime->dwLowDateTime = 0;
585 if (usertime) usertime->dwHighDateTime = usertime->dwLowDateTime = 0;
586 FIXME("Cannot get kerneltime or usertime of other threads\n");
593 /**********************************************************************
594 * VWin32_BoostThreadGroup [KERNEL.535]
596 VOID WINAPI VWin32_BoostThreadGroup( DWORD threadId, INT boost )
598 FIXME("(0x%08lx,%d): stub\n", threadId, boost);
602 /**********************************************************************
603 * VWin32_BoostThreadStatic [KERNEL.536]
605 VOID WINAPI VWin32_BoostThreadStatic( DWORD threadId, INT boost )
607 FIXME("(0x%08lx,%d): stub\n", threadId, boost);
611 /***********************************************************************
612 * GetCurrentThread [KERNEL32.@] Gets pseudohandle for current thread
615 * Pseudohandle for the current thread
617 #undef GetCurrentThread
618 HANDLE WINAPI GetCurrentThread(void)
620 return (HANDLE)0xfffffffe;
626 /***********************************************************************
627 * SetLastError (KERNEL.147)
628 * SetLastError (KERNEL32.@)
630 /* void WINAPI SetLastError( DWORD error ); */
631 __ASM_GLOBAL_FUNC( SetLastError,
632 "movl 4(%esp),%eax\n\t"
637 /***********************************************************************
638 * GetLastError (KERNEL.148)
639 * GetLastError (KERNEL32.@)
641 /* DWORD WINAPI GetLastError(void); */
642 __ASM_GLOBAL_FUNC( GetLastError, ".byte 0x64\n\tmovl 0x34,%eax\n\tret" )
644 /***********************************************************************
645 * GetCurrentProcessId (KERNEL.471)
646 * GetCurrentProcessId (KERNEL32.@)
648 /* DWORD WINAPI GetCurrentProcessId(void) */
649 __ASM_GLOBAL_FUNC( GetCurrentProcessId, ".byte 0x64\n\tmovl 0x20,%eax\n\tret" )
651 /***********************************************************************
652 * GetCurrentThreadId (KERNEL.462)
653 * GetCurrentThreadId (KERNEL32.@)
655 /* DWORD WINAPI GetCurrentThreadId(void) */
656 __ASM_GLOBAL_FUNC( GetCurrentThreadId, ".byte 0x64\n\tmovl 0x24,%eax\n\tret" )
660 /**********************************************************************
661 * SetLastError (KERNEL.147)
662 * SetLastError (KERNEL32.@)
664 * Sets the last-error code.
666 void WINAPI SetLastError( DWORD error ) /* [in] Per-thread error code */
668 NtCurrentTeb()->LastErrorValue = error;
671 /**********************************************************************
672 * GetLastError (KERNEL.148)
673 * GetLastError (KERNEL32.@)
675 * Returns last-error code.
677 DWORD WINAPI GetLastError(void)
679 return NtCurrentTeb()->LastErrorValue;
682 /***********************************************************************
683 * GetCurrentProcessId (KERNEL.471)
684 * GetCurrentProcessId (KERNEL32.@)
686 * Returns process identifier.
688 DWORD WINAPI GetCurrentProcessId(void)
690 return (DWORD)NtCurrentTeb()->ClientId.UniqueProcess;
693 /***********************************************************************
694 * GetCurrentThreadId (KERNEL.462)
695 * GetCurrentThreadId (KERNEL32.@)
697 * Returns thread identifier.
699 DWORD WINAPI GetCurrentThreadId(void)
701 return (DWORD)NtCurrentTeb()->ClientId.UniqueThread;
704 #endif /* __i386__ */