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