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