Store %gs in the TEB on every call to 16-bit code, and don't restore
[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 #elif defined(__powerpc__)
87     /* On PowerPC, the current TEB is in the gpr13 register */
88     __asm__ __volatile__("mr 2, %0" : : "r" (teb));
89 #elif defined(HAVE__LWP_CREATE)
90     /* On non-i386 Solaris, we use the LWP private pointer */
91     _lwp_setprivate( teb );
92 #endif
93 }
94
95
96 /***********************************************************************
97  *           call_on_thread_stack
98  *
99  * Call a function once we switched to the thread stack.
100  */
101 static void call_on_thread_stack( void *func )
102 {
103     __TRY
104     {
105         void (*funcptr)(void) = func;
106         funcptr();
107     }
108     __EXCEPT(UnhandledExceptionFilter)
109     {
110         TerminateThread( GetCurrentThread(), GetExceptionCode() );
111     }
112     __ENDTRY
113     SYSDEPS_ExitThread(0);  /* should never get here */
114 }
115
116
117 /***********************************************************************
118  *           get_temp_stack
119  *
120  * Get a temporary stack address to run the thread exit code on.
121  */
122 inline static char *get_temp_stack(void)
123 {
124     unsigned int next = InterlockedExchangeAdd( &next_temp_stack, 1 );
125     return temp_stacks[next % NB_TEMP_STACKS];
126 }
127
128
129 /***********************************************************************
130  *           cleanup_thread
131  *
132  * Cleanup the remains of a thread. Runs on a temporary stack.
133  */
134 static void cleanup_thread( void *ptr )
135 {
136     /* copy the info structure since it is on the stack we will free */
137     struct thread_cleanup_info info = *(struct thread_cleanup_info *)ptr;
138     munmap( info.stack_base, info.stack_size );
139     wine_ldt_free_fs( wine_get_fs() );
140 #ifdef HAVE__LWP_CREATE
141     _lwp_exit();
142 #endif
143     _exit( info.status );
144 }
145
146
147 /***********************************************************************
148  *           SYSDEPS_StartThread
149  *
150  * Startup routine for a new thread.
151  */
152 static void SYSDEPS_StartThread( TEB *teb )
153 {
154     SYSDEPS_SetCurThread( teb );
155     SIGNAL_Init();
156     CLIENT_InitThread();
157     __TRY
158     {
159         teb->startup();
160     }
161     __EXCEPT(UnhandledExceptionFilter)
162     {
163         TerminateThread( GetCurrentThread(), GetExceptionCode() );
164     }
165     __ENDTRY
166     SYSDEPS_ExitThread(0);  /* should never get here */
167 }
168
169
170 /***********************************************************************
171  *           SYSDEPS_SpawnThread
172  *
173  * Start running a new thread.
174  * Return -1 on error, 0 if OK.
175  */
176 int SYSDEPS_SpawnThread( TEB *teb )
177 {
178 #ifdef HAVE_CLONE
179     if (clone( (int (*)(void *))SYSDEPS_StartThread, teb->stack_top,
180                CLONE_VM | CLONE_FS | CLONE_FILES, teb ) < 0)
181         return -1;
182     return 0;
183 #elif defined(HAVE_RFORK)
184     void **sp = (void **)teb->stack_top;
185     *--sp = teb;
186     *--sp = 0;
187     *--sp = SYSDEPS_StartThread;
188     __asm__ __volatile__(
189     "pushl %2;\n\t"             /* flags */
190     "pushl $0;\n\t"             /* 0 ? */
191     "movl %1,%%eax;\n\t"        /* SYS_rfork */
192     ".byte 0x9a; .long 0; .word 7;\n\t" /* lcall 7:0... FreeBSD syscall */
193     "cmpl $0, %%edx;\n\t"
194     "je 1f;\n\t"
195     "movl %0,%%esp;\n\t"        /* child -> new thread */
196     "ret;\n"
197     "1:\n\t"            /* parent -> caller thread */
198     "addl $8,%%esp" :
199     : "r" (sp), "g" (SYS_rfork), "g" (RFPROC | RFMEM)
200     : "eax", "edx");
201     return 0;
202 #elif defined(HAVE__LWP_CREATE)
203     ucontext_t context;
204     _lwp_makecontext( &context, (void(*)(void *))SYSDEPS_StartThread, teb,
205                       NULL, teb->stack_base, (char *)teb->stack_top - (char *)teb->stack_base );
206     if ( _lwp_create( &context, 0, NULL ) )
207         return -1;
208     return 0;
209 #endif
210
211     FIXME("CreateThread: stub\n" );
212     return -1;
213 }
214
215
216 /***********************************************************************
217  *           SYSDEPS_CallOnStack
218  */
219 void DECLSPEC_NORETURN SYSDEPS_CallOnStack( void (*func)(LPVOID), LPVOID arg );
220 #ifdef __i386__
221 #  ifdef __GNUC__
222 __ASM_GLOBAL_FUNC( SYSDEPS_CallOnStack,
223                    "movl 4(%esp),%ecx\n\t"  /* func */
224                    "movl 8(%esp),%edx\n\t"  /* arg */
225                    ".byte 0x64\n\tmovl 0x04,%esp\n\t"  /* teb->stack_top */
226                    "pushl %edx\n\t"
227                    "xorl %ebp,%ebp\n\t"
228                    "call *%ecx\n\t"
229                    "int $3" /* we never return here */ );
230 #  elif defined(_MSC_VER)
231 __declspec(naked) void SYSDEPS_CallOnStack( void (*func)(LPVOID), LPVOID arg )
232 {
233   __asm mov ecx, 4[esp];
234   __asm mov edx, 8[esp];
235   __asm mov fs:[0x04], esp;
236   __asm push edx;
237   __asm xor ebp, ebp;
238   __asm call [ecx];
239   __asm int 3;
240 }
241 #  endif /* defined(__GNUC__) || defined(_MSC_VER) */
242 #elif defined(__sparc__) && defined(__GNUC__)
243 __ASM_GLOBAL_FUNC( SYSDEPS_CallOnStack,
244                    "mov %o0, %l0\n\t" /* store first argument */
245                    "call " __ASM_NAME("NtCurrentTeb") ", 0\n\t"
246                    "mov %o1, %l1\n\t" /* delay slot: store second argument */
247                    "ld [%o0+4], %sp\n\t" /* teb->stack_top */
248                    "call %l0, 0\n\t" /* call func */
249                    "mov %l1, %o0\n\t" /* delay slot:  arg for func */
250                    "ta 0x01\n\t"); /* breakpoint - we never get here */
251 #else /* !sparc, !i386 */
252 void SYSDEPS_CallOnStack( void (*func)(LPVOID), LPVOID arg )
253 {
254     func( arg );
255     while(1); /* avoid warning */
256 }
257 #endif /* !defined(__i386__) && !defined(__sparc__) */
258
259
260 /***********************************************************************
261  *           SYSDEPS_SwitchToThreadStack
262  */
263 void SYSDEPS_SwitchToThreadStack( void (*func)(void) )
264 {
265     SYSDEPS_CallOnStack( call_on_thread_stack, func );
266 }
267
268
269 /***********************************************************************
270  *           SYSDEPS_ExitThread
271  *
272  * Exit a running thread; must not return.
273  */
274 void SYSDEPS_ExitThread( int status )
275 {
276     TEB *teb = NtCurrentTeb();
277     struct thread_cleanup_info info;
278     MEMORY_BASIC_INFORMATION meminfo;
279
280     wine_ldt_free_entries( teb->stack_sel, 1 );
281     VirtualQuery( teb->stack_top, &meminfo, sizeof(meminfo) );
282     info.stack_base = meminfo.AllocationBase;
283     info.stack_size = meminfo.RegionSize + ((char *)teb->stack_top - (char *)meminfo.AllocationBase);
284     info.status     = status;
285
286     SIGNAL_Block();
287     SIGNAL_Reset();
288
289     VirtualFree( teb->stack_base, 0, MEM_RELEASE | MEM_SYSTEM );
290     close( teb->wait_fd[0] );
291     close( teb->wait_fd[1] );
292     close( teb->reply_fd );
293     close( teb->request_fd );
294     teb->stack_low = get_temp_stack();
295     teb->stack_top = (char *) teb->stack_low + TEMP_STACK_SIZE;
296     SYSDEPS_CallOnStack( cleanup_thread, &info );
297 }
298
299
300 /***********************************************************************
301  *           SYSDEPS_AbortThread
302  *
303  * Same as SYSDEPS_ExitThread, but must not do anything that requires a server call.
304  */
305 void SYSDEPS_AbortThread( int status )
306 {
307     SIGNAL_Block();
308     SIGNAL_Reset();
309     close( NtCurrentTeb()->wait_fd[0] );
310     close( NtCurrentTeb()->wait_fd[1] );
311     close( NtCurrentTeb()->reply_fd );
312     close( NtCurrentTeb()->request_fd );
313 #ifdef HAVE__LWP_CREATE
314     _lwp_exit();
315 #endif
316     for (;;)  /* avoid warning */
317         _exit( status );
318 }
319
320
321 /**********************************************************************
322  *           NtCurrentTeb   (NTDLL.@)
323  *
324  * This will crash and burn if called before threading is initialized
325  */
326 #if defined(__i386__) && defined(__GNUC__)
327 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" );
328 #elif defined(__i386__) && defined(_MSC_VER)
329 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
330 #elif defined(HAVE__LWP_CREATE)
331 /***********************************************************************
332  *              NtCurrentTeb (NTDLL.@)
333  */
334 struct _TEB * WINAPI NtCurrentTeb(void)
335 {
336     extern void *_lwp_getprivate(void);
337     return (struct _TEB *)_lwp_getprivate();
338 }
339 #elif defined(__powerpc__)
340 __ASM_GLOBAL_FUNC( NtCurrentTeb, "\n\tmr 3,2\n\tblr" );
341 #else
342 # error NtCurrentTeb not defined for this architecture
343 #endif  /* __i386__ */