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