4 * Copyright 1996 Alexandre Julliard
10 #include <sys/socket.h>
13 #include "wine/winbase16.h"
21 #include "selectors.h"
25 #include "stackframe.h"
26 #include "debugtools.h"
30 DEFAULT_DEBUG_CHANNEL(thread
)
32 /* TEB of the initial thread */
33 static TEB initial_teb
;
35 /* Global thread list (FIXME: not thread-safe) */
36 TEB
*THREAD_First
= &initial_teb
;
38 /***********************************************************************
41 BOOL
THREAD_IsWin16( TEB
*teb
)
43 return !teb
|| !(teb
->flags
& TEBF_WIN32
);
46 /***********************************************************************
49 * Convert a thread id to a TEB, making sure it is valid.
51 TEB
*THREAD_IdToTEB( DWORD id
)
53 TEB
*teb
= THREAD_First
;
55 if (!id
) return NtCurrentTeb();
58 if ((DWORD
)teb
->tid
== id
) return teb
;
61 /* Allow task handles to be used; convert to main thread */
64 TDB
*pTask
= (TDB
*)GlobalLock16( id
);
65 if (pTask
) return pTask
->teb
;
67 SetLastError( ERROR_INVALID_PARAMETER
);
72 /***********************************************************************
75 * Initialization of a newly created TEB.
77 static BOOL
THREAD_InitTEB( TEB
*teb
, DWORD stack_size
, BOOL alloc_stack16
,
78 LPSECURITY_ATTRIBUTES sa
)
82 /* Allocate the stack */
85 * If stacksize smaller than 1 MB, allocate 1MB
86 * (one program wanted only 10 kB, which is recommendable, but some WINE
87 * functions, noteably in the files subdir, push HUGE structures and
88 * arrays on the stack. They probably shouldn't.)
89 * If stacksize larger than 16 MB, warn the user. (We could shrink the stack
90 * but this could give more or less unexplainable crashes.)
92 if (stack_size
<1024*1024)
93 stack_size
= 1024 * 1024;
94 if (stack_size
>= 16*1024*1024)
95 WARN("Thread stack size is %ld MB.\n",stack_size
/1024/1024);
96 teb
->stack_base
= VirtualAlloc(NULL
, stack_size
+ SIGNAL_STACK_SIZE
+
97 (alloc_stack16
? 0x10000 : 0),
98 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
);
99 if (!teb
->stack_base
) goto error
;
100 /* Set a guard page at the bottom of the stack */
101 VirtualProtect( teb
->stack_base
, 1, PAGE_EXECUTE_READWRITE
| PAGE_GUARD
, &old_prot
);
102 teb
->stack_top
= (char *)teb
->stack_base
+ stack_size
;
103 teb
->stack_low
= teb
->stack_base
;
104 teb
->signal_stack
= teb
->stack_top
; /* start of signal stack */
106 /* Allocate the 16-bit stack selector */
110 teb
->stack_sel
= SELECTOR_AllocBlock( teb
->stack_top
, 0x10000, SEGMENT_DATA
,
112 if (!teb
->stack_sel
) goto error
;
113 teb
->cur_stack
= PTR_SEG_OFF_TO_SEGPTR( teb
->stack_sel
,
114 0x10000 - sizeof(STACK16FRAME
) );
115 teb
->signal_stack
= (char *)teb
->signal_stack
+ 0x10000;
118 /* Create the thread event */
120 if (!(teb
->event
= CreateEventA( NULL
, FALSE
, FALSE
, NULL
))) goto error
;
121 teb
->event
= ConvertToGlobalHandle( teb
->event
);
125 if (teb
->event
) CloseHandle( teb
->event
);
126 if (teb
->stack_sel
) SELECTOR_FreeBlock( teb
->stack_sel
, 1 );
127 if (teb
->stack_base
) VirtualFree( teb
->stack_base
, 0, MEM_RELEASE
);
132 /***********************************************************************
135 * Free data structures associated with a thread.
136 * Must be called from the context of another thread.
138 void CALLBACK
THREAD_FreeTEB( ULONG_PTR arg
)
140 TEB
*teb
= (TEB
*)arg
;
141 TEB
**pptr
= &THREAD_First
;
143 TRACE("(%p) called\n", teb
);
144 SERVICE_Delete( teb
->cleanup
);
146 PROCESS_CallUserSignalProc( USIG_THREAD_EXIT
, 0 );
148 CloseHandle( teb
->event
);
149 while (*pptr
&& (*pptr
!= teb
)) pptr
= &(*pptr
)->next
;
150 if (*pptr
) *pptr
= teb
->next
;
152 /* Free the associated memory */
154 if (teb
->stack_sel
) SELECTOR_FreeBlock( teb
->stack_sel
, 1 );
155 SELECTOR_FreeBlock( teb
->teb_sel
, 1 );
156 close( teb
->socket
);
157 if (teb
->buffer
) munmap( teb
->buffer
, teb
->buffer_size
);
158 VirtualFree( teb
->stack_base
, 0, MEM_RELEASE
);
159 HeapFree( SystemHeap
, 0, teb
);
163 /***********************************************************************
164 * THREAD_CreateInitialThread
166 * Create the initial thread.
168 TEB
*THREAD_CreateInitialThread( PDB
*pdb
, int server_fd
)
170 initial_teb
.except
= (void *)-1;
171 initial_teb
.self
= &initial_teb
;
172 initial_teb
.flags
= /* TEBF_WIN32 */ 0;
173 initial_teb
.tls_ptr
= initial_teb
.tls_array
;
174 initial_teb
.process
= pdb
;
175 initial_teb
.exit_code
= 0x103; /* STILL_ACTIVE */
176 initial_teb
.socket
= server_fd
;
178 /* Allocate the TEB selector (%fs register) */
180 if (!(initial_teb
.teb_sel
= SELECTOR_AllocBlock( &initial_teb
, 0x1000,
181 SEGMENT_DATA
, TRUE
, FALSE
)))
183 MESSAGE("Could not allocate fs register for initial thread\n" );
186 SYSDEPS_SetCurThread( &initial_teb
);
188 /* Now proceed with normal initialization */
190 if (CLIENT_InitThread()) return NULL
;
191 if (!THREAD_InitTEB( &initial_teb
, 0, TRUE
, NULL
)) return NULL
;
196 /***********************************************************************
199 TEB
*THREAD_Create( PDB
*pdb
, DWORD flags
, DWORD stack_size
, BOOL alloc_stack16
,
200 LPSECURITY_ATTRIBUTES sa
, int *server_handle
)
202 struct new_thread_request
*req
= get_req_buffer();
204 HANDLE cleanup_object
;
206 TEB
*teb
= HeapAlloc( SystemHeap
, HEAP_ZERO_MEMORY
, sizeof(TEB
) );
207 if (!teb
) return NULL
;
208 teb
->except
= (void *)-1;
209 teb
->htask16
= pdb
->task
;
211 teb
->flags
= (pdb
->flags
& PDB32_WIN16_PROC
)? 0 : TEBF_WIN32
;
212 teb
->tls_ptr
= teb
->tls_array
;
214 teb
->exit_code
= 0x103; /* STILL_ACTIVE */
217 /* Allocate the TEB selector (%fs register) */
220 teb
->teb_sel
= SELECTOR_AllocBlock( teb
, 0x1000, SEGMENT_DATA
, TRUE
, FALSE
);
221 if (!teb
->teb_sel
) goto error
;
223 /* Create the socket pair for server communication */
225 if (socketpair( AF_UNIX
, SOCK_STREAM
, 0, fd
) == -1)
227 SetLastError( ERROR_TOO_MANY_OPEN_FILES
); /* FIXME */
231 fcntl( fd
[0], F_SETFD
, 1 ); /* set close on exec flag */
233 /* Create the thread on the server side */
235 req
->pid
= teb
->process
->server_pid
;
236 req
->suspend
= ((flags
& CREATE_SUSPENDED
) != 0);
237 req
->inherit
= (sa
&& (sa
->nLength
>=sizeof(*sa
)) && sa
->bInheritHandle
);
238 if (server_call_fd( REQ_NEW_THREAD
, fd
[1], NULL
)) goto error
;
240 *server_handle
= req
->handle
;
242 /* Do the rest of the initialization */
244 if (!THREAD_InitTEB( teb
, stack_size
, alloc_stack16
, sa
)) goto error
;
245 teb
->next
= THREAD_First
;
248 /* Install cleanup handler */
249 if ( !DuplicateHandle( GetCurrentProcess(), *server_handle
,
250 GetCurrentProcess(), &cleanup_object
,
251 0, FALSE
, DUPLICATE_SAME_ACCESS
) ) goto error
;
252 teb
->cleanup
= SERVICE_AddObject( cleanup_object
, THREAD_FreeTEB
, (ULONG_PTR
)teb
);
257 if (*server_handle
!= -1) CloseHandle( *server_handle
);
258 if (teb
->teb_sel
) SELECTOR_FreeBlock( teb
->teb_sel
, 1 );
259 if (teb
->socket
!= -1) close( teb
->socket
);
260 HeapFree( SystemHeap
, 0, teb
);
265 /***********************************************************************
268 * Start execution of a newly created thread. Does not return.
270 static void THREAD_Start(void)
272 LPTHREAD_START_ROUTINE func
= (LPTHREAD_START_ROUTINE
)NtCurrentTeb()->entry_point
;
273 PROCESS_CallUserSignalProc( USIG_THREAD_INIT
, 0 );
275 MODULE_DllThreadAttach( NULL
);
277 if (NtCurrentTeb()->process
->flags
& PDB32_DEBUGGED
) DEBUG_SendCreateThreadEvent( func
);
279 ExitThread( func( NtCurrentTeb()->entry_arg
) );
283 /***********************************************************************
284 * CreateThread (KERNEL32.63)
286 HANDLE WINAPI
CreateThread( SECURITY_ATTRIBUTES
*sa
, DWORD stack
,
287 LPTHREAD_START_ROUTINE start
, LPVOID param
,
288 DWORD flags
, LPDWORD id
)
291 TEB
*teb
= THREAD_Create( PROCESS_Current(), flags
, stack
, TRUE
, sa
, &handle
);
292 if (!teb
) return INVALID_HANDLE_VALUE
;
293 teb
->flags
|= TEBF_WIN32
;
294 teb
->entry_point
= start
;
295 teb
->entry_arg
= param
;
296 teb
->startup
= THREAD_Start
;
297 if (SYSDEPS_SpawnThread( teb
) == -1)
299 CloseHandle( handle
);
300 return INVALID_HANDLE_VALUE
;
302 if (id
) *id
= (DWORD
)teb
->tid
;
307 /***********************************************************************
308 * ExitThread [KERNEL32.215] Ends a thread
313 void WINAPI
ExitThread( DWORD code
) /* [in] Exit code for this thread */
315 MODULE_DllThreadDetach( NULL
);
316 TerminateThread( GetCurrentThread(), code
);
320 /***********************************************************************
321 * GetCurrentThread [KERNEL32.200] Gets pseudohandle for current thread
324 * Pseudohandle for the current thread
326 HANDLE WINAPI
GetCurrentThread(void)
328 return CURRENT_THREAD_PSEUDOHANDLE
;
332 /**********************************************************************
333 * GetLastError [KERNEL.148] [KERNEL32.227] Returns last-error code.
336 * Calling thread's last error code value.
338 DWORD WINAPI
GetLastError(void)
340 return NtCurrentTeb()->last_error
;
344 /**********************************************************************
345 * SetLastErrorEx [USER32.485] Sets the last-error code.
350 void WINAPI
SetLastErrorEx(
351 DWORD error
, /* [in] Per-thread error code */
352 DWORD type
) /* [in] Error type */
354 TRACE("(0x%08lx, 0x%08lx)\n", error
,type
);
361 /* Fall through for now */
363 FIXME("(error=%08lx, type=%08lx): Unhandled type\n", error
,type
);
366 SetLastError( error
);
370 /**********************************************************************
371 * TlsAlloc [KERNEL32.530] Allocates a TLS index.
373 * Allocates a thread local storage index
377 * Failure: 0xFFFFFFFF
379 DWORD WINAPI
TlsAlloc( void )
381 PDB
*process
= PROCESS_Current();
382 DWORD i
, mask
, ret
= 0;
383 DWORD
*bits
= process
->tls_bits
;
384 EnterCriticalSection( &process
->crit_section
);
385 if (*bits
== 0xffffffff)
389 if (*bits
== 0xffffffff)
391 LeaveCriticalSection( &process
->crit_section
);
392 SetLastError( ERROR_NO_MORE_ITEMS
);
396 for (i
= 0, mask
= 1; i
< 32; i
++, mask
<<= 1) if (!(*bits
& mask
)) break;
398 LeaveCriticalSection( &process
->crit_section
);
403 /**********************************************************************
404 * TlsFree [KERNEL32.531] Releases a TLS index.
406 * Releases a thread local storage index, making it available for reuse
413 DWORD index
) /* [in] TLS Index to free */
415 PDB
*process
= PROCESS_Current();
417 DWORD
*bits
= process
->tls_bits
;
420 SetLastError( ERROR_INVALID_PARAMETER
);
423 EnterCriticalSection( &process
->crit_section
);
424 if (index
>= 32) bits
++;
425 mask
= (1 << (index
& 31));
426 if (!(*bits
& mask
)) /* already free? */
428 LeaveCriticalSection( &process
->crit_section
);
429 SetLastError( ERROR_INVALID_PARAMETER
);
433 NtCurrentTeb()->tls_array
[index
] = 0;
434 /* FIXME: should zero all other thread values */
435 LeaveCriticalSection( &process
->crit_section
);
440 /**********************************************************************
441 * TlsGetValue [KERNEL32.532] Gets value in a thread's TLS slot
444 * Success: Value stored in calling thread's TLS slot for index
445 * Failure: 0 and GetLastError returns NO_ERROR
447 LPVOID WINAPI
TlsGetValue(
448 DWORD index
) /* [in] TLS index to retrieve value for */
452 SetLastError( ERROR_INVALID_PARAMETER
);
455 SetLastError( ERROR_SUCCESS
);
456 return NtCurrentTeb()->tls_array
[index
];
460 /**********************************************************************
461 * TlsSetValue [KERNEL32.533] Stores a value in the thread's TLS slot.
467 BOOL WINAPI
TlsSetValue(
468 DWORD index
, /* [in] TLS index to set value for */
469 LPVOID value
) /* [in] Value to be stored */
473 SetLastError( ERROR_INVALID_PARAMETER
);
476 NtCurrentTeb()->tls_array
[index
] = value
;
481 /***********************************************************************
482 * SetThreadContext [KERNEL32.670] Sets context of thread.
488 BOOL WINAPI
SetThreadContext(
489 HANDLE handle
, /* [in] Handle to thread with context */
490 CONTEXT
*context
) /* [out] Address of context structure */
492 FIXME("not implemented\n" );
496 /***********************************************************************
497 * GetThreadContext [KERNEL32.294] Retrieves context of thread.
503 BOOL WINAPI
GetThreadContext(
504 HANDLE handle
, /* [in] Handle to thread with context */
505 CONTEXT
*context
) /* [out] Address of context structure */
509 FIXME("returning dummy info\n" );
511 /* make up some plausible values for segment registers */
524 /**********************************************************************
525 * GetThreadPriority [KERNEL32.296] Returns priority for thread.
528 * Success: Thread's priority level.
529 * Failure: THREAD_PRIORITY_ERROR_RETURN
531 INT WINAPI
GetThreadPriority(
532 HANDLE hthread
) /* [in] Handle to thread */
534 INT ret
= THREAD_PRIORITY_ERROR_RETURN
;
535 struct get_thread_info_request
*req
= get_req_buffer();
536 req
->handle
= hthread
;
537 if (!server_call( REQ_GET_THREAD_INFO
)) ret
= req
->priority
;
542 /**********************************************************************
543 * SetThreadPriority [KERNEL32.514] Sets priority for thread.
549 BOOL WINAPI
SetThreadPriority(
550 HANDLE hthread
, /* [in] Handle to thread */
551 INT priority
) /* [in] Thread priority level */
553 struct set_thread_info_request
*req
= get_req_buffer();
554 req
->handle
= hthread
;
555 req
->priority
= priority
;
556 req
->mask
= SET_THREAD_INFO_PRIORITY
;
557 return !server_call( REQ_SET_THREAD_INFO
);
561 /**********************************************************************
562 * SetThreadAffinityMask (KERNEL32.669)
564 DWORD WINAPI
SetThreadAffinityMask( HANDLE hThread
, DWORD dwThreadAffinityMask
)
566 struct set_thread_info_request
*req
= get_req_buffer();
567 req
->handle
= hThread
;
568 req
->affinity
= dwThreadAffinityMask
;
569 req
->mask
= SET_THREAD_INFO_AFFINITY
;
570 if (server_call( REQ_SET_THREAD_INFO
)) return 0;
571 return 1; /* FIXME: should return previous value */
575 /**********************************************************************
576 * TerminateThread [KERNEL32.685] Terminates a thread
582 BOOL WINAPI
TerminateThread(
583 HANDLE handle
, /* [in] Handle to thread */
584 DWORD exitcode
) /* [in] Exit code for thread */
586 struct terminate_thread_request
*req
= get_req_buffer();
587 req
->handle
= handle
;
588 req
->exit_code
= exitcode
;
589 return !server_call( REQ_TERMINATE_THREAD
);
593 /**********************************************************************
594 * GetExitCodeThread [KERNEL32.???] Gets termination status of thread.
600 BOOL WINAPI
GetExitCodeThread(
601 HANDLE hthread
, /* [in] Handle to thread */
602 LPDWORD exitcode
) /* [out] Address to receive termination status */
605 struct get_thread_info_request
*req
= get_req_buffer();
606 req
->handle
= hthread
;
607 if (!server_call( REQ_GET_THREAD_INFO
))
609 if (exitcode
) *exitcode
= req
->exit_code
;
616 /**********************************************************************
617 * ResumeThread [KERNEL32.587] Resumes a thread.
619 * Decrements a thread's suspend count. When count is zero, the
620 * execution of the thread is resumed.
623 * Success: Previous suspend count
624 * Failure: 0xFFFFFFFF
627 DWORD WINAPI
ResumeThread(
628 HANDLE hthread
) /* [in] Identifies thread to restart */
630 DWORD ret
= 0xffffffff;
631 struct resume_thread_request
*req
= get_req_buffer();
632 req
->handle
= hthread
;
633 if (!server_call( REQ_RESUME_THREAD
)) ret
= req
->count
;
638 /**********************************************************************
639 * SuspendThread [KERNEL32.681] Suspends a thread.
642 * Success: Previous suspend count
643 * Failure: 0xFFFFFFFF
645 DWORD WINAPI
SuspendThread(
646 HANDLE hthread
) /* [in] Handle to the thread */
648 DWORD ret
= 0xffffffff;
649 struct suspend_thread_request
*req
= get_req_buffer();
650 req
->handle
= hthread
;
651 if (!server_call( REQ_SUSPEND_THREAD
)) ret
= req
->count
;
656 /***********************************************************************
657 * QueueUserAPC (KERNEL32.566)
659 DWORD WINAPI
QueueUserAPC( PAPCFUNC func
, HANDLE hthread
, ULONG_PTR data
)
661 struct queue_apc_request
*req
= get_req_buffer();
662 req
->handle
= hthread
;
664 req
->param
= (void *)data
;
665 return !server_call( REQ_QUEUE_APC
);
669 /**********************************************************************
670 * GetThreadTimes [KERNEL32.???] Obtains timing information.
673 * What are the fields where these values are stored?
679 BOOL WINAPI
GetThreadTimes(
680 HANDLE thread
, /* [in] Specifies the thread of interest */
681 LPFILETIME creationtime
, /* [out] When the thread was created */
682 LPFILETIME exittime
, /* [out] When the thread was destroyed */
683 LPFILETIME kerneltime
, /* [out] Time thread spent in kernel mode */
684 LPFILETIME usertime
) /* [out] Time thread spent in user mode */
686 FIXME("(0x%08x): stub\n",thread
);
687 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
692 /**********************************************************************
693 * AttachThreadInput [KERNEL32.8] Attaches input of 1 thread to other
695 * Attaches the input processing mechanism of one thread to that of
703 * 1. Reset the Key State (currenly per thread key state is not maintained)
705 BOOL WINAPI
AttachThreadInput(
706 DWORD idAttach
, /* [in] Thread to attach */
707 DWORD idAttachTo
, /* [in] Thread to attach to */
708 BOOL fAttach
) /* [in] Attach or detach */
710 MESSAGEQUEUE
*pSrcMsgQ
= 0, *pTgtMsgQ
= 0;
713 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
715 /* A thread cannot attach to itself */
716 if ( idAttach
== idAttachTo
)
719 /* According to the docs this method should fail if a
720 * "Journal record" hook is installed. (attaches all input queues together)
722 if ( HOOK_IsHooked( WH_JOURNALRECORD
) )
725 /* Retrieve message queues corresponding to the thread id's */
726 pTgtMsgQ
= (MESSAGEQUEUE
*)QUEUE_Lock( GetThreadQueue16( idAttach
) );
727 pSrcMsgQ
= (MESSAGEQUEUE
*)QUEUE_Lock( GetThreadQueue16( idAttachTo
) );
729 /* Ensure we have message queues and that Src and Tgt threads
730 * are not system threads.
732 if ( !pSrcMsgQ
|| !pTgtMsgQ
|| !pSrcMsgQ
->pQData
|| !pTgtMsgQ
->pQData
)
735 if (fAttach
) /* Attach threads */
737 /* Only attach if currently detached */
738 if ( pTgtMsgQ
->pQData
!= pSrcMsgQ
->pQData
)
740 /* First release the target threads perQData */
741 PERQDATA_Release( pTgtMsgQ
->pQData
);
743 /* Share a reference to the source threads perQDATA */
744 PERQDATA_Addref( pSrcMsgQ
->pQData
);
745 pTgtMsgQ
->pQData
= pSrcMsgQ
->pQData
;
748 else /* Detach threads */
750 /* Only detach if currently attached */
751 if ( pTgtMsgQ
->pQData
== pSrcMsgQ
->pQData
)
753 /* First release the target threads perQData */
754 PERQDATA_Release( pTgtMsgQ
->pQData
);
756 /* Give the target thread its own private perQDATA once more */
757 pTgtMsgQ
->pQData
= PERQDATA_CreateInstance();
761 /* TODO: Reset the Key State */
763 bRet
= 1; /* Success */
767 /* Unlock the queues before returning */
769 QUEUE_Unlock( pSrcMsgQ
);
771 QUEUE_Unlock( pTgtMsgQ
);
776 /**********************************************************************
777 * VWin32_BoostThreadGroup [KERNEL.535]
779 VOID WINAPI
VWin32_BoostThreadGroup( DWORD threadId
, INT boost
)
781 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
784 /**********************************************************************
785 * VWin32_BoostThreadStatic [KERNEL.536]
787 VOID WINAPI
VWin32_BoostThreadStatic( DWORD threadId
, INT boost
)
789 FIXME("(0x%08lx,%d): stub\n", threadId
, boost
);
792 /**********************************************************************
793 * SetThreadLocale [KERNEL32.671] Sets the calling threads current locale.
800 * Implemented in NT only (3.1 and above according to MS
802 BOOL WINAPI
SetThreadLocale(
803 LCID lcid
) /* [in] Locale identifier */
805 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
810 /**********************************************************************
811 * SetLastError [KERNEL.147] [KERNEL32.497] Sets the last-error code.
817 void WINAPI
SetLastError( DWORD error
) /* [in] Per-thread error code */
819 NtCurrentTeb()->last_error
= error
;
823 /***********************************************************************
824 * GetCurrentThreadId [KERNEL32.201] Returns thread identifier.
827 * Thread identifier of calling thread
829 #undef GetCurrentThreadId
830 DWORD WINAPI
GetCurrentThreadId(void)
832 return (DWORD
)NtCurrentTeb()->tid
;