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