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