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