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/library.h"
44 #include "wine/server.h"
45 #include "wine/debug.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(thread);
48 WINE_DECLARE_DEBUG_CHANNEL(relay);
51 /***********************************************************************
54 * Initialization of a newly created TEB.
56 static BOOL THREAD_InitTEB( TEB *teb )
58 teb->Tib.ExceptionList = (void *)~0UL;
59 teb->Tib.StackBase = (void *)~0UL;
60 teb->Tib.Self = &teb->Tib;
61 teb->tibflags = TEBF_WIN32;
62 teb->exit_code = STILL_ACTIVE;
67 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
68 teb->StaticUnicodeString.Buffer = (PWSTR)teb->StaticUnicodeBuffer;
69 InitializeListHead(&teb->TlsLinks);
70 teb->teb_sel = wine_ldt_alloc_fs();
71 return (teb->teb_sel != 0);
75 /***********************************************************************
78 * Allocate the stack of a thread.
80 TEB *THREAD_InitStack( TEB *teb, DWORD stack_size )
82 DWORD old_prot, total_size;
83 DWORD page_size = getpagesize();
86 /* Allocate the stack */
88 /* if size is smaller than default, get stack size from parent */
89 if (stack_size < 1024 * 1024)
92 stack_size = 1024 * 1024; /* no parent */
94 stack_size = ((char *)NtCurrentTeb()->Tib.StackBase
95 - (char *)NtCurrentTeb()->DeallocationStack
96 - SIGNAL_STACK_SIZE - 3 * page_size);
99 /* FIXME: some Wine functions use a lot of stack, so we add 64Kb here */
100 stack_size += 64 * 1024;
102 /* Memory layout in allocated block:
105 * 1 page NOACCESS guard page
106 * SIGNAL_STACK_SIZE signal stack
107 * 1 page NOACCESS guard page
108 * 1 page PAGE_GUARD guard page
109 * stack_size normal stack
110 * 1 page TEB (except for initial thread)
113 stack_size = (stack_size + (page_size - 1)) & ~(page_size - 1);
114 total_size = stack_size + SIGNAL_STACK_SIZE + 3 * page_size;
115 if (!teb) total_size += page_size;
117 if (!(base = VirtualAlloc( NULL, total_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE )))
122 teb = (TEB *)((char *)base + total_size - page_size);
123 if (!THREAD_InitTEB( teb ))
125 VirtualFree( base, 0, MEM_RELEASE );
130 teb->DeallocationStack = base;
131 teb->signal_stack = (char *)base + page_size;
132 teb->Tib.StackBase = (char *)base + 3 * page_size + SIGNAL_STACK_SIZE + stack_size;
133 teb->Tib.StackLimit = base; /* note: limit is lower than base since the stack grows down */
135 /* Setup guard pages */
137 VirtualProtect( base, 1, PAGE_NOACCESS, &old_prot );
138 VirtualProtect( (char *)teb->signal_stack + SIGNAL_STACK_SIZE, 1, PAGE_NOACCESS, &old_prot );
139 VirtualProtect( (char *)teb->signal_stack + SIGNAL_STACK_SIZE + page_size, 1,
140 PAGE_EXECUTE_READWRITE | PAGE_GUARD, &old_prot );
145 /***********************************************************************
148 * Start execution of a newly created thread. Does not return.
150 static void THREAD_Start( TEB *teb )
152 LPTHREAD_START_ROUTINE func = (LPTHREAD_START_ROUTINE)teb->entry_point;
153 struct debug_info info;
155 info.str_pos = info.strings;
156 info.out_pos = info.output;
157 teb->debug_info = &info;
159 SYSDEPS_SetCurThread( teb );
161 wine_server_init_thread();
164 DPRINTF("%04lx:Starting thread (entryproc=%p)\n", GetCurrentThreadId(), func );
168 MODULE_DllThreadAttach( NULL );
169 ExitThread( func( NtCurrentTeb()->entry_arg ) );
171 __EXCEPT(UnhandledExceptionFilter)
173 TerminateThread( GetCurrentThread(), GetExceptionCode() );
179 /***********************************************************************
180 * CreateThread (KERNEL32.@)
182 HANDLE WINAPI CreateThread( SECURITY_ATTRIBUTES *sa, SIZE_T stack,
183 LPTHREAD_START_ROUTINE start, LPVOID param,
184 DWORD flags, LPDWORD id )
191 if (pipe( request_pipe ) == -1)
193 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
196 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
197 wine_server_send_fd( request_pipe[0] );
199 SERVER_START_REQ( new_thread )
201 req->suspend = ((flags & CREATE_SUSPENDED) != 0);
202 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
203 req->request_fd = request_pipe[0];
204 if (!wine_server_call_err( req ))
206 handle = reply->handle;
209 close( request_pipe[0] );
213 if (!handle || !(teb = THREAD_InitStack( NULL, stack )))
215 close( request_pipe[1] );
219 teb->Peb = NtCurrentTeb()->Peb;
220 teb->ClientId.UniqueThread = (HANDLE)tid;
221 teb->request_fd = request_pipe[1];
222 teb->entry_point = start;
223 teb->entry_arg = param;
224 teb->htask16 = GetCurrentTask();
226 InsertHeadList( &NtCurrentTeb()->TlsLinks, &teb->TlsLinks );
230 if (SYSDEPS_SpawnThread( THREAD_Start, teb ) == -1)
232 CloseHandle( handle );
233 close( request_pipe[1] );
235 RemoveEntryList( &teb->TlsLinks );
237 wine_ldt_free_fs( teb->teb_sel );
238 VirtualFree( teb->DeallocationStack, 0, MEM_RELEASE );
245 /***********************************************************************
246 * OpenThread [KERNEL32.@] Retrieves a handle to a thread from its thread id
248 HANDLE WINAPI OpenThread( DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId )
251 SERVER_START_REQ( open_thread )
253 req->tid = dwThreadId;
254 req->access = dwDesiredAccess;
255 req->inherit = bInheritHandle;
256 if (!wine_server_call_err( req )) ret = reply->handle;
263 /***********************************************************************
264 * ExitThread [KERNEL32.@] Ends a thread
269 void WINAPI ExitThread( DWORD code ) /* [in] Exit code for this thread */
272 SERVER_START_REQ( terminate_thread )
274 /* send the exit code to the server */
275 req->handle = GetCurrentThread();
276 req->exit_code = code;
277 wine_server_call( req );
284 LdrShutdownProcess();
291 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
293 SYSDEPS_ExitThread( code );
298 /**********************************************************************
299 * TerminateThread [KERNEL32.@] Terminates a thread
305 BOOL WINAPI TerminateThread( HANDLE handle, /* [in] Handle to thread */
306 DWORD exit_code) /* [in] Exit code for thread */
308 NTSTATUS status = NtTerminateThread( handle, exit_code );
309 if (status) SetLastError( RtlNtStatusToDosError(status) );
314 /***********************************************************************
315 * FreeLibraryAndExitThread (KERNEL32.@)
317 void WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
319 FreeLibrary(hLibModule);
320 ExitThread(dwExitCode);
324 /**********************************************************************
325 * GetExitCodeThread (KERNEL32.@)
327 * Gets termination status of thread.
333 BOOL WINAPI GetExitCodeThread(
334 HANDLE hthread, /* [in] Handle to thread */
335 LPDWORD exitcode) /* [out] Address to receive termination status */
337 THREAD_BASIC_INFORMATION info;
338 NTSTATUS status = NtQueryInformationThread( hthread, ThreadBasicInformation,
339 &info, sizeof(info), NULL );
343 SetLastError( RtlNtStatusToDosError(status) );
346 if (exitcode) *exitcode = info.ExitStatus;
351 /***********************************************************************
352 * SetThreadContext [KERNEL32.@] Sets context of thread.
358 BOOL WINAPI SetThreadContext( HANDLE handle, /* [in] Handle to thread with context */
359 const CONTEXT *context ) /* [in] Address of context structure */
361 NTSTATUS status = NtSetContextThread( handle, context );
362 if (status) SetLastError( RtlNtStatusToDosError(status) );
367 /***********************************************************************
368 * GetThreadContext [KERNEL32.@] Retrieves context of thread.
374 BOOL WINAPI GetThreadContext( HANDLE handle, /* [in] Handle to thread with context */
375 CONTEXT *context ) /* [out] Address of context structure */
377 NTSTATUS status = NtGetContextThread( handle, context );
378 if (status) SetLastError( RtlNtStatusToDosError(status) );
383 /**********************************************************************
384 * SuspendThread [KERNEL32.@] Suspends a thread.
387 * Success: Previous suspend count
388 * Failure: 0xFFFFFFFF
390 DWORD WINAPI SuspendThread( HANDLE hthread ) /* [in] Handle to the thread */
393 NTSTATUS status = NtSuspendThread( hthread, &ret );
398 SetLastError( RtlNtStatusToDosError(status) );
404 /**********************************************************************
405 * ResumeThread [KERNEL32.@] Resumes a thread.
407 * Decrements a thread's suspend count. When count is zero, the
408 * execution of the thread is resumed.
411 * Success: Previous suspend count
412 * Failure: 0xFFFFFFFF
415 DWORD WINAPI ResumeThread( HANDLE hthread ) /* [in] Identifies thread to restart */
418 NTSTATUS status = NtResumeThread( hthread, &ret );
423 SetLastError( RtlNtStatusToDosError(status) );
429 /**********************************************************************
430 * GetThreadPriority [KERNEL32.@] Returns priority for thread.
433 * Success: Thread's priority level.
434 * Failure: THREAD_PRIORITY_ERROR_RETURN
436 INT WINAPI GetThreadPriority(
437 HANDLE hthread) /* [in] Handle to thread */
439 THREAD_BASIC_INFORMATION info;
440 NTSTATUS status = NtQueryInformationThread( hthread, ThreadBasicInformation,
441 &info, sizeof(info), NULL );
445 SetLastError( RtlNtStatusToDosError(status) );
446 return THREAD_PRIORITY_ERROR_RETURN;
448 return info.Priority;
452 /**********************************************************************
453 * SetThreadPriority [KERNEL32.@] Sets priority for thread.
459 BOOL WINAPI SetThreadPriority(
460 HANDLE hthread, /* [in] Handle to thread */
461 INT priority) /* [in] Thread priority level */
464 SERVER_START_REQ( set_thread_info )
466 req->handle = hthread;
467 req->priority = priority;
468 req->mask = SET_THREAD_INFO_PRIORITY;
469 ret = !wine_server_call_err( req );
476 /**********************************************************************
477 * GetThreadPriorityBoost [KERNEL32.@] Returns priority boost for thread.
479 * Always reports that priority boost is disabled.
485 BOOL WINAPI GetThreadPriorityBoost(
486 HANDLE hthread, /* [in] Handle to thread */
487 PBOOL pstate) /* [out] pointer to var that receives the boost state */
489 if (pstate) *pstate = FALSE;
494 /**********************************************************************
495 * SetThreadPriorityBoost [KERNEL32.@] Sets priority boost for thread.
497 * Priority boost is not implemented. Thsi function always returns
498 * FALSE and sets last error to ERROR_CALL_NOT_IMPLEMENTED
501 * Always returns FALSE to indicate a failure
503 BOOL WINAPI SetThreadPriorityBoost(
504 HANDLE hthread, /* [in] Handle to thread */
505 BOOL disable) /* [in] TRUE to disable priority boost */
507 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
512 /**********************************************************************
513 * SetThreadAffinityMask (KERNEL32.@)
515 DWORD WINAPI SetThreadAffinityMask( HANDLE hThread, DWORD dwThreadAffinityMask )
518 SERVER_START_REQ( set_thread_info )
520 req->handle = hThread;
521 req->affinity = dwThreadAffinityMask;
522 req->mask = SET_THREAD_INFO_AFFINITY;
523 ret = !wine_server_call_err( req );
524 /* FIXME: should return previous value */
531 /**********************************************************************
532 * SetThreadIdealProcessor [KERNEL32.@] Obtains timing information.
535 * Success: Value of last call to SetThreadIdealProcessor
538 DWORD WINAPI SetThreadIdealProcessor(
539 HANDLE hThread, /* [in] Specifies the thread of interest */
540 DWORD dwIdealProcessor) /* [in] Specifies the new preferred processor */
542 FIXME("(%p): stub\n",hThread);
543 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
548 /* callback for QueueUserAPC */
549 static void CALLBACK call_user_apc( ULONG_PTR arg1, ULONG_PTR arg2, ULONG_PTR arg3 )
551 PAPCFUNC func = (PAPCFUNC)arg1;
555 /***********************************************************************
556 * QueueUserAPC (KERNEL32.@)
558 DWORD WINAPI QueueUserAPC( PAPCFUNC func, HANDLE hthread, ULONG_PTR data )
560 NTSTATUS status = NtQueueApcThread( hthread, call_user_apc, (ULONG_PTR)func, data, 0 );
562 if (status) SetLastError( RtlNtStatusToDosError(status) );
567 /**********************************************************************
568 * GetThreadTimes [KERNEL32.@] Obtains timing information.
574 BOOL WINAPI GetThreadTimes(
575 HANDLE thread, /* [in] Specifies the thread of interest */
576 LPFILETIME creationtime, /* [out] When the thread was created */
577 LPFILETIME exittime, /* [out] When the thread was destroyed */
578 LPFILETIME kerneltime, /* [out] Time thread spent in kernel mode */
579 LPFILETIME usertime) /* [out] Time thread spent in user mode */
583 if (creationtime || exittime)
585 /* We need to do a server call to get the creation time or exit time */
586 /* This works on any thread */
588 SERVER_START_REQ( get_thread_info )
590 req->handle = thread;
592 if ((ret = !wine_server_call_err( req )))
595 RtlSecondsSince1970ToTime( reply->creation_time, (LARGE_INTEGER*)creationtime );
597 RtlSecondsSince1970ToTime( reply->exit_time, (LARGE_INTEGER*)exittime );
602 if (ret && (kerneltime || usertime))
604 /* We call times(2) for kernel time or user time */
605 /* We can only (portably) do this for the current thread */
606 if (thread == GetCurrentThread())
610 long clocks_per_sec = sysconf(_SC_CLK_TCK);
615 time = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
616 kerneltime->dwHighDateTime = time >> 32;
617 kerneltime->dwLowDateTime = (DWORD)time;
621 time = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
622 usertime->dwHighDateTime = time >> 32;
623 usertime->dwLowDateTime = (DWORD)time;
628 if (kerneltime) kerneltime->dwHighDateTime = kerneltime->dwLowDateTime = 0;
629 if (usertime) usertime->dwHighDateTime = usertime->dwLowDateTime = 0;
630 FIXME("Cannot get kerneltime or usertime of other threads\n");
637 /**********************************************************************
638 * VWin32_BoostThreadGroup [KERNEL.535]
640 VOID WINAPI VWin32_BoostThreadGroup( DWORD threadId, INT boost )
642 FIXME("(0x%08lx,%d): stub\n", threadId, boost);
646 /**********************************************************************
647 * VWin32_BoostThreadStatic [KERNEL.536]
649 VOID WINAPI VWin32_BoostThreadStatic( DWORD threadId, INT boost )
651 FIXME("(0x%08lx,%d): stub\n", threadId, boost);
655 /***********************************************************************
656 * GetCurrentThread [KERNEL32.@] Gets pseudohandle for current thread
659 * Pseudohandle for the current thread
661 #undef GetCurrentThread
662 HANDLE WINAPI GetCurrentThread(void)
664 return (HANDLE)0xfffffffe;
670 /***********************************************************************
671 * SetLastError (KERNEL.147)
672 * SetLastError (KERNEL32.@)
674 /* void WINAPI SetLastError( DWORD error ); */
675 __ASM_GLOBAL_FUNC( SetLastError,
676 "movl 4(%esp),%eax\n\t"
681 /***********************************************************************
682 * GetLastError (KERNEL.148)
683 * GetLastError (KERNEL32.@)
685 /* DWORD WINAPI GetLastError(void); */
686 __ASM_GLOBAL_FUNC( GetLastError, ".byte 0x64\n\tmovl 0x60,%eax\n\tret" );
688 /***********************************************************************
689 * GetCurrentProcessId (KERNEL.471)
690 * GetCurrentProcessId (KERNEL32.@)
692 /* DWORD WINAPI GetCurrentProcessId(void) */
693 __ASM_GLOBAL_FUNC( GetCurrentProcessId, ".byte 0x64\n\tmovl 0x20,%eax\n\tret" );
695 /***********************************************************************
696 * GetCurrentThreadId (KERNEL.462)
697 * GetCurrentThreadId (KERNEL32.@)
699 /* DWORD WINAPI GetCurrentThreadId(void) */
700 __ASM_GLOBAL_FUNC( GetCurrentThreadId, ".byte 0x64\n\tmovl 0x24,%eax\n\tret" );
704 /**********************************************************************
705 * SetLastError (KERNEL.147)
706 * SetLastError (KERNEL32.@)
708 * Sets the last-error code.
710 void WINAPI SetLastError( DWORD error ) /* [in] Per-thread error code */
712 NtCurrentTeb()->last_error = error;
715 /**********************************************************************
716 * GetLastError (KERNEL.148)
717 * GetLastError (KERNEL32.@)
719 * Returns last-error code.
721 DWORD WINAPI GetLastError(void)
723 return NtCurrentTeb()->last_error;
726 /***********************************************************************
727 * GetCurrentProcessId (KERNEL.471)
728 * GetCurrentProcessId (KERNEL32.@)
730 * Returns process identifier.
732 DWORD WINAPI GetCurrentProcessId(void)
734 return (DWORD)NtCurrentTeb()->ClientId.UniqueProcess;
737 /***********************************************************************
738 * GetCurrentThreadId (KERNEL.462)
739 * GetCurrentThreadId (KERNEL32.@)
741 * Returns thread identifier.
743 DWORD WINAPI GetCurrentThreadId(void)
745 return (DWORD)NtCurrentTeb()->ClientId.UniqueThread;
748 #endif /* __i386__ */