Fix building libwine_unicode with w32api headers.
[wine/hacks.git] / scheduler / thread.c
blob700006a0d6cbfddcf9f0a3ca067234db4e495e60
1 /*
2 * Win32 threads
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
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <fcntl.h>
26 #include <sys/types.h>
27 #ifdef HAVE_SYS_MMAN_H
28 #include <sys/mman.h>
29 #endif
30 #ifdef HAVE_SYS_TIMES_H
31 #include <sys/times.h>
32 #endif
33 #ifdef HAVE_UNISTD_H
34 # include <unistd.h>
35 #endif
36 #include "wine/winbase16.h"
37 #include "thread.h"
38 #include "task.h"
39 #include "module.h"
40 #include "winerror.h"
41 #include "selectors.h"
42 #include "winnt.h"
43 #include "wine/server.h"
44 #include "stackframe.h"
45 #include "wine/debug.h"
46 #include "winnls.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 /***********************************************************************
57 * THREAD_IdToTEB
59 * Convert a thread id to a TEB, making sure it is valid.
61 TEB *THREAD_IdToTEB( DWORD id )
63 TEB *ret = NULL;
65 if (!id || id == GetCurrentThreadId()) return NtCurrentTeb();
67 SERVER_START_REQ( get_thread_info )
69 req->handle = 0;
70 req->tid_in = id;
71 if (!wine_server_call( req )) ret = reply->teb;
73 SERVER_END_REQ;
75 if (!ret)
77 /* Allow task handles to be used; convert to main thread */
78 if ( IsTask16( id ) )
80 TDB *pTask = TASK_GetPtr( id );
81 if (pTask) return pTask->teb;
83 SetLastError( ERROR_INVALID_PARAMETER );
85 return ret;
89 /***********************************************************************
90 * THREAD_InitTEB
92 * Initialization of a newly created TEB.
94 static BOOL THREAD_InitTEB( TEB *teb )
96 teb->except = (void *)~0UL;
97 teb->self = teb;
98 teb->tibflags = TEBF_WIN32;
99 teb->exit_code = STILL_ACTIVE;
100 teb->request_fd = -1;
101 teb->reply_fd = -1;
102 teb->wait_fd[0] = -1;
103 teb->wait_fd[1] = -1;
104 teb->stack_top = (void *)~0UL;
105 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
106 teb->StaticUnicodeString.Buffer = (PWSTR)teb->StaticUnicodeBuffer;
107 teb->teb_sel = wine_ldt_alloc_fs();
108 return (teb->teb_sel != 0);
112 /***********************************************************************
113 * THREAD_FreeTEB
115 * Free data structures associated with a thread.
116 * Must be called from the context of another thread.
118 static void THREAD_FreeTEB( TEB *teb )
120 TRACE("(%p) called\n", teb );
121 /* Free the associated memory */
122 wine_ldt_free_fs( teb->teb_sel );
123 VirtualFree( teb->stack_base, 0, MEM_RELEASE );
127 /***********************************************************************
128 * THREAD_InitStack
130 * Allocate the stack of a thread.
132 TEB *THREAD_InitStack( TEB *teb, DWORD stack_size )
134 DWORD old_prot, total_size;
135 DWORD page_size = getpagesize();
136 void *base;
138 /* Allocate the stack */
140 if (stack_size >= 16*1024*1024)
141 WARN("Thread stack size is %ld MB.\n",stack_size/1024/1024);
143 /* if size is smaller than default, get stack size from parent */
144 if (stack_size < 1024 * 1024)
146 if (teb)
147 stack_size = 1024 * 1024; /* no parent */
148 else
149 stack_size = ((char *)NtCurrentTeb()->stack_top - (char *)NtCurrentTeb()->stack_base
150 - SIGNAL_STACK_SIZE - 3 * page_size);
153 /* FIXME: some Wine functions use a lot of stack, so we add 64Kb here */
154 stack_size += 64 * 1024;
156 /* Memory layout in allocated block:
158 * size contents
159 * 1 page NOACCESS guard page
160 * SIGNAL_STACK_SIZE signal stack
161 * 1 page NOACCESS guard page
162 * 1 page PAGE_GUARD guard page
163 * stack_size normal stack
164 * 1 page TEB (except for initial thread)
165 * 1 page debug info (except for initial thread)
168 stack_size = (stack_size + (page_size - 1)) & ~(page_size - 1);
169 total_size = stack_size + SIGNAL_STACK_SIZE + 3 * page_size;
170 if (!teb) total_size += 2 * page_size;
172 if (!(base = VirtualAlloc( NULL, total_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE )))
173 return NULL;
175 if (!teb)
177 teb = (TEB *)((char *)base + total_size - 2 * page_size);
178 if (!THREAD_InitTEB( teb ))
180 VirtualFree( base, 0, MEM_RELEASE );
181 return NULL;
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 );
197 return teb;
201 /***********************************************************************
202 * THREAD_Init
204 * Setup the initial thread.
206 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
208 void THREAD_Init(void)
210 if (!initial_teb.self) /* do it only once */
212 THREAD_InitTEB( &initial_teb );
213 assert( initial_teb.teb_sel );
214 initial_teb.Peb = (PEB *)&current_process; /* FIXME */
215 SYSDEPS_SetCurThread( &initial_teb );
219 DECL_GLOBAL_CONSTRUCTOR(thread_init) { THREAD_Init(); }
222 /***********************************************************************
223 * THREAD_Start
225 * Start execution of a newly created thread. Does not return.
227 static void THREAD_Start(void)
229 LPTHREAD_START_ROUTINE func = (LPTHREAD_START_ROUTINE)NtCurrentTeb()->entry_point;
231 if (TRACE_ON(relay))
232 DPRINTF("%04lx:Starting thread (entryproc=%p)\n", GetCurrentThreadId(), func );
234 __TRY
236 MODULE_DllThreadAttach( NULL );
237 ExitThread( func( NtCurrentTeb()->entry_arg ) );
239 __EXCEPT(UnhandledExceptionFilter)
241 TerminateThread( GetCurrentThread(), GetExceptionCode() );
243 __ENDTRY
247 /***********************************************************************
248 * CreateThread (KERNEL32.@)
250 HANDLE WINAPI CreateThread( SECURITY_ATTRIBUTES *sa, SIZE_T stack,
251 LPTHREAD_START_ROUTINE start, LPVOID param,
252 DWORD flags, LPDWORD id )
254 HANDLE handle = 0;
255 TEB *teb;
256 DWORD tid = 0;
257 int request_pipe[2];
259 if (pipe( request_pipe ) == -1)
261 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
262 return 0;
264 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
265 wine_server_send_fd( request_pipe[0] );
267 SERVER_START_REQ( new_thread )
269 req->suspend = ((flags & CREATE_SUSPENDED) != 0);
270 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
271 req->request_fd = request_pipe[0];
272 if (!wine_server_call_err( req ))
274 handle = reply->handle;
275 tid = reply->tid;
277 close( request_pipe[0] );
279 SERVER_END_REQ;
281 if (!handle || !(teb = THREAD_InitStack( NULL, stack )))
283 close( request_pipe[1] );
284 return 0;
287 teb->Peb = NtCurrentTeb()->Peb;
288 teb->tid = tid;
289 teb->request_fd = request_pipe[1];
290 teb->entry_point = start;
291 teb->entry_arg = param;
292 teb->startup = THREAD_Start;
293 teb->htask16 = GetCurrentTask();
295 if (id) *id = tid;
296 if (SYSDEPS_SpawnThread( teb ) == -1)
298 CloseHandle( handle );
299 close( request_pipe[1] );
300 THREAD_FreeTEB( teb );
301 return 0;
303 return handle;
306 /***********************************************************************
307 * ExitThread [KERNEL32.@] Ends a thread
309 * RETURNS
310 * None
312 void WINAPI ExitThread( DWORD code ) /* [in] Exit code for this thread */
314 BOOL last;
315 SERVER_START_REQ( terminate_thread )
317 /* send the exit code to the server */
318 req->handle = GetCurrentThread();
319 req->exit_code = code;
320 wine_server_call( req );
321 last = reply->last;
323 SERVER_END_REQ;
325 if (last)
327 LdrShutdownProcess();
328 exit( code );
330 else
332 LdrShutdownThread();
333 if (!(NtCurrentTeb()->tibflags & TEBF_WIN32)) TASK_ExitTask();
334 SYSDEPS_ExitThread( code );
338 /***********************************************************************
339 * OpenThread Retrieves a handle to a thread from its thread id
341 * RETURNS
342 * None
344 HANDLE WINAPI OpenThread( DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId )
346 HANDLE ret = 0;
347 SERVER_START_REQ( open_thread )
349 req->tid = dwThreadId;
350 req->access = dwDesiredAccess;
351 req->inherit = bInheritHandle;
352 if (!wine_server_call_err( req )) ret = reply->handle;
354 SERVER_END_REQ;
355 return ret;
358 /**********************************************************************
359 * TerminateThread [KERNEL32.@] Terminates a thread
361 * RETURNS
362 * Success: TRUE
363 * Failure: FALSE
365 BOOL WINAPI TerminateThread( HANDLE handle, /* [in] Handle to thread */
366 DWORD exit_code) /* [in] Exit code for thread */
368 NTSTATUS status = NtTerminateThread( handle, exit_code );
369 if (status) SetLastError( RtlNtStatusToDosError(status) );
370 return !status;
374 /**********************************************************************
375 * GetExitCodeThread (KERNEL32.@)
377 * Gets termination status of thread.
379 * RETURNS
380 * Success: TRUE
381 * Failure: FALSE
383 BOOL WINAPI GetExitCodeThread(
384 HANDLE hthread, /* [in] Handle to thread */
385 LPDWORD exitcode) /* [out] Address to receive termination status */
387 THREAD_BASIC_INFORMATION info;
388 NTSTATUS status = NtQueryInformationThread( hthread, ThreadBasicInformation,
389 &info, sizeof(info), NULL );
391 if (status)
393 SetLastError( RtlNtStatusToDosError(status) );
394 return FALSE;
396 if (exitcode) *exitcode = info.ExitStatus;
397 return TRUE;
401 /* callback for QueueUserAPC */
402 static void CALLBACK call_user_apc( ULONG_PTR arg1, ULONG_PTR arg2, ULONG_PTR arg3 )
404 PAPCFUNC func = (PAPCFUNC)arg1;
405 func( arg2 );
408 /***********************************************************************
409 * QueueUserAPC (KERNEL32.@)
411 DWORD WINAPI QueueUserAPC( PAPCFUNC func, HANDLE hthread, ULONG_PTR data )
413 NTSTATUS status = NtQueueApcThread( hthread, call_user_apc, (ULONG_PTR)func, data, 0 );
415 if (status) SetLastError( RtlNtStatusToDosError(status) );
416 return !status;
420 /***********************************************************************
421 * ProcessIdToSessionId (KERNEL32.@)
422 * This function is available on Terminal Server 4SP4 and Windows 2000
424 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
426 /* According to MSDN, if the calling process is not in a terminal
427 * services environment, then the sessionid returned is zero.
429 *sessionid_ptr = 0;
430 return TRUE;
434 #ifdef __i386__
436 /***********************************************************************
437 * SetLastError (KERNEL.147)
438 * SetLastError (KERNEL32.@)
440 /* void WINAPI SetLastError( DWORD error ); */
441 __ASM_GLOBAL_FUNC( SetLastError,
442 "movl 4(%esp),%eax\n\t"
443 ".byte 0x64\n\t"
444 "movl %eax,0x60\n\t"
445 "ret $4" );
447 /***********************************************************************
448 * GetLastError (KERNEL.148)
449 * GetLastError (KERNEL32.@)
451 /* DWORD WINAPI GetLastError(void); */
452 __ASM_GLOBAL_FUNC( GetLastError, ".byte 0x64\n\tmovl 0x60,%eax\n\tret" );
454 /***********************************************************************
455 * GetCurrentProcessId (KERNEL.471)
456 * GetCurrentProcessId (KERNEL32.@)
458 /* DWORD WINAPI GetCurrentProcessId(void) */
459 __ASM_GLOBAL_FUNC( GetCurrentProcessId, ".byte 0x64\n\tmovl 0x20,%eax\n\tret" );
461 /***********************************************************************
462 * GetCurrentThreadId (KERNEL.462)
463 * GetCurrentThreadId (KERNEL32.@)
465 /* DWORD WINAPI GetCurrentThreadId(void) */
466 __ASM_GLOBAL_FUNC( GetCurrentThreadId, ".byte 0x64\n\tmovl 0x24,%eax\n\tret" );
468 #else /* __i386__ */
470 /**********************************************************************
471 * SetLastError (KERNEL.147)
472 * SetLastError (KERNEL32.@)
474 * Sets the last-error code.
476 void WINAPI SetLastError( DWORD error ) /* [in] Per-thread error code */
478 NtCurrentTeb()->last_error = error;
481 /**********************************************************************
482 * GetLastError (KERNEL.148)
483 * GetLastError (KERNEL32.@)
485 * Returns last-error code.
487 DWORD WINAPI GetLastError(void)
489 return NtCurrentTeb()->last_error;
492 /***********************************************************************
493 * GetCurrentProcessId (KERNEL.471)
494 * GetCurrentProcessId (KERNEL32.@)
496 * Returns process identifier.
498 DWORD WINAPI GetCurrentProcessId(void)
500 return (DWORD)NtCurrentTeb()->pid;
503 /***********************************************************************
504 * GetCurrentThreadId (KERNEL.462)
505 * GetCurrentThreadId (KERNEL32.@)
507 * Returns thread identifier.
509 DWORD WINAPI GetCurrentThreadId(void)
511 return NtCurrentTeb()->tid;
514 #endif /* __i386__ */