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