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