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