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