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 = SELECTOR_AllocBlock( teb, 0x1000, WINE_LDT_FLAGS_DATA|WINE_LDT_FLAGS_32BIT );
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 FreeSelector16( teb->stack_sel );
124 FreeSelector16( teb->teb_sel );
125 VirtualFree( teb->stack_base, 0, MEM_RELEASE );
129 /***********************************************************************
132 * Allocate the stack of a thread.
134 TEB *THREAD_InitStack( TEB *teb, DWORD stack_size )
136 DWORD old_prot, total_size;
137 DWORD page_size = getpagesize();
140 /* Allocate the stack */
142 if (stack_size >= 16*1024*1024)
143 WARN("Thread stack size is %ld MB.\n",stack_size/1024/1024);
145 /* if size is smaller than default, get stack size from parent */
146 if (stack_size < 1024 * 1024)
149 stack_size = 1024 * 1024; /* no parent */
151 stack_size = ((char *)NtCurrentTeb()->stack_top - (char *)NtCurrentTeb()->stack_base
152 - SIGNAL_STACK_SIZE - 3 * page_size);
155 /* FIXME: some Wine functions use a lot of stack, so we add 64Kb here */
156 stack_size += 64 * 1024;
158 /* Memory layout in allocated block:
161 * 1 page NOACCESS guard page
162 * SIGNAL_STACK_SIZE signal stack
163 * 1 page NOACCESS guard page
164 * 1 page PAGE_GUARD guard page
165 * stack_size normal stack
166 * 64Kb 16-bit stack (optional)
167 * 1 page TEB (except for initial thread)
168 * 1 page debug info (except for initial thread)
171 stack_size = (stack_size + (page_size - 1)) & ~(page_size - 1);
172 total_size = stack_size + SIGNAL_STACK_SIZE + 3 * page_size;
173 total_size += 0x10000; /* 16-bit stack */
174 if (!teb) total_size += 2 * page_size;
176 if (!(base = VirtualAlloc( NULL, total_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE )))
181 teb = (TEB *)((char *)base + total_size - 2 * page_size);
182 if (!THREAD_InitTEB( teb )) goto error;
183 teb->debug_info = (char *)teb + page_size;
186 teb->stack_low = base;
187 teb->stack_base = base;
188 teb->signal_stack = (char *)base + page_size;
189 teb->stack_top = (char *)base + 3 * page_size + SIGNAL_STACK_SIZE + stack_size;
191 /* Setup guard pages */
193 VirtualProtect( base, 1, PAGE_NOACCESS, &old_prot );
194 VirtualProtect( (char *)teb->signal_stack + SIGNAL_STACK_SIZE, 1, PAGE_NOACCESS, &old_prot );
195 VirtualProtect( (char *)teb->signal_stack + SIGNAL_STACK_SIZE + page_size, 1,
196 PAGE_EXECUTE_READWRITE | PAGE_GUARD, &old_prot );
198 /* Allocate the 16-bit stack selector */
200 teb->stack_sel = SELECTOR_AllocBlock( teb->stack_top, 0x10000, WINE_LDT_FLAGS_DATA );
201 if (!teb->stack_sel) goto error;
202 teb->cur_stack = MAKESEGPTR( teb->stack_sel, 0x10000 - sizeof(STACK16FRAME) );
207 FreeSelector16( teb->teb_sel );
208 VirtualFree( base, 0, MEM_RELEASE );
213 /***********************************************************************
214 * thread_errno_location
216 * Get the per-thread errno location.
218 static int *thread_errno_location(void)
220 return &NtCurrentTeb()->thread_errno;
223 /***********************************************************************
224 * thread_h_errno_location
226 * Get the per-thread h_errno location.
228 static int *thread_h_errno_location(void)
230 return &NtCurrentTeb()->thread_h_errno;
233 /***********************************************************************
236 * Setup the initial thread.
238 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
240 void THREAD_Init(void)
242 if (!initial_teb.self) /* do it only once */
244 THREAD_InitTEB( &initial_teb );
245 assert( initial_teb.teb_sel );
246 initial_teb.process = ¤t_process;
247 SYSDEPS_SetCurThread( &initial_teb );
248 wine_errno_location = thread_errno_location;
249 wine_h_errno_location = thread_h_errno_location;
253 DECL_GLOBAL_CONSTRUCTOR(thread_init) { THREAD_Init(); }
256 /***********************************************************************
259 * Start execution of a newly created thread. Does not return.
261 static void THREAD_Start(void)
263 LPTHREAD_START_ROUTINE func = (LPTHREAD_START_ROUTINE)NtCurrentTeb()->entry_point;
266 DPRINTF("%08lx:Starting thread (entryproc=%p)\n", GetCurrentThreadId(), func );
268 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
269 MODULE_DllThreadAttach( NULL );
270 ExitThread( func( NtCurrentTeb()->entry_arg ) );
274 /***********************************************************************
275 * CreateThread (KERNEL32.@)
277 HANDLE WINAPI CreateThread( SECURITY_ATTRIBUTES *sa, SIZE_T stack,
278 LPTHREAD_START_ROUTINE start, LPVOID param,
279 DWORD flags, LPDWORD id )
286 if (pipe( request_pipe ) == -1)
288 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
291 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
292 wine_server_send_fd( request_pipe[0] );
294 SERVER_START_REQ( new_thread )
296 req->suspend = ((flags & CREATE_SUSPENDED) != 0);
297 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
298 req->request_fd = request_pipe[0];
299 if (!wine_server_call_err( req ))
301 handle = reply->handle;
304 close( request_pipe[0] );
308 if (!handle || !(teb = THREAD_InitStack( NULL, stack )))
310 close( request_pipe[1] );
314 teb->process = NtCurrentTeb()->process;
316 teb->request_fd = request_pipe[1];
317 teb->entry_point = start;
318 teb->entry_arg = param;
319 teb->startup = THREAD_Start;
320 teb->htask16 = GetCurrentTask();
323 if (SYSDEPS_SpawnThread( teb ) == -1)
325 CloseHandle( handle );
326 close( request_pipe[1] );
327 THREAD_FreeTEB( teb );
333 /***********************************************************************
334 * CreateThread16 (KERNEL.441)
336 static DWORD CALLBACK THREAD_StartThread16( LPVOID threadArgs )
338 FARPROC16 start = ((FARPROC16 *)threadArgs)[0];
339 DWORD param = ((DWORD *)threadArgs)[1];
340 HeapFree( GetProcessHeap(), 0, threadArgs );
342 ((LPDWORD)CURRENT_STACK16)[-1] = param;
343 return wine_call_to_16( start, sizeof(DWORD) );
345 HANDLE WINAPI CreateThread16( SECURITY_ATTRIBUTES *sa, DWORD stack,
346 FARPROC16 start, SEGPTR param,
347 DWORD flags, LPDWORD id )
349 DWORD *threadArgs = HeapAlloc( GetProcessHeap(), 0, 2*sizeof(DWORD) );
350 if (!threadArgs) return INVALID_HANDLE_VALUE;
351 threadArgs[0] = (DWORD)start;
352 threadArgs[1] = (DWORD)param;
354 return CreateThread( sa, stack, THREAD_StartThread16, threadArgs, flags, id );
358 /***********************************************************************
359 * ExitThread [KERNEL32.@] Ends a thread
364 void WINAPI ExitThread( DWORD code ) /* [in] Exit code for this thread */
367 SERVER_START_REQ( terminate_thread )
369 /* send the exit code to the server */
370 req->handle = GetCurrentThread();
371 req->exit_code = code;
372 wine_server_call( req );
379 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
384 MODULE_DllThreadDetach( NULL );
385 if (!(NtCurrentTeb()->tibflags & TEBF_WIN32)) TASK_ExitTask();
386 SYSDEPS_ExitThread( code );
390 /***********************************************************************
391 * OpenThread Retrieves a handle to a thread from its thread id
396 HANDLE WINAPI OpenThread( DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId )
399 SERVER_START_REQ( open_thread )
401 req->tid = dwThreadId;
402 req->access = dwDesiredAccess;
403 req->inherit = bInheritHandle;
404 if (!wine_server_call_err( req )) ret = reply->handle;
410 /***********************************************************************
411 * SetThreadContext [KERNEL32.@] Sets context of thread.
417 BOOL WINAPI SetThreadContext( HANDLE handle, /* [in] Handle to thread with context */
418 const CONTEXT *context ) /* [in] Address of context structure */
421 SERVER_START_REQ( set_thread_context )
423 req->handle = handle;
424 req->flags = context->ContextFlags;
425 wine_server_add_data( req, context, sizeof(*context) );
426 ret = !wine_server_call_err( req );
433 /***********************************************************************
434 * GetThreadContext [KERNEL32.@] Retrieves context of thread.
440 BOOL WINAPI GetThreadContext( HANDLE handle, /* [in] Handle to thread with context */
441 CONTEXT *context ) /* [out] Address of context structure */
444 SERVER_START_REQ( get_thread_context )
446 req->handle = handle;
447 req->flags = context->ContextFlags;
448 wine_server_add_data( req, context, sizeof(*context) );
449 wine_server_set_reply( req, context, sizeof(*context) );
450 ret = !wine_server_call_err( req );
457 /**********************************************************************
458 * GetThreadPriority [KERNEL32.@] Returns priority for thread.
461 * Success: Thread's priority level.
462 * Failure: THREAD_PRIORITY_ERROR_RETURN
464 INT WINAPI GetThreadPriority(
465 HANDLE hthread) /* [in] Handle to thread */
467 INT ret = THREAD_PRIORITY_ERROR_RETURN;
468 SERVER_START_REQ( get_thread_info )
470 req->handle = hthread;
472 if (!wine_server_call_err( req )) ret = reply->priority;
479 /**********************************************************************
480 * SetThreadPriority [KERNEL32.@] Sets priority for thread.
486 BOOL WINAPI SetThreadPriority(
487 HANDLE hthread, /* [in] Handle to thread */
488 INT priority) /* [in] Thread priority level */
491 SERVER_START_REQ( set_thread_info )
493 req->handle = hthread;
494 req->priority = priority;
495 req->mask = SET_THREAD_INFO_PRIORITY;
496 ret = !wine_server_call_err( req );
503 /**********************************************************************
504 * GetThreadPriorityBoost [KERNEL32.@] Returns priority boost for thread.
506 * Always reports that priority boost is disabled.
512 BOOL WINAPI GetThreadPriorityBoost(
513 HANDLE hthread, /* [in] Handle to thread */
514 PBOOL pstate) /* [out] pointer to var that receives the boost state */
516 if (pstate) *pstate = FALSE;
521 /**********************************************************************
522 * SetThreadPriorityBoost [KERNEL32.@] Sets priority boost for thread.
524 * Priority boost is not implemented. Thsi function always returns
525 * FALSE and sets last error to ERROR_CALL_NOT_IMPLEMENTED
528 * Always returns FALSE to indicate a failure
530 BOOL WINAPI SetThreadPriorityBoost(
531 HANDLE hthread, /* [in] Handle to thread */
532 BOOL disable) /* [in] TRUE to disable priority boost */
534 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
539 /**********************************************************************
540 * SetThreadAffinityMask (KERNEL32.@)
542 DWORD WINAPI SetThreadAffinityMask( HANDLE hThread, DWORD dwThreadAffinityMask )
545 SERVER_START_REQ( set_thread_info )
547 req->handle = hThread;
548 req->affinity = dwThreadAffinityMask;
549 req->mask = SET_THREAD_INFO_AFFINITY;
550 ret = !wine_server_call_err( req );
551 /* FIXME: should return previous value */
557 /**********************************************************************
558 * SetThreadIdealProcessor [KERNEL32.@] Obtains timing information.
561 * Success: Value of last call to SetThreadIdealProcessor
564 DWORD WINAPI SetThreadIdealProcessor(
565 HANDLE hThread, /* [in] Specifies the thread of interest */
566 DWORD dwIdealProcessor) /* [in] Specifies the new preferred processor */
568 FIXME("(0x%p): stub\n",hThread);
569 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
573 /**********************************************************************
574 * TerminateThread [KERNEL32.@] Terminates a thread
580 BOOL WINAPI TerminateThread( HANDLE handle, /* [in] Handle to thread */
581 DWORD exit_code) /* [in] Exit code for thread */
583 NTSTATUS status = NtTerminateThread( handle, exit_code );
584 if (status) SetLastError( RtlNtStatusToDosError(status) );
589 /**********************************************************************
590 * GetExitCodeThread (KERNEL32.@)
592 * Gets termination status of thread.
598 BOOL WINAPI GetExitCodeThread(
599 HANDLE hthread, /* [in] Handle to thread */
600 LPDWORD exitcode) /* [out] Address to receive termination status */
603 SERVER_START_REQ( get_thread_info )
605 req->handle = hthread;
607 ret = !wine_server_call_err( req );
608 if (ret && exitcode) *exitcode = reply->exit_code;
615 /**********************************************************************
616 * ResumeThread [KERNEL32.@] Resumes a thread.
618 * Decrements a thread's suspend count. When count is zero, the
619 * execution of the thread is resumed.
622 * Success: Previous suspend count
623 * Failure: 0xFFFFFFFF
626 DWORD WINAPI ResumeThread(
627 HANDLE hthread) /* [in] Identifies thread to restart */
629 DWORD ret = 0xffffffff;
630 SERVER_START_REQ( resume_thread )
632 req->handle = hthread;
633 if (!wine_server_call_err( req )) ret = reply->count;
640 /**********************************************************************
641 * SuspendThread [KERNEL32.@] Suspends a thread.
644 * Success: Previous suspend count
645 * Failure: 0xFFFFFFFF
647 DWORD WINAPI SuspendThread(
648 HANDLE hthread) /* [in] Handle to the thread */
650 DWORD ret = 0xffffffff;
651 SERVER_START_REQ( suspend_thread )
653 req->handle = hthread;
654 if (!wine_server_call_err( req )) ret = reply->count;
661 /***********************************************************************
662 * QueueUserAPC (KERNEL32.@)
664 DWORD WINAPI QueueUserAPC( PAPCFUNC func, HANDLE hthread, ULONG_PTR data )
667 SERVER_START_REQ( queue_apc )
669 req->handle = hthread;
672 req->param = (void *)data;
673 ret = !wine_server_call_err( req );
680 /**********************************************************************
681 * GetThreadTimes [KERNEL32.@] Obtains timing information.
687 BOOL WINAPI GetThreadTimes(
688 HANDLE thread, /* [in] Specifies the thread of interest */
689 LPFILETIME creationtime, /* [out] When the thread was created */
690 LPFILETIME exittime, /* [out] When the thread was destroyed */
691 LPFILETIME kerneltime, /* [out] Time thread spent in kernel mode */
692 LPFILETIME usertime) /* [out] Time thread spent in user mode */
696 if (creationtime || exittime)
698 /* We need to do a server call to get the creation time or exit time */
699 /* This works on any thread */
701 SERVER_START_REQ( get_thread_info )
703 req->handle = thread;
705 if ((ret = !wine_server_call_err( req )))
708 RtlSecondsSince1970ToTime( reply->creation_time, (LARGE_INTEGER*)creationtime );
710 RtlSecondsSince1970ToTime( reply->exit_time, (LARGE_INTEGER*)exittime );
715 if (ret && (kerneltime || usertime))
717 /* We call times(2) for kernel time or user time */
718 /* We can only (portably) do this for the current thread */
719 if (thread == GetCurrentThread())
723 long clocks_per_sec = sysconf(_SC_CLK_TCK);
728 time = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
729 kerneltime->dwHighDateTime = time >> 32;
730 kerneltime->dwLowDateTime = (DWORD)time;
734 time = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
735 usertime->dwHighDateTime = time >> 32;
736 usertime->dwLowDateTime = (DWORD)time;
741 if (kerneltime) kerneltime->dwHighDateTime = kerneltime->dwLowDateTime = 0;
742 if (usertime) usertime->dwHighDateTime = usertime->dwLowDateTime = 0;
743 FIXME("Cannot get kerneltime or usertime of other threads\n");
750 /**********************************************************************
751 * VWin32_BoostThreadGroup [KERNEL.535]
753 VOID WINAPI VWin32_BoostThreadGroup( DWORD threadId, INT boost )
755 FIXME("(0x%08lx,%d): stub\n", threadId, boost);
758 /**********************************************************************
759 * VWin32_BoostThreadStatic [KERNEL.536]
761 VOID WINAPI VWin32_BoostThreadStatic( DWORD threadId, INT boost )
763 FIXME("(0x%08lx,%d): stub\n", threadId, boost);
767 /***********************************************************************
768 * GetCurrentThread [KERNEL32.@] Gets pseudohandle for current thread
771 * Pseudohandle for the current thread
773 #undef GetCurrentThread
774 HANDLE WINAPI GetCurrentThread(void)
776 return (HANDLE)0xfffffffe;
780 /***********************************************************************
781 * ProcessIdToSessionId (KERNEL32.@)
782 * This function is available on Terminal Server 4SP4 and Windows 2000
784 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
786 /* According to MSDN, if the calling process is not in a terminal
787 * services environment, then the sessionid returned is zero.
793 /***********************************************************************
794 * SetThreadExecutionState (KERNEL32.@)
796 * Informs the system that activity is taking place for
797 * power management purposes.
799 EXECUTION_STATE WINAPI SetThreadExecutionState(EXECUTION_STATE flags)
801 static EXECUTION_STATE current =
802 ES_SYSTEM_REQUIRED|ES_DISPLAY_REQUIRED|ES_USER_PRESENT;
803 EXECUTION_STATE old = current;
805 if (!(current & ES_CONTINUOUS) || (flags & ES_CONTINUOUS))
807 FIXME("(0x%lx): stub, harmless (power management).\n", flags);
814 /***********************************************************************
815 * SetLastError (KERNEL.147)
816 * SetLastError (KERNEL32.@)
818 /* void WINAPI SetLastError( DWORD error ); */
819 __ASM_GLOBAL_FUNC( SetLastError,
820 "movl 4(%esp),%eax\n\t"
825 /***********************************************************************
826 * GetLastError (KERNEL.148)
827 * GetLastError (KERNEL32.@)
829 /* DWORD WINAPI GetLastError(void); */
830 __ASM_GLOBAL_FUNC( GetLastError, ".byte 0x64\n\tmovl 0x60,%eax\n\tret" );
832 /***********************************************************************
833 * GetCurrentProcessId (KERNEL.471)
834 * GetCurrentProcessId (KERNEL32.@)
836 /* DWORD WINAPI GetCurrentProcessId(void) */
837 __ASM_GLOBAL_FUNC( GetCurrentProcessId, ".byte 0x64\n\tmovl 0x20,%eax\n\tret" );
839 /***********************************************************************
840 * GetCurrentThreadId (KERNEL.462)
841 * GetCurrentThreadId (KERNEL32.@)
843 /* DWORD WINAPI GetCurrentThreadId(void) */
844 __ASM_GLOBAL_FUNC( GetCurrentThreadId, ".byte 0x64\n\tmovl 0x24,%eax\n\tret" );
848 /**********************************************************************
849 * SetLastError (KERNEL.147)
850 * SetLastError (KERNEL32.@)
852 * Sets the last-error code.
854 void WINAPI SetLastError( DWORD error ) /* [in] Per-thread error code */
856 NtCurrentTeb()->last_error = error;
859 /**********************************************************************
860 * GetLastError (KERNEL.148)
861 * GetLastError (KERNEL32.@)
863 * Returns last-error code.
865 DWORD WINAPI GetLastError(void)
867 return NtCurrentTeb()->last_error;
870 /***********************************************************************
871 * GetCurrentProcessId (KERNEL.471)
872 * GetCurrentProcessId (KERNEL32.@)
874 * Returns process identifier.
876 DWORD WINAPI GetCurrentProcessId(void)
878 return (DWORD)NtCurrentTeb()->pid;
881 /***********************************************************************
882 * GetCurrentThreadId (KERNEL.462)
883 * GetCurrentThreadId (KERNEL32.@)
885 * Returns thread identifier.
887 DWORD WINAPI GetCurrentThreadId(void)
889 return (DWORD)NtCurrentTeb()->tid;
892 #endif /* __i386__ */