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 #include "kernel_private.h"
51 WINE_DEFAULT_DEBUG_CHANNEL(thread);
52 WINE_DECLARE_DEBUG_CHANNEL(relay);
55 /***********************************************************************
58 * Allocate the stack of a thread.
60 TEB *THREAD_InitStack( TEB *teb, DWORD stack_size )
63 DWORD page_size = getpagesize();
66 stack_size = (stack_size + (page_size - 1)) & ~(page_size - 1);
67 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
69 if (!(base = VirtualAlloc( NULL, stack_size, MEM_COMMIT, PAGE_READWRITE )))
72 teb->DeallocationStack = base;
73 teb->Tib.StackBase = (char *)base + stack_size;
74 teb->Tib.StackLimit = base; /* note: limit is lower than base since the stack grows down */
76 /* Setup guard pages */
78 VirtualProtect( base, 1, PAGE_READWRITE | PAGE_GUARD, &old_prot );
83 struct new_thread_info
85 LPTHREAD_START_ROUTINE func;
89 /***********************************************************************
92 * Start execution of a newly created thread. Does not return.
94 static void CALLBACK THREAD_Start( void *ptr )
96 struct new_thread_info *info = ptr;
97 LPTHREAD_START_ROUTINE func = info->func;
98 void *arg = info->arg;
100 RtlFreeHeap( GetProcessHeap(), 0, info );
103 DPRINTF("%04lx:Starting thread (entryproc=%p)\n", GetCurrentThreadId(), func );
107 MODULE_DllThreadAttach( NULL );
108 ExitThread( func( arg ) );
110 __EXCEPT(UnhandledExceptionFilter)
112 TerminateThread( GetCurrentThread(), GetExceptionCode() );
118 /***********************************************************************
119 * CreateThread (KERNEL32.@)
121 HANDLE WINAPI CreateThread( SECURITY_ATTRIBUTES *sa, SIZE_T stack,
122 LPTHREAD_START_ROUTINE start, LPVOID param,
123 DWORD flags, LPDWORD id )
125 return CreateRemoteThread( GetCurrentProcess(),
126 sa, stack, start, param, flags, id );
130 /***************************************************************************
131 * CreateRemoteThread (KERNEL32.@)
133 * Creates a thread that runs in the address space of another process
138 * Success: Handle to the new thread.
139 * Failure: NULL. Use GetLastError() to find the error cause.
142 * Improper memory allocation: there's no ability to free new_thread_info
144 * Bad start address for RtlCreateUserThread because the library
145 * may be loaded at different address in other process.
147 HANDLE WINAPI CreateRemoteThread( HANDLE hProcess, SECURITY_ATTRIBUTES *sa, SIZE_T stack,
148 LPTHREAD_START_ROUTINE start, LPVOID param,
149 DWORD flags, LPDWORD id )
154 SIZE_T stack_reserve = 0, stack_commit = 0;
155 struct new_thread_info *info;
157 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
159 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
165 if (flags & STACK_SIZE_PARAM_IS_A_RESERVATION) stack_reserve = stack;
166 else stack_commit = stack;
168 status = RtlCreateUserThread( hProcess, NULL, TRUE,
169 NULL, stack_reserve, stack_commit,
170 THREAD_Start, info, &handle, &client_id );
171 if (status == STATUS_SUCCESS)
173 if (id) *id = (DWORD)client_id.UniqueThread;
174 if (sa && (sa->nLength >= sizeof(*sa)) && sa->bInheritHandle)
175 SetHandleInformation( handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT );
176 if (!(flags & CREATE_SUSPENDED))
179 if (NtResumeThread( handle, &ret ))
182 RtlFreeHeap( GetProcessHeap(), 0, info );
183 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
190 RtlFreeHeap( GetProcessHeap(), 0, info );
191 SetLastError( RtlNtStatusToDosError(status) );
198 /***********************************************************************
199 * OpenThread [KERNEL32.@] Retrieves a handle to a thread from its thread id
201 HANDLE WINAPI OpenThread( DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId )
205 OBJECT_ATTRIBUTES attr;
208 attr.Length = sizeof(attr);
209 attr.RootDirectory = 0;
210 attr.Attributes = bInheritHandle ? OBJ_INHERIT : 0;
211 attr.ObjectName = NULL;
212 attr.SecurityDescriptor = NULL;
213 attr.SecurityQualityOfService = NULL;
215 cid.UniqueProcess = 0; /* FIXME */
216 cid.UniqueThread = (HANDLE)dwThreadId;
217 status = NtOpenThread( &handle, dwDesiredAccess, &attr, &cid );
220 SetLastError( RtlNtStatusToDosError(status) );
227 /***********************************************************************
228 * ExitThread [KERNEL32.@] Ends a thread
233 void WINAPI ExitThread( DWORD code ) /* [in] Exit code for this thread */
236 SERVER_START_REQ( terminate_thread )
238 /* send the exit code to the server */
239 req->handle = GetCurrentThread();
240 req->exit_code = code;
241 wine_server_call( req );
248 LdrShutdownProcess();
251 else RtlExitUserThread( code );
255 /**********************************************************************
256 * TerminateThread [KERNEL32.@] Terminates a thread
262 BOOL WINAPI TerminateThread( HANDLE handle, /* [in] Handle to thread */
263 DWORD exit_code) /* [in] Exit code for thread */
265 NTSTATUS status = NtTerminateThread( handle, exit_code );
266 if (status) SetLastError( RtlNtStatusToDosError(status) );
271 /***********************************************************************
272 * FreeLibraryAndExitThread (KERNEL32.@)
274 void WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
276 FreeLibrary(hLibModule);
277 ExitThread(dwExitCode);
281 /**********************************************************************
282 * GetExitCodeThread (KERNEL32.@)
284 * Gets termination status of thread.
290 BOOL WINAPI GetExitCodeThread(
291 HANDLE hthread, /* [in] Handle to thread */
292 LPDWORD exitcode) /* [out] Address to receive termination status */
294 THREAD_BASIC_INFORMATION info;
295 NTSTATUS status = NtQueryInformationThread( hthread, ThreadBasicInformation,
296 &info, sizeof(info), NULL );
300 SetLastError( RtlNtStatusToDosError(status) );
303 if (exitcode) *exitcode = info.ExitStatus;
308 /***********************************************************************
309 * SetThreadContext [KERNEL32.@] Sets context of thread.
315 BOOL WINAPI SetThreadContext( HANDLE handle, /* [in] Handle to thread with context */
316 const CONTEXT *context ) /* [in] Address of context structure */
318 NTSTATUS status = NtSetContextThread( handle, context );
319 if (status) SetLastError( RtlNtStatusToDosError(status) );
324 /***********************************************************************
325 * GetThreadContext [KERNEL32.@] Retrieves context of thread.
331 BOOL WINAPI GetThreadContext( HANDLE handle, /* [in] Handle to thread with context */
332 CONTEXT *context ) /* [out] Address of context structure */
334 NTSTATUS status = NtGetContextThread( handle, context );
335 if (status) SetLastError( RtlNtStatusToDosError(status) );
340 /**********************************************************************
341 * SuspendThread [KERNEL32.@] Suspends a thread.
344 * Success: Previous suspend count
345 * Failure: 0xFFFFFFFF
347 DWORD WINAPI SuspendThread( HANDLE hthread ) /* [in] Handle to the thread */
350 NTSTATUS status = NtSuspendThread( hthread, &ret );
355 SetLastError( RtlNtStatusToDosError(status) );
361 /**********************************************************************
362 * ResumeThread [KERNEL32.@] Resumes a thread.
364 * Decrements a thread's suspend count. When count is zero, the
365 * execution of the thread is resumed.
368 * Success: Previous suspend count
369 * Failure: 0xFFFFFFFF
372 DWORD WINAPI ResumeThread( HANDLE hthread ) /* [in] Identifies thread to restart */
375 NTSTATUS status = NtResumeThread( hthread, &ret );
380 SetLastError( RtlNtStatusToDosError(status) );
386 /**********************************************************************
387 * GetThreadPriority [KERNEL32.@] Returns priority for thread.
390 * Success: Thread's priority level.
391 * Failure: THREAD_PRIORITY_ERROR_RETURN
393 INT WINAPI GetThreadPriority(
394 HANDLE hthread) /* [in] Handle to thread */
396 THREAD_BASIC_INFORMATION info;
397 NTSTATUS status = NtQueryInformationThread( hthread, ThreadBasicInformation,
398 &info, sizeof(info), NULL );
402 SetLastError( RtlNtStatusToDosError(status) );
403 return THREAD_PRIORITY_ERROR_RETURN;
405 return info.Priority;
409 /**********************************************************************
410 * SetThreadPriority [KERNEL32.@] Sets priority for thread.
416 BOOL WINAPI SetThreadPriority(
417 HANDLE hthread, /* [in] Handle to thread */
418 INT priority) /* [in] Thread priority level */
421 SERVER_START_REQ( set_thread_info )
423 req->handle = hthread;
424 req->priority = priority;
425 req->mask = SET_THREAD_INFO_PRIORITY;
426 ret = !wine_server_call_err( req );
433 /**********************************************************************
434 * GetThreadPriorityBoost [KERNEL32.@] Returns priority boost for thread.
436 * Always reports that priority boost is disabled.
442 BOOL WINAPI GetThreadPriorityBoost(
443 HANDLE hthread, /* [in] Handle to thread */
444 PBOOL pstate) /* [out] pointer to var that receives the boost state */
446 if (pstate) *pstate = FALSE;
451 /**********************************************************************
452 * SetThreadPriorityBoost [KERNEL32.@] Sets priority boost for thread.
454 * Priority boost is not implemented. Thsi function always returns
455 * FALSE and sets last error to ERROR_CALL_NOT_IMPLEMENTED
458 * Always returns FALSE to indicate a failure
460 BOOL WINAPI SetThreadPriorityBoost(
461 HANDLE hthread, /* [in] Handle to thread */
462 BOOL disable) /* [in] TRUE to disable priority boost */
464 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
469 /**********************************************************************
470 * SetThreadAffinityMask (KERNEL32.@)
472 DWORD WINAPI SetThreadAffinityMask( HANDLE hThread, DWORD dwThreadAffinityMask )
475 SERVER_START_REQ( set_thread_info )
477 req->handle = hThread;
478 req->affinity = dwThreadAffinityMask;
479 req->mask = SET_THREAD_INFO_AFFINITY;
480 ret = !wine_server_call_err( req );
481 /* FIXME: should return previous value */
488 /**********************************************************************
489 * SetThreadIdealProcessor [KERNEL32.@] Obtains timing information.
492 * Success: Value of last call to SetThreadIdealProcessor
495 DWORD WINAPI SetThreadIdealProcessor(
496 HANDLE hThread, /* [in] Specifies the thread of interest */
497 DWORD dwIdealProcessor) /* [in] Specifies the new preferred processor */
499 FIXME("(%p): stub\n",hThread);
500 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
505 /* callback for QueueUserAPC */
506 static void CALLBACK call_user_apc( ULONG_PTR arg1, ULONG_PTR arg2, ULONG_PTR arg3 )
508 PAPCFUNC func = (PAPCFUNC)arg1;
512 /***********************************************************************
513 * QueueUserAPC (KERNEL32.@)
515 DWORD WINAPI QueueUserAPC( PAPCFUNC func, HANDLE hthread, ULONG_PTR data )
517 NTSTATUS status = NtQueueApcThread( hthread, call_user_apc, (ULONG_PTR)func, data, 0 );
519 if (status) SetLastError( RtlNtStatusToDosError(status) );
523 /***********************************************************************
524 * QueueUserWorkItem (KERNEL32.@)
526 BOOL WINAPI QueueUserWorkItem( LPTHREAD_START_ROUTINE Function, PVOID Context, ULONG Flags )
528 FIXME("(%p,%p,0x%08lx): stub\n", Function, Context, Flags);
532 /**********************************************************************
533 * GetThreadTimes [KERNEL32.@] Obtains timing information.
539 BOOL WINAPI GetThreadTimes(
540 HANDLE thread, /* [in] Specifies the thread of interest */
541 LPFILETIME creationtime, /* [out] When the thread was created */
542 LPFILETIME exittime, /* [out] When the thread was destroyed */
543 LPFILETIME kerneltime, /* [out] Time thread spent in kernel mode */
544 LPFILETIME usertime) /* [out] Time thread spent in user mode */
548 if (creationtime || exittime)
550 /* We need to do a server call to get the creation time or exit time */
551 /* This works on any thread */
553 SERVER_START_REQ( get_thread_info )
555 req->handle = thread;
557 if ((ret = !wine_server_call_err( req )))
560 RtlSecondsSince1970ToTime( reply->creation_time, (LARGE_INTEGER*)creationtime );
562 RtlSecondsSince1970ToTime( reply->exit_time, (LARGE_INTEGER*)exittime );
567 if (ret && (kerneltime || usertime))
569 /* We call times(2) for kernel time or user time */
570 /* We can only (portably) do this for the current thread */
571 if (thread == GetCurrentThread())
575 long clocks_per_sec = sysconf(_SC_CLK_TCK);
580 time = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
581 kerneltime->dwHighDateTime = time >> 32;
582 kerneltime->dwLowDateTime = (DWORD)time;
586 time = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
587 usertime->dwHighDateTime = time >> 32;
588 usertime->dwLowDateTime = (DWORD)time;
593 if (kerneltime) kerneltime->dwHighDateTime = kerneltime->dwLowDateTime = 0;
594 if (usertime) usertime->dwHighDateTime = usertime->dwLowDateTime = 0;
595 FIXME("Cannot get kerneltime or usertime of other threads\n");
602 /**********************************************************************
603 * VWin32_BoostThreadGroup [KERNEL.535]
605 VOID WINAPI VWin32_BoostThreadGroup( DWORD threadId, INT boost )
607 FIXME("(0x%08lx,%d): stub\n", threadId, boost);
611 /**********************************************************************
612 * VWin32_BoostThreadStatic [KERNEL.536]
614 VOID WINAPI VWin32_BoostThreadStatic( DWORD threadId, INT boost )
616 FIXME("(0x%08lx,%d): stub\n", threadId, boost);
620 /***********************************************************************
621 * GetCurrentThread [KERNEL32.@] Gets pseudohandle for current thread
624 * Pseudohandle for the current thread
626 #undef GetCurrentThread
627 HANDLE WINAPI GetCurrentThread(void)
629 return (HANDLE)0xfffffffe;
635 /***********************************************************************
636 * SetLastError (KERNEL.147)
637 * SetLastError (KERNEL32.@)
639 /* void WINAPI SetLastError( DWORD error ); */
640 __ASM_GLOBAL_FUNC( SetLastError,
641 "movl 4(%esp),%eax\n\t"
646 /***********************************************************************
647 * GetLastError (KERNEL.148)
648 * GetLastError (KERNEL32.@)
650 /* DWORD WINAPI GetLastError(void); */
651 __ASM_GLOBAL_FUNC( GetLastError, ".byte 0x64\n\tmovl 0x34,%eax\n\tret" )
653 /***********************************************************************
654 * GetCurrentProcessId (KERNEL.471)
655 * GetCurrentProcessId (KERNEL32.@)
657 /* DWORD WINAPI GetCurrentProcessId(void) */
658 __ASM_GLOBAL_FUNC( GetCurrentProcessId, ".byte 0x64\n\tmovl 0x20,%eax\n\tret" )
660 /***********************************************************************
661 * GetCurrentThreadId (KERNEL.462)
662 * GetCurrentThreadId (KERNEL32.@)
664 /* DWORD WINAPI GetCurrentThreadId(void) */
665 __ASM_GLOBAL_FUNC( GetCurrentThreadId, ".byte 0x64\n\tmovl 0x24,%eax\n\tret" )
669 /**********************************************************************
670 * SetLastError (KERNEL.147)
671 * SetLastError (KERNEL32.@)
673 * Sets the last-error code.
675 void WINAPI SetLastError( DWORD error ) /* [in] Per-thread error code */
677 NtCurrentTeb()->LastErrorValue = error;
680 /**********************************************************************
681 * GetLastError (KERNEL.148)
682 * GetLastError (KERNEL32.@)
684 * Returns last-error code.
686 DWORD WINAPI GetLastError(void)
688 return NtCurrentTeb()->LastErrorValue;
691 /***********************************************************************
692 * GetCurrentProcessId (KERNEL.471)
693 * GetCurrentProcessId (KERNEL32.@)
695 * Returns process identifier.
697 DWORD WINAPI GetCurrentProcessId(void)
699 return (DWORD)NtCurrentTeb()->ClientId.UniqueProcess;
702 /***********************************************************************
703 * GetCurrentThreadId (KERNEL.462)
704 * GetCurrentThreadId (KERNEL32.@)
706 * Returns thread identifier.
708 DWORD WINAPI GetCurrentThreadId(void)
710 return (DWORD)NtCurrentTeb()->ClientId.UniqueThread;
713 #endif /* __i386__ */