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

Last change on this file since 10606 was 10606, checked in by sandervl, 21 years ago

KOM: Updates

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