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