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