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