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