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