source: trunk/src/kernel32/thread.cpp@ 9945

Last change on this file since 9945 was 9945, checked in by sandervl, 22 years ago

updates

File size: 17.8 KB
Line 
1/* $Id: thread.cpp,v 1.53 2003-03-27 14:00:54 sandervl Exp $ */
2
3/*
4 * Win32 Thread API functions
5 *
6 * TODO: Initialize threadInfo structure during thread creation
7 *
8 * Copyright 1998 Sander van Leeuwen (sandervl@xs4all.nl)
9 *
10 * Project Odin Software License can be found in LICENSE.TXT
11 *
12 */
13
14/*****************************************************************************
15 * Includes *
16 *****************************************************************************/
17
18#include <odin.h>
19#include <odinwrap.h>
20#include <os2sel.h>
21
22#include <os2win.h>
23#include <stdarg.h>
24#include <string.h>
25#include "thread.h"
26#include <misc.h>
27#include <cpuhlp.h>
28#include <wprocess.h>
29#include <windllbase.h>
30#include <winexebase.h>
31#include "exceptutil.h"
32#include "oslibmisc.h"
33#include "oslibdos.h"
34#include "oslibthread.h"
35#include <handlemanager.h>
36#include <codepage.h>
37
38#include <FastInfoBlocks.h>
39
40#define DBG_LOCALLOG DBG_thread
41#include "dbglocal.h"
42
43ODINDEBUGCHANNEL(KERNEL32-THREAD)
44
45static ULONG priorityclass = NORMAL_PRIORITY_CLASS;
46
47//******************************************************************************
48//******************************************************************************
49DWORD WIN32API GetCurrentThreadId()
50{
51 // check cached identifier
52 TEB *teb = GetThreadTEB();
53 if(teb != NULL && teb->o.odin.threadId != 0xFFFFFFFF)
54 {
55 // this is set in InitializeTIB() already.
56 return teb->o.odin.threadId;
57 }
58
59//// dprintf(("GetCurrentThreadId\n"));
60 return MAKE_THREADID(O32_GetCurrentProcessId(), O32_GetCurrentThreadId());
61}
62//******************************************************************************
63//******************************************************************************
64HANDLE WIN32API GetCurrentThread()
65{
66 TEB *teb;
67
68 teb = GetThreadTEB();
69 if(teb == 0) {
70 DebugInt3();
71 SetLastError(ERROR_INVALID_HANDLE); //todo
72 return 0;
73 }
74 return teb->o.odin.hThread;
75}
76//******************************************************************************
77// these two debugging functions allow access to a
78// calldepth counter inside the TEB block of each thread
79//******************************************************************************
80ULONG WIN32API dbg_GetThreadCallDepth()
81{
82#ifdef DEBUG
83 TEB *teb;
84
85 teb = GetThreadTEB();
86 if(teb == NULL)
87 return 0;
88 else
89 return teb->o.odin.dbgCallDepth;
90#else
91 return 0;
92#endif
93}
94//******************************************************************************
95//******************************************************************************
96void WIN32API dbg_IncThreadCallDepth()
97{
98#ifdef DEBUG
99 TEB *teb;
100
101 teb = GetThreadTEB();
102 if(teb != NULL)
103 teb->o.odin.dbgCallDepth++;
104#endif
105}
106//******************************************************************************
107#define MAX_CALLSTACK_SIZE 128
108#ifdef DEBUG
109static char *pszLastCaller = NULL;
110#endif
111//******************************************************************************
112void WIN32API dbg_ThreadPushCall(char *pszCaller)
113{
114#ifdef DEBUG
115 TEB *teb;
116
117 // embedded dbg_IncThreadCallDepth
118 teb = GetThreadTEB();
119 if(teb == NULL)
120 return;
121
122 // add caller name to call stack trace
123 int iIndex = teb->o.odin.dbgCallDepth;
124
125 // allocate callstack on demand
126 if (teb->o.odin.arrstrCallStack == NULL)
127 teb->o.odin.arrstrCallStack = (PVOID*)malloc( sizeof(LPSTR) * MAX_CALLSTACK_SIZE);
128
129 // insert entry
130 if (iIndex < MAX_CALLSTACK_SIZE)
131 teb->o.odin.arrstrCallStack[iIndex] = (PVOID)pszCaller;
132
133 teb->o.odin.dbgCallDepth++;
134
135 pszLastCaller = pszCaller;
136#endif
137}
138//******************************************************************************
139//******************************************************************************
140void WIN32API dbg_DecThreadCallDepth()
141{
142#ifdef DEBUG
143 TEB *teb;
144
145 teb = GetThreadTEB();
146 if(teb != NULL)
147 --(teb->o.odin.dbgCallDepth);
148#endif
149}
150//******************************************************************************
151//******************************************************************************
152void WIN32API dbg_ThreadPopCall()
153{
154#ifdef DEBUG
155 TEB *teb;
156
157 // embedded dbg_DecThreadCallDepth
158 teb = GetThreadTEB();
159 if(teb == NULL)
160 return;
161
162 --(teb->o.odin.dbgCallDepth);
163
164 // add caller name to call stack trace
165 int iIndex = teb->o.odin.dbgCallDepth;
166
167 // insert entry
168 if (teb->o.odin.arrstrCallStack)
169 if (iIndex < MAX_CALLSTACK_SIZE)
170 teb->o.odin.arrstrCallStack[iIndex] = NULL;
171#endif
172}
173//******************************************************************************
174//******************************************************************************
175char* WIN32API dbg_GetLastCallerName()
176{
177#ifdef DEBUG
178 // retrieve last caller name from stack
179 TEB *teb;
180
181 // embedded dbg_DecThreadCallDepth
182 teb = GetThreadTEB();
183 if(teb != NULL)
184 {
185 int iIndex = teb->o.odin.dbgCallDepth - 1;
186 if ( (iIndex > 0) &&
187 (iIndex < MAX_CALLSTACK_SIZE) )
188 {
189 return (char*)teb->o.odin.arrstrCallStack[iIndex];
190 }
191 }
192#endif
193
194 return NULL;
195}
196//******************************************************************************
197//******************************************************************************
198VOID WIN32API ExitThread(DWORD exitcode)
199{
200 EXCEPTION_FRAME *exceptFrame;
201 TEB *teb;
202
203 dprintf(("ExitThread %x (%x)", GetCurrentThread(), exitcode));
204
205 teb = GetThreadTEB();
206 if(teb != 0) {
207 exceptFrame = (EXCEPTION_FRAME *)teb->o.odin.exceptFrame;
208 }
209 else DebugInt3();
210
211 HMSetThreadTerminated(GetCurrentThread());
212 Win32DllBase::detachThreadFromAllDlls(); //send DLL_THREAD_DETACH message to all dlls
213 Win32DllBase::tlsDetachThreadFromAllDlls(); //destroy TLS structures of all dlls
214 if(WinExe) WinExe->tlsDetachThread(); //destroy TLS structure of main exe
215
216 if(teb) DestroyTEB(teb);
217
218 if(exceptFrame) OS2UnsetExceptionHandler((void *)exceptFrame);
219
220 O32_ExitThread(exitcode);
221}
222/*****************************************************************************
223 * Name : DWORD SetThreadAffinityMask
224 * Purpose : The SetThreadAffinityMask function sets a processor affinity
225 * mask for a specified thread.
226 * A thread affinity mask is a bit vector in which each bit
227 * represents the processors that a thread is allowed to run on.
228 * A thread affinity mask must be a proper subset of the process
229 * affinity mask for the containing process of a thread. A thread
230 * is only allowed to run on the processors its process is allowed to run on.
231 * Parameters: HANDLE hThread handle to the thread of interest
232 * DWORD dwThreadAffinityMask a thread affinity mask
233 * Variables :
234 * Result : TRUE / FALSE
235 * Remark :
236 * Status : Fully functional
237 *
238 * Author : SvL
239 *****************************************************************************/
240
241DWORD WIN32API SetThreadAffinityMask(HANDLE hThread,
242 DWORD dwThreadAffinityMask)
243{
244 dprintf(("KERNEL32: SetThreadAffinityMask(%08xh,%08xh)", hThread, dwThreadAffinityMask));
245
246 if(hThread != GetCurrentThread()) {
247 dprintf(("WARNING: Setting the affinity mask for another thread than the current one is not supported!!"));
248 return FALSE;
249 }
250 return OSLibDosSetThreadAffinity(dwThreadAffinityMask);
251}
252//******************************************************************************
253//******************************************************************************
254VOID WIN32API Sleep(DWORD mSecs)
255{
256 dprintf2(("KERNEL32: Sleep %d", mSecs));
257 OSLibDosSleep(mSecs);
258}
259//******************************************************************************
260//******************************************************************************
261DWORD WIN32API GetPriorityClass(HANDLE hProcess)
262{
263 dprintf(("KERNEL32: GetPriorityClass %x", hProcess));
264 return priorityclass;
265// return O32_GetPriorityClass(hProcess);
266}
267//******************************************************************************
268//******************************************************************************
269BOOL WIN32API SetPriorityClass(HANDLE hProcess, DWORD dwPriority)
270{
271 dprintf(("KERNEL32: SetPriorityClass %x %x", hProcess, dwPriority));
272 priorityclass = dwPriority;
273 return TRUE;
274// return O32_SetPriorityClass(hProcess, dwPriority);
275}
276//******************************************************************************
277//******************************************************************************
278Win32Thread::Win32Thread(LPTHREAD_START_ROUTINE pUserCallback, LPVOID lpData, DWORD dwFlags, HANDLE hThread)
279{
280 lpUserData = lpData;
281 pCallback = pUserCallback;
282 this->dwFlags = dwFlags;
283 this->hThread = hThread;
284
285 teb = CreateTEB(hThread, 0xFFFFFFFF);
286 if(teb == NULL) {
287 DebugInt3();
288 }
289}
290//******************************************************************************
291//******************************************************************************
292DWORD OPEN32API Win32ThreadProc(LPVOID lpData)
293{
294 EXCEPTION_FRAME exceptFrame;
295 Win32Thread *me = (Win32Thread *)lpData;
296 ULONG threadCallback = (ULONG)me->pCallback;
297 LPVOID userdata = me->lpUserData;
298 DWORD rc;
299 TEB *winteb = (TEB *)me->teb;
300
301 delete(me); //only called once
302
303 if(InitializeThread(winteb) == FALSE) {
304 dprintf(("Win32ThreadProc: InitializeTIB failed!!"));
305 DebugInt3();
306 return 0;
307 }
308 dprintf(("Win32ThreadProc: Thread handle 0x%x, thread id %d", GetCurrentThread(), GetCurrentThreadId()));
309
310 winteb->flags = me->dwFlags;
311
312 winteb->entry_point = (void *)threadCallback;
313 winteb->entry_arg = (void *)userdata;
314
315 winteb->o.odin.hab = OSLibWinInitialize();
316 dprintf(("Thread HAB %x", winteb->o.odin.hab));
317 winteb->o.odin.hmq = OSLibWinQueryMsgQueue(winteb->o.odin.hab);
318 rc = OSLibWinSetCp(winteb->o.odin.hmq, GetDisplayCodepage());
319 dprintf(("WinSetCP was %sOK", rc ? "" : "not "));
320
321 dprintf(("Win32ThreadProc: hab %x hmq %x", winteb->o.odin.hab, winteb->o.odin.hmq));
322 dprintf(("Stack top 0x%x, stack end 0x%x", winteb->stack_top, winteb->stack_low));
323
324 //Note: The Win32 exception structure referenced by FS:[0] is the same
325 // in OS/2
326 OS2SetExceptionHandler((void *)&exceptFrame);
327 winteb->o.odin.exceptFrame = (ULONG)&exceptFrame;
328
329 //Determine if thread callback is inside a PE dll; if true, then force
330 //switch to win32 TIB (FS selector)
331 //(necessary for Opera when loading win32 plugins that create threads)
332 Win32DllBase *dll;
333 dll = Win32DllBase::findModuleByAddr(threadCallback);
334 if(dll && dll->isPEImage()) {
335 dprintf(("Win32ThreadProc: Force win32 TIB switch"));
336 SetWin32TIB(TIB_SWITCH_FORCE_WIN32);
337 }
338 else SetWin32TIB(TIB_SWITCH_DEFAULT); //executable type determines whether or not FS is changed
339
340 DWORD dwProcessAffinityMask, dwSystemAffinityMask;
341
342 //Change the affinity mask of this thread to the mask for the whole process
343 if(GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask) == TRUE) {
344 SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
345 }
346
347 if(WinExe) WinExe->tlsAttachThread(); //setup TLS structure of main exe
348 Win32DllBase::tlsAttachThreadToAllDlls(); //setup TLS structures of all dlls
349 Win32DllBase::attachThreadToAllDlls(); //send DLL_THREAD_ATTACH message to all dlls
350
351 BOOL fAlignStack = ((ULONG)winteb->stack_top - (ULONG)winteb->stack_low) >= 128*1024;
352
353 //Set FPU control word to 0x27F (same as in NT)
354 CONTROL87(0x27F, 0xFFF);
355 rc = AsmCallThreadHandler(fAlignStack, threadCallback, userdata);
356
357 if(fExitProcess) {
358 OSLibDosExitThread(rc);
359 }
360 else {
361 HMSetThreadTerminated(GetCurrentThread());
362 winteb->o.odin.exceptFrame = 0;
363 Win32DllBase::detachThreadFromAllDlls(); //send DLL_THREAD_DETACH message to all dlls
364 Win32DllBase::tlsDetachThreadFromAllDlls(); //destroy TLS structures of all dlls
365 if(WinExe) WinExe->tlsDetachThread(); //destroy TLS structure of main exe
366 DestroyTEB(winteb); //destroys TIB and restores FS
367 OS2UnsetExceptionHandler((void *)&exceptFrame);
368 }
369
370 return rc;
371}
372//******************************************************************************
373//******************************************************************************
374
375/**
376 * Enter odin context with this thread.
377 *
378 * Is called when an OS/2 process is calling into an Odin32 DLL.
379 * This may be called also in a nested fashion and supports that.
380 * The conterpart of ODIN_ThreadLeaveOdinContext().
381 *
382 * @returns The old FS selector.
383 * @returns 0 if TEB creation failed.
384 * @param pExceptionRegRec OS/2 Exception Registration Record (2 ULONGs)
385 * must be located on the callers stack.
386 * @param fForceFSSwitch If set we will force switching to Odin32 FS selector.
387 * If clear it depends on defaults.
388 */
389USHORT WIN32API ODIN_ThreadEnterOdinContext(void *pExceptionRegRec, BOOL fForceFSSwitch)
390{
391 USHORT selFSOld = 0;
392
393 /*
394 * Get TEB pointer, create it if necessary.
395 * @todo Check if this really is the thread which the TEB was created
396 * for. If not create the TEB.
397 */
398 TEB *pTeb = GetThreadTEB();
399 if (!pTeb)
400 {
401 BOOL fMainThread = fibGetTid() == 1;
402 HANDLE hThreadMain = HMCreateThread(NULL, 0, 0, 0, 0, 0, fMainThread);
403 pTeb = CreateTEB(hThreadMain, fibGetTid());
404 if (!pTeb || InitializeThread(pTeb, fMainThread) == FALSE)
405 {
406 dprintf(("ODIN_ThreadEnterOdinContext: Failed to create TEB!"));
407 }
408 }
409
410 /*
411 * Install the Odin32 exception handler.
412 * Note: The Win32 exception structure referenced by FS:[0] is the same in OS/2
413 */
414 if (pExceptionRegRec)
415 OS2SetExceptionHandler(pExceptionRegRec);
416 if ( pTeb
417 && !pTeb->o.odin.exceptFrame) /* if allready present, we'll keep the first one. */
418 pTeb->o.odin.exceptFrame = (ULONG)pExceptionRegRec;
419
420 /*
421 * Switch Selector if TIB was created.
422 */
423 if (pTeb)
424 selFSOld = SetWin32TIB(fForceFSSwitch ? TIB_SWITCH_FORCE_WIN32 : TIB_SWITCH_DEFAULT);
425
426 return selFSOld;
427}
428
429
430/**
431 * Leave odin context with this thread.
432 *
433 * Is called when an OS/2 process is returning from an Odin32 DLL.
434 * This may be called also in a nested fashion and supports that.
435 * The conterpart of ODIN_ThreadEnterOdinContext().
436 *
437 * @returns The old FS selector.
438 * @returns 0 if TEB creation failed.
439 * @param pExceptionRegRec OS/2 Exception Registration Record (2 ULONGs)
440 * must be located on the callers stack.
441 * @param fForceFSSwitch If set we will force switching to Odin32 FS selector.
442 * If clear it depends on defaults.
443 */
444void WIN32API ODIN_ThreadLeaveOdinContext(void *pExceptionRegRec, USHORT selFSOld)
445{
446 /*
447 * Install the Odin32 exception handler.
448 * Note: The Win32 exception structure referenced by FS:[0] is the same in OS/2
449 */
450 if (pExceptionRegRec)
451 OS2UnsetExceptionHandler(pExceptionRegRec);
452 TEB *pTeb = GetThreadTEB();
453 if ( pTeb
454 && pTeb->o.odin.exceptFrame == (ULONG)pExceptionRegRec)
455 pTeb->o.odin.exceptFrame = 0;
456
457 /*
458 * Switch Back FS Selector.
459 */
460 if (selFSOld)
461 SetFS(selFSOld);
462}
463
464
465/**
466 * Leave odin context to call back into OS/2 code.
467 *
468 * Is called when and Odin32 Dll/Exe calls back into the OS/2 code.
469 * The conterpart of ODIN_ThreadEnterOdinContextNested().
470 *
471 * @returns The old FS selector.
472 * @returns 0 on failure.
473 * @param pExceptionRegRec New OS/2 exception handler frame which are to be registered
474 * before the Odin handler in the chain.
475 * Must be located on the callers stack.
476 * @param fRemoveOdinExcpt Remove the odin exception handler.
477 */
478USHORT WIN32API ODIN_ThreadLeaveOdinContextNested(void *pExceptionRegRec, BOOL fRemoveOdinExcpt)
479{
480 /*
481 * Set OS/2 FS Selector.
482 */
483 USHORT selFSOld = RestoreOS2FS();
484
485 /*
486 * Remove the Odin exception handler (if requested).
487 */
488 if (fRemoveOdinExcpt)
489 {
490 TEB *pTeb = GetThreadTEB();
491 if (pTeb)
492 OS2UnsetExceptionHandler((void*)pTeb->o.odin.exceptFrame);
493 /* else: no TEB created propbably no exception handler to remove. */
494 }
495
496 /*
497 * Change exception handler if required.
498 */
499 if (pExceptionRegRec)
500 {
501 extern unsigned long _System DosSetExceptionHandler(void *);
502 DosSetExceptionHandler(pExceptionRegRec);
503 }
504
505 return selFSOld;
506}
507
508
509/**
510 * Re-enter Odin context after being back in OS/2 code.
511 *
512 * Is called when returning to Odin from OS/2 code.
513 * The conterpart of ODIN_ThreadLeaveOdinContextNested().
514 *
515 * @param pExceptionRegRec The exception registration record for the OS/2
516 * exception handler used with Nested Leave. NULL
517 * if not used.
518 * @param fRestoreOdinExcpt Restore the Odin exception handler.
519 * This flag must not be set unless fRemoveOdinExcpt
520 * was set when leaving the Odin context!
521 * @param selFSOld The Odin FS selector returned by the Nested Leave api.
522 *
523 */
524void WIN32API ODIN_ThreadEnterOdinContextNested(void *pExceptionRegRec, BOOL fRestoreOdinExcpt, USHORT selFSOld)
525{
526 /*
527 * Remove the exception handler registered in ODIN_ThreadLeaveOdinContextNested
528 */
529 if (pExceptionRegRec)
530 OS2UnsetExceptionHandler(pExceptionRegRec);
531
532 /*
533 * Restore Odin exception handler (if requested).
534 */
535 if (fRestoreOdinExcpt)
536 {
537 TEB *pTeb = GetThreadTEB();
538 if (pTeb)
539 OS2SetExceptionHandler((void*)pTeb->o.odin.exceptFrame);
540 }
541
542 /*
543 * Switch Back FS Selector.
544 */
545 if (selFSOld)
546 SetFS(selFSOld);
547}
548
549
Note: See TracBrowser for help on using the repository browser.