Make a distinction between the thread Unix pid and the process wide
[wine] / scheduler / sysdeps.c
1 /*
2  * System-dependent scheduler support
3  *
4  * Copyright 1998 Alexandre Julliard
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <signal.h>
25 #include <stdio.h>
26 #ifdef HAVE_UNISTD_H
27 # include <unistd.h>
28 #endif
29 #ifdef HAVE_SYS_TIME_H
30 # include <sys/time.h>
31 #endif
32 #ifdef HAVE_SYS_SYSCALL_H
33 # include <sys/syscall.h>
34 #endif
35 #ifdef HAVE_SYS_LWP_H
36 # include <sys/lwp.h>
37 #endif
38 #ifdef HAVE_UCONTEXT_H
39 # include <ucontext.h>
40 #endif
41 #ifdef HAVE_SYS_MMAN_H
42 #include <sys/mman.h>
43 #endif
44 #ifdef HAVE_SCHED_H
45 #include <sched.h>
46 #endif
47
48 #include "thread.h"
49 #include "wine/server.h"
50 #include "winbase.h"
51 #include "wine/winbase16.h"
52 #include "wine/exception.h"
53 #include "wine/library.h"
54 #include "wine/debug.h"
55
56 WINE_DEFAULT_DEBUG_CHANNEL(thread);
57
58 struct thread_cleanup_info
59 {
60     void *stack_base;
61     int   stack_size;
62     int   status;
63 };
64
65 /* temporary stacks used on thread exit */
66 #define TEMP_STACK_SIZE 1024
67 #define NB_TEMP_STACKS  8
68 static char temp_stacks[NB_TEMP_STACKS][TEMP_STACK_SIZE];
69 static LONG next_temp_stack;  /* next temp stack to use */
70
71 /***********************************************************************
72  *           SYSDEPS_SetCurThread
73  *
74  * Make 'thread' the current thread.
75  */
76 void SYSDEPS_SetCurThread( TEB *teb )
77 {
78 #if defined(__i386__)
79     /* On the i386, the current thread is in the %fs register */
80     LDT_ENTRY fs_entry;
81
82     wine_ldt_set_base( &fs_entry, teb );
83     wine_ldt_set_limit( &fs_entry, 0xfff );
84     wine_ldt_set_flags( &fs_entry, WINE_LDT_FLAGS_DATA|WINE_LDT_FLAGS_32BIT );
85     wine_ldt_init_fs( teb->teb_sel, &fs_entry );
86     teb->gs_sel = wine_get_gs();
87 #elif defined(__powerpc__)
88     /* On PowerPC, the current TEB is in the gpr13 register */
89     __asm__ __volatile__("mr 2, %0" : : "r" (teb));
90 #elif defined(HAVE__LWP_CREATE)
91     /* On non-i386 Solaris, we use the LWP private pointer */
92     _lwp_setprivate( teb );
93 #endif
94 }
95
96
97 /***********************************************************************
98  *           call_on_thread_stack
99  *
100  * Call a function once we switched to the thread stack.
101  */
102 static void call_on_thread_stack( void *func )
103 {
104     __TRY
105     {
106         void (*funcptr)(void) = func;
107         funcptr();
108     }
109     __EXCEPT(UnhandledExceptionFilter)
110     {
111         TerminateThread( GetCurrentThread(), GetExceptionCode() );
112     }
113     __ENDTRY
114     SYSDEPS_ExitThread(0);  /* should never get here */
115 }
116
117
118 /***********************************************************************
119  *           get_temp_stack
120  *
121  * Get a temporary stack address to run the thread exit code on.
122  */
123 inline static char *get_temp_stack(void)
124 {
125     unsigned int next = InterlockedExchangeAdd( &next_temp_stack, 1 );
126     return temp_stacks[next % NB_TEMP_STACKS];
127 }
128
129
130 /***********************************************************************
131  *           cleanup_thread
132  *
133  * Cleanup the remains of a thread. Runs on a temporary stack.
134  */
135 static void cleanup_thread( void *ptr )
136 {
137     /* copy the info structure since it is on the stack we will free */
138     struct thread_cleanup_info info = *(struct thread_cleanup_info *)ptr;
139     munmap( info.stack_base, info.stack_size );
140     wine_ldt_free_fs( wine_get_fs() );
141 #ifdef HAVE__LWP_CREATE
142     _lwp_exit();
143 #endif
144     _exit( info.status );
145 }
146
147
148 /***********************************************************************
149  *           SYSDEPS_StartThread
150  *
151  * Startup routine for a new thread.
152  */
153 static void SYSDEPS_StartThread( TEB *teb )
154 {
155     SYSDEPS_SetCurThread( teb );
156     SIGNAL_Init();
157     CLIENT_InitThread();
158     __TRY
159     {
160         teb->startup();
161     }
162     __EXCEPT(UnhandledExceptionFilter)
163     {
164         TerminateThread( GetCurrentThread(), GetExceptionCode() );
165     }
166     __ENDTRY
167     SYSDEPS_ExitThread(0);  /* should never get here */
168 }
169
170
171 /***********************************************************************
172  *           SYSDEPS_SpawnThread
173  *
174  * Start running a new thread.
175  * Return -1 on error, 0 if OK.
176  */
177 int SYSDEPS_SpawnThread( TEB *teb )
178 {
179 #ifdef HAVE_CLONE
180     if (clone( (int (*)(void *))SYSDEPS_StartThread, teb->stack_top,
181                CLONE_VM | CLONE_FS | CLONE_FILES, teb ) < 0)
182         return -1;
183     return 0;
184 #elif defined(HAVE_RFORK)
185     void **sp = (void **)teb->stack_top;
186     *--sp = teb;
187     *--sp = 0;
188     *--sp = SYSDEPS_StartThread;
189     __asm__ __volatile__(
190     "pushl %2;\n\t"             /* flags */
191     "pushl $0;\n\t"             /* 0 ? */
192     "movl %1,%%eax;\n\t"        /* SYS_rfork */
193     ".byte 0x9a; .long 0; .word 7;\n\t" /* lcall 7:0... FreeBSD syscall */
194     "cmpl $0, %%edx;\n\t"
195     "je 1f;\n\t"
196     "movl %0,%%esp;\n\t"        /* child -> new thread */
197     "ret;\n"
198     "1:\n\t"            /* parent -> caller thread */
199     "addl $8,%%esp" :
200     : "r" (sp), "g" (SYS_rfork), "g" (RFPROC | RFMEM)
201     : "eax", "edx");
202     return 0;
203 #elif defined(HAVE__LWP_CREATE)
204     ucontext_t context;
205     _lwp_makecontext( &context, (void(*)(void *))SYSDEPS_StartThread, teb,
206                       NULL, teb->stack_base, (char *)teb->stack_top - (char *)teb->stack_base );
207     if ( _lwp_create( &context, 0, NULL ) )
208         return -1;
209     return 0;
210 #endif
211
212     FIXME("CreateThread: stub\n" );
213     return -1;
214 }
215
216
217 /***********************************************************************
218  *           SYSDEPS_CallOnStack
219  */
220 void DECLSPEC_NORETURN SYSDEPS_CallOnStack( void (*func)(LPVOID), LPVOID arg );
221 #ifdef __i386__
222 #  ifdef __GNUC__
223 __ASM_GLOBAL_FUNC( SYSDEPS_CallOnStack,
224                    "movl 4(%esp),%ecx\n\t"  /* func */
225                    "movl 8(%esp),%edx\n\t"  /* arg */
226                    ".byte 0x64\n\tmovl 0x04,%esp\n\t"  /* teb->stack_top */
227                    "pushl %edx\n\t"
228                    "xorl %ebp,%ebp\n\t"
229                    "call *%ecx\n\t"
230                    "int $3" /* we never return here */ );
231 #  elif defined(_MSC_VER)
232 __declspec(naked) void SYSDEPS_CallOnStack( void (*func)(LPVOID), LPVOID arg )
233 {
234   __asm mov ecx, 4[esp];
235   __asm mov edx, 8[esp];
236   __asm mov fs:[0x04], esp;
237   __asm push edx;
238   __asm xor ebp, ebp;
239   __asm call [ecx];
240   __asm int 3;
241 }
242 #  endif /* defined(__GNUC__) || defined(_MSC_VER) */
243 #elif defined(__sparc__) && defined(__GNUC__)
244 __ASM_GLOBAL_FUNC( SYSDEPS_CallOnStack,
245                    "mov %o0, %l0\n\t" /* store first argument */
246                    "call " __ASM_NAME("NtCurrentTeb") ", 0\n\t"
247                    "mov %o1, %l1\n\t" /* delay slot: store second argument */
248                    "ld [%o0+4], %sp\n\t" /* teb->stack_top */
249                    "call %l0, 0\n\t" /* call func */
250                    "mov %l1, %o0\n\t" /* delay slot:  arg for func */
251                    "ta 0x01\n\t"); /* breakpoint - we never get here */
252 #else /* !sparc, !i386 */
253 void SYSDEPS_CallOnStack( void (*func)(LPVOID), LPVOID arg )
254 {
255     func( arg );
256     while(1); /* avoid warning */
257 }
258 #endif /* !defined(__i386__) && !defined(__sparc__) */
259
260
261 /***********************************************************************
262  *           SYSDEPS_SwitchToThreadStack
263  */
264 void SYSDEPS_SwitchToThreadStack( void (*func)(void) )
265 {
266     SYSDEPS_CallOnStack( call_on_thread_stack, func );
267 }
268
269
270 /***********************************************************************
271  *           SYSDEPS_ExitThread
272  *
273  * Exit a running thread; must not return.
274  */
275 void SYSDEPS_ExitThread( int status )
276 {
277     TEB *teb = NtCurrentTeb();
278     struct thread_cleanup_info info;
279     MEMORY_BASIC_INFORMATION meminfo;
280
281     wine_ldt_free_entries( teb->stack_sel, 1 );
282     VirtualQuery( teb->stack_top, &meminfo, sizeof(meminfo) );
283     info.stack_base = meminfo.AllocationBase;
284     info.stack_size = meminfo.RegionSize + ((char *)teb->stack_top - (char *)meminfo.AllocationBase);
285     info.status     = status;
286
287     SIGNAL_Block();
288     SIGNAL_Reset();
289
290     VirtualFree( teb->stack_base, 0, MEM_RELEASE | MEM_SYSTEM );
291     close( teb->wait_fd[0] );
292     close( teb->wait_fd[1] );
293     close( teb->reply_fd );
294     close( teb->request_fd );
295     teb->stack_low = get_temp_stack();
296     teb->stack_top = (char *) teb->stack_low + TEMP_STACK_SIZE;
297     SYSDEPS_CallOnStack( cleanup_thread, &info );
298 }
299
300
301 /***********************************************************************
302  *           SYSDEPS_AbortThread
303  *
304  * Same as SYSDEPS_ExitThread, but must not do anything that requires a server call.
305  */
306 void SYSDEPS_AbortThread( int status )
307 {
308     SIGNAL_Block();
309     SIGNAL_Reset();
310     close( NtCurrentTeb()->wait_fd[0] );
311     close( NtCurrentTeb()->wait_fd[1] );
312     close( NtCurrentTeb()->reply_fd );
313     close( NtCurrentTeb()->request_fd );
314 #ifdef HAVE__LWP_CREATE
315     _lwp_exit();
316 #endif
317     for (;;)  /* avoid warning */
318         _exit( status );
319 }
320
321
322 /**********************************************************************
323  *           NtCurrentTeb   (NTDLL.@)
324  *
325  * This will crash and burn if called before threading is initialized
326  */
327 #if defined(__i386__) && defined(__GNUC__)
328 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" );
329 #elif defined(__i386__) && defined(_MSC_VER)
330 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
331 #elif defined(HAVE__LWP_CREATE)
332 /***********************************************************************
333  *              NtCurrentTeb (NTDLL.@)
334  */
335 struct _TEB * WINAPI NtCurrentTeb(void)
336 {
337     extern void *_lwp_getprivate(void);
338     return (struct _TEB *)_lwp_getprivate();
339 }
340 #elif defined(__powerpc__)
341 __ASM_GLOBAL_FUNC( NtCurrentTeb, "\n\tmr 3,2\n\tblr" );
342 #else
343 # error NtCurrentTeb not defined for this architecture
344 #endif  /* __i386__ */