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