- Remove <string.h> from winnt.h.
[wine] / loader / task.c
1 /*
2  * Task functions
3  *
4  * Copyright 1995 Alexandre Julliard
5  */
6
7 #include <stdlib.h>
8 #include <string.h>
9 #include <assert.h>
10 #include <unistd.h>
11
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"
34
35
36 DEFAULT_DEBUG_CHANNEL(task);
37 DECLARE_DEBUG_CHANNEL(relay);
38 DECLARE_DEBUG_CHANNEL(toolhelp);
39
40   /* Min. number of thunks allocated when creating a new segment */
41 #define MIN_THUNKS  32
42
43
44 static THHOOK DefaultThhook;
45 THHOOK *pThhook = &DefaultThhook;
46
47 #define hCurrentTask (pThhook->CurTDB)
48 #define hFirstTask   (pThhook->HeadTDB)
49 #define hLockedTask  (pThhook->LockTDB)
50
51 static UINT16 nTaskCount = 0;
52
53 static HTASK initial_task;
54
55 /***********************************************************************
56  *           TASK_InstallTHHook
57  */
58 void TASK_InstallTHHook( THHOOK *pNewThhook )
59 {
60      THHOOK *pOldThhook = pThhook;
61
62      pThhook = pNewThhook? pNewThhook : &DefaultThhook;
63
64      *pThhook = *pOldThhook;
65 }
66
67 /***********************************************************************
68  *           TASK_GetNextTask
69  */
70 HTASK16 TASK_GetNextTask( HTASK16 hTask )
71 {
72     TDB* pTask = (TDB*)GlobalLock16(hTask);
73
74     if (pTask->hNext) return pTask->hNext;
75     return (hFirstTask != hTask) ? hFirstTask : 0; 
76 }
77
78 /***********************************************************************
79  *           TASK_LinkTask
80  */
81 static void TASK_LinkTask( HTASK16 hTask )
82 {
83     HTASK16 *prevTask;
84     TDB *pTask;
85
86     if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
87     prevTask = &hFirstTask;
88     while (*prevTask)
89     {
90         TDB *prevTaskPtr = (TDB *)GlobalLock16( *prevTask );
91         if (prevTaskPtr->priority >= pTask->priority) break;
92         prevTask = &prevTaskPtr->hNext;
93     }
94     pTask->hNext = *prevTask;
95     *prevTask = hTask;
96     nTaskCount++;
97 }
98
99
100 /***********************************************************************
101  *           TASK_UnlinkTask
102  */
103 static void TASK_UnlinkTask( HTASK16 hTask )
104 {
105     HTASK16 *prevTask;
106     TDB *pTask;
107
108     prevTask = &hFirstTask;
109     while (*prevTask && (*prevTask != hTask))
110     {
111         pTask = (TDB *)GlobalLock16( *prevTask );
112         prevTask = &pTask->hNext;
113     }
114     if (*prevTask)
115     {
116         pTask = (TDB *)GlobalLock16( *prevTask );
117         *prevTask = pTask->hNext;
118         pTask->hNext = 0;
119         nTaskCount--;
120     }
121 }
122
123
124 /***********************************************************************
125  *           TASK_CreateThunks
126  *
127  * Create a thunk free-list in segment 'handle', starting from offset 'offset'
128  * and containing 'count' entries.
129  */
130 static void TASK_CreateThunks( HGLOBAL16 handle, WORD offset, WORD count )
131 {
132     int i;
133     WORD free;
134     THUNKS *pThunk;
135
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++)
142     {
143         free += 8;  /* Offset of next thunk */
144         pThunk->thunks[4*i] = free;
145     }
146     pThunk->thunks[4*i] = 0;  /* Last thunk */
147 }
148
149
150 /***********************************************************************
151  *           TASK_AllocThunk
152  *
153  * Allocate a thunk for MakeProcInstance().
154  */
155 static SEGPTR TASK_AllocThunk( HTASK16 hTask )
156 {
157     TDB *pTask;
158     THUNKS *pThunk;
159     WORD sel, base;
160     
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)
166     {
167         sel = pThunk->next;
168         if (!sel)  /* Allocate a new segment */
169         {
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;
175         }
176         pThunk = (THUNKS *)GlobalLock16( sel );
177         base = 0;
178     }
179     base += pThunk->free;
180     pThunk->free = *(WORD *)((BYTE *)pThunk + pThunk->free);
181     return MAKESEGPTR( sel, base );
182 }
183
184
185 /***********************************************************************
186  *           TASK_FreeThunk
187  *
188  * Free a MakeProcInstance() thunk.
189  */
190 static BOOL TASK_FreeThunk( HTASK16 hTask, SEGPTR thunk )
191 {
192     TDB *pTask;
193     THUNKS *pThunk;
194     WORD sel, base;
195     
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)))
201     {
202         sel = pThunk->next;
203         pThunk = (THUNKS *)GlobalLock16( sel );
204         base = 0;
205     }
206     if (!sel) return FALSE;
207     *(WORD *)((BYTE *)pThunk + LOWORD(thunk) - base) = pThunk->free;
208     pThunk->free = LOWORD(thunk) - base;
209     return TRUE;
210 }
211
212
213 /***********************************************************************
214  *           TASK_Create
215  *
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.
220  */
221 BOOL TASK_Create( NE_MODULE *pModule, UINT16 cmdShow, TEB *teb, LPCSTR cmdline, BYTE len )
222 {
223     HTASK16 hTask;
224     TDB *pTask;
225     char name[10];
226
227       /* Allocate the task structure */
228
229     hTask = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, sizeof(TDB) );
230     if (!hTask) return FALSE;
231     pTask = (TDB *)GlobalLock16( hTask );
232     FarSetOwner16( hTask, pModule->self );
233
234     /* Fill the task structure */
235
236     pTask->hSelf = hTask;
237
238     if (teb->tibflags & TEBF_WIN32)
239     {
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 */
245     }
246
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 );
257
258       /* Create the thunks block */
259
260     TASK_CreateThunks( hTask, (int)&pTask->thunks - (int)pTask, 7 );
261
262       /* Copy the module name */
263
264     GetModuleName16( pModule->self, name, sizeof(name) );
265     strncpy( pTask->module_name, name, sizeof(pTask->module_name) );
266
267       /* Allocate a selector for the PDB */
268
269     pTask->hPDB = GLOBAL_CreateBlock( GMEM_FIXED, &pTask->pdb, sizeof(PDB16),
270                                       pModule->self, WINE_LDT_FLAGS_DATA );
271
272       /* Fill the PDB */
273
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;
288
289     /* Fill the command line */
290
291     if (!cmdline)
292     {
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);
300     }
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; */
305
306     TRACE("module='%s' cmdline='%.*s' task=%04x\n", name, len, cmdline, hTask );
307
308       /* Get the compatibility flags */
309
310     pTask->compat_flags = GetProfileIntA( "Compatibility", name, 0 );
311
312       /* Allocate a code segment alias for the TDB */
313
314     pTask->hCSAlias = GLOBAL_CreateBlock( GMEM_FIXED, (void *)pTask,
315                                           sizeof(TDB), pTask->hPDB, WINE_LDT_FLAGS_CODE );
316
317       /* Default DTA overwrites command line */
318
319     pTask->dta = MAKESEGPTR( pTask->hPDB, (int)&pTask->pdb.cmdLine - (int)&pTask->pdb );
320
321     /* Create scheduler event for 16-bit tasks */
322
323     if ( !(pTask->flags & TDBF_WIN32) )
324         NtCreateEvent( &pTask->hEvent, EVENT_ALL_ACCESS, NULL, TRUE, FALSE );
325
326     /* Enter task handle into thread and process */
327
328     teb->htask16 = hTask;
329     if (!initial_task) initial_task = hTask;
330
331     /* Add the task to the linked list */
332
333     _EnterWin16Lock();
334     TASK_LinkTask( hTask );
335     _LeaveWin16Lock();
336
337     return TRUE;
338 }
339
340 /***********************************************************************
341  *           TASK_DeleteTask
342  */
343 static void TASK_DeleteTask( HTASK16 hTask )
344 {
345     TDB *pTask;
346     HGLOBAL16 hPDB;
347
348     if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
349     hPDB = pTask->hPDB;
350
351     pTask->magic = 0xdead; /* invalidate signature */
352
353     /* Free the selector aliases */
354
355     GLOBAL_FreeBlock( pTask->hCSAlias );
356     GLOBAL_FreeBlock( pTask->hPDB );
357
358     /* Free the task module */
359
360     FreeModule16( pTask->hModule );
361
362     /* Free the task structure itself */
363
364     GlobalFree16( hTask );
365
366     /* Free all memory used by this task (including the 32-bit stack, */
367     /* the environment block and the thunk segments). */
368
369     GlobalFreeAll16( hPDB );
370 }
371
372 /***********************************************************************
373  *           TASK_KillTask
374  */
375 void TASK_ExitTask(void)
376 {
377     TDB *pTask; 
378     DWORD lockCount;
379
380     /* Enter the Win16Lock to protect global data structures */
381     _EnterWin16Lock();
382
383     pTask = (TDB *)GlobalLock16( GetCurrentTask() );
384     if ( !pTask ) 
385     {
386         _LeaveWin16Lock();
387         return;
388     }
389
390     TRACE("Killing task %04x\n", pTask->hSelf );
391
392     /* Perform USER cleanup */
393
394     TASK_CallTaskSignalProc( USIG16_TERMINATION, pTask->hSelf );
395     PROCESS_CallUserSignalProc( USIG_PROCESS_EXIT, 0 );
396     PROCESS_CallUserSignalProc( USIG_THREAD_EXIT, 0 );
397     PROCESS_CallUserSignalProc( USIG_PROCESS_DESTROY, 0 );
398
399     /* Remove the task from the list to be sure we never switch back to it */
400     TASK_UnlinkTask( pTask->hSelf );
401
402     if (!nTaskCount || (nTaskCount == 1 && hFirstTask == initial_task))
403     {
404         TRACE("this is the last task, exiting\n" );
405         ExitKernel16();
406     }
407
408     if( nTaskCount )
409     {
410         TDB* p = (TDB *)GlobalLock16( hFirstTask );
411         while( p )
412         {
413             if( p->hYieldTo == pTask->hSelf ) p->hYieldTo = 0;
414             p = (TDB *)GlobalLock16( p->hNext );
415         }
416     }
417
418     pTask->nEvents = 0;
419
420     if ( hLockedTask == pTask->hSelf )
421         hLockedTask = 0;
422
423     TASK_DeleteTask( pTask->hSelf );
424
425     /* ... schedule another one ... */
426     TASK_Reschedule();
427
428     /* ... and completely release the Win16Lock, just in case. */
429     ReleaseThunkLock( &lockCount );
430 }
431
432 /***********************************************************************
433  *           TASK_Reschedule
434  *
435  * This is where all the magic of task-switching happens!
436  *
437  * 16-bit Windows performs non-preemptive (cooperative) multitasking.
438  * This means that each 16-bit task runs until it voluntarily yields 
439  * control, at which point the scheduler gets active and selects the
440  * next task to run.
441  *
442  * In Wine, all processes, even 16-bit ones, are scheduled preemptively
443  * by the standard scheduler of the underlying OS.  As many 16-bit apps
444  * *rely* on the behaviour of the Windows scheduler, however, we have
445  * to simulate that behaviour.
446  *
447  * This is achieved as follows: every 16-bit task is at time (except
448  * during task creation and deletion) in one of two states: either it
449  * is the one currently running, then the global variable hCurrentTask
450  * contains its task handle, or it is not currently running, then it
451  * is blocked on a special scheduler event, a global handle which
452  * is stored in the task struct.
453  *
454  * When the current task yields control, this routine gets called. Its
455  * purpose is to determine the next task to be active, signal the 
456  * scheduler event of that task, and then put the current task to sleep
457  * waiting for *its* scheduler event to get signalled again.
458  *
459  * This routine can get called in a few other special situations as well:
460  *
461  * - On creation of a 16-bit task, the Unix process executing the task
462  *   calls TASK_Reschedule once it has completed its initialization.
463  *   At this point, the task needs to be blocked until its scheduler
464  *   event is signalled the first time (this will be done by the parent
465  *   process to get the task up and running).
466  *
467  * - When the task currently running terminates itself, this routine gets
468  *   called and has to schedule another task, *without* blocking the 
469  *   terminating task.
470  *
471  * - When a 32-bit thread posts an event for a 16-bit task, it might be
472  *   the case that *no* 16-bit task is currently running.  In this case
473  *   the task that has now an event pending is to be scheduled.
474  *
475  */
476 void TASK_Reschedule(void)
477 {
478     TDB *pOldTask = NULL, *pNewTask = NULL;
479     HTASK16 hOldTask = 0, hNewTask = 0;
480     enum { MODE_YIELD, MODE_SLEEP, MODE_WAKEUP } mode;
481     DWORD lockCount;
482
483     _EnterWin16Lock();
484
485     /* Check what we need to do */
486     hOldTask = GetCurrentTask();
487     pOldTask = (TDB *)GlobalLock16( hOldTask );
488     TRACE( "entered with hCurrentTask %04x by hTask %04x (pid %ld)\n", 
489            hCurrentTask, hOldTask, (long) getpid() );
490
491     if ( pOldTask && THREAD_IsWin16( NtCurrentTeb() ) )
492     {
493         /* We are called by an active (non-deleted) 16-bit task */
494
495         /* If we don't even have a current task, or else the current
496            task has yielded, we'll need to schedule a new task and
497            (possibly) put the calling task to sleep.  Otherwise, we
498            only block the caller. */
499
500         if ( !hCurrentTask || hCurrentTask == hOldTask )
501             mode = MODE_YIELD;
502         else
503             mode = MODE_SLEEP;
504     }
505     else
506     {
507         /* We are called by a deleted 16-bit task or a 32-bit thread */
508
509         /* The only situation where we need to do something is if we
510            now do not have a current task.  Then, we'll need to wake up
511            some task that has events pending. */
512
513         if ( !hCurrentTask || hCurrentTask == hOldTask )
514             mode = MODE_WAKEUP;
515         else
516         {
517             /* nothing to do */
518             _LeaveWin16Lock();
519             return;
520         }
521     }
522
523     /* Find a task to yield to: check for DirectedYield() */
524     if ( mode == MODE_YIELD && pOldTask && pOldTask->hYieldTo )
525     {
526         hNewTask = pOldTask->hYieldTo;
527         pNewTask = (TDB *)GlobalLock16( hNewTask );
528         if( !pNewTask || !pNewTask->nEvents) hNewTask = 0;
529         pOldTask->hYieldTo = 0;
530     }
531
532     /* Find a task to yield to: check for pending events */
533     if ( (mode == MODE_YIELD || mode == MODE_WAKEUP) && !hNewTask )
534     {
535         hNewTask = hFirstTask;
536         while (hNewTask)
537         {
538             pNewTask = (TDB *)GlobalLock16( hNewTask );
539
540             TRACE( "\ttask = %04x, events = %i\n", hNewTask, pNewTask->nEvents );
541
542             if (pNewTask->nEvents) break;
543             hNewTask = pNewTask->hNext;
544         }
545         if (hLockedTask && (hNewTask != hLockedTask)) hNewTask = 0;
546     }
547
548     /* If we are still the task with highest priority, just return ... */
549     if ( mode == MODE_YIELD && hNewTask && hNewTask == hCurrentTask )
550     {
551         TRACE("returning to the current task (%04x)\n", hCurrentTask );
552         _LeaveWin16Lock();
553
554         /* Allow Win32 threads to thunk down even while a Win16 task is
555            in a tight PeekMessage() or Yield() loop ... */
556         ReleaseThunkLock( &lockCount );
557         RestoreThunkLock( lockCount );
558         return;
559     }
560
561     /* If no task to yield to found, suspend 16-bit scheduler ... */
562     if ( mode == MODE_YIELD && !hNewTask )
563     {
564         TRACE("No currently active task\n");
565         hCurrentTask = 0;
566     }
567
568     /* If we found a task to wake up, do it ... */
569     if ( (mode == MODE_YIELD || mode == MODE_WAKEUP) && hNewTask )
570     {
571         TRACE("Switching to task %04x (%.8s)\n",
572                       hNewTask, pNewTask->module_name );
573
574         pNewTask->priority++;
575         TASK_UnlinkTask( hNewTask );
576         TASK_LinkTask( hNewTask );
577         pNewTask->priority--;
578
579         hCurrentTask = hNewTask;
580         NtSetEvent( pNewTask->hEvent, NULL );
581
582         /* This is set just in case some app reads it ... */
583         pNewTask->ss_sp = pNewTask->teb->cur_stack;
584     }
585
586     /* If we need to put the current task to sleep, do it ... */
587     if ( (mode == MODE_YIELD || mode == MODE_SLEEP) && hOldTask != hCurrentTask )
588     {
589         NtResetEvent( pOldTask->hEvent, NULL );
590
591         ReleaseThunkLock( &lockCount );
592         SYSLEVEL_CheckNotLevel( 1 );
593         WaitForSingleObject( pOldTask->hEvent, INFINITE );
594         RestoreThunkLock( lockCount );
595     }
596
597     _LeaveWin16Lock();
598 }
599
600 /***********************************************************************
601  *           InitTask  (KERNEL.91)
602  *
603  * Called by the application startup code.
604  */
605 void WINAPI InitTask16( CONTEXT86 *context )
606 {
607     TDB *pTask;
608     INSTANCEDATA *pinstance;
609     SEGPTR ptr;
610
611     context->Eax = 0;
612     if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return;
613
614     /* Note: we need to trust that BX/CX contain the stack/heap sizes, 
615        as some apps, notably Visual Basic apps, *modify* the heap/stack
616        size of the instance data segment before calling InitTask() */
617
618     /* Initialize the INSTANCEDATA structure */
619     pinstance = MapSL( MAKESEGPTR(CURRENT_DS, 0) );
620     pinstance->stackmin    = OFFSETOF( pTask->teb->cur_stack ) + sizeof( STACK16FRAME );
621     pinstance->stackbottom = pinstance->stackmin; /* yup, that's right. Confused me too. */
622     pinstance->stacktop    = ( pinstance->stackmin > LOWORD(context->Ebx) ?
623                                pinstance->stackmin - LOWORD(context->Ebx) : 0 ) + 150;
624
625     /* Initialize the local heap */
626     if (LOWORD(context->Ecx))
627         LocalInit16( GlobalHandleToSel16(pTask->hInstance), 0, LOWORD(context->Ecx) );
628
629     /* Initialize implicitly loaded DLLs */
630     NE_InitializeDLLs( pTask->hModule );
631     NE_DllProcessAttach( pTask->hModule );
632
633     /* Registers on return are:
634      * ax     1 if OK, 0 on error
635      * cx     stack limit in bytes
636      * dx     cmdShow parameter
637      * si     instance handle of the previous instance
638      * di     instance handle of the new task
639      * es:bx  pointer to command line inside PSP
640      *
641      * 0 (=%bp) is pushed on the stack
642      */
643     ptr = stack16_push( sizeof(WORD) );
644     *(WORD *)MapSL(ptr) = 0;
645     context->Esp -= 2;
646
647     context->Eax = 1;
648
649     if (!pTask->pdb.cmdLine[0]) context->Ebx = 0x80;
650     else
651     {
652         LPBYTE p = &pTask->pdb.cmdLine[1];
653         while ((*p == ' ') || (*p == '\t')) p++;
654         context->Ebx = 0x80 + (p - pTask->pdb.cmdLine);
655     }
656     context->Ecx   = pinstance->stacktop;
657     context->Edx   = pTask->nCmdShow;
658     context->Esi   = (DWORD)pTask->hPrevInstance;
659     context->Edi   = (DWORD)pTask->hInstance;
660     context->SegEs = (WORD)pTask->hPDB;
661 }
662
663
664 /***********************************************************************
665  *           WaitEvent  (KERNEL.30)
666  */
667 BOOL16 WINAPI WaitEvent16( HTASK16 hTask )
668 {
669     TDB *pTask;
670
671     if (!hTask) hTask = GetCurrentTask();
672     pTask = (TDB *)GlobalLock16( hTask );
673
674     if ( !THREAD_IsWin16( NtCurrentTeb() ) )
675     {
676         FIXME("called for Win32 thread (%04x)!\n", NtCurrentTeb()->teb_sel);
677         return TRUE;
678     }
679
680     if (pTask->nEvents > 0)
681     {
682         pTask->nEvents--;
683         return FALSE;
684     }
685     TASK_Reschedule();
686
687     /* When we get back here, we have an event */
688
689     if (pTask->nEvents > 0) pTask->nEvents--;
690     return TRUE;
691 }
692
693
694 /***********************************************************************
695  *           PostEvent  (KERNEL.31)
696  */
697 void WINAPI PostEvent16( HTASK16 hTask )
698 {
699     TDB *pTask;
700
701     if (!hTask) hTask = GetCurrentTask();
702     if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
703
704     if ( !THREAD_IsWin16( pTask->teb ) )
705     {
706         FIXME("called for Win32 thread (%04x)!\n", pTask->teb->teb_sel );
707         return;
708     }
709
710     pTask->nEvents++;
711
712     /* If we are a 32-bit task, we might need to wake up the 16-bit scheduler */
713     if ( !THREAD_IsWin16( NtCurrentTeb() ) )
714         TASK_Reschedule();
715 }
716
717
718 /***********************************************************************
719  *           SetPriority  (KERNEL.32)
720  */
721 void WINAPI SetPriority16( HTASK16 hTask, INT16 delta )
722 {
723     TDB *pTask;
724     INT16 newpriority;
725
726     if (!hTask) hTask = GetCurrentTask();
727     if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
728     newpriority = pTask->priority + delta;
729     if (newpriority < -32) newpriority = -32;
730     else if (newpriority > 15) newpriority = 15;
731
732     pTask->priority = newpriority + 1;
733     TASK_UnlinkTask( hTask );
734     TASK_LinkTask( hTask );
735     pTask->priority--;
736 }
737
738
739 /***********************************************************************
740  *           LockCurrentTask  (KERNEL.33)
741  */
742 HTASK16 WINAPI LockCurrentTask16( BOOL16 bLock )
743 {
744     if (bLock) hLockedTask = GetCurrentTask();
745     else hLockedTask = 0;
746     return hLockedTask;
747 }
748
749
750 /***********************************************************************
751  *           IsTaskLocked  (KERNEL.122)
752  */
753 HTASK16 WINAPI IsTaskLocked16(void)
754 {
755     return hLockedTask;
756 }
757
758
759 /***********************************************************************
760  *           OldYield  (KERNEL.117)
761  */
762 void WINAPI OldYield16(void)
763 {
764     TDB *pCurTask = (TDB *)GlobalLock16( GetCurrentTask() );
765
766     if ( !THREAD_IsWin16( NtCurrentTeb() ) )
767     {
768         FIXME("called for Win32 thread (%04x)!\n", NtCurrentTeb()->teb_sel);
769         return;
770     }
771
772     if (pCurTask) pCurTask->nEvents++;  /* Make sure we get back here */
773     TASK_Reschedule();
774     if (pCurTask) pCurTask->nEvents--;
775 }
776
777 /***********************************************************************
778  *           WIN32_OldYield16  (KERNEL.447)
779  */
780 void WINAPI WIN32_OldYield16(void)
781 {
782    DWORD count;
783
784    ReleaseThunkLock(&count);
785    RestoreThunkLock(count);
786 }
787
788 /***********************************************************************
789  *           DirectedYield  (KERNEL.150)
790  */
791 void WINAPI DirectedYield16( HTASK16 hTask )
792 {
793     TDB *pCurTask = (TDB *)GlobalLock16( GetCurrentTask() );
794
795     if ( !THREAD_IsWin16( NtCurrentTeb() ) )
796     {
797         FIXME("called for Win32 thread (%04x)!\n", NtCurrentTeb()->teb_sel);
798         return;
799     }
800
801     TRACE("%04x: DirectedYield(%04x)\n", pCurTask->hSelf, hTask );
802
803     pCurTask->hYieldTo = hTask;
804     OldYield16();
805
806     TRACE("%04x: back from DirectedYield(%04x)\n", pCurTask->hSelf, hTask );
807 }
808
809 /***********************************************************************
810  *           Yield16  (KERNEL.29)
811  */
812 void WINAPI Yield16(void)
813 {
814     TDB *pCurTask = (TDB *)GlobalLock16( GetCurrentTask() );
815
816     if (pCurTask) pCurTask->hYieldTo = 0;
817     if (pCurTask && pCurTask->hQueue && Callout.UserYield16) Callout.UserYield16();
818     else OldYield16();
819 }
820
821 /***********************************************************************
822  *           KERNEL_490  (KERNEL.490)
823  */
824 HTASK16 WINAPI KERNEL_490( HTASK16 someTask )
825 {
826     if ( !someTask ) return 0;
827
828     FIXME("(%04x): stub\n", someTask );
829     return 0;
830 }
831
832 /***********************************************************************
833  *           MakeProcInstance16  (KERNEL.51)
834  */
835 FARPROC16 WINAPI MakeProcInstance16( FARPROC16 func, HANDLE16 hInstance )
836 {
837     BYTE *thunk,*lfunc;
838     SEGPTR thunkaddr;
839     WORD hInstanceSelector;
840
841     hInstanceSelector = GlobalHandleToSel16(hInstance);
842
843     TRACE("(%08lx, %04x);\n", (DWORD)func, hInstance);
844
845     if (!HIWORD(func)) {
846       /* Win95 actually protects via SEH, but this is better for debugging */
847       WARN("Ouch ! Called with invalid func 0x%08lx !\n", (DWORD)func);
848       return (FARPROC16)0;
849     }
850
851     if (hInstance)
852     {
853         if ( (!(hInstance & 4)) ||
854              ((hInstance != 0xffff) && IS_SELECTOR_FREE(hInstance|7)) )
855         {
856             WARN("Invalid hInstance (%04x) passed to MakeProcInstance !\n",
857                 hInstance);
858             return 0;
859         }
860     }
861
862     if ( (GlobalHandleToSel16(CURRENT_DS) != hInstanceSelector)
863       && (hInstance != 0)
864       && (hInstance != 0xffff) )
865     {
866         /* calling MPI with a foreign DSEG is invalid ! */
867         WARN("Problem with hInstance? Got %04x, using %04x instead\n",
868                    hInstance,CURRENT_DS);
869     }
870
871     /* Always use the DSEG that MPI was entered with.
872      * We used to set hInstance to GetTaskDS16(), but this should be wrong
873      * as CURRENT_DS provides the DSEG value we need.
874      * ("calling" DS, *not* "task" DS !) */
875     hInstanceSelector = CURRENT_DS;
876     hInstance = GlobalHandle16(hInstanceSelector);
877
878     /* no thunking for DLLs */
879     if (NE_GetPtr(FarGetOwner16(hInstance))->flags & NE_FFLAGS_LIBMODULE)
880         return func;
881
882     thunkaddr = TASK_AllocThunk( GetCurrentTask() );
883     if (!thunkaddr) return (FARPROC16)0;
884     thunk = MapSL( thunkaddr );
885     lfunc = MapSL( (SEGPTR)func );
886
887     TRACE("(%08lx,%04x): got thunk %08lx\n",
888           (DWORD)func, hInstance, (DWORD)thunkaddr );
889     if (((lfunc[0]==0x8c) && (lfunc[1]==0xd8)) || /* movw %ds, %ax */
890         ((lfunc[0]==0x1e) && (lfunc[1]==0x58))    /* pushw %ds, popw %ax */
891     ) {
892         WARN("This was the (in)famous \"thunk useless\" warning. We thought we have to overwrite with nop;nop;, but this isn't true.\n");
893     }
894
895     *thunk++ = 0xb8;    /* movw instance, %ax */
896     *thunk++ = (BYTE)(hInstanceSelector & 0xff);
897     *thunk++ = (BYTE)(hInstanceSelector >> 8);
898     *thunk++ = 0xea;    /* ljmp func */
899     *(DWORD *)thunk = (DWORD)func;
900     return (FARPROC16)thunkaddr;
901     /* CX reg indicates if thunkaddr != NULL, implement if needed */
902 }
903
904
905 /***********************************************************************
906  *           FreeProcInstance16  (KERNEL.52)
907  */
908 void WINAPI FreeProcInstance16( FARPROC16 func )
909 {
910     TRACE("(%08lx)\n", (DWORD)func );
911     TASK_FreeThunk( GetCurrentTask(), (SEGPTR)func );
912 }
913
914 /**********************************************************************
915  *          TASK_GetCodeSegment
916  * 
917  * Helper function for GetCodeHandle/GetCodeInfo: Retrieve the module 
918  * and logical segment number of a given code segment.
919  *
920  * 'proc' either *is* already a pair of module handle and segment number,
921  * in which case there's nothing to do.  Otherwise, it is a pointer to
922  * a function, and we need to retrieve the code segment.  If the pointer
923  * happens to point to a thunk, we'll retrieve info about the code segment
924  * where the function pointed to by the thunk resides, not the thunk itself.
925  *
926  * FIXME: if 'proc' is a SNOOP16 return stub, we should retrieve info about
927  *        the function the snoop code will return to ...
928  *
929  */
930 static BOOL TASK_GetCodeSegment( FARPROC16 proc, NE_MODULE **ppModule, 
931                                  SEGTABLEENTRY **ppSeg, int *pSegNr )
932 {
933     NE_MODULE *pModule = NULL;
934     SEGTABLEENTRY *pSeg = NULL;
935     int segNr=0;
936
937     /* Try pair of module handle / segment number */
938     pModule = (NE_MODULE *) GlobalLock16( HIWORD( proc ) );
939     if ( pModule && pModule->magic == IMAGE_OS2_SIGNATURE )
940     {
941         segNr = LOWORD( proc );
942         if ( segNr && segNr <= pModule->seg_count )
943             pSeg = NE_SEG_TABLE( pModule ) + segNr-1;
944     }
945
946     /* Try thunk or function */
947     else 
948     {
949         BYTE *thunk = MapSL( (SEGPTR)proc );
950         WORD selector;
951
952         if ((thunk[0] == 0xb8) && (thunk[3] == 0xea))
953             selector = thunk[6] + (thunk[7] << 8);
954         else
955             selector = HIWORD( proc );
956
957         pModule = NE_GetPtr( GlobalHandle16( selector ) );
958         pSeg = pModule? NE_SEG_TABLE( pModule ) : NULL;
959
960         if ( pModule )
961             for ( segNr = 1; segNr <= pModule->seg_count; segNr++, pSeg++ )
962                 if ( GlobalHandleToSel16(pSeg->hSeg) == selector )
963                     break;
964
965         if ( pModule && segNr > pModule->seg_count )
966             pSeg = NULL;
967     }
968
969     /* Abort if segment not found */
970
971     if ( !pModule || !pSeg )
972         return FALSE;
973
974     /* Return segment data */
975
976     if ( ppModule ) *ppModule = pModule;
977     if ( ppSeg    ) *ppSeg    = pSeg;
978     if ( pSegNr   ) *pSegNr   = segNr;
979
980     return TRUE;
981 }
982
983 /**********************************************************************
984  *          GetCodeHandle    (KERNEL.93)
985  */
986 HANDLE16 WINAPI GetCodeHandle16( FARPROC16 proc )
987 {
988     SEGTABLEENTRY *pSeg;
989
990     if ( !TASK_GetCodeSegment( proc, NULL, &pSeg, NULL ) )
991         return (HANDLE16)0;
992
993     return pSeg->hSeg;
994 }
995
996 /**********************************************************************
997  *          GetCodeInfo    (KERNEL.104)
998  */
999 BOOL16 WINAPI GetCodeInfo16( FARPROC16 proc, SEGINFO *segInfo )
1000 {
1001     NE_MODULE *pModule;
1002     SEGTABLEENTRY *pSeg;
1003     int segNr;
1004
1005     if ( !TASK_GetCodeSegment( proc, &pModule, &pSeg, &segNr ) )
1006         return FALSE;
1007
1008     /* Fill in segment information */
1009
1010     segInfo->offSegment = pSeg->filepos;
1011     segInfo->cbSegment  = pSeg->size;
1012     segInfo->flags      = pSeg->flags;
1013     segInfo->cbAlloc    = pSeg->minsize;
1014     segInfo->h          = pSeg->hSeg;
1015     segInfo->alignShift = pModule->alignment;
1016
1017     if ( segNr == pModule->dgroup )
1018         segInfo->cbAlloc += pModule->heap_size + pModule->stack_size;
1019
1020     /* Return module handle in %es */
1021
1022     CURRENT_STACK16->es = GlobalHandleToSel16( pModule->self );
1023
1024     return TRUE;
1025 }
1026
1027
1028 /**********************************************************************
1029  *          DefineHandleTable16    (KERNEL.94)
1030  */
1031 BOOL16 WINAPI DefineHandleTable16( WORD wOffset )
1032 {
1033     FIXME("(%04x): stub ?\n", wOffset);
1034     return TRUE;
1035 }
1036
1037
1038 /***********************************************************************
1039  *           SetTaskQueue  (KERNEL.34)
1040  */
1041 HQUEUE16 WINAPI SetTaskQueue16( HTASK16 hTask, HQUEUE16 hQueue )
1042 {
1043     HQUEUE16 hPrev;
1044     TDB *pTask;
1045
1046     if (!hTask) hTask = GetCurrentTask();
1047     if (!(pTask = (TDB *)GlobalLock16( hTask ))) return 0;
1048
1049     hPrev = pTask->hQueue;
1050     pTask->hQueue = hQueue;
1051
1052     return hPrev;
1053 }
1054
1055
1056 /***********************************************************************
1057  *           GetTaskQueue  (KERNEL.35)
1058  */
1059 HQUEUE16 WINAPI GetTaskQueue16( HTASK16 hTask )
1060 {
1061     TDB *pTask;
1062
1063     if (!hTask) hTask = GetCurrentTask();
1064     if (!(pTask = (TDB *)GlobalLock16( hTask ))) return 0;
1065     return pTask->hQueue;
1066 }
1067
1068 /***********************************************************************
1069  *           SetThreadQueue  (KERNEL.463)
1070  */
1071 HQUEUE16 WINAPI SetThreadQueue16( DWORD thread, HQUEUE16 hQueue )
1072 {
1073     TEB *teb = thread? THREAD_IdToTEB( thread ) : NtCurrentTeb();
1074     HQUEUE16 oldQueue = teb? teb->queue : 0;
1075
1076     if ( teb )
1077     {
1078         teb->queue = hQueue;
1079
1080         if ( GetTaskQueue16( teb->htask16 ) == oldQueue )
1081             SetTaskQueue16( teb->htask16, hQueue );
1082     }
1083
1084     return oldQueue;
1085 }
1086
1087 /***********************************************************************
1088  *           GetThreadQueue  (KERNEL.464)
1089  */
1090 HQUEUE16 WINAPI GetThreadQueue16( DWORD thread )
1091 {
1092     TEB *teb = NULL;
1093     if ( !thread )
1094         teb = NtCurrentTeb();
1095     else if ( HIWORD(thread) )
1096         teb = THREAD_IdToTEB( thread );
1097     else if ( IsTask16( (HTASK16)thread ) )
1098         teb = ((TDB *)GlobalLock16( (HANDLE16)thread ))->teb;
1099
1100     return (HQUEUE16)(teb? teb->queue : 0);
1101 }
1102
1103 /***********************************************************************
1104  *           SetFastQueue  (KERNEL.624)
1105  */
1106 VOID WINAPI SetFastQueue16( DWORD thread, HANDLE hQueue )
1107 {
1108     TEB *teb = NULL;
1109     if ( !thread )
1110         teb = NtCurrentTeb();
1111     else if ( HIWORD(thread) )
1112         teb = THREAD_IdToTEB( thread );
1113     else if ( IsTask16( (HTASK16)thread ) )
1114         teb = ((TDB *)GlobalLock16( (HANDLE16)thread ))->teb;
1115
1116     if ( teb ) teb->queue = (HQUEUE16) hQueue;
1117 }
1118
1119 /***********************************************************************
1120  *           GetFastQueue  (KERNEL.625)
1121  */
1122 HANDLE WINAPI GetFastQueue16( void )
1123 {
1124     TEB *teb = NtCurrentTeb();
1125     if (!teb) return 0;
1126
1127     if (!teb->queue && Callout.InitThreadInput16)
1128         Callout.InitThreadInput16( 0, THREAD_IsWin16(teb)? 4 : 5 );
1129
1130     if (!teb->queue)
1131         FIXME("(): should initialize thread-local queue, expect failure!\n" );
1132
1133     return (HANDLE)teb->queue;
1134 }
1135
1136 /***********************************************************************
1137  *           SwitchStackTo   (KERNEL.108)
1138  */
1139 void WINAPI SwitchStackTo16( WORD seg, WORD ptr, WORD top )
1140 {
1141     TDB *pTask;
1142     STACK16FRAME *oldFrame, *newFrame;
1143     INSTANCEDATA *pData;
1144     UINT16 copySize;
1145
1146     if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return;
1147     if (!(pData = (INSTANCEDATA *)GlobalLock16( seg ))) return;
1148     TRACE("old=%04x:%04x new=%04x:%04x\n",
1149           SELECTOROF( pTask->teb->cur_stack ),
1150           OFFSETOF( pTask->teb->cur_stack ), seg, ptr );
1151
1152     /* Save the old stack */
1153
1154     oldFrame = THREAD_STACK16( pTask->teb );
1155     /* pop frame + args and push bp */
1156     pData->old_ss_sp   = pTask->teb->cur_stack + sizeof(STACK16FRAME)
1157                            + 2 * sizeof(WORD);
1158     *(WORD *)MapSL(pData->old_ss_sp) = oldFrame->bp;
1159     pData->stacktop    = top;
1160     pData->stackmin    = ptr;
1161     pData->stackbottom = ptr;
1162
1163     /* Switch to the new stack */
1164
1165     /* Note: we need to take the 3 arguments into account; otherwise,
1166      * the stack will underflow upon return from this function.
1167      */
1168     copySize = oldFrame->bp - OFFSETOF(pData->old_ss_sp);
1169     copySize += 3 * sizeof(WORD) + sizeof(STACK16FRAME);
1170     pTask->teb->cur_stack = MAKESEGPTR( seg, ptr - copySize );
1171     newFrame = THREAD_STACK16( pTask->teb );
1172
1173     /* Copy the stack frame and the local variables to the new stack */
1174
1175     memmove( newFrame, oldFrame, copySize );
1176     newFrame->bp = ptr;
1177     *(WORD *)MapSL( MAKESEGPTR( seg, ptr ) ) = 0;  /* clear previous bp */
1178 }
1179
1180
1181 /***********************************************************************
1182  *           SwitchStackBack   (KERNEL.109)
1183  */
1184 void WINAPI SwitchStackBack16( CONTEXT86 *context )
1185 {
1186     STACK16FRAME *oldFrame, *newFrame;
1187     INSTANCEDATA *pData;
1188
1189     if (!(pData = (INSTANCEDATA *)GlobalLock16(SELECTOROF(NtCurrentTeb()->cur_stack))))
1190         return;
1191     if (!pData->old_ss_sp)
1192     {
1193         WARN("No previous SwitchStackTo\n" );
1194         return;
1195     }
1196     TRACE("restoring stack %04x:%04x\n",
1197           SELECTOROF(pData->old_ss_sp), OFFSETOF(pData->old_ss_sp) );
1198
1199     oldFrame = CURRENT_STACK16;
1200
1201     /* Pop bp from the previous stack */
1202
1203     BP_reg(context) = *(WORD *)MapSL(pData->old_ss_sp);
1204     pData->old_ss_sp += sizeof(WORD);
1205
1206     /* Switch back to the old stack */
1207
1208     NtCurrentTeb()->cur_stack = pData->old_ss_sp - sizeof(STACK16FRAME);
1209     context->SegSs = SELECTOROF(pData->old_ss_sp);
1210     context->Esp   = OFFSETOF(pData->old_ss_sp) - sizeof(DWORD); /*ret addr*/
1211     pData->old_ss_sp = 0;
1212
1213     /* Build a stack frame for the return */
1214
1215     newFrame = CURRENT_STACK16;
1216     newFrame->frame32     = oldFrame->frame32;
1217     newFrame->module_cs   = oldFrame->module_cs;
1218     newFrame->callfrom_ip = oldFrame->callfrom_ip;
1219     newFrame->entry_ip    = oldFrame->entry_ip;
1220 }
1221
1222
1223 /***********************************************************************
1224  *           GetTaskQueueDS16  (KERNEL.118)
1225  */
1226 void WINAPI GetTaskQueueDS16(void)
1227 {
1228     CURRENT_STACK16->ds = GlobalHandleToSel16( GetTaskQueue16(0) );
1229 }
1230
1231
1232 /***********************************************************************
1233  *           GetTaskQueueES16  (KERNEL.119)
1234  */
1235 void WINAPI GetTaskQueueES16(void)
1236 {
1237     CURRENT_STACK16->es = GlobalHandleToSel16( GetTaskQueue16(0) );
1238 }
1239
1240
1241 /***********************************************************************
1242  *           GetCurrentTask   (KERNEL.36)
1243  */
1244 HTASK16 WINAPI GetCurrentTask(void)
1245 {
1246     return NtCurrentTeb()->htask16;
1247 }
1248
1249 DWORD WINAPI WIN16_GetCurrentTask(void)
1250 {
1251     /* This is the version used by relay code; the first task is */
1252     /* returned in the high word of the result */
1253     return MAKELONG( GetCurrentTask(), hFirstTask );
1254 }
1255
1256
1257 /***********************************************************************
1258  *           GetCurrentPDB   (KERNEL.37)
1259  *
1260  * UNDOC: returns PSP of KERNEL in high word
1261  */
1262 DWORD WINAPI GetCurrentPDB16(void)
1263 {
1264     TDB *pTask;
1265
1266     if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1267     return MAKELONG(pTask->hPDB, 0); /* FIXME */
1268 }
1269
1270
1271 /***********************************************************************
1272  *           GetCurPID16   (KERNEL.157)
1273  */
1274 DWORD WINAPI GetCurPID16( DWORD unused )
1275 {
1276     return 0;
1277 }
1278
1279
1280 /***********************************************************************
1281  *           GetInstanceData   (KERNEL.54)
1282  */
1283 INT16 WINAPI GetInstanceData16( HINSTANCE16 instance, WORD buffer, INT16 len )
1284 {
1285     char *ptr = (char *)GlobalLock16( instance );
1286     if (!ptr || !len) return 0;
1287     if ((int)buffer + len >= 0x10000) len = 0x10000 - buffer;
1288     memcpy( (char *)GlobalLock16(CURRENT_DS) + buffer, ptr + buffer, len );
1289     return len;
1290 }
1291
1292
1293 /***********************************************************************
1294  *           GetExeVersion   (KERNEL.105)
1295  */
1296 WORD WINAPI GetExeVersion16(void)
1297 {
1298     TDB *pTask;
1299
1300     if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1301     return pTask->version;
1302 }
1303
1304
1305 /***********************************************************************
1306  *           SetErrorMode16   (KERNEL.107)
1307  */
1308 UINT16 WINAPI SetErrorMode16( UINT16 mode )
1309 {
1310     TDB *pTask;
1311     if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1312     pTask->error_mode = mode;
1313     return SetErrorMode( mode );
1314 }
1315
1316
1317 /***********************************************************************
1318  *           GetNumTasks   (KERNEL.152)
1319  */
1320 UINT16 WINAPI GetNumTasks16(void)
1321 {
1322     return nTaskCount;
1323 }
1324
1325
1326 /***********************************************************************
1327  *           GetTaskDS   (KERNEL.155)
1328  *
1329  * Note: this function apparently returns a DWORD with LOWORD == HIWORD.
1330  * I don't think we need to bother with this.
1331  */
1332 HINSTANCE16 WINAPI GetTaskDS16(void)
1333 {
1334     TDB *pTask;
1335
1336     if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1337     return GlobalHandleToSel16(pTask->hInstance);
1338 }
1339
1340 /***********************************************************************
1341  *           GetDummyModuleHandleDS   (KERNEL.602)
1342  */
1343 WORD WINAPI GetDummyModuleHandleDS16(void)
1344 {
1345     TDB *pTask;
1346     WORD selector;
1347
1348     if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1349     if (!(pTask->flags & TDBF_WIN32)) return 0;
1350     selector = GlobalHandleToSel16( pTask->hModule );
1351     CURRENT_DS = selector;
1352     return selector;
1353 }
1354
1355 /***********************************************************************
1356  *           IsTask   (KERNEL.320)
1357  */
1358 BOOL16 WINAPI IsTask16( HTASK16 hTask )
1359 {
1360     TDB *pTask;
1361
1362     if (!(pTask = (TDB *)GlobalLock16( hTask ))) return FALSE;
1363     if (GlobalSize16( hTask ) < sizeof(TDB)) return FALSE;
1364     return (pTask->magic == TDB_MAGIC);
1365 }
1366
1367
1368 /***********************************************************************
1369  *           IsWinOldApTask16   (KERNEL.158)
1370  */
1371 BOOL16 WINAPI IsWinOldApTask16( HTASK16 hTask )
1372 {
1373     /* should return bit 0 of byte 0x48 in PSP */
1374     return FALSE;
1375 }
1376
1377 /***********************************************************************
1378  *           SetTaskSignalProc   (KERNEL.38)
1379  */
1380 FARPROC16 WINAPI SetTaskSignalProc( HTASK16 hTask, FARPROC16 proc )
1381 {
1382     TDB *pTask;
1383     FARPROC16 oldProc;
1384
1385     if (!hTask) hTask = GetCurrentTask();
1386     if (!(pTask = (TDB *)GlobalLock16( hTask ))) return NULL;
1387     oldProc = pTask->userhandler;
1388     pTask->userhandler = proc;
1389     return oldProc;
1390 }
1391
1392 /***********************************************************************
1393  *           TASK_CallTaskSignalProc
1394  */
1395 /* ### start build ### */
1396 extern WORD CALLBACK TASK_CallTo16_word_wwwww(FARPROC16,WORD,WORD,WORD,WORD,WORD);
1397 /* ### stop build ### */
1398 void TASK_CallTaskSignalProc( UINT16 uCode, HANDLE16 hTaskOrModule )
1399 {
1400     TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
1401     if ( !pTask || !pTask->userhandler ) return;
1402
1403     TASK_CallTo16_word_wwwww( pTask->userhandler, 
1404                               hTaskOrModule, uCode, 0, 
1405                               pTask->hInstance, pTask->hQueue );
1406 }
1407
1408 /***********************************************************************
1409  *           SetSigHandler   (KERNEL.140)
1410  */
1411 WORD WINAPI SetSigHandler16( FARPROC16 newhandler, FARPROC16* oldhandler,
1412                            UINT16 *oldmode, UINT16 newmode, UINT16 flag )
1413 {
1414     FIXME("(%p,%p,%p,%d,%d), unimplemented.\n",
1415           newhandler,oldhandler,oldmode,newmode,flag );
1416
1417     if (flag != 1) return 0;
1418     if (!newmode) newhandler = NULL;  /* Default handler */
1419     if (newmode != 4)
1420     {
1421         TDB *pTask;
1422
1423         if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1424         if (oldmode) *oldmode = pTask->signal_flags;
1425         pTask->signal_flags = newmode;
1426         if (oldhandler) *oldhandler = pTask->sighandler;
1427         pTask->sighandler = newhandler;
1428     }
1429     return 0;
1430 }
1431
1432
1433 /***********************************************************************
1434  *           GlobalNotify   (KERNEL.154)
1435  *
1436  * Note that GlobalNotify does _not_ return the old NotifyProc
1437  * -- contrary to LocalNotify !!
1438  */
1439 VOID WINAPI GlobalNotify16( FARPROC16 proc )
1440 {
1441     TDB *pTask;
1442
1443     if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return;
1444     pTask->discardhandler = proc;
1445 }
1446
1447
1448 /***********************************************************************
1449  *           GetExePtr   (KERNEL.133)
1450  */
1451 static inline HMODULE16 GetExePtrHelper( HANDLE16 handle, HTASK16 *hTask )
1452 {
1453     char *ptr;
1454     HANDLE16 owner;
1455
1456       /* Check for module handle */
1457
1458     if (!(ptr = GlobalLock16( handle ))) return 0;
1459     if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return handle;
1460
1461       /* Search for this handle inside all tasks */
1462
1463     *hTask = hFirstTask;
1464     while (*hTask)
1465     {
1466         TDB *pTask = (TDB *)GlobalLock16( *hTask );
1467         if ((*hTask == handle) ||
1468             (pTask->hInstance == handle) ||
1469             (pTask->hQueue == handle) ||
1470             (pTask->hPDB == handle)) return pTask->hModule;
1471         *hTask = pTask->hNext;
1472     }
1473
1474       /* Check the owner for module handle */
1475
1476     owner = FarGetOwner16( handle );
1477     if (!(ptr = GlobalLock16( owner ))) return 0;
1478     if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return owner;
1479
1480       /* Search for the owner inside all tasks */
1481
1482     *hTask = hFirstTask;
1483     while (*hTask)
1484     {
1485         TDB *pTask = (TDB *)GlobalLock16( *hTask );
1486         if ((*hTask == owner) ||
1487             (pTask->hInstance == owner) ||
1488             (pTask->hQueue == owner) ||
1489             (pTask->hPDB == owner)) return pTask->hModule;
1490         *hTask = pTask->hNext;
1491     }
1492
1493     return 0;
1494 }
1495
1496 /**********************************************************************/
1497
1498 HMODULE16 WINAPI WIN16_GetExePtr( HANDLE16 handle )
1499 {
1500     HTASK16 hTask = 0;
1501     HMODULE16 hModule = GetExePtrHelper( handle, &hTask );
1502     STACK16FRAME *frame = CURRENT_STACK16;
1503     frame->ecx = hModule;
1504     if (hTask) frame->es = hTask;
1505     return hModule;
1506 }
1507
1508 /**********************************************************************/
1509
1510 HMODULE16 WINAPI GetExePtr( HANDLE16 handle )
1511 {
1512     HTASK16 hTask = 0;
1513     return GetExePtrHelper( handle, &hTask );
1514 }
1515
1516
1517 /***********************************************************************
1518  *           TaskFirst   (TOOLHELP.63)
1519  */
1520 BOOL16 WINAPI TaskFirst16( TASKENTRY *lpte )
1521 {
1522     lpte->hNext = hFirstTask;
1523     return TaskNext16( lpte );
1524 }
1525
1526
1527 /***********************************************************************
1528  *           TaskNext   (TOOLHELP.64)
1529  */
1530 BOOL16 WINAPI TaskNext16( TASKENTRY *lpte )
1531 {
1532     TDB *pTask;
1533     INSTANCEDATA *pInstData;
1534
1535     TRACE_(toolhelp)("(%p): task=%04x\n", lpte, lpte->hNext );
1536     if (!lpte->hNext) return FALSE;
1537
1538     /* make sure that task and hInstance are valid (skip initial Wine task !) */
1539     while (1) {
1540         pTask = (TDB *)GlobalLock16( lpte->hNext );
1541         if (!pTask || pTask->magic != TDB_MAGIC) return FALSE;
1542         if (pTask->hInstance)
1543             break;
1544         lpte->hNext = pTask->hNext;
1545     }
1546     pInstData = MapSL( MAKESEGPTR( GlobalHandleToSel16(pTask->hInstance), 0 ) );
1547     lpte->hTask         = lpte->hNext;
1548     lpte->hTaskParent   = pTask->hParent;
1549     lpte->hInst         = pTask->hInstance;
1550     lpte->hModule       = pTask->hModule;
1551     lpte->wSS           = SELECTOROF( pTask->teb->cur_stack );
1552     lpte->wSP           = OFFSETOF( pTask->teb->cur_stack );
1553     lpte->wStackTop     = pInstData->stacktop;
1554     lpte->wStackMinimum = pInstData->stackmin;
1555     lpte->wStackBottom  = pInstData->stackbottom;
1556     lpte->wcEvents      = pTask->nEvents;
1557     lpte->hQueue        = pTask->hQueue;
1558     lstrcpynA( lpte->szModule, pTask->module_name, sizeof(lpte->szModule) );
1559     lpte->wPSPOffset    = 0x100;  /*??*/
1560     lpte->hNext         = pTask->hNext;
1561     return TRUE;
1562 }
1563
1564
1565 /***********************************************************************
1566  *           TaskFindHandle   (TOOLHELP.65)
1567  */
1568 BOOL16 WINAPI TaskFindHandle16( TASKENTRY *lpte, HTASK16 hTask )
1569 {
1570     lpte->hNext = hTask;
1571     return TaskNext16( lpte );
1572 }
1573
1574
1575 /**************************************************************************
1576  *           FatalAppExit16   (KERNEL.137)
1577  */
1578 void WINAPI FatalAppExit16( UINT16 action, LPCSTR str )
1579 {
1580     TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
1581
1582     if (!pTask || !(pTask->error_mode & SEM_NOGPFAULTERRORBOX))
1583     {
1584         if (Callout.MessageBoxA)
1585             Callout.MessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
1586         else
1587             ERR( "%s\n", debugstr_a(str) );
1588     }
1589     ExitThread(0xff);
1590 }
1591
1592
1593 /***********************************************************************
1594  *           TerminateApp16   (TOOLHELP.77)
1595  *
1596  * See "Undocumented Windows".
1597  */
1598 void WINAPI TerminateApp16(HTASK16 hTask, WORD wFlags)
1599 {
1600     if (hTask && hTask != GetCurrentTask())
1601     {
1602         FIXME("cannot terminate task %x\n", hTask);
1603         return;
1604     }
1605
1606     if (wFlags & NO_UAE_BOX)
1607     {
1608         UINT16 old_mode;
1609         old_mode = SetErrorMode16(0);
1610         SetErrorMode16(old_mode|SEM_NOGPFAULTERRORBOX);
1611     }
1612     FatalAppExit16( 0, NULL );
1613
1614     /* hmm, we're still alive ?? */
1615
1616     /* check undocumented flag */
1617     if (!(wFlags & 0x8000))
1618         TASK_CallTaskSignalProc( USIG16_TERMINATION, hTask );
1619
1620     /* UndocWin says to call int 0x21/0x4c exit=0xff here,
1621        but let's just call ExitThread */
1622     ExitThread(0xff);
1623 }
1624
1625
1626 /***********************************************************************
1627  *           GetAppCompatFlags16   (KERNEL.354)
1628  */
1629 DWORD WINAPI GetAppCompatFlags16( HTASK16 hTask )
1630 {
1631     return GetAppCompatFlags( hTask );
1632 }
1633
1634
1635 /***********************************************************************
1636  *           GetAppCompatFlags   (USER32.206)
1637  */
1638 DWORD WINAPI GetAppCompatFlags( HTASK hTask )
1639 {
1640     TDB *pTask;
1641
1642     if (!hTask) hTask = GetCurrentTask();
1643     if (!(pTask=(TDB *)GlobalLock16( (HTASK16)hTask ))) return 0;
1644     if (GlobalSize16(hTask) < sizeof(TDB)) return 0;
1645     return pTask->compat_flags;
1646 }