Add de-interleaving for GIF images.
[wine] / dlls / ntdll / thread.c
1 /*
2  * NT threads support
3  *
4  * Copyright 1996, 2003 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 <sys/types.h>
25 #ifdef HAVE_SYS_MMAN_H
26 #include <sys/mman.h>
27 #endif
28
29 #include "ntstatus.h"
30 #include "thread.h"
31 #include "winternl.h"
32 #include "wine/library.h"
33 #include "wine/server.h"
34 #include "wine/pthread.h"
35 #include "wine/debug.h"
36 #include "ntdll_misc.h"
37
38 WINE_DEFAULT_DEBUG_CHANNEL(thread);
39
40 /* info passed to a starting thread */
41 struct startup_info
42 {
43     struct wine_pthread_thread_info pthread_info;
44     PRTL_THREAD_START_ROUTINE       entry_point;
45     void                           *entry_arg;
46 };
47
48 static PEB peb;
49 static PEB_LDR_DATA ldr;
50 static RTL_USER_PROCESS_PARAMETERS params;  /* default parameters if no parent */
51 static RTL_BITMAP tls_bitmap;
52 static LIST_ENTRY tls_links;
53
54
55 /***********************************************************************
56  *           alloc_teb
57  */
58 static TEB *alloc_teb( ULONG *size )
59 {
60     TEB *teb;
61
62     *size = SIGNAL_STACK_SIZE + sizeof(TEB);
63     teb = wine_anon_mmap( NULL, *size, PROT_READ | PROT_WRITE | PROT_EXEC, 0 );
64     if (teb == (TEB *)-1) return NULL;
65     if (!(teb->teb_sel = wine_ldt_alloc_fs()))
66     {
67         munmap( teb, *size );
68         return NULL;
69     }
70     teb->Tib.ExceptionList = (void *)~0UL;
71     teb->Tib.StackBase     = (void *)~0UL;
72     teb->Tib.Self          = &teb->Tib;
73     teb->Peb               = &peb;
74     teb->StaticUnicodeString.Buffer        = teb->StaticUnicodeBuffer;
75     teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
76     return teb;
77 }
78
79
80 /***********************************************************************
81  *           free_teb
82  */
83 static inline void free_teb( TEB *teb )
84 {
85     ULONG size = 0;
86     void *addr = teb;
87
88     NtFreeVirtualMemory( GetCurrentProcess(), &addr, &size, MEM_RELEASE );
89     wine_ldt_free_fs( teb->teb_sel );
90     munmap( teb, SIGNAL_STACK_SIZE + sizeof(TEB) );
91 }
92
93
94 /***********************************************************************
95  *           thread_init
96  *
97  * Setup the initial thread.
98  *
99  * NOTES: The first allocated TEB on NT is at 0x7ffde000.
100  */
101 void thread_init(void)
102 {
103     TEB *teb;
104     void *addr;
105     ULONG size;
106     struct wine_pthread_thread_info thread_info;
107     static struct debug_info debug_info;  /* debug info for initial thread */
108
109     peb.NumberOfProcessors = 1;
110     peb.ProcessParameters  = &params;
111     peb.TlsBitmap          = &tls_bitmap;
112     peb.LdrData            = &ldr;
113     RtlInitializeBitMap( &tls_bitmap, peb.TlsBitmapBits, sizeof(peb.TlsBitmapBits) * 8 );
114     InitializeListHead( &ldr.InLoadOrderModuleList );
115     InitializeListHead( &ldr.InMemoryOrderModuleList );
116     InitializeListHead( &ldr.InInitializationOrderModuleList );
117     InitializeListHead( &tls_links );
118
119     teb = alloc_teb( &size );
120     teb->request_fd    = -1;
121     teb->reply_fd      = -1;
122     teb->wait_fd[0]    = -1;
123     teb->wait_fd[1]    = -1;
124     teb->debug_info    = &debug_info;
125     InsertHeadList( &tls_links, &teb->TlsLinks );
126
127     thread_info.stack_base = NULL;
128     thread_info.stack_size = 0;
129     thread_info.teb_base   = teb;
130     thread_info.teb_size   = size;
131     thread_info.teb_sel    = teb->teb_sel;
132     wine_pthread_init_current_teb( &thread_info );
133     wine_pthread_init_thread( &thread_info );
134
135     debug_info.str_pos = debug_info.strings;
136     debug_info.out_pos = debug_info.output;
137     debug_init();
138     virtual_init();
139
140     /* setup the server connection */
141     server_init_process();
142     server_init_thread( thread_info.pid, thread_info.tid, NULL );
143
144     /* create a memory view for the TEB */
145     NtAllocateVirtualMemory( GetCurrentProcess(), &addr, teb, &size,
146                              MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
147
148     /* create the process heap */
149     if (!(peb.ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
150     {
151         MESSAGE( "wine: failed to create the process heap\n" );
152         exit(1);
153     }
154 }
155
156
157 /***********************************************************************
158  *           start_thread
159  *
160  * Startup routine for a newly created thread.
161  */
162 static void start_thread( struct wine_pthread_thread_info *info )
163 {
164     TEB *teb = info->teb_base;
165     struct startup_info *startup_info = (struct startup_info *)info;
166     PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
167     void *arg = startup_info->entry_arg;
168     struct debug_info debug_info;
169     ULONG size;
170
171     debug_info.str_pos = debug_info.strings;
172     debug_info.out_pos = debug_info.output;
173     teb->debug_info = &debug_info;
174
175     wine_pthread_init_current_teb( info );
176     SIGNAL_Init();
177     server_init_thread( info->pid, info->tid, func );
178     wine_pthread_init_thread( info );
179
180     /* allocate a memory view for the stack */
181     size = info->stack_size;
182     NtAllocateVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, info->stack_base,
183                              &size, MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
184     /* limit is lower than base since the stack grows down */
185     teb->Tib.StackBase  = (char *)info->stack_base + info->stack_size;
186     teb->Tib.StackLimit = info->stack_base;
187
188     /* setup the guard page */
189     size = 1;
190     NtProtectVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size,
191                             PAGE_EXECUTE_READWRITE | PAGE_GUARD, NULL );
192     RtlFreeHeap( GetProcessHeap(), 0, info );
193
194     RtlAcquirePebLock();
195     InsertHeadList( &tls_links, &teb->TlsLinks );
196     RtlReleasePebLock();
197
198     func( arg );
199 }
200
201
202 /***********************************************************************
203  *              RtlCreateUserThread   (NTDLL.@)
204  */
205 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
206                                      BOOLEAN suspended, PVOID stack_addr,
207                                      SIZE_T stack_reserve, SIZE_T stack_commit,
208                                      PRTL_THREAD_START_ROUTINE start, void *param,
209                                      HANDLE *handle_ptr, CLIENT_ID *id )
210 {
211     struct startup_info *info = NULL;
212     HANDLE handle = 0;
213     TEB *teb = NULL;
214     DWORD tid = 0;
215     ULONG size;
216     int request_pipe[2];
217     NTSTATUS status;
218
219     if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
220     fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
221     wine_server_send_fd( request_pipe[0] );
222
223     SERVER_START_REQ( new_thread )
224     {
225         req->suspend    = suspended;
226         req->inherit    = 0;  /* FIXME */
227         req->request_fd = request_pipe[0];
228         if (!(status = wine_server_call( req )))
229         {
230             handle = reply->handle;
231             tid = reply->tid;
232         }
233         close( request_pipe[0] );
234     }
235     SERVER_END_REQ;
236
237     if (status) goto error;
238
239     if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
240     {
241         status = STATUS_NO_MEMORY;
242         goto error;
243     }
244
245     if (!(teb = alloc_teb( &size )))
246     {
247         status = STATUS_NO_MEMORY;
248         goto error;
249     }
250     teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
251     teb->ClientId.UniqueThread  = (HANDLE)tid;
252
253     teb->exit_code   = STILL_ACTIVE;
254     teb->request_fd  = request_pipe[1];
255     teb->reply_fd    = -1;
256     teb->wait_fd[0]  = -1;
257     teb->wait_fd[1]  = -1;
258     teb->htask16     = NtCurrentTeb()->htask16;
259
260     NtAllocateVirtualMemory( GetCurrentProcess(), &info->pthread_info.teb_base, teb, &size,
261                              MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
262     info->pthread_info.teb_size = size;
263     info->pthread_info.teb_sel  = teb->teb_sel;
264
265     if (!stack_reserve || !stack_commit)
266     {
267         IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
268         if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
269         if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
270     }
271     if (stack_reserve < stack_commit) stack_reserve = stack_commit;
272     stack_reserve = (stack_reserve + 0xffff) & ~0xffff;  /* round to 64K boundary */
273     if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024;  /* Xlib needs a large stack */
274
275     info->pthread_info.stack_base = NULL;
276     info->pthread_info.stack_size = stack_reserve;
277     info->pthread_info.entry      = start_thread;
278     info->entry_point             = start;
279     info->entry_arg               = param;
280
281     if (wine_pthread_create_thread( &info->pthread_info ) == -1)
282     {
283         status = STATUS_NO_MEMORY;
284         goto error;
285     }
286
287     if (id) id->UniqueThread = (HANDLE)tid;
288     if (handle_ptr) *handle_ptr = handle;
289     else NtClose( handle );
290
291     return STATUS_SUCCESS;
292
293 error:
294     if (teb) free_teb( teb );
295     if (info) RtlFreeHeap( GetProcessHeap(), 0, info );
296     if (handle) NtClose( handle );
297     close( request_pipe[1] );
298     return status;
299 }
300
301
302 /***********************************************************************
303  *              NtOpenThread   (NTDLL.@)
304  *              ZwOpenThread   (NTDLL.@)
305  */
306 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
307                               const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
308 {
309     NTSTATUS ret;
310
311     SERVER_START_REQ( open_thread )
312     {
313         req->tid     = (thread_id_t)id->UniqueThread;
314         req->access  = access;
315         req->inherit = attr && (attr->Attributes & OBJ_INHERIT);
316         ret = wine_server_call( req );
317         *handle = reply->handle;
318     }
319     SERVER_END_REQ;
320     return ret;
321 }
322
323
324 /******************************************************************************
325  *              NtSuspendThread   (NTDLL.@)
326  *              ZwSuspendThread   (NTDLL.@)
327  */
328 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
329 {
330     NTSTATUS ret;
331
332     SERVER_START_REQ( suspend_thread )
333     {
334         req->handle = handle;
335         if (!(ret = wine_server_call( req ))) *count = reply->count;
336     }
337     SERVER_END_REQ;
338     return ret;
339 }
340
341
342 /******************************************************************************
343  *              NtResumeThread   (NTDLL.@)
344  *              ZwResumeThread   (NTDLL.@)
345  */
346 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
347 {
348     NTSTATUS ret;
349
350     SERVER_START_REQ( resume_thread )
351     {
352         req->handle = handle;
353         if (!(ret = wine_server_call( req ))) *count = reply->count;
354     }
355     SERVER_END_REQ;
356     return ret;
357 }
358
359
360 /******************************************************************************
361  *              NtTerminateThread  (NTDLL.@)
362  *              ZwTerminateThread  (NTDLL.@)
363  */
364 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
365 {
366     NTSTATUS ret;
367     BOOL self, last;
368
369     SERVER_START_REQ( terminate_thread )
370     {
371         req->handle    = handle;
372         req->exit_code = exit_code;
373         ret = wine_server_call( req );
374         self = !ret && reply->self;
375         last = reply->last;
376     }
377     SERVER_END_REQ;
378
379     if (self)
380     {
381         if (last) exit( exit_code );
382         else server_abort_thread( exit_code );
383     }
384     return ret;
385 }
386
387
388 /******************************************************************************
389  *              NtQueueApcThread  (NTDLL.@)
390  */
391 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
392                                   ULONG_PTR arg2, ULONG_PTR arg3 )
393 {
394     NTSTATUS ret;
395     SERVER_START_REQ( queue_apc )
396     {
397         req->handle = handle;
398         req->user   = 1;
399         req->func   = func;
400         req->arg1   = (void *)arg1;
401         req->arg2   = (void *)arg2;
402         req->arg3   = (void *)arg3;
403         ret = wine_server_call( req );
404     }
405     SERVER_END_REQ;
406     return ret;
407 }
408
409
410 /***********************************************************************
411  *              NtSetContextThread  (NTDLL.@)
412  *              ZwSetContextThread  (NTDLL.@)
413  */
414 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
415 {
416     NTSTATUS ret;
417
418     SERVER_START_REQ( set_thread_context )
419     {
420         req->handle = handle;
421         req->flags  = context->ContextFlags;
422         wine_server_add_data( req, context, sizeof(*context) );
423         ret = wine_server_call( req );
424     }
425     SERVER_END_REQ;
426     return ret;
427 }
428
429
430 /***********************************************************************
431  *              NtGetContextThread  (NTDLL.@)
432  *              ZwGetContextThread  (NTDLL.@)
433  */
434 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
435 {
436     NTSTATUS ret;
437
438     SERVER_START_REQ( get_thread_context )
439     {
440         req->handle = handle;
441         req->flags = context->ContextFlags;
442         wine_server_add_data( req, context, sizeof(*context) );
443         wine_server_set_reply( req, context, sizeof(*context) );
444         ret = wine_server_call( req );
445     }
446     SERVER_END_REQ;
447     return ret;
448 }
449
450
451 /******************************************************************************
452  *              NtQueryInformationThread  (NTDLL.@)
453  *              ZwQueryInformationThread  (NTDLL.@)
454  */
455 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
456                                           void *data, ULONG length, ULONG *ret_len )
457 {
458     NTSTATUS status;
459
460     switch(class)
461     {
462     case ThreadBasicInformation:
463         {
464             THREAD_BASIC_INFORMATION info;
465
466             SERVER_START_REQ( get_thread_info )
467             {
468                 req->handle = handle;
469                 req->tid_in = 0;
470                 if (!(status = wine_server_call( req )))
471                 {
472                     info.ExitStatus             = reply->exit_code;
473                     info.TebBaseAddress         = reply->teb;
474                     info.ClientId.UniqueProcess = (HANDLE)reply->pid;
475                     info.ClientId.UniqueThread  = (HANDLE)reply->tid;
476                     info.AffinityMask           = reply->affinity;
477                     info.Priority               = reply->priority;
478                     info.BasePriority           = reply->priority;  /* FIXME */
479                 }
480             }
481             SERVER_END_REQ;
482             if (status == STATUS_SUCCESS)
483             {
484                 if (data) memcpy( data, &info, min( length, sizeof(info) ));
485                 if (ret_len) *ret_len = min( length, sizeof(info) );
486             }
487         }
488         return status;
489     case ThreadTimes:
490     case ThreadPriority:
491     case ThreadBasePriority:
492     case ThreadAffinityMask:
493     case ThreadImpersonationToken:
494     case ThreadDescriptorTableEntry:
495     case ThreadEnableAlignmentFaultFixup:
496     case ThreadEventPair_Reusable:
497     case ThreadQuerySetWin32StartAddress:
498     case ThreadZeroTlsCell:
499     case ThreadPerformanceCount:
500     case ThreadAmILastThread:
501     case ThreadIdealProcessor:
502     case ThreadPriorityBoost:
503     case ThreadSetTlsArrayAddress:
504     case ThreadIsIoPending:
505     default:
506         FIXME( "info class %d not supported yet\n", class );
507         return STATUS_NOT_IMPLEMENTED;
508     }
509 }
510
511
512 /******************************************************************************
513  *              NtSetInformationThread  (NTDLL.@)
514  *              ZwSetInformationThread  (NTDLL.@)
515  */
516 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
517                                         LPCVOID data, ULONG length )
518 {
519     switch(class)
520     {
521     case ThreadZeroTlsCell:
522         if (handle == GetCurrentThread())
523         {
524             LIST_ENTRY *entry;
525             DWORD index;
526
527             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
528             index = *(const DWORD *)data;
529             if (index >= 64) return STATUS_INVALID_PARAMETER;
530             RtlAcquirePebLock();
531             for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
532             {
533                 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
534                 teb->TlsSlots[index] = 0;
535             }
536             RtlReleasePebLock();
537             return STATUS_SUCCESS;
538         }
539         FIXME( "ZeroTlsCell not supported on other threads\n" );
540         return STATUS_NOT_IMPLEMENTED;
541
542     case ThreadImpersonationToken:
543         {
544             const HANDLE *phToken = data;
545             if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
546             FIXME("Set ThreadImpersonationToken handle to %p\n", *phToken );
547             return STATUS_SUCCESS;
548         }
549     case ThreadBasicInformation:
550     case ThreadTimes:
551     case ThreadPriority:
552     case ThreadBasePriority:
553     case ThreadAffinityMask:
554     case ThreadDescriptorTableEntry:
555     case ThreadEnableAlignmentFaultFixup:
556     case ThreadEventPair_Reusable:
557     case ThreadQuerySetWin32StartAddress:
558     case ThreadPerformanceCount:
559     case ThreadAmILastThread:
560     case ThreadIdealProcessor:
561     case ThreadPriorityBoost:
562     case ThreadSetTlsArrayAddress:
563     case ThreadIsIoPending:
564     default:
565         FIXME( "info class %d not supported yet\n", class );
566         return STATUS_NOT_IMPLEMENTED;
567     }
568 }
569
570
571 /**********************************************************************
572  *           NtCurrentTeb   (NTDLL.@)
573  */
574 #if defined(__i386__) && defined(__GNUC__)
575
576 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" );
577
578 #elif defined(__i386__) && defined(_MSC_VER)
579
580 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
581
582 #else
583
584 /**********************************************************************/
585
586 TEB * WINAPI NtCurrentTeb(void)
587 {
588     return wine_pthread_get_current_teb();
589 }
590
591 #endif  /* __i386__ */