Don't call strtok twice if it failed the first time.
[wine.git] / loader / task.c
blob52e1270b9c46b84065c60bce67a568484c788e33
1 /*
2 * Task functions
4 * Copyright 1995 Alexandre Julliard
5 */
7 #include <stdlib.h>
8 #include <string.h>
9 #include <assert.h>
10 #include <unistd.h>
12 #include "wine/port.h"
13 #include "wine/winbase16.h"
14 #include "ntddk.h"
15 #include "callback.h"
16 #include "drive.h"
17 #include "file.h"
18 #include "global.h"
19 #include "instance.h"
20 #include "miscemu.h"
21 #include "module.h"
22 #include "queue.h"
23 #include "selectors.h"
24 #include "stackframe.h"
25 #include "task.h"
26 #include "thread.h"
27 #include "toolhelp.h"
28 #include "winnt.h"
29 #include "syslevel.h"
30 #include "winsock.h"
31 #include "debugtools.h"
32 #include "services.h"
33 #include "server.h"
36 DEFAULT_DEBUG_CHANNEL(task);
37 DECLARE_DEBUG_CHANNEL(relay);
38 DECLARE_DEBUG_CHANNEL(toolhelp);
40 /* Min. number of thunks allocated when creating a new segment */
41 #define MIN_THUNKS 32
44 static THHOOK DefaultThhook;
45 THHOOK *pThhook = &DefaultThhook;
47 #define hCurrentTask (pThhook->CurTDB)
48 #define hFirstTask (pThhook->HeadTDB)
49 #define hLockedTask (pThhook->LockTDB)
51 static UINT16 nTaskCount = 0;
53 static HTASK initial_task;
55 /***********************************************************************
56 * TASK_InstallTHHook
58 void TASK_InstallTHHook( THHOOK *pNewThhook )
60 THHOOK *pOldThhook = pThhook;
62 pThhook = pNewThhook? pNewThhook : &DefaultThhook;
64 *pThhook = *pOldThhook;
67 /***********************************************************************
68 * TASK_GetNextTask
70 HTASK16 TASK_GetNextTask( HTASK16 hTask )
72 TDB* pTask = (TDB*)GlobalLock16(hTask);
74 if (pTask->hNext) return pTask->hNext;
75 return (hFirstTask != hTask) ? hFirstTask : 0;
78 /***********************************************************************
79 * TASK_LinkTask
81 static void TASK_LinkTask( HTASK16 hTask )
83 HTASK16 *prevTask;
84 TDB *pTask;
86 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
87 prevTask = &hFirstTask;
88 while (*prevTask)
90 TDB *prevTaskPtr = (TDB *)GlobalLock16( *prevTask );
91 if (prevTaskPtr->priority >= pTask->priority) break;
92 prevTask = &prevTaskPtr->hNext;
94 pTask->hNext = *prevTask;
95 *prevTask = hTask;
96 nTaskCount++;
100 /***********************************************************************
101 * TASK_UnlinkTask
103 static void TASK_UnlinkTask( HTASK16 hTask )
105 HTASK16 *prevTask;
106 TDB *pTask;
108 prevTask = &hFirstTask;
109 while (*prevTask && (*prevTask != hTask))
111 pTask = (TDB *)GlobalLock16( *prevTask );
112 prevTask = &pTask->hNext;
114 if (*prevTask)
116 pTask = (TDB *)GlobalLock16( *prevTask );
117 *prevTask = pTask->hNext;
118 pTask->hNext = 0;
119 nTaskCount--;
124 /***********************************************************************
125 * TASK_CreateThunks
127 * Create a thunk free-list in segment 'handle', starting from offset 'offset'
128 * and containing 'count' entries.
130 static void TASK_CreateThunks( HGLOBAL16 handle, WORD offset, WORD count )
132 int i;
133 WORD free;
134 THUNKS *pThunk;
136 pThunk = (THUNKS *)((BYTE *)GlobalLock16( handle ) + offset);
137 pThunk->next = 0;
138 pThunk->magic = THUNK_MAGIC;
139 pThunk->free = (int)&pThunk->thunks - (int)pThunk;
140 free = pThunk->free;
141 for (i = 0; i < count-1; i++)
143 free += 8; /* Offset of next thunk */
144 pThunk->thunks[4*i] = free;
146 pThunk->thunks[4*i] = 0; /* Last thunk */
150 /***********************************************************************
151 * TASK_AllocThunk
153 * Allocate a thunk for MakeProcInstance().
155 static SEGPTR TASK_AllocThunk( HTASK16 hTask )
157 TDB *pTask;
158 THUNKS *pThunk;
159 WORD sel, base;
161 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return 0;
162 sel = pTask->hCSAlias;
163 pThunk = &pTask->thunks;
164 base = (int)pThunk - (int)pTask;
165 while (!pThunk->free)
167 sel = pThunk->next;
168 if (!sel) /* Allocate a new segment */
170 sel = GLOBAL_Alloc( GMEM_FIXED, sizeof(THUNKS) + (MIN_THUNKS-1)*8,
171 pTask->hPDB, WINE_LDT_FLAGS_CODE );
172 if (!sel) return (SEGPTR)0;
173 TASK_CreateThunks( sel, 0, MIN_THUNKS );
174 pThunk->next = sel;
176 pThunk = (THUNKS *)GlobalLock16( sel );
177 base = 0;
179 base += pThunk->free;
180 pThunk->free = *(WORD *)((BYTE *)pThunk + pThunk->free);
181 return MAKESEGPTR( sel, base );
185 /***********************************************************************
186 * TASK_FreeThunk
188 * Free a MakeProcInstance() thunk.
190 static BOOL TASK_FreeThunk( HTASK16 hTask, SEGPTR thunk )
192 TDB *pTask;
193 THUNKS *pThunk;
194 WORD sel, base;
196 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return 0;
197 sel = pTask->hCSAlias;
198 pThunk = &pTask->thunks;
199 base = (int)pThunk - (int)pTask;
200 while (sel && (sel != HIWORD(thunk)))
202 sel = pThunk->next;
203 pThunk = (THUNKS *)GlobalLock16( sel );
204 base = 0;
206 if (!sel) return FALSE;
207 *(WORD *)((BYTE *)pThunk + LOWORD(thunk) - base) = pThunk->free;
208 pThunk->free = LOWORD(thunk) - base;
209 return TRUE;
213 /***********************************************************************
214 * TASK_Create
216 * NOTE: This routine might be called by a Win32 thread. Thus, we need
217 * to be careful to protect global data structures. We do this
218 * by entering the Win16Lock while linking the task into the
219 * global task list.
221 static TDB *TASK_Create( NE_MODULE *pModule, UINT16 cmdShow, TEB *teb, LPCSTR cmdline, BYTE len )
223 HTASK16 hTask;
224 TDB *pTask;
225 char name[10];
227 /* Allocate the task structure */
229 hTask = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, sizeof(TDB) );
230 if (!hTask) return NULL;
231 pTask = (TDB *)GlobalLock16( hTask );
232 FarSetOwner16( hTask, pModule->self );
234 /* Fill the task structure */
236 pTask->hSelf = hTask;
238 if (teb && teb->tibflags & TEBF_WIN32)
240 pTask->flags |= TDBF_WIN32;
241 pTask->hInstance = pModule->self;
242 pTask->hPrevInstance = 0;
243 /* NOTE: for 16-bit tasks, the instance handles are updated later on
244 in NE_InitProcess */
247 pTask->version = pModule->expected_version;
248 pTask->hModule = pModule->self;
249 pTask->hParent = GetCurrentTask();
250 pTask->magic = TDB_MAGIC;
251 pTask->nCmdShow = cmdShow;
252 pTask->teb = teb;
253 pTask->curdrive = DRIVE_GetCurrentDrive() | 0x80;
254 strcpy( pTask->curdir, "\\" );
255 lstrcpynA( pTask->curdir + 1, DRIVE_GetDosCwd( DRIVE_GetCurrentDrive() ),
256 sizeof(pTask->curdir) - 1 );
258 /* Create the thunks block */
260 TASK_CreateThunks( hTask, (int)&pTask->thunks - (int)pTask, 7 );
262 /* Copy the module name */
264 GetModuleName16( pModule->self, name, sizeof(name) );
265 strncpy( pTask->module_name, name, sizeof(pTask->module_name) );
267 /* Allocate a selector for the PDB */
269 pTask->hPDB = GLOBAL_CreateBlock( GMEM_FIXED, &pTask->pdb, sizeof(PDB16),
270 pModule->self, WINE_LDT_FLAGS_DATA );
272 /* Fill the PDB */
274 pTask->pdb.int20 = 0x20cd;
275 pTask->pdb.dispatcher[0] = 0x9a; /* ljmp */
276 PUT_UA_DWORD(&pTask->pdb.dispatcher[1],
277 (DWORD)GetProcAddress16( GetModuleHandle16("KERNEL"), "DOS3Call" ));
278 pTask->pdb.savedint22 = INT_GetPMHandler( 0x22 );
279 pTask->pdb.savedint23 = INT_GetPMHandler( 0x23 );
280 pTask->pdb.savedint24 = INT_GetPMHandler( 0x24 );
281 pTask->pdb.fileHandlesPtr =
282 MAKESEGPTR( GlobalHandleToSel16(pTask->hPDB), (int)&((PDB16 *)0)->fileHandles );
283 pTask->pdb.hFileHandles = 0;
284 memset( pTask->pdb.fileHandles, 0xff, sizeof(pTask->pdb.fileHandles) );
285 /* FIXME: should we make a copy of the environment? */
286 pTask->pdb.environment = SELECTOROF(GetDOSEnvironment16());
287 pTask->pdb.nbFiles = 20;
289 /* Fill the command line */
291 if (!cmdline)
293 cmdline = GetCommandLineA();
294 /* remove the first word (program name) */
295 if (*cmdline == '"')
296 if (!(cmdline = strchr( cmdline+1, '"' ))) cmdline = GetCommandLineA();
297 while (*cmdline && (*cmdline != ' ') && (*cmdline != '\t')) cmdline++;
298 while ((*cmdline == ' ') || (*cmdline == '\t')) cmdline++;
299 len = strlen(cmdline);
301 if (len >= sizeof(pTask->pdb.cmdLine)) len = sizeof(pTask->pdb.cmdLine)-1;
302 pTask->pdb.cmdLine[0] = len;
303 memcpy( pTask->pdb.cmdLine + 1, cmdline, len );
304 /* pTask->pdb.cmdLine[len+1] = 0; */
306 TRACE("module='%s' cmdline='%.*s' task=%04x\n", name, len, cmdline, hTask );
308 /* Get the compatibility flags */
310 pTask->compat_flags = GetProfileIntA( "Compatibility", name, 0 );
312 /* Allocate a code segment alias for the TDB */
314 pTask->hCSAlias = GLOBAL_CreateBlock( GMEM_FIXED, (void *)pTask,
315 sizeof(TDB), pTask->hPDB, WINE_LDT_FLAGS_CODE );
317 /* Default DTA overwrites command line */
319 pTask->dta = MAKESEGPTR( pTask->hPDB, (int)&pTask->pdb.cmdLine - (int)&pTask->pdb );
321 /* Create scheduler event for 16-bit tasks */
323 if ( !(pTask->flags & TDBF_WIN32) )
324 NtCreateEvent( &pTask->hEvent, EVENT_ALL_ACCESS, NULL, TRUE, FALSE );
326 /* Enter task handle into thread */
328 if (teb) teb->htask16 = hTask;
329 if (!initial_task) initial_task = hTask;
331 return pTask;
335 /***********************************************************************
336 * TASK_DeleteTask
338 static void TASK_DeleteTask( HTASK16 hTask )
340 TDB *pTask;
341 HGLOBAL16 hPDB;
343 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
344 hPDB = pTask->hPDB;
346 pTask->magic = 0xdead; /* invalidate signature */
348 /* Free the selector aliases */
350 GLOBAL_FreeBlock( pTask->hCSAlias );
351 GLOBAL_FreeBlock( pTask->hPDB );
353 /* Free the task module */
355 FreeModule16( pTask->hModule );
357 /* Free the task structure itself */
359 GlobalFree16( hTask );
361 /* Free all memory used by this task (including the 32-bit stack, */
362 /* the environment block and the thunk segments). */
364 GlobalFreeAll16( hPDB );
368 /***********************************************************************
369 * TASK_CreateMainTask
371 * Create a task for the main (32-bit) process.
373 void TASK_CreateMainTask(void)
375 TDB *pTask;
376 STARTUPINFOA startup_info;
377 UINT cmdShow = 1; /* SW_SHOWNORMAL but we don't want to include winuser.h here */
379 GetStartupInfoA( &startup_info );
380 if (startup_info.dwFlags & STARTF_USESHOWWINDOW) cmdShow = startup_info.wShowWindow;
381 pTask = TASK_Create( (NE_MODULE *)GlobalLock16( MapHModuleLS(GetModuleHandleA(0)) ),
382 cmdShow, NtCurrentTeb(), NULL, 0 );
383 if (!pTask)
385 ERR("could not create task for main process\n");
386 ExitProcess(1);
389 /* Add the task to the linked list */
390 /* (no need to get the win16 lock, we are the only thread at this point) */
391 TASK_LinkTask( pTask->hSelf );
395 /* startup routine for a new 16-bit thread */
396 static DWORD CALLBACK task_start( TDB *pTask )
398 DWORD ret;
400 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
401 NtCurrentTeb()->htask16 = pTask->hSelf;
403 _EnterWin16Lock();
404 TASK_LinkTask( pTask->hSelf );
405 pTask->teb = NtCurrentTeb();
406 ret = NE_StartTask();
407 _LeaveWin16Lock();
408 return ret;
412 /***********************************************************************
413 * TASK_SpawnTask
415 * Spawn a new 16-bit task.
417 HTASK TASK_SpawnTask( NE_MODULE *pModule, WORD cmdShow, LPCSTR cmdline, BYTE len, HANDLE *hThread )
419 TDB *pTask;
421 if (!(pTask = TASK_Create( pModule, cmdShow, NULL, cmdline, len ))) return 0;
422 if (!(*hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)task_start, pTask, 0, NULL )))
424 TASK_DeleteTask( pTask->hSelf );
425 return 0;
427 return pTask->hSelf;
431 /***********************************************************************
432 * TASK_KillTask
434 void TASK_ExitTask(void)
436 TDB *pTask;
437 DWORD lockCount;
439 /* Enter the Win16Lock to protect global data structures */
440 _EnterWin16Lock();
442 pTask = (TDB *)GlobalLock16( GetCurrentTask() );
443 if ( !pTask )
445 _LeaveWin16Lock();
446 return;
449 TRACE("Killing task %04x\n", pTask->hSelf );
451 /* Perform USER cleanup */
453 TASK_CallTaskSignalProc( USIG16_TERMINATION, pTask->hSelf );
454 PROCESS_CallUserSignalProc( USIG_PROCESS_EXIT, 0 );
455 PROCESS_CallUserSignalProc( USIG_THREAD_EXIT, 0 );
456 PROCESS_CallUserSignalProc( USIG_PROCESS_DESTROY, 0 );
458 /* Remove the task from the list to be sure we never switch back to it */
459 TASK_UnlinkTask( pTask->hSelf );
461 if (!nTaskCount || (nTaskCount == 1 && hFirstTask == initial_task))
463 TRACE("this is the last task, exiting\n" );
464 ExitKernel16();
467 if( nTaskCount )
469 TDB* p = (TDB *)GlobalLock16( hFirstTask );
470 while( p )
472 if( p->hYieldTo == pTask->hSelf ) p->hYieldTo = 0;
473 p = (TDB *)GlobalLock16( p->hNext );
477 pTask->nEvents = 0;
479 if ( hLockedTask == pTask->hSelf )
480 hLockedTask = 0;
482 TASK_DeleteTask( pTask->hSelf );
484 /* ... schedule another one ... */
485 TASK_Reschedule();
487 /* ... and completely release the Win16Lock, just in case. */
488 ReleaseThunkLock( &lockCount );
491 /***********************************************************************
492 * TASK_Reschedule
494 * This is where all the magic of task-switching happens!
496 * 16-bit Windows performs non-preemptive (cooperative) multitasking.
497 * This means that each 16-bit task runs until it voluntarily yields
498 * control, at which point the scheduler gets active and selects the
499 * next task to run.
501 * In Wine, all processes, even 16-bit ones, are scheduled preemptively
502 * by the standard scheduler of the underlying OS. As many 16-bit apps
503 * *rely* on the behaviour of the Windows scheduler, however, we have
504 * to simulate that behaviour.
506 * This is achieved as follows: every 16-bit task is at time (except
507 * during task creation and deletion) in one of two states: either it
508 * is the one currently running, then the global variable hCurrentTask
509 * contains its task handle, or it is not currently running, then it
510 * is blocked on a special scheduler event, a global handle which
511 * is stored in the task struct.
513 * When the current task yields control, this routine gets called. Its
514 * purpose is to determine the next task to be active, signal the
515 * scheduler event of that task, and then put the current task to sleep
516 * waiting for *its* scheduler event to get signalled again.
518 * This routine can get called in a few other special situations as well:
520 * - On creation of a 16-bit task, the Unix process executing the task
521 * calls TASK_Reschedule once it has completed its initialization.
522 * At this point, the task needs to be blocked until its scheduler
523 * event is signalled the first time (this will be done by the parent
524 * process to get the task up and running).
526 * - When the task currently running terminates itself, this routine gets
527 * called and has to schedule another task, *without* blocking the
528 * terminating task.
530 * - When a 32-bit thread posts an event for a 16-bit task, it might be
531 * the case that *no* 16-bit task is currently running. In this case
532 * the task that has now an event pending is to be scheduled.
535 void TASK_Reschedule(void)
537 TDB *pOldTask = NULL, *pNewTask = NULL;
538 HTASK16 hOldTask = 0, hNewTask = 0;
539 enum { MODE_YIELD, MODE_SLEEP, MODE_WAKEUP } mode;
540 DWORD lockCount;
542 _EnterWin16Lock();
544 /* Check what we need to do */
545 hOldTask = GetCurrentTask();
546 pOldTask = (TDB *)GlobalLock16( hOldTask );
547 TRACE( "entered with hCurrentTask %04x by hTask %04x (pid %ld)\n",
548 hCurrentTask, hOldTask, (long) getpid() );
550 if ( pOldTask && THREAD_IsWin16( NtCurrentTeb() ) )
552 /* We are called by an active (non-deleted) 16-bit task */
554 /* If we don't even have a current task, or else the current
555 task has yielded, we'll need to schedule a new task and
556 (possibly) put the calling task to sleep. Otherwise, we
557 only block the caller. */
559 if ( !hCurrentTask || hCurrentTask == hOldTask )
560 mode = MODE_YIELD;
561 else
562 mode = MODE_SLEEP;
564 else
566 /* We are called by a deleted 16-bit task or a 32-bit thread */
568 /* The only situation where we need to do something is if we
569 now do not have a current task. Then, we'll need to wake up
570 some task that has events pending. */
572 if ( !hCurrentTask || hCurrentTask == hOldTask )
573 mode = MODE_WAKEUP;
574 else
576 /* nothing to do */
577 _LeaveWin16Lock();
578 return;
582 /* Find a task to yield to: check for DirectedYield() */
583 if ( mode == MODE_YIELD && pOldTask && pOldTask->hYieldTo )
585 hNewTask = pOldTask->hYieldTo;
586 pNewTask = (TDB *)GlobalLock16( hNewTask );
587 if( !pNewTask || !pNewTask->nEvents || !pNewTask->teb) hNewTask = 0;
588 pOldTask->hYieldTo = 0;
591 /* Find a task to yield to: check for pending events */
592 if ( (mode == MODE_YIELD || mode == MODE_WAKEUP) && !hNewTask )
594 hNewTask = hFirstTask;
595 while (hNewTask)
597 pNewTask = (TDB *)GlobalLock16( hNewTask );
599 TRACE( "\ttask = %04x, events = %i\n", hNewTask, pNewTask->nEvents );
601 if (pNewTask->nEvents) break;
602 hNewTask = pNewTask->hNext;
604 if (hLockedTask && (hNewTask != hLockedTask)) hNewTask = 0;
607 /* If we are still the task with highest priority, just return ... */
608 if ( mode == MODE_YIELD && hNewTask && hNewTask == hCurrentTask )
610 TRACE("returning to the current task (%04x)\n", hCurrentTask );
611 _LeaveWin16Lock();
613 /* Allow Win32 threads to thunk down even while a Win16 task is
614 in a tight PeekMessage() or Yield() loop ... */
615 ReleaseThunkLock( &lockCount );
616 RestoreThunkLock( lockCount );
617 return;
620 /* If no task to yield to found, suspend 16-bit scheduler ... */
621 if ( mode == MODE_YIELD && !hNewTask )
623 TRACE("No currently active task\n");
624 hCurrentTask = 0;
627 /* If we found a task to wake up, do it ... */
628 if ( (mode == MODE_YIELD || mode == MODE_WAKEUP) && hNewTask )
630 TRACE("Switching to task %04x (%.8s)\n",
631 hNewTask, pNewTask->module_name );
633 pNewTask->priority++;
634 TASK_UnlinkTask( hNewTask );
635 TASK_LinkTask( hNewTask );
636 pNewTask->priority--;
638 hCurrentTask = hNewTask;
639 NtSetEvent( pNewTask->hEvent, NULL );
641 /* This is set just in case some app reads it ... */
642 pNewTask->ss_sp = pNewTask->teb->cur_stack;
645 /* If we need to put the current task to sleep, do it ... */
646 if ( (mode == MODE_YIELD || mode == MODE_SLEEP) && hOldTask != hCurrentTask )
648 NtResetEvent( pOldTask->hEvent, NULL );
650 ReleaseThunkLock( &lockCount );
651 SYSLEVEL_CheckNotLevel( 1 );
652 WaitForSingleObject( pOldTask->hEvent, INFINITE );
653 RestoreThunkLock( lockCount );
656 _LeaveWin16Lock();
659 /***********************************************************************
660 * InitTask (KERNEL.91)
662 * Called by the application startup code.
664 void WINAPI InitTask16( CONTEXT86 *context )
666 TDB *pTask;
667 INSTANCEDATA *pinstance;
668 SEGPTR ptr;
670 context->Eax = 0;
671 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return;
673 /* Note: we need to trust that BX/CX contain the stack/heap sizes,
674 as some apps, notably Visual Basic apps, *modify* the heap/stack
675 size of the instance data segment before calling InitTask() */
677 /* Initialize the INSTANCEDATA structure */
678 pinstance = MapSL( MAKESEGPTR(CURRENT_DS, 0) );
679 pinstance->stackmin = OFFSETOF( pTask->teb->cur_stack ) + sizeof( STACK16FRAME );
680 pinstance->stackbottom = pinstance->stackmin; /* yup, that's right. Confused me too. */
681 pinstance->stacktop = ( pinstance->stackmin > LOWORD(context->Ebx) ?
682 pinstance->stackmin - LOWORD(context->Ebx) : 0 ) + 150;
684 /* Initialize the local heap */
685 if (LOWORD(context->Ecx))
686 LocalInit16( GlobalHandleToSel16(pTask->hInstance), 0, LOWORD(context->Ecx) );
688 /* Initialize implicitly loaded DLLs */
689 NE_InitializeDLLs( pTask->hModule );
690 NE_DllProcessAttach( pTask->hModule );
692 /* Registers on return are:
693 * ax 1 if OK, 0 on error
694 * cx stack limit in bytes
695 * dx cmdShow parameter
696 * si instance handle of the previous instance
697 * di instance handle of the new task
698 * es:bx pointer to command line inside PSP
700 * 0 (=%bp) is pushed on the stack
702 ptr = stack16_push( sizeof(WORD) );
703 *(WORD *)MapSL(ptr) = 0;
704 context->Esp -= 2;
706 context->Eax = 1;
708 if (!pTask->pdb.cmdLine[0]) context->Ebx = 0x80;
709 else
711 LPBYTE p = &pTask->pdb.cmdLine[1];
712 while ((*p == ' ') || (*p == '\t')) p++;
713 context->Ebx = 0x80 + (p - pTask->pdb.cmdLine);
715 context->Ecx = pinstance->stacktop;
716 context->Edx = pTask->nCmdShow;
717 context->Esi = (DWORD)pTask->hPrevInstance;
718 context->Edi = (DWORD)pTask->hInstance;
719 context->SegEs = (WORD)pTask->hPDB;
723 /***********************************************************************
724 * WaitEvent (KERNEL.30)
726 BOOL16 WINAPI WaitEvent16( HTASK16 hTask )
728 TDB *pTask;
730 if (!hTask) hTask = GetCurrentTask();
731 pTask = (TDB *)GlobalLock16( hTask );
733 if ( !THREAD_IsWin16( NtCurrentTeb() ) )
735 FIXME("called for Win32 thread (%04x)!\n", NtCurrentTeb()->teb_sel);
736 return TRUE;
739 if (pTask->nEvents > 0)
741 pTask->nEvents--;
742 return FALSE;
744 TASK_Reschedule();
746 /* When we get back here, we have an event */
748 if (pTask->nEvents > 0) pTask->nEvents--;
749 return TRUE;
753 /***********************************************************************
754 * PostEvent (KERNEL.31)
756 void WINAPI PostEvent16( HTASK16 hTask )
758 TDB *pTask;
760 if (!hTask) hTask = GetCurrentTask();
761 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
763 if ( !THREAD_IsWin16( pTask->teb ) )
765 FIXME("called for Win32 thread (%04x)!\n", pTask->teb->teb_sel );
766 return;
769 pTask->nEvents++;
771 /* If we are a 32-bit task, we might need to wake up the 16-bit scheduler */
772 if ( !THREAD_IsWin16( NtCurrentTeb() ) )
773 TASK_Reschedule();
777 /***********************************************************************
778 * SetPriority (KERNEL.32)
780 void WINAPI SetPriority16( HTASK16 hTask, INT16 delta )
782 TDB *pTask;
783 INT16 newpriority;
785 if (!hTask) hTask = GetCurrentTask();
786 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
787 newpriority = pTask->priority + delta;
788 if (newpriority < -32) newpriority = -32;
789 else if (newpriority > 15) newpriority = 15;
791 pTask->priority = newpriority + 1;
792 TASK_UnlinkTask( hTask );
793 TASK_LinkTask( hTask );
794 pTask->priority--;
798 /***********************************************************************
799 * LockCurrentTask (KERNEL.33)
801 HTASK16 WINAPI LockCurrentTask16( BOOL16 bLock )
803 if (bLock) hLockedTask = GetCurrentTask();
804 else hLockedTask = 0;
805 return hLockedTask;
809 /***********************************************************************
810 * IsTaskLocked (KERNEL.122)
812 HTASK16 WINAPI IsTaskLocked16(void)
814 return hLockedTask;
818 /***********************************************************************
819 * OldYield (KERNEL.117)
821 void WINAPI OldYield16(void)
823 TDB *pCurTask = (TDB *)GlobalLock16( GetCurrentTask() );
825 if ( !THREAD_IsWin16( NtCurrentTeb() ) )
827 FIXME("called for Win32 thread (%04x)!\n", NtCurrentTeb()->teb_sel);
828 return;
831 if (pCurTask) pCurTask->nEvents++; /* Make sure we get back here */
832 TASK_Reschedule();
833 if (pCurTask) pCurTask->nEvents--;
836 /***********************************************************************
837 * WIN32_OldYield16 (KERNEL.447)
839 void WINAPI WIN32_OldYield16(void)
841 DWORD count;
843 ReleaseThunkLock(&count);
844 RestoreThunkLock(count);
847 /***********************************************************************
848 * DirectedYield (KERNEL.150)
850 void WINAPI DirectedYield16( HTASK16 hTask )
852 TDB *pCurTask = (TDB *)GlobalLock16( GetCurrentTask() );
854 if ( !THREAD_IsWin16( NtCurrentTeb() ) )
856 FIXME("called for Win32 thread (%04x)!\n", NtCurrentTeb()->teb_sel);
857 return;
860 TRACE("%04x: DirectedYield(%04x)\n", pCurTask->hSelf, hTask );
862 pCurTask->hYieldTo = hTask;
863 OldYield16();
865 TRACE("%04x: back from DirectedYield(%04x)\n", pCurTask->hSelf, hTask );
868 /***********************************************************************
869 * Yield16 (KERNEL.29)
871 void WINAPI Yield16(void)
873 TDB *pCurTask = (TDB *)GlobalLock16( GetCurrentTask() );
875 if (pCurTask) pCurTask->hYieldTo = 0;
876 if (pCurTask && pCurTask->hQueue && Callout.UserYield16) Callout.UserYield16();
877 else OldYield16();
880 /***********************************************************************
881 * KERNEL_490 (KERNEL.490)
883 HTASK16 WINAPI KERNEL_490( HTASK16 someTask )
885 if ( !someTask ) return 0;
887 FIXME("(%04x): stub\n", someTask );
888 return 0;
891 /***********************************************************************
892 * MakeProcInstance16 (KERNEL.51)
894 FARPROC16 WINAPI MakeProcInstance16( FARPROC16 func, HANDLE16 hInstance )
896 BYTE *thunk,*lfunc;
897 SEGPTR thunkaddr;
898 WORD hInstanceSelector;
900 hInstanceSelector = GlobalHandleToSel16(hInstance);
902 TRACE("(%08lx, %04x);\n", (DWORD)func, hInstance);
904 if (!HIWORD(func)) {
905 /* Win95 actually protects via SEH, but this is better for debugging */
906 WARN("Ouch ! Called with invalid func 0x%08lx !\n", (DWORD)func);
907 return (FARPROC16)0;
910 if (hInstance)
912 if ( (!(hInstance & 4)) ||
913 ((hInstance != 0xffff) && IS_SELECTOR_FREE(hInstance|7)) )
915 WARN("Invalid hInstance (%04x) passed to MakeProcInstance !\n",
916 hInstance);
917 return 0;
921 if ( (GlobalHandleToSel16(CURRENT_DS) != hInstanceSelector)
922 && (hInstance != 0)
923 && (hInstance != 0xffff) )
925 /* calling MPI with a foreign DSEG is invalid ! */
926 WARN("Problem with hInstance? Got %04x, using %04x instead\n",
927 hInstance,CURRENT_DS);
930 /* Always use the DSEG that MPI was entered with.
931 * We used to set hInstance to GetTaskDS16(), but this should be wrong
932 * as CURRENT_DS provides the DSEG value we need.
933 * ("calling" DS, *not* "task" DS !) */
934 hInstanceSelector = CURRENT_DS;
935 hInstance = GlobalHandle16(hInstanceSelector);
937 /* no thunking for DLLs */
938 if (NE_GetPtr(FarGetOwner16(hInstance))->flags & NE_FFLAGS_LIBMODULE)
939 return func;
941 thunkaddr = TASK_AllocThunk( GetCurrentTask() );
942 if (!thunkaddr) return (FARPROC16)0;
943 thunk = MapSL( thunkaddr );
944 lfunc = MapSL( (SEGPTR)func );
946 TRACE("(%08lx,%04x): got thunk %08lx\n",
947 (DWORD)func, hInstance, (DWORD)thunkaddr );
948 if (((lfunc[0]==0x8c) && (lfunc[1]==0xd8)) || /* movw %ds, %ax */
949 ((lfunc[0]==0x1e) && (lfunc[1]==0x58)) /* pushw %ds, popw %ax */
951 WARN("This was the (in)famous \"thunk useless\" warning. We thought we have to overwrite with nop;nop;, but this isn't true.\n");
954 *thunk++ = 0xb8; /* movw instance, %ax */
955 *thunk++ = (BYTE)(hInstanceSelector & 0xff);
956 *thunk++ = (BYTE)(hInstanceSelector >> 8);
957 *thunk++ = 0xea; /* ljmp func */
958 *(DWORD *)thunk = (DWORD)func;
959 return (FARPROC16)thunkaddr;
960 /* CX reg indicates if thunkaddr != NULL, implement if needed */
964 /***********************************************************************
965 * FreeProcInstance16 (KERNEL.52)
967 void WINAPI FreeProcInstance16( FARPROC16 func )
969 TRACE("(%08lx)\n", (DWORD)func );
970 TASK_FreeThunk( GetCurrentTask(), (SEGPTR)func );
973 /**********************************************************************
974 * TASK_GetCodeSegment
976 * Helper function for GetCodeHandle/GetCodeInfo: Retrieve the module
977 * and logical segment number of a given code segment.
979 * 'proc' either *is* already a pair of module handle and segment number,
980 * in which case there's nothing to do. Otherwise, it is a pointer to
981 * a function, and we need to retrieve the code segment. If the pointer
982 * happens to point to a thunk, we'll retrieve info about the code segment
983 * where the function pointed to by the thunk resides, not the thunk itself.
985 * FIXME: if 'proc' is a SNOOP16 return stub, we should retrieve info about
986 * the function the snoop code will return to ...
989 static BOOL TASK_GetCodeSegment( FARPROC16 proc, NE_MODULE **ppModule,
990 SEGTABLEENTRY **ppSeg, int *pSegNr )
992 NE_MODULE *pModule = NULL;
993 SEGTABLEENTRY *pSeg = NULL;
994 int segNr=0;
996 /* Try pair of module handle / segment number */
997 pModule = (NE_MODULE *) GlobalLock16( HIWORD( proc ) );
998 if ( pModule && pModule->magic == IMAGE_OS2_SIGNATURE )
1000 segNr = LOWORD( proc );
1001 if ( segNr && segNr <= pModule->seg_count )
1002 pSeg = NE_SEG_TABLE( pModule ) + segNr-1;
1005 /* Try thunk or function */
1006 else
1008 BYTE *thunk = MapSL( (SEGPTR)proc );
1009 WORD selector;
1011 if ((thunk[0] == 0xb8) && (thunk[3] == 0xea))
1012 selector = thunk[6] + (thunk[7] << 8);
1013 else
1014 selector = HIWORD( proc );
1016 pModule = NE_GetPtr( GlobalHandle16( selector ) );
1017 pSeg = pModule? NE_SEG_TABLE( pModule ) : NULL;
1019 if ( pModule )
1020 for ( segNr = 1; segNr <= pModule->seg_count; segNr++, pSeg++ )
1021 if ( GlobalHandleToSel16(pSeg->hSeg) == selector )
1022 break;
1024 if ( pModule && segNr > pModule->seg_count )
1025 pSeg = NULL;
1028 /* Abort if segment not found */
1030 if ( !pModule || !pSeg )
1031 return FALSE;
1033 /* Return segment data */
1035 if ( ppModule ) *ppModule = pModule;
1036 if ( ppSeg ) *ppSeg = pSeg;
1037 if ( pSegNr ) *pSegNr = segNr;
1039 return TRUE;
1042 /**********************************************************************
1043 * GetCodeHandle (KERNEL.93)
1045 HANDLE16 WINAPI GetCodeHandle16( FARPROC16 proc )
1047 SEGTABLEENTRY *pSeg;
1049 if ( !TASK_GetCodeSegment( proc, NULL, &pSeg, NULL ) )
1050 return (HANDLE16)0;
1052 return pSeg->hSeg;
1055 /**********************************************************************
1056 * GetCodeInfo (KERNEL.104)
1058 BOOL16 WINAPI GetCodeInfo16( FARPROC16 proc, SEGINFO *segInfo )
1060 NE_MODULE *pModule;
1061 SEGTABLEENTRY *pSeg;
1062 int segNr;
1064 if ( !TASK_GetCodeSegment( proc, &pModule, &pSeg, &segNr ) )
1065 return FALSE;
1067 /* Fill in segment information */
1069 segInfo->offSegment = pSeg->filepos;
1070 segInfo->cbSegment = pSeg->size;
1071 segInfo->flags = pSeg->flags;
1072 segInfo->cbAlloc = pSeg->minsize;
1073 segInfo->h = pSeg->hSeg;
1074 segInfo->alignShift = pModule->alignment;
1076 if ( segNr == pModule->dgroup )
1077 segInfo->cbAlloc += pModule->heap_size + pModule->stack_size;
1079 /* Return module handle in %es */
1081 CURRENT_STACK16->es = GlobalHandleToSel16( pModule->self );
1083 return TRUE;
1087 /**********************************************************************
1088 * DefineHandleTable16 (KERNEL.94)
1090 BOOL16 WINAPI DefineHandleTable16( WORD wOffset )
1092 FIXME("(%04x): stub ?\n", wOffset);
1093 return TRUE;
1097 /***********************************************************************
1098 * SetTaskQueue (KERNEL.34)
1100 HQUEUE16 WINAPI SetTaskQueue16( HTASK16 hTask, HQUEUE16 hQueue )
1102 HQUEUE16 hPrev;
1103 TDB *pTask;
1105 if (!hTask) hTask = GetCurrentTask();
1106 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return 0;
1108 hPrev = pTask->hQueue;
1109 pTask->hQueue = hQueue;
1111 return hPrev;
1115 /***********************************************************************
1116 * GetTaskQueue (KERNEL.35)
1118 HQUEUE16 WINAPI GetTaskQueue16( HTASK16 hTask )
1120 TDB *pTask;
1122 if (!hTask) hTask = GetCurrentTask();
1123 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return 0;
1124 return pTask->hQueue;
1127 /***********************************************************************
1128 * SetThreadQueue (KERNEL.463)
1130 HQUEUE16 WINAPI SetThreadQueue16( DWORD thread, HQUEUE16 hQueue )
1132 TEB *teb = thread? THREAD_IdToTEB( thread ) : NtCurrentTeb();
1133 HQUEUE16 oldQueue = teb? teb->queue : 0;
1135 if ( teb )
1137 teb->queue = hQueue;
1139 if ( GetTaskQueue16( teb->htask16 ) == oldQueue )
1140 SetTaskQueue16( teb->htask16, hQueue );
1143 return oldQueue;
1146 /***********************************************************************
1147 * GetThreadQueue (KERNEL.464)
1149 HQUEUE16 WINAPI GetThreadQueue16( DWORD thread )
1151 TEB *teb = NULL;
1152 if ( !thread )
1153 teb = NtCurrentTeb();
1154 else if ( HIWORD(thread) )
1155 teb = THREAD_IdToTEB( thread );
1156 else if ( IsTask16( (HTASK16)thread ) )
1157 teb = ((TDB *)GlobalLock16( (HANDLE16)thread ))->teb;
1159 return (HQUEUE16)(teb? teb->queue : 0);
1162 /***********************************************************************
1163 * SetFastQueue (KERNEL.624)
1165 VOID WINAPI SetFastQueue16( DWORD thread, HANDLE hQueue )
1167 TEB *teb = NULL;
1168 if ( !thread )
1169 teb = NtCurrentTeb();
1170 else if ( HIWORD(thread) )
1171 teb = THREAD_IdToTEB( thread );
1172 else if ( IsTask16( (HTASK16)thread ) )
1173 teb = ((TDB *)GlobalLock16( (HANDLE16)thread ))->teb;
1175 if ( teb ) teb->queue = (HQUEUE16) hQueue;
1178 /***********************************************************************
1179 * GetFastQueue (KERNEL.625)
1181 HANDLE WINAPI GetFastQueue16( void )
1183 TEB *teb = NtCurrentTeb();
1184 if (!teb) return 0;
1186 if (!teb->queue)
1188 if (!Callout.InitThreadInput16)
1190 THUNK_InitCallout();
1191 if (!Callout.InitThreadInput16)
1193 FIXME("InitThreadInput16 callout not found, trouble ahead\n");
1194 return 0;
1197 Callout.InitThreadInput16( 0, THREAD_IsWin16(teb)? 4 : 5 );
1199 if (!teb->queue)
1200 FIXME("(): should initialize thread-local queue, expect failure!\n" );
1203 return (HANDLE)teb->queue;
1206 /***********************************************************************
1207 * SwitchStackTo (KERNEL.108)
1209 void WINAPI SwitchStackTo16( WORD seg, WORD ptr, WORD top )
1211 TDB *pTask;
1212 STACK16FRAME *oldFrame, *newFrame;
1213 INSTANCEDATA *pData;
1214 UINT16 copySize;
1216 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return;
1217 if (!(pData = (INSTANCEDATA *)GlobalLock16( seg ))) return;
1218 TRACE("old=%04x:%04x new=%04x:%04x\n",
1219 SELECTOROF( pTask->teb->cur_stack ),
1220 OFFSETOF( pTask->teb->cur_stack ), seg, ptr );
1222 /* Save the old stack */
1224 oldFrame = THREAD_STACK16( pTask->teb );
1225 /* pop frame + args and push bp */
1226 pData->old_ss_sp = pTask->teb->cur_stack + sizeof(STACK16FRAME)
1227 + 2 * sizeof(WORD);
1228 *(WORD *)MapSL(pData->old_ss_sp) = oldFrame->bp;
1229 pData->stacktop = top;
1230 pData->stackmin = ptr;
1231 pData->stackbottom = ptr;
1233 /* Switch to the new stack */
1235 /* Note: we need to take the 3 arguments into account; otherwise,
1236 * the stack will underflow upon return from this function.
1238 copySize = oldFrame->bp - OFFSETOF(pData->old_ss_sp);
1239 copySize += 3 * sizeof(WORD) + sizeof(STACK16FRAME);
1240 pTask->teb->cur_stack = MAKESEGPTR( seg, ptr - copySize );
1241 newFrame = THREAD_STACK16( pTask->teb );
1243 /* Copy the stack frame and the local variables to the new stack */
1245 memmove( newFrame, oldFrame, copySize );
1246 newFrame->bp = ptr;
1247 *(WORD *)MapSL( MAKESEGPTR( seg, ptr ) ) = 0; /* clear previous bp */
1251 /***********************************************************************
1252 * SwitchStackBack (KERNEL.109)
1254 void WINAPI SwitchStackBack16( CONTEXT86 *context )
1256 STACK16FRAME *oldFrame, *newFrame;
1257 INSTANCEDATA *pData;
1259 if (!(pData = (INSTANCEDATA *)GlobalLock16(SELECTOROF(NtCurrentTeb()->cur_stack))))
1260 return;
1261 if (!pData->old_ss_sp)
1263 WARN("No previous SwitchStackTo\n" );
1264 return;
1266 TRACE("restoring stack %04x:%04x\n",
1267 SELECTOROF(pData->old_ss_sp), OFFSETOF(pData->old_ss_sp) );
1269 oldFrame = CURRENT_STACK16;
1271 /* Pop bp from the previous stack */
1273 BP_reg(context) = *(WORD *)MapSL(pData->old_ss_sp);
1274 pData->old_ss_sp += sizeof(WORD);
1276 /* Switch back to the old stack */
1278 NtCurrentTeb()->cur_stack = pData->old_ss_sp - sizeof(STACK16FRAME);
1279 context->SegSs = SELECTOROF(pData->old_ss_sp);
1280 context->Esp = OFFSETOF(pData->old_ss_sp) - sizeof(DWORD); /*ret addr*/
1281 pData->old_ss_sp = 0;
1283 /* Build a stack frame for the return */
1285 newFrame = CURRENT_STACK16;
1286 newFrame->frame32 = oldFrame->frame32;
1287 newFrame->module_cs = oldFrame->module_cs;
1288 newFrame->callfrom_ip = oldFrame->callfrom_ip;
1289 newFrame->entry_ip = oldFrame->entry_ip;
1293 /***********************************************************************
1294 * GetTaskQueueDS16 (KERNEL.118)
1296 void WINAPI GetTaskQueueDS16(void)
1298 CURRENT_STACK16->ds = GlobalHandleToSel16( GetTaskQueue16(0) );
1302 /***********************************************************************
1303 * GetTaskQueueES16 (KERNEL.119)
1305 void WINAPI GetTaskQueueES16(void)
1307 CURRENT_STACK16->es = GlobalHandleToSel16( GetTaskQueue16(0) );
1311 /***********************************************************************
1312 * GetCurrentTask (KERNEL.36)
1314 HTASK16 WINAPI GetCurrentTask(void)
1316 return NtCurrentTeb()->htask16;
1319 DWORD WINAPI WIN16_GetCurrentTask(void)
1321 /* This is the version used by relay code; the first task is */
1322 /* returned in the high word of the result */
1323 return MAKELONG( GetCurrentTask(), hFirstTask );
1327 /***********************************************************************
1328 * GetCurrentPDB (KERNEL.37)
1330 * UNDOC: returns PSP of KERNEL in high word
1332 DWORD WINAPI GetCurrentPDB16(void)
1334 TDB *pTask;
1336 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1337 return MAKELONG(pTask->hPDB, 0); /* FIXME */
1341 /***********************************************************************
1342 * GetCurPID16 (KERNEL.157)
1344 DWORD WINAPI GetCurPID16( DWORD unused )
1346 return 0;
1350 /***********************************************************************
1351 * GetInstanceData (KERNEL.54)
1353 INT16 WINAPI GetInstanceData16( HINSTANCE16 instance, WORD buffer, INT16 len )
1355 char *ptr = (char *)GlobalLock16( instance );
1356 if (!ptr || !len) return 0;
1357 if ((int)buffer + len >= 0x10000) len = 0x10000 - buffer;
1358 memcpy( (char *)GlobalLock16(CURRENT_DS) + buffer, ptr + buffer, len );
1359 return len;
1363 /***********************************************************************
1364 * GetExeVersion (KERNEL.105)
1366 WORD WINAPI GetExeVersion16(void)
1368 TDB *pTask;
1370 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1371 return pTask->version;
1375 /***********************************************************************
1376 * SetErrorMode16 (KERNEL.107)
1378 UINT16 WINAPI SetErrorMode16( UINT16 mode )
1380 TDB *pTask;
1381 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1382 pTask->error_mode = mode;
1383 return SetErrorMode( mode );
1387 /***********************************************************************
1388 * GetNumTasks (KERNEL.152)
1390 UINT16 WINAPI GetNumTasks16(void)
1392 return nTaskCount;
1396 /***********************************************************************
1397 * GetTaskDS (KERNEL.155)
1399 * Note: this function apparently returns a DWORD with LOWORD == HIWORD.
1400 * I don't think we need to bother with this.
1402 HINSTANCE16 WINAPI GetTaskDS16(void)
1404 TDB *pTask;
1406 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1407 return GlobalHandleToSel16(pTask->hInstance);
1410 /***********************************************************************
1411 * GetDummyModuleHandleDS (KERNEL.602)
1413 WORD WINAPI GetDummyModuleHandleDS16(void)
1415 TDB *pTask;
1416 WORD selector;
1418 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1419 if (!(pTask->flags & TDBF_WIN32)) return 0;
1420 selector = GlobalHandleToSel16( pTask->hModule );
1421 CURRENT_DS = selector;
1422 return selector;
1425 /***********************************************************************
1426 * IsTask (KERNEL.320)
1427 * IsTask16 (KERNEL32.@)
1429 BOOL16 WINAPI IsTask16( HTASK16 hTask )
1431 TDB *pTask;
1433 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return FALSE;
1434 if (GlobalSize16( hTask ) < sizeof(TDB)) return FALSE;
1435 return (pTask->magic == TDB_MAGIC);
1439 /***********************************************************************
1440 * IsWinOldApTask16 (KERNEL.158)
1442 BOOL16 WINAPI IsWinOldApTask16( HTASK16 hTask )
1444 /* should return bit 0 of byte 0x48 in PSP */
1445 return FALSE;
1448 /***********************************************************************
1449 * SetTaskSignalProc (KERNEL.38)
1451 FARPROC16 WINAPI SetTaskSignalProc( HTASK16 hTask, FARPROC16 proc )
1453 TDB *pTask;
1454 FARPROC16 oldProc;
1456 if (!hTask) hTask = GetCurrentTask();
1457 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return NULL;
1458 oldProc = pTask->userhandler;
1459 pTask->userhandler = proc;
1460 return oldProc;
1463 /***********************************************************************
1464 * TASK_CallTaskSignalProc
1466 /* ### start build ### */
1467 extern WORD CALLBACK TASK_CallTo16_word_wwwww(FARPROC16,WORD,WORD,WORD,WORD,WORD);
1468 /* ### stop build ### */
1469 void TASK_CallTaskSignalProc( UINT16 uCode, HANDLE16 hTaskOrModule )
1471 TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
1472 if ( !pTask || !pTask->userhandler ) return;
1474 TASK_CallTo16_word_wwwww( pTask->userhandler,
1475 hTaskOrModule, uCode, 0,
1476 pTask->hInstance, pTask->hQueue );
1479 /***********************************************************************
1480 * SetSigHandler (KERNEL.140)
1482 WORD WINAPI SetSigHandler16( FARPROC16 newhandler, FARPROC16* oldhandler,
1483 UINT16 *oldmode, UINT16 newmode, UINT16 flag )
1485 FIXME("(%p,%p,%p,%d,%d), unimplemented.\n",
1486 newhandler,oldhandler,oldmode,newmode,flag );
1488 if (flag != 1) return 0;
1489 if (!newmode) newhandler = NULL; /* Default handler */
1490 if (newmode != 4)
1492 TDB *pTask;
1494 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1495 if (oldmode) *oldmode = pTask->signal_flags;
1496 pTask->signal_flags = newmode;
1497 if (oldhandler) *oldhandler = pTask->sighandler;
1498 pTask->sighandler = newhandler;
1500 return 0;
1504 /***********************************************************************
1505 * GlobalNotify (KERNEL.154)
1507 * Note that GlobalNotify does _not_ return the old NotifyProc
1508 * -- contrary to LocalNotify !!
1510 VOID WINAPI GlobalNotify16( FARPROC16 proc )
1512 TDB *pTask;
1514 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return;
1515 pTask->discardhandler = proc;
1519 /***********************************************************************
1520 * GetExePtr (KERNEL.133)
1522 static inline HMODULE16 GetExePtrHelper( HANDLE16 handle, HTASK16 *hTask )
1524 char *ptr;
1525 HANDLE16 owner;
1527 /* Check for module handle */
1529 if (!(ptr = GlobalLock16( handle ))) return 0;
1530 if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return handle;
1532 /* Search for this handle inside all tasks */
1534 *hTask = hFirstTask;
1535 while (*hTask)
1537 TDB *pTask = (TDB *)GlobalLock16( *hTask );
1538 if ((*hTask == handle) ||
1539 (pTask->hInstance == handle) ||
1540 (pTask->hQueue == handle) ||
1541 (pTask->hPDB == handle)) return pTask->hModule;
1542 *hTask = pTask->hNext;
1545 /* Check the owner for module handle */
1547 owner = FarGetOwner16( handle );
1548 if (!(ptr = GlobalLock16( owner ))) return 0;
1549 if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return owner;
1551 /* Search for the owner inside all tasks */
1553 *hTask = hFirstTask;
1554 while (*hTask)
1556 TDB *pTask = (TDB *)GlobalLock16( *hTask );
1557 if ((*hTask == owner) ||
1558 (pTask->hInstance == owner) ||
1559 (pTask->hQueue == owner) ||
1560 (pTask->hPDB == owner)) return pTask->hModule;
1561 *hTask = pTask->hNext;
1564 return 0;
1567 /**********************************************************************/
1569 HMODULE16 WINAPI WIN16_GetExePtr( HANDLE16 handle )
1571 HTASK16 hTask = 0;
1572 HMODULE16 hModule = GetExePtrHelper( handle, &hTask );
1573 STACK16FRAME *frame = CURRENT_STACK16;
1574 frame->ecx = hModule;
1575 if (hTask) frame->es = hTask;
1576 return hModule;
1579 /**********************************************************************/
1581 HMODULE16 WINAPI GetExePtr( HANDLE16 handle )
1583 HTASK16 hTask = 0;
1584 return GetExePtrHelper( handle, &hTask );
1588 /***********************************************************************
1589 * TaskFirst (TOOLHELP.63)
1591 BOOL16 WINAPI TaskFirst16( TASKENTRY *lpte )
1593 lpte->hNext = hFirstTask;
1594 return TaskNext16( lpte );
1598 /***********************************************************************
1599 * TaskNext (TOOLHELP.64)
1601 BOOL16 WINAPI TaskNext16( TASKENTRY *lpte )
1603 TDB *pTask;
1604 INSTANCEDATA *pInstData;
1606 TRACE_(toolhelp)("(%p): task=%04x\n", lpte, lpte->hNext );
1607 if (!lpte->hNext) return FALSE;
1609 /* make sure that task and hInstance are valid (skip initial Wine task !) */
1610 while (1) {
1611 pTask = (TDB *)GlobalLock16( lpte->hNext );
1612 if (!pTask || pTask->magic != TDB_MAGIC) return FALSE;
1613 if (pTask->hInstance)
1614 break;
1615 lpte->hNext = pTask->hNext;
1617 pInstData = MapSL( MAKESEGPTR( GlobalHandleToSel16(pTask->hInstance), 0 ) );
1618 lpte->hTask = lpte->hNext;
1619 lpte->hTaskParent = pTask->hParent;
1620 lpte->hInst = pTask->hInstance;
1621 lpte->hModule = pTask->hModule;
1622 lpte->wSS = SELECTOROF( pTask->teb->cur_stack );
1623 lpte->wSP = OFFSETOF( pTask->teb->cur_stack );
1624 lpte->wStackTop = pInstData->stacktop;
1625 lpte->wStackMinimum = pInstData->stackmin;
1626 lpte->wStackBottom = pInstData->stackbottom;
1627 lpte->wcEvents = pTask->nEvents;
1628 lpte->hQueue = pTask->hQueue;
1629 lstrcpynA( lpte->szModule, pTask->module_name, sizeof(lpte->szModule) );
1630 lpte->wPSPOffset = 0x100; /*??*/
1631 lpte->hNext = pTask->hNext;
1632 return TRUE;
1636 /***********************************************************************
1637 * TaskFindHandle (TOOLHELP.65)
1639 BOOL16 WINAPI TaskFindHandle16( TASKENTRY *lpte, HTASK16 hTask )
1641 lpte->hNext = hTask;
1642 return TaskNext16( lpte );
1646 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND hWnd, LPCSTR text, LPCSTR title, UINT type);
1648 /**************************************************************************
1649 * FatalAppExit16 (KERNEL.137)
1651 void WINAPI FatalAppExit16( UINT16 action, LPCSTR str )
1653 TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
1655 if (!pTask || !(pTask->error_mode & SEM_NOGPFAULTERRORBOX))
1657 HMODULE mod = GetModuleHandleA( "user32.dll" );
1658 if (mod)
1660 MessageBoxA_funcptr pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
1661 if (pMessageBoxA)
1663 pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
1664 goto done;
1667 ERR( "%s\n", debugstr_a(str) );
1669 done:
1670 ExitThread(0xff);
1674 /***********************************************************************
1675 * TerminateApp16 (TOOLHELP.77)
1677 * See "Undocumented Windows".
1679 void WINAPI TerminateApp16(HTASK16 hTask, WORD wFlags)
1681 if (hTask && hTask != GetCurrentTask())
1683 FIXME("cannot terminate task %x\n", hTask);
1684 return;
1687 if (wFlags & NO_UAE_BOX)
1689 UINT16 old_mode;
1690 old_mode = SetErrorMode16(0);
1691 SetErrorMode16(old_mode|SEM_NOGPFAULTERRORBOX);
1693 FatalAppExit16( 0, NULL );
1695 /* hmm, we're still alive ?? */
1697 /* check undocumented flag */
1698 if (!(wFlags & 0x8000))
1699 TASK_CallTaskSignalProc( USIG16_TERMINATION, hTask );
1701 /* UndocWin says to call int 0x21/0x4c exit=0xff here,
1702 but let's just call ExitThread */
1703 ExitThread(0xff);
1707 /***********************************************************************
1708 * GetAppCompatFlags16 (KERNEL.354)
1710 DWORD WINAPI GetAppCompatFlags16( HTASK16 hTask )
1712 return GetAppCompatFlags( hTask );
1716 /***********************************************************************
1717 * GetAppCompatFlags (USER32.206)
1719 DWORD WINAPI GetAppCompatFlags( HTASK hTask )
1721 TDB *pTask;
1723 if (!hTask) hTask = GetCurrentTask();
1724 if (!(pTask=(TDB *)GlobalLock16( (HTASK16)hTask ))) return 0;
1725 if (GlobalSize16(hTask) < sizeof(TDB)) return 0;
1726 return pTask->compat_flags;