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