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

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

YD: Changes for header updates

File size: 18.8 KB
Line 
1/* $Id: thread.cpp,v 1.54 2003-04-02 12:58:31 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//******************************************************************************
278/*****************************************************************************
279 * Name : BOOL SetThreadPriorityBoost
280 * Purpose : The SetThreadPriorityBoost function disables or enables
281 * the ability of the system to temporarily boost the priority
282 * of a thread.
283 * Parameters: Unknown (wrong)
284 * Variables :
285 * Result : Unknown
286 * Remark :
287 * Status : UNTESTED STUB
288 *
289 * Author : Patrick Haller [Tue, 1999/06/08 21:44]
290 *****************************************************************************/
291
292BOOL WIN32API SetThreadPriorityBoost(HANDLE hThread,
293 BOOL DisablePriorityBoost)
294{
295 dprintf(("KERNEL32: SetThreadPriorityBoost(%08xh, %08xh) not implemented\n",
296 hThread,DisablePriorityBoost));
297
298 return FALSE;
299}
300//******************************************************************************
301//******************************************************************************
302Win32Thread::Win32Thread(LPTHREAD_START_ROUTINE pUserCallback, LPVOID lpData, DWORD dwFlags, HANDLE hThread)
303{
304 lpUserData = lpData;
305 pCallback = pUserCallback;
306 this->dwFlags = dwFlags;
307 this->hThread = hThread;
308
309 teb = CreateTEB(hThread, 0xFFFFFFFF);
310 if(teb == NULL) {
311 DebugInt3();
312 }
313}
314//******************************************************************************
315//******************************************************************************
316DWORD OPEN32API Win32ThreadProc(LPVOID lpData)
317{
318 EXCEPTION_FRAME exceptFrame;
319 Win32Thread *me = (Win32Thread *)lpData;
320 ULONG threadCallback = (ULONG)me->pCallback;
321 LPVOID userdata = me->lpUserData;
322 DWORD rc;
323 TEB *winteb = (TEB *)me->teb;
324
325 delete(me); //only called once
326
327 if(InitializeThread(winteb) == FALSE) {
328 dprintf(("Win32ThreadProc: InitializeTIB failed!!"));
329 DebugInt3();
330 return 0;
331 }
332 dprintf(("Win32ThreadProc: Thread handle 0x%x, thread id %d", GetCurrentThread(), GetCurrentThreadId()));
333
334 winteb->flags = me->dwFlags;
335
336 winteb->entry_point = (void *)threadCallback;
337 winteb->entry_arg = (void *)userdata;
338
339 winteb->o.odin.hab = OSLibWinInitialize();
340 dprintf(("Thread HAB %x", winteb->o.odin.hab));
341 winteb->o.odin.hmq = OSLibWinQueryMsgQueue(winteb->o.odin.hab);
342 rc = OSLibWinSetCp(winteb->o.odin.hmq, GetDisplayCodepage());
343 dprintf(("WinSetCP was %sOK", rc ? "" : "not "));
344
345 dprintf(("Win32ThreadProc: hab %x hmq %x", winteb->o.odin.hab, winteb->o.odin.hmq));
346 dprintf(("Stack top 0x%x, stack end 0x%x", winteb->stack_top, winteb->stack_low));
347
348 //Note: The Win32 exception structure referenced by FS:[0] is the same
349 // in OS/2
350 OS2SetExceptionHandler((void *)&exceptFrame);
351 winteb->o.odin.exceptFrame = (ULONG)&exceptFrame;
352
353 //Determine if thread callback is inside a PE dll; if true, then force
354 //switch to win32 TIB (FS selector)
355 //(necessary for Opera when loading win32 plugins that create threads)
356 Win32DllBase *dll;
357 dll = Win32DllBase::findModuleByAddr(threadCallback);
358 if(dll && dll->isPEImage()) {
359 dprintf(("Win32ThreadProc: Force win32 TIB switch"));
360 SetWin32TIB(TIB_SWITCH_FORCE_WIN32);
361 }
362 else SetWin32TIB(TIB_SWITCH_DEFAULT); //executable type determines whether or not FS is changed
363
364 DWORD dwProcessAffinityMask, dwSystemAffinityMask;
365
366 //Change the affinity mask of this thread to the mask for the whole process
367 if(GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask) == TRUE) {
368 SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
369 }
370
371 if(WinExe) WinExe->tlsAttachThread(); //setup TLS structure of main exe
372 Win32DllBase::tlsAttachThreadToAllDlls(); //setup TLS structures of all dlls
373 Win32DllBase::attachThreadToAllDlls(); //send DLL_THREAD_ATTACH message to all dlls
374
375 BOOL fAlignStack = ((ULONG)winteb->stack_top - (ULONG)winteb->stack_low) >= 128*1024;
376
377 //Set FPU control word to 0x27F (same as in NT)
378 CONTROL87(0x27F, 0xFFF);
379 rc = AsmCallThreadHandler(fAlignStack, threadCallback, userdata);
380
381 if(fExitProcess) {
382 OSLibDosExitThread(rc);
383 }
384 else {
385 HMSetThreadTerminated(GetCurrentThread());
386 winteb->o.odin.exceptFrame = 0;
387 Win32DllBase::detachThreadFromAllDlls(); //send DLL_THREAD_DETACH message to all dlls
388 Win32DllBase::tlsDetachThreadFromAllDlls(); //destroy TLS structures of all dlls
389 if(WinExe) WinExe->tlsDetachThread(); //destroy TLS structure of main exe
390 DestroyTEB(winteb); //destroys TIB and restores FS
391 OS2UnsetExceptionHandler((void *)&exceptFrame);
392 }
393
394 return rc;
395}
396//******************************************************************************
397//******************************************************************************
398
399/**
400 * Enter odin context with this thread.
401 *
402 * Is called when an OS/2 process is calling into an Odin32 DLL.
403 * This may be called also in a nested fashion and supports that.
404 * The conterpart of ODIN_ThreadLeaveOdinContext().
405 *
406 * @returns The old FS selector.
407 * @returns 0 if TEB creation failed.
408 * @param pExceptionRegRec OS/2 Exception Registration Record (2 ULONGs)
409 * must be located on the callers stack.
410 * @param fForceFSSwitch If set we will force switching to Odin32 FS selector.
411 * If clear it depends on defaults.
412 */
413USHORT WIN32API ODIN_ThreadEnterOdinContext(void *pExceptionRegRec, BOOL fForceFSSwitch)
414{
415 USHORT selFSOld = 0;
416
417 /*
418 * Get TEB pointer, create it if necessary.
419 * @todo Check if this really is the thread which the TEB was created
420 * for. If not create the TEB.
421 */
422 TEB *pTeb = GetThreadTEB();
423 if (!pTeb)
424 {
425 BOOL fMainThread = fibGetTid() == 1;
426 HANDLE hThreadMain = HMCreateThread(NULL, 0, 0, 0, 0, 0, fMainThread);
427 pTeb = CreateTEB(hThreadMain, fibGetTid());
428 if (!pTeb || InitializeThread(pTeb, fMainThread) == FALSE)
429 {
430 dprintf(("ODIN_ThreadEnterOdinContext: Failed to create TEB!"));
431 }
432 }
433
434 /*
435 * Install the Odin32 exception handler.
436 * Note: The Win32 exception structure referenced by FS:[0] is the same in OS/2
437 */
438 if (pExceptionRegRec)
439 OS2SetExceptionHandler(pExceptionRegRec);
440 if ( pTeb
441 && !pTeb->o.odin.exceptFrame) /* if allready present, we'll keep the first one. */
442 pTeb->o.odin.exceptFrame = (ULONG)pExceptionRegRec;
443
444 /*
445 * Switch Selector if TIB was created.
446 */
447 if (pTeb)
448 selFSOld = SetWin32TIB(fForceFSSwitch ? TIB_SWITCH_FORCE_WIN32 : TIB_SWITCH_DEFAULT);
449
450 return selFSOld;
451}
452
453
454/**
455 * Leave odin context with this thread.
456 *
457 * Is called when an OS/2 process is returning from an Odin32 DLL.
458 * This may be called also in a nested fashion and supports that.
459 * The conterpart of ODIN_ThreadEnterOdinContext().
460 *
461 * @returns The old FS selector.
462 * @returns 0 if TEB creation failed.
463 * @param pExceptionRegRec OS/2 Exception Registration Record (2 ULONGs)
464 * must be located on the callers stack.
465 * @param fForceFSSwitch If set we will force switching to Odin32 FS selector.
466 * If clear it depends on defaults.
467 */
468void WIN32API ODIN_ThreadLeaveOdinContext(void *pExceptionRegRec, USHORT selFSOld)
469{
470 /*
471 * Install the Odin32 exception handler.
472 * Note: The Win32 exception structure referenced by FS:[0] is the same in OS/2
473 */
474 if (pExceptionRegRec)
475 OS2UnsetExceptionHandler(pExceptionRegRec);
476 TEB *pTeb = GetThreadTEB();
477 if ( pTeb
478 && pTeb->o.odin.exceptFrame == (ULONG)pExceptionRegRec)
479 pTeb->o.odin.exceptFrame = 0;
480
481 /*
482 * Switch Back FS Selector.
483 */
484 if (selFSOld)
485 SetFS(selFSOld);
486}
487
488
489/**
490 * Leave odin context to call back into OS/2 code.
491 *
492 * Is called when and Odin32 Dll/Exe calls back into the OS/2 code.
493 * The conterpart of ODIN_ThreadEnterOdinContextNested().
494 *
495 * @returns The old FS selector.
496 * @returns 0 on failure.
497 * @param pExceptionRegRec New OS/2 exception handler frame which are to be registered
498 * before the Odin handler in the chain.
499 * Must be located on the callers stack.
500 * @param fRemoveOdinExcpt Remove the odin exception handler.
501 */
502USHORT WIN32API ODIN_ThreadLeaveOdinContextNested(void *pExceptionRegRec, BOOL fRemoveOdinExcpt)
503{
504 /*
505 * Set OS/2 FS Selector.
506 */
507 USHORT selFSOld = RestoreOS2FS();
508
509 /*
510 * Remove the Odin exception handler (if requested).
511 */
512 if (fRemoveOdinExcpt)
513 {
514 TEB *pTeb = GetThreadTEB();
515 if (pTeb)
516 OS2UnsetExceptionHandler((void*)pTeb->o.odin.exceptFrame);
517 /* else: no TEB created propbably no exception handler to remove. */
518 }
519
520 /*
521 * Change exception handler if required.
522 */
523 if (pExceptionRegRec)
524 {
525 extern unsigned long _System DosSetExceptionHandler(void *);
526 DosSetExceptionHandler(pExceptionRegRec);
527 }
528
529 return selFSOld;
530}
531
532
533/**
534 * Re-enter Odin context after being back in OS/2 code.
535 *
536 * Is called when returning to Odin from OS/2 code.
537 * The conterpart of ODIN_ThreadLeaveOdinContextNested().
538 *
539 * @param pExceptionRegRec The exception registration record for the OS/2
540 * exception handler used with Nested Leave. NULL
541 * if not used.
542 * @param fRestoreOdinExcpt Restore the Odin exception handler.
543 * This flag must not be set unless fRemoveOdinExcpt
544 * was set when leaving the Odin context!
545 * @param selFSOld The Odin FS selector returned by the Nested Leave api.
546 *
547 */
548void WIN32API ODIN_ThreadEnterOdinContextNested(void *pExceptionRegRec, BOOL fRestoreOdinExcpt, USHORT selFSOld)
549{
550 /*
551 * Remove the exception handler registered in ODIN_ThreadLeaveOdinContextNested
552 */
553 if (pExceptionRegRec)
554 OS2UnsetExceptionHandler(pExceptionRegRec);
555
556 /*
557 * Restore Odin exception handler (if requested).
558 */
559 if (fRestoreOdinExcpt)
560 {
561 TEB *pTeb = GetThreadTEB();
562 if (pTeb)
563 OS2SetExceptionHandler((void*)pTeb->o.odin.exceptFrame);
564 }
565
566 /*
567 * Switch Back FS Selector.
568 */
569 if (selFSOld)
570 SetFS(selFSOld);
571}
572
573
Note: See TracBrowser for help on using the repository browser.