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