~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Wine Cross Reference
wine/dlls/kernel32/task.c

Version: ~ [ wine-1.0-rc1 ] ~ [ wine-0.9.61 ] ~ [ wine-0.9.60 ] ~ [ wine-0.9.59 ] ~ [ wine-0.9.58 ] ~ [ wine-0.9.57 ] ~ [ wine-0.9.56 ] ~ [ wine-0.9.55 ] ~ [ wine-0.9.54 ] ~ [ wine-0.9.53 ] ~ [ wine-0.9.52 ] ~ [ wine-0.9.51 ] ~ [ wine-0.9.50 ] ~ [ wine-0.9.49 ] ~ [ wine-0.9.48 ] ~ [ wine-0.9.47 ] ~ [ wine-0.9.46 ] ~ [ wine-0.9.45 ] ~ [ wine-0.9.44 ] ~ [ wine-0.9.43 ] ~ [ wine-0.9.42 ] ~ [ wine-0.9.41 ] ~ [ wine-0.9.40 ] ~ [ wine-0.9.39 ] ~ [ wine-0.9.38 ] ~ [ wine-0.9.37 ] ~ [ wine-0.9.36 ] ~ [ wine-0.9.35 ] ~ [ wine-0.9.34 ] ~ [ wine-0.9.33 ] ~ [ wine-0.9.32 ] ~ [ wine-0.9.31 ] ~ [ wine-0.9.30 ] ~ [ wine-0.9.29 ] ~ [ wine-0.9.28 ] ~ [ wine-0.9.27 ] ~ [ wine-0.9.26 ] ~ [ wine-0.9.25 ] ~ [ wine-0.9.24 ] ~ [ wine-0.9.23 ] ~ [ wine-0.9.22 ] ~ [ wine-0.9.21 ] ~ [ wine-0.9.20 ] ~ [ wine-0.9.19 ] ~ [ wine-0.9.18 ] ~ [ wine-0.9.17 ] ~ [ wine-0.9.16 ] ~ [ wine-0.9.15 ] ~ [ wine-0.9.14 ] ~ [ wine-0.9.13 ] ~ [ wine-0.9.12 ] ~ [ wine-0.9.11 ] ~ [ wine-0.9.10 ] ~ [ wine-0.9.9 ] ~ [ wine-0.9.8 ] ~ [ wine-0.9.7 ] ~ [ wine-0.9.6 ] ~ [ wine-0.9.5 ] ~ [ wine-0.9.4 ] ~ [ wine-0.9.3 ] ~ [ wine-0.9.2 ] ~ [ wine-0.9.1 ] ~ [ wine-0.9 ] ~ [ wine20050930 ] ~ [ wine20050830 ] ~ [ wine20050725 ] ~ [ wine20050628 ] ~ [ wine20050524 ] ~ [ wine20050419 ] ~ [ wine20050310 ] ~ [ wine20050211 ] ~ [ wine20050111 ] ~ [ wine20041201 ] ~ [ wine20041019 ] ~ [ wine20040914 ] ~ [ wine20040813 ] ~ [ wine20040716 ] ~ [ wine20040615 ] ~ [ wine20040505 ] ~ [ wine20040408 ] ~ [ wine20040309 ] ~ [ wine20040213 ] ~ [ wine20040121 ] ~ [ wine20031212 ] ~ [ wine20031118 ] ~ [ wine20031016 ] ~ [ wine20030911 ] ~ [ wine20030813 ] ~ [ wine20030709 ] ~ [ wine20030618 ] ~ [ wine20030508 ] ~ [ wine20030408 ] ~ [ wine20030318 ] ~ [ wine20030219 ] ~ [ wine20030115 ] ~ [ wine20021219 ] ~ [ wine20021125 ] ~ [ wine20021031 ] ~ [ wine20021007 ] ~ [ wine20020904 ] ~ [ wine20020804 ] ~ [ wine20020710 ] ~ [ wine20020605 ] ~ [ wine20020509 ] ~ [ wine20020411 ] ~ [ wine20020310 ] ~ [ wine20020228 ] ~ [ wine20011226 ] ~ [ wine20011108 ] ~ [ wine20011004 ] ~ [ wine20010824 ] ~ [ wine20010731 ] ~ [ wine20010629 ] ~ [ wine20010510 ] ~ [ wine20010418 ] ~ [ wine20010326 ] ~ [ wine20010305 ] ~ [ wine20010216 ] ~ [ wine20010112 ] ~ [ wine20001222 ] ~ [ wine20001202 ] ~ [ wine20001026 ] ~ [ wine20001002 ] ~ [ wine20000909 ] ~ [ wine20000821 ] ~ [ wine20000801 ] ~ [ wine20000716 ] ~ [ wine20000326 ] ~ [ wine20000227 ] ~ [ wine20000130 ] ~ [ wine20000109 ] ~

  1 /*
  2  * Task functions
  3  *
  4  * Copyright 1995 Alexandre Julliard
  5  *
  6  * This library is free software; you can redistribute it and/or
  7  * modify it under the terms of the GNU Lesser General Public
  8  * License as published by the Free Software Foundation; either
  9  * version 2.1 of the License, or (at your option) any later version.
 10  *
 11  * This library is distributed in the hope that it will be useful,
 12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
 13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 14  * Lesser General Public License for more details.
 15  *
 16  * You should have received a copy of the GNU Lesser General Public
 17  * License along with this library; if not, write to the Free Software
 18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 19  */
 20 
 21 #include "config.h"
 22 #include "wine/port.h"
 23 
 24 #include <stdarg.h>
 25 #include <stdlib.h>
 26 #include <string.h>
 27 #include <assert.h>
 28 #ifdef HAVE_UNISTD_H
 29 # include <unistd.h>
 30 #endif
 31 
 32 #include "windef.h"
 33 #include "winbase.h"
 34 #include "wingdi.h"
 35 #include "winnt.h"
 36 #include "wownt32.h"
 37 #include "winuser.h"
 38 
 39 #include "wine/winbase16.h"
 40 #include "winternl.h"
 41 #include "toolhelp.h"
 42 #include "kernel_private.h"
 43 #include "kernel16_private.h"
 44 
 45 #include "wine/debug.h"
 46 
 47 WINE_DEFAULT_DEBUG_CHANNEL(task);
 48 WINE_DECLARE_DEBUG_CHANNEL(toolhelp);
 49 
 50 #include "pshpack1.h"
 51 
 52 /* Segment containing MakeProcInstance() thunks */
 53 typedef struct
 54 {
 55     WORD  next;       /* Selector of next segment */
 56     WORD  magic;      /* Thunks signature */
 57     WORD  unused;
 58     WORD  free;       /* Head of the free list */
 59     WORD  thunks[4];  /* Each thunk is 4 words long */
 60 } THUNKS;
 61 
 62 #include "poppack.h"
 63 
 64 #define THUNK_MAGIC  ('P' | ('T' << 8))
 65 
 66   /* Min. number of thunks allocated when creating a new segment */
 67 #define MIN_THUNKS  32
 68 
 69 #define TDB_MAGIC    ('T' | ('D' << 8))
 70 
 71 static THHOOK DefaultThhook;
 72 THHOOK *pThhook = &DefaultThhook;
 73 
 74 #define hFirstTask   (pThhook->HeadTDB)
 75 #define hLockedTask  (pThhook->LockTDB)
 76 
 77 static UINT16 nTaskCount = 0;
 78 
 79 static HTASK16 initial_task, main_task;
 80 
 81 /***********************************************************************
 82  *           TASK_InstallTHHook
 83  */
 84 void TASK_InstallTHHook( THHOOK *pNewThhook )
 85 {
 86      THHOOK *pOldThhook = pThhook;
 87 
 88      pThhook = pNewThhook? pNewThhook : &DefaultThhook;
 89 
 90      *pThhook = *pOldThhook;
 91 }
 92 
 93 /***********************************************************************
 94  *           TASK_GetPtr
 95  */
 96 static TDB *TASK_GetPtr( HTASK16 hTask )
 97 {
 98     return GlobalLock16( hTask );
 99 }
100 
101 
102 /***********************************************************************
103  *           TASK_GetCurrent
104  */
105 TDB *TASK_GetCurrent(void)
106 {
107     return TASK_GetPtr( GetCurrentTask() );
108 }
109 
110 
111 /***********************************************************************
112  *           TASK_LinkTask
113  */
114 static void TASK_LinkTask( HTASK16 hTask )
115 {
116     HTASK16 *prevTask;
117     TDB *pTask;
118 
119     if (!(pTask = TASK_GetPtr( hTask ))) return;
120     prevTask = &hFirstTask;
121     while (*prevTask)
122     {
123         TDB *prevTaskPtr = TASK_GetPtr( *prevTask );
124         if (prevTaskPtr->priority >= pTask->priority) break;
125         prevTask = &prevTaskPtr->hNext;
126     }
127     pTask->hNext = *prevTask;
128     *prevTask = hTask;
129     nTaskCount++;
130 }
131 
132 
133 /***********************************************************************
134  *           TASK_UnlinkTask
135  */
136 static void TASK_UnlinkTask( HTASK16 hTask )
137 {
138     HTASK16 *prevTask;
139     TDB *pTask;
140 
141     prevTask = &hFirstTask;
142     while (*prevTask && (*prevTask != hTask))
143     {
144         pTask = TASK_GetPtr( *prevTask );
145         prevTask = &pTask->hNext;
146     }
147     if (*prevTask)
148     {
149         pTask = TASK_GetPtr( *prevTask );
150         *prevTask = pTask->hNext;
151         pTask->hNext = 0;
152         nTaskCount--;
153     }
154 }
155 
156 
157 /***********************************************************************
158  *           TASK_CreateThunks
159  *
160  * Create a thunk free-list in segment 'handle', starting from offset 'offset'
161  * and containing 'count' entries.
162  */
163 static void TASK_CreateThunks( HGLOBAL16 handle, WORD offset, WORD count )
164 {
165     int i;
166     WORD free;
167     THUNKS *pThunk;
168 
169     pThunk = (THUNKS *)((BYTE *)GlobalLock16( handle ) + offset);
170     pThunk->next = 0;
171     pThunk->magic = THUNK_MAGIC;
172     pThunk->free = (int)&pThunk->thunks - (int)pThunk;
173     free = pThunk->free;
174     for (i = 0; i < count-1; i++)
175     {
176         free += 8;  /* Offset of next thunk */
177         pThunk->thunks[4*i] = free;
178     }
179     pThunk->thunks[4*i] = 0;  /* Last thunk */
180 }
181 
182 
183 /***********************************************************************
184  *           TASK_AllocThunk
185  *
186  * Allocate a thunk for MakeProcInstance().
187  */
188 static SEGPTR TASK_AllocThunk(void)
189 {
190     TDB *pTask;
191     THUNKS *pThunk;
192     WORD sel, base;
193 
194     if (!(pTask = TASK_GetCurrent())) return 0;
195     sel = pTask->hCSAlias;
196     pThunk = (THUNKS *)&pTask->thunks;
197     base = (char *)pThunk - (char *)pTask;
198     while (!pThunk->free)
199     {
200         sel = pThunk->next;
201         if (!sel)  /* Allocate a new segment */
202         {
203             sel = GLOBAL_Alloc( GMEM_FIXED, sizeof(THUNKS) + (MIN_THUNKS-1)*8,
204                                 pTask->hPDB, WINE_LDT_FLAGS_CODE );
205             if (!sel) return (SEGPTR)0;
206             TASK_CreateThunks( sel, 0, MIN_THUNKS );
207             pThunk->next = sel;
208         }
209         pThunk = (THUNKS *)GlobalLock16( sel );
210         base = 0;
211     }
212     base += pThunk->free;
213     pThunk->free = *(WORD *)((BYTE *)pThunk + pThunk->free);
214     return MAKESEGPTR( sel, base );
215 }
216 
217 
218 /***********************************************************************
219  *           TASK_FreeThunk
220  *
221  * Free a MakeProcInstance() thunk.
222  */
223 static BOOL TASK_FreeThunk( SEGPTR thunk )
224 {
225     TDB *pTask;
226     THUNKS *pThunk;
227     WORD sel, base;
228 
229     if (!(pTask = TASK_GetCurrent())) return 0;
230     sel = pTask->hCSAlias;
231     pThunk = (THUNKS *)&pTask->thunks;
232     base = (char *)pThunk - (char *)pTask;
233     while (sel && (sel != HIWORD(thunk)))
234     {
235         sel = pThunk->next;
236         pThunk = (THUNKS *)GlobalLock16( sel );
237         base = 0;
238     }
239     if (!sel) return FALSE;
240     *(WORD *)((BYTE *)pThunk + LOWORD(thunk) - base) = pThunk->free;
241     pThunk->free = LOWORD(thunk) - base;
242     return TRUE;
243 }
244 
245 
246 /***********************************************************************
247  *           TASK_Create
248  *
249  * NOTE: This routine might be called by a Win32 thread. Thus, we need
250  *       to be careful to protect global data structures. We do this
251  *       by entering the Win16Lock while linking the task into the
252  *       global task list.
253  */
254 static TDB *TASK_Create( NE_MODULE *pModule, UINT16 cmdShow, LPCSTR cmdline, BYTE len )
255 {
256     HTASK16 hTask;
257     TDB *pTask;
258     FARPROC16 proc;
259     char curdir[MAX_PATH];
260     HMODULE16 hModule = pModule ? pModule->self : 0;
261 
262       /* Allocate the task structure */
263 
264     hTask = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, sizeof(TDB) );
265     if (!hTask) return NULL;
266     pTask = TASK_GetPtr( hTask );
267     FarSetOwner16( hTask, hModule );
268 
269     /* Fill the task structure */
270 
271     pTask->hSelf = hTask;
272 
273     pTask->version       = pModule ? pModule->ne_expver : 0x0400;
274     pTask->hModule       = hModule;
275     pTask->hParent       = GetCurrentTask();
276     pTask->magic         = TDB_MAGIC;
277     pTask->nCmdShow      = cmdShow;
278 
279     GetCurrentDirectoryA( sizeof(curdir), curdir );
280     GetShortPathNameA( curdir, curdir, sizeof(curdir) );
281     pTask->curdrive = (curdir[0] - 'A') | 0x80;
282     lstrcpynA( pTask->curdir, curdir + 2, sizeof(pTask->curdir) );
283 
284       /* Create the thunks block */
285 
286     TASK_CreateThunks( hTask, (char *)&pTask->thunks - (char *)pTask, 7 );
287 
288       /* Copy the module name */
289 
290     if (hModule)
291     {
292         char name[sizeof(pTask->module_name)+1];
293         size_t len;
294         GetModuleName16( hModule, name, sizeof(name) );
295         len = strlen(name) + 1;
296         memcpy(pTask->module_name, name, min(len,sizeof(pTask->module_name)));
297         pTask->compat_flags = GetProfileIntA( "Compatibility", name, 0 );
298     }
299 
300       /* Allocate a selector for the PDB */
301 
302     pTask->hPDB = GLOBAL_CreateBlock( GMEM_FIXED, &pTask->pdb, sizeof(PDB16),
303                                       hModule, WINE_LDT_FLAGS_DATA );
304 
305       /* Fill the PDB */
306 
307     pTask->pdb.int20 = 0x20cd;
308     pTask->pdb.dispatcher[0] = 0x9a;  /* ljmp */
309     proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DOS3Call" );
310     memcpy( &pTask->pdb.dispatcher[1], &proc, sizeof(proc) );
311     pTask->pdb.savedint22 = 0;
312     pTask->pdb.savedint23 = 0;
313     pTask->pdb.savedint24 = 0;
314     pTask->pdb.fileHandlesPtr =
315         MAKESEGPTR( GlobalHandleToSel16(pTask->hPDB), (int)&((PDB16 *)0)->fileHandles );
316     pTask->pdb.hFileHandles = 0;
317     memset( pTask->pdb.fileHandles, 0xff, sizeof(pTask->pdb.fileHandles) );
318     /* FIXME: should we make a copy of the environment? */
319     pTask->pdb.environment    = SELECTOROF(GetDOSEnvironment16());
320     pTask->pdb.nbFiles        = 20;
321 
322     /* Fill the command line */
323 
324     if (!cmdline)
325     {
326         cmdline = GetCommandLineA();
327         /* remove the first word (program name) */
328         if (*cmdline == '"')
329             if (!(cmdline = strchr( cmdline+1, '"' ))) cmdline = GetCommandLineA();
330         while (*cmdline && (*cmdline != ' ') && (*cmdline != '\t')) cmdline++;
331         while ((*cmdline == ' ') || (*cmdline == '\t')) cmdline++;
332         len = strlen(cmdline);
333     }
334     if (len >= sizeof(pTask->pdb.cmdLine)) len = sizeof(pTask->pdb.cmdLine)-1;
335     pTask->pdb.cmdLine[0] = len;
336     memcpy( pTask->pdb.cmdLine + 1, cmdline, len );
337     /* pTask->pdb.cmdLine[len+1] = 0; */
338 
339     TRACE("cmdline='%.*s' task=%04x\n", len, cmdline, hTask );
340 
341       /* Allocate a code segment alias for the TDB */
342 
343     pTask->hCSAlias = GLOBAL_CreateBlock( GMEM_FIXED, (void *)pTask,
344                                           sizeof(TDB), pTask->hPDB, WINE_LDT_FLAGS_CODE );
345 
346       /* Default DTA overwrites command line */
347 
348     pTask->dta = MAKESEGPTR( pTask->hPDB, (int)&pTask->pdb.cmdLine - (int)&pTask->pdb );
349 
350     /* Create scheduler event for 16-bit tasks */
351 
352     if ( !(pTask->flags & TDBF_WIN32) )
353         NtCreateEvent( &pTask->hEvent, EVENT_ALL_ACCESS, NULL, TRUE, FALSE );
354 
355     if (!initial_task) initial_task = hTask;
356 
357     return pTask;
358 }
359 
360 
361 /***********************************************************************
362  *           TASK_DeleteTask
363  */
364 static void TASK_DeleteTask( HTASK16 hTask )
365 {
366     TDB *pTask;
367     HGLOBAL16 hPDB;
368 
369     if (!(pTask = TASK_GetPtr( hTask ))) return;
370     hPDB = pTask->hPDB;
371 
372     pTask->magic = 0xdead; /* invalidate signature */
373 
374     /* Free the selector aliases */
375 
376     GLOBAL_FreeBlock( pTask->hCSAlias );
377     GLOBAL_FreeBlock( pTask->hPDB );
378 
379     /* Free the task module */
380 
381     FreeModule16( pTask->hModule );
382 
383     /* Free the task structure itself */
384 
385     GlobalFree16( hTask );
386 
387     /* Free all memory used by this task (including the 32-bit stack, */
388     /* the environment block and the thunk segments). */
389 
390     GlobalFreeAll16( hPDB );
391 }
392 
393 
394 /***********************************************************************
395  *           TASK_CreateMainTask
396  *
397  * Create a task for the main (32-bit) process.
398  */
399 void TASK_CreateMainTask(void)
400 {
401     TDB *pTask;
402     STARTUPINFOA startup_info;
403     UINT cmdShow = 1; /* SW_SHOWNORMAL but we don't want to include winuser.h here */
404 
405     GetStartupInfoA( &startup_info );
406     if (startup_info.dwFlags & STARTF_USESHOWWINDOW) cmdShow = startup_info.wShowWindow;
407     pTask = TASK_Create( NULL, cmdShow, NULL, 0 );
408     if (!pTask)
409     {
410         ERR("could not create task for main process\n");
411         ExitProcess(1);
412     }
413 
414     pTask->flags        |= TDBF_WIN32;
415     pTask->hInstance     = 0;
416     pTask->hPrevInstance = 0;
417     pTask->teb           = NtCurrentTeb();
418 
419     /* Add the task to the linked list */
420     /* (no need to get the win16 lock, we are the only thread at this point) */
421     TASK_LinkTask( pTask->hSelf );
422     main_task = pTask->hSelf;
423 }
424 
425 
426 struct create_data
427 {
428     TDB                 *task;
429     WIN16_SUBSYSTEM_TIB *tib;
430 };
431 
432 /* allocate the win16 TIB for a new 16-bit task */
433 static WIN16_SUBSYSTEM_TIB *allocate_win16_tib( TDB *pTask )
434 {
435     WCHAR path[MAX_PATH];
436     WIN16_SUBSYSTEM_TIB *tib;
437     UNICODE_STRING *curdir;
438     NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
439 
440     if (!(tib = HeapAlloc( GetProcessHeap(), 0, sizeof(*tib) ))) return NULL;
441     MultiByteToWideChar( CP_ACP, 0, NE_MODULE_NAME(pModule), -1, path, MAX_PATH );
442     GetLongPathNameW( path, path, MAX_PATH );
443     if (RtlCreateUnicodeString( &tib->exe_str, path )) tib->exe_name = &tib->exe_str;
444     else tib->exe_name = NULL;
445 
446     RtlAcquirePebLock();
447     if (NtCurrentTeb()->Tib.SubSystemTib)
448         curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
449     else
450         curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
451     tib->curdir.DosPath.MaximumLength = sizeof(tib->curdir_buffer);
452     tib->curdir.DosPath.Length = min( curdir->Length, tib->curdir.DosPath.MaximumLength-sizeof(WCHAR) );
453     tib->curdir.DosPath.Buffer = tib->curdir_buffer;
454     tib->curdir.Handle = 0;
455     memcpy( tib->curdir_buffer, curdir->Buffer, tib->curdir.DosPath.Length );
456     tib->curdir_buffer[tib->curdir.DosPath.Length/sizeof(WCHAR)] = 0;
457     RtlReleasePebLock();
458     return tib;
459 }
460 
461 static inline void free_win16_tib( WIN16_SUBSYSTEM_TIB *tib )
462 {
463     if (tib->exe_name) RtlFreeUnicodeString( tib->exe_name );
464     HeapFree( GetProcessHeap(), 0, tib );
465 }
466 
467 /* startup routine for a new 16-bit thread */
468 static DWORD CALLBACK task_start( LPVOID p )
469 {
470     struct create_data *data = p;
471     TDB *pTask = data->task;
472     DWORD ret;
473 
474     kernel_get_thread_data()->htask16 = pTask->hSelf;
475     NtCurrentTeb()->Tib.SubSystemTib = data->tib;
476     HeapFree( GetProcessHeap(), 0, data );
477 
478     _EnterWin16Lock();
479     TASK_LinkTask( pTask->hSelf );
480     pTask->teb = NtCurrentTeb();
481     ret = NE_StartTask();
482     _LeaveWin16Lock();
483     return ret;
484 }
485 
486 
487 /***********************************************************************
488  *           TASK_SpawnTask
489  *
490  * Spawn a new 16-bit task.
491  */
492 HTASK16 TASK_SpawnTask( NE_MODULE *pModule, WORD cmdShow,
493                         LPCSTR cmdline, BYTE len, HANDLE *hThread )
494 {
495     struct create_data *data = NULL;
496     WIN16_SUBSYSTEM_TIB *tib;
497     TDB *pTask;
498 
499     if (!(pTask = TASK_Create( pModule, cmdShow, cmdline, len ))) return 0;
500     if (!(tib = allocate_win16_tib( pTask ))) goto failed;
501     if (!(data = HeapAlloc( GetProcessHeap(), 0, sizeof(*data)))) goto failed;
502     data->task = pTask;
503     data->tib = tib;
504     if (!(*hThread = CreateThread( NULL, 0, task_start, data, 0, NULL ))) goto failed;
505     return pTask->hSelf;
506 
507 failed:
508     if (tib) free_win16_tib( tib );
509     HeapFree( GetProcessHeap(), 0, data );
510     TASK_DeleteTask( pTask->hSelf );
511     return 0;
512 }
513 
514 
515 /***********************************************************************
516  *           TASK_GetTaskFromThread
517  */
518 HTASK16 TASK_GetTaskFromThread( DWORD thread )
519 {
520     TDB *p = TASK_GetPtr( hFirstTask );
521     while (p)
522     {
523         if (p->teb->ClientId.UniqueThread == (HANDLE)thread) return p->hSelf;
524         p = TASK_GetPtr( p->hNext );
525     }
526     return 0;
527 }
528 
529 
530 /***********************************************************************
531  *           TASK_CallTaskSignalProc
532  */
533 static void TASK_CallTaskSignalProc( UINT16 uCode, HANDLE16 hTaskOrModule )
534 {
535     WORD args[5];
536     TDB *pTask = TASK_GetCurrent();
537 
538     if ( !pTask || !pTask->userhandler ) return;
539 
540     args[4] = hTaskOrModule;
541     args[3] = uCode;
542     args[2] = 0;
543     args[1] = pTask->hInstance;
544     args[0] = pTask->hQueue;
545     WOWCallback16Ex( (DWORD)pTask->userhandler, WCB16_PASCAL, sizeof(args), args, NULL );
546 }
547 
548 
549 /***********************************************************************
550  *           TASK_ExitTask
551  */
552 void TASK_ExitTask(void)
553 {
554     WIN16_SUBSYSTEM_TIB *tib;
555     TDB *pTask;
556     DWORD lockCount;
557 
558     /* Enter the Win16Lock to protect global data structures */
559     _EnterWin16Lock();
560 
561     pTask = TASK_GetCurrent();
562     if ( !pTask )
563     {
564         _LeaveWin16Lock();
565         return;
566     }
567 
568     TRACE("Killing task %04x\n", pTask->hSelf );
569 
570     /* Perform USER cleanup */
571 
572     TASK_CallTaskSignalProc( USIG16_TERMINATION, pTask->hSelf );
573 
574     /* Remove the task from the list to be sure we never switch back to it */
575     TASK_UnlinkTask( pTask->hSelf );
576 
577     if (!nTaskCount || (nTaskCount == 1 && hFirstTask == initial_task))
578     {
579         TRACE("this is the last task, exiting\n" );
580         ExitKernel16();
581     }
582 
583     pTask->nEvents = 0;
584 
585     if ( hLockedTask == pTask->hSelf )
586         hLockedTask = 0;
587 
588     TASK_DeleteTask( pTask->hSelf );
589 
590     if ((tib = NtCurrentTeb()->Tib.SubSystemTib))
591     {
592         free_win16_tib( tib );
593         NtCurrentTeb()->Tib.SubSystemTib = NULL;
594     }
595 
596     /* ... and completely release the Win16Lock, just in case. */
597     ReleaseThunkLock( &lockCount );
598 }
599 
600 
601 /***********************************************************************
602  *           ExitKernel (KERNEL.2)
603  *
604  * Clean-up everything and exit the Wine process.
605  */
606 void WINAPI ExitKernel16(void)
607 {
608     WriteOutProfiles16();
609     TerminateProcess( GetCurrentProcess(), 0 );
610 }
611 
612 
613 /***********************************************************************
614  *           InitTask  (KERNEL.91)
615  *
616  * Called by the application startup code.
617  */
618 void WINAPI InitTask16( CONTEXT86 *context )
619 {
620     TDB *pTask;
621     INSTANCEDATA *pinstance;
622     SEGPTR ptr;
623 
624     context->Eax = 0;
625     if (!(pTask = TASK_GetCurrent())) return;
626 
627     /* Note: we need to trust that BX/CX contain the stack/heap sizes,
628        as some apps, notably Visual Basic apps, *modify* the heap/stack
629        size of the instance data segment before calling InitTask() */
630 
631     /* Initialize the INSTANCEDATA structure */
632     pinstance = MapSL( MAKESEGPTR(CURRENT_DS, 0) );
633     pinstance->stackmin    = OFFSETOF(NtCurrentTeb()->WOW32Reserved) + sizeof( STACK16FRAME );
634     pinstance->stackbottom = pinstance->stackmin; /* yup, that's right. Confused me too. */
635     pinstance->stacktop    = ( pinstance->stackmin > LOWORD(context->Ebx) ?
636                                pinstance->stackmin - LOWORD(context->Ebx) : 0 ) + 150;
637 
638     /* Initialize the local heap */
639     if (LOWORD(context->Ecx))
640         LocalInit16( GlobalHandleToSel16(pTask->hInstance), 0, LOWORD(context->Ecx) );
641 
642     /* Initialize implicitly loaded DLLs */
643     NE_InitializeDLLs( pTask->hModule );
644     NE_DllProcessAttach( pTask->hModule );
645 
646     /* Registers on return are:
647      * ax     1 if OK, 0 on error
648      * cx     stack limit in bytes
649      * dx     cmdShow parameter
650      * si     instance handle of the previous instance
651      * di     instance handle of the new task
652      * es:bx  pointer to command line inside PSP
653      *
654      * 0 (=%bp) is pushed on the stack
655      */
656     ptr = stack16_push( sizeof(WORD) );
657     *(WORD *)MapSL(ptr) = 0;
658     context->Esp -= 2;
659 
660     context->Eax = 1;
661 
662     if (!pTask->pdb.cmdLine[0]) context->Ebx = 0x80;
663     else
664     {
665         LPBYTE p = &pTask->pdb.cmdLine[1];
666         while ((*p == ' ') || (*p == '\t')) p++;
667         context->Ebx = 0x80 + (p - pTask->pdb.cmdLine);
668     }
669     context->Ecx   = pinstance->stacktop;
670     context->Edx   = pTask->nCmdShow;
671     context->Esi   = (DWORD)pTask->hPrevInstance;
672     context->Edi   = (DWORD)pTask->hInstance;
673     context->SegEs = (WORD)pTask->hPDB;
674 }
675 
676 
677 /***********************************************************************
678  *           WaitEvent  (KERNEL.30)
679  */
680 BOOL16 WINAPI WaitEvent16( HTASK16 hTask )
681 {
682     TDB *pTask;
683 
684     if (!hTask) hTask = GetCurrentTask();
685     pTask = TASK_GetPtr( hTask );
686 
687     if (pTask->flags & TDBF_WIN32)
688     {
689         FIXME("called for Win32 thread (%04x)!\n", GetCurrentThreadId());
690         return TRUE;
691     }
692 
693     if (pTask->nEvents > 0)
694     {
695         pTask->nEvents--;
696         return FALSE;
697     }
698 
699     if (pTask->teb == NtCurrentTeb())
700     {
701         DWORD lockCount;
702 
703         NtResetEvent( pTask->hEvent, NULL );
704         ReleaseThunkLock( &lockCount );
705         SYSLEVEL_CheckNotLevel( 1 );
706         WaitForSingleObject( pTask->hEvent, INFINITE );
707         RestoreThunkLock( lockCount );
708         if (pTask->nEvents > 0) pTask->nEvents--;
709     }
710     else FIXME("for other task %04x cur=%04x\n",pTask->hSelf,GetCurrentTask());
711 
712     return TRUE;
713 }
714 
715 
716 /***********************************************************************
717  *           PostEvent  (KERNEL.31)
718  */
719 void WINAPI PostEvent16( HTASK16 hTask )
720 {
721     TDB *pTask;
722 
723     if (!hTask) hTask = GetCurrentTask();
724     if (!(pTask = TASK_GetPtr( hTask ))) return;
725 
726     if (pTask->flags & TDBF_WIN32)
727     {
728         FIXME("called for Win32 thread (%04x)!\n", (DWORD)pTask->teb->ClientId.UniqueThread );
729         return;
730     }
731 
732     pTask->nEvents++;
733 
734     if (pTask->nEvents == 1) NtSetEvent( pTask->hEvent, NULL );
735 }
736 
737 
738 /***********************************************************************
739  *           SetPriority  (KERNEL.32)
740  */
741 void WINAPI SetPriority16( HTASK16 hTask, INT16 delta )
742 {
743     TDB *pTask;
744     INT16 newpriority;
745 
746     if (!hTask) hTask = GetCurrentTask();
747     if (!(pTask = TASK_GetPtr( hTask ))) return;
748     newpriority = pTask->priority + delta;
749     if (newpriority < -32) newpriority = -32;
750     else if (newpriority > 15) newpriority = 15;
751 
752     pTask->priority = newpriority + 1;
753     TASK_UnlinkTask( pTask->hSelf );
754     TASK_LinkTask( pTask->hSelf );
755     pTask->priority--;
756 }
757 
758 
759 /***********************************************************************
760  *           LockCurrentTask  (KERNEL.33)
761  */
762 HTASK16 WINAPI LockCurrentTask16( BOOL16 bLock )
763 {
764     if (bLock) hLockedTask = GetCurrentTask();
765     else hLockedTask = 0;
766     return hLockedTask;
767 }
768 
769 
770 /***********************************************************************
771  *           IsTaskLocked  (KERNEL.122)
772  */
773 HTASK16 WINAPI IsTaskLocked16(void)
774 {
775     return hLockedTask;
776 }
777 
778 
779 /***********************************************************************
780  *           OldYield  (KERNEL.117)
781  */
782 void WINAPI OldYield16(void)
783 {
784    DWORD count;
785 
786    ReleaseThunkLock(&count);
787    RestoreThunkLock(count);
788 }
789 
790 /***********************************************************************
791  *           WIN32_OldYield  (KERNEL.447)
792  */
793 void WINAPI WIN32_OldYield16(void)
794 {
795    DWORD count;
796 
797    ReleaseThunkLock(&count);
798    RestoreThunkLock(count);
799 }
800 
801 /***********************************************************************
802  *           DirectedYield  (KERNEL.150)
803  */
804 void WINAPI DirectedYield16( HTASK16 hTask )
805 {
806     OldYield16();
807 }
808 
809 /***********************************************************************
810  *           Yield  (KERNEL.29)
811  */
812 void WINAPI Yield16(void)
813 {
814     TDB *pCurTask = TASK_GetCurrent();
815 
816     if (pCurTask && pCurTask->hQueue)
817     {
818         HMODULE mod = GetModuleHandleA( "user32.dll" );
819         if (mod)
820         {
821             FARPROC proc = GetProcAddress( mod, "UserYield16" );
822             if (proc)
823             {
824                 proc();
825                 return;
826             }
827         }
828     }
829     OldYield16();
830 }
831 
832 /***********************************************************************
833  *           KERNEL_490  (KERNEL.490)
834  */
835 HTASK16 WINAPI KERNEL_490( HTASK16 someTask )
836 {
837     if ( !someTask ) return 0;
838 
839     FIXME("(%04x): stub\n", someTask );
840     return 0;
841 }
842 
843 /***********************************************************************
844  *           MakeProcInstance  (KERNEL.51)
845  */
846 FARPROC16 WINAPI MakeProcInstance16( FARPROC16 func, HANDLE16 hInstance )
847 {
848     BYTE *thunk,*lfunc;
849     SEGPTR thunkaddr;
850     WORD hInstanceSelector;
851 
852     hInstanceSelector = GlobalHandleToSel16(hInstance);
853 
854     TRACE("(%p, %04x);\n", func, hInstance);
855 
856     if (!HIWORD(func)) {
857       /* Win95 actually protects via SEH, but this is better for debugging */
858       WARN("Ouch ! Called with invalid func %p !\n", func);
859       return (FARPROC16)0;
860     }
861 
862     if ( (GlobalHandleToSel16(CURRENT_DS) != hInstanceSelector)
863       && (hInstance != 0)
864       && (hInstance != 0xffff) )
865     {
866         /* calling MPI with a foreign DSEG is invalid ! */
867         WARN("Problem with hInstance? Got %04x, using %04x instead\n",
868                    hInstance,CURRENT_DS);
869     }
870 
871     /* Always use the DSEG that MPI was entered with.
872      * We used to set hInstance to GetTaskDS16(), but this should be wrong
873      * as CURRENT_DS provides the DSEG value we need.
874      * ("calling" DS, *not* "task" DS !) */
875     hInstanceSelector = CURRENT_DS;
876     hInstance = GlobalHandle16(hInstanceSelector);
877 
878     /* no thunking for DLLs */
879     if (NE_GetPtr(FarGetOwner16(hInstance))->ne_flags & NE_FFLAGS_LIBMODULE)
880         return func;
881 
882     thunkaddr = TASK_AllocThunk();
883     if (!thunkaddr) return (FARPROC16)0;
884     thunk = MapSL( thunkaddr );
885     lfunc = MapSL( (SEGPTR)func );
886 
887     TRACE("(%p,%04x): got thunk %08x\n", func, hInstance, thunkaddr );
888     if (((lfunc[0]==0x8c) && (lfunc[1]==0xd8)) || /* movw %ds, %ax */
889         ((lfunc[0]==0x1e) && (lfunc[1]==0x58))    /* pushw %ds, popw %ax */
890     ) {
891         WARN("This was the (in)famous \"thunk useless\" warning. We thought we have to overwrite with nop;nop;, but this isn't true.\n");
892     }
893 
894     *thunk++ = 0xb8;    /* movw instance, %ax */
895     *thunk++ = (BYTE)(hInstanceSelector & 0xff);
896     *thunk++ = (BYTE)(hInstanceSelector >> 8);
897     *thunk++ = 0xea;    /* ljmp func */
898     *(DWORD *)thunk = (DWORD)func;
899     return (FARPROC16)thunkaddr;
900     /* CX reg indicates if thunkaddr != NULL, implement if needed */
901 }
902 
903 
904 /***********************************************************************
905  *           FreeProcInstance  (KERNEL.52)
906  */
907 void WINAPI FreeProcInstance16( FARPROC16 func )
908 {
909     TRACE("(%p)\n", func );
910     TASK_FreeThunk( (SEGPTR)func );
911 }
912 
913 /**********************************************************************
914  *          TASK_GetCodeSegment
915  *
916  * Helper function for GetCodeHandle/GetCodeInfo: Retrieve the module
917  * and logical segment number of a given code segment.
918  *
919  * 'proc' either *is* already a pair of module handle and segment number,
920  * in which case there's nothing to do.  Otherwise, it is a pointer to
921  * a function, and we need to retrieve the code segment.  If the pointer
922  * happens to point to a thunk, we'll retrieve info about the code segment
923  * where the function pointed to by the thunk resides, not the thunk itself.
924  *
925  * FIXME: if 'proc' is a SNOOP16 return stub, we should retrieve info about
926  *        the function the snoop code will return to ...
927  *
928  */
929 static BOOL TASK_GetCodeSegment( FARPROC16 proc, NE_MODULE **ppModule,
930                                  SEGTABLEENTRY **ppSeg, int *pSegNr )
931 {
932     NE_MODULE *pModule = NULL;
933     SEGTABLEENTRY *pSeg = NULL;
934     int segNr=0;
935 
936     /* Try pair of module handle / segment number */
937     pModule = (NE_MODULE *) GlobalLock16( HIWORD( proc ) );
938     if ( pModule && pModule->ne_magic == IMAGE_OS2_SIGNATURE )
939     {
940         segNr = LOWORD( proc );
941         if ( segNr && segNr <= pModule->ne_cseg )
942             pSeg = NE_SEG_TABLE( pModule ) + segNr-1;
943     }
944 
945     /* Try thunk or function */
946     else
947     {
948         BYTE *thunk = MapSL( (SEGPTR)proc );
949         WORD selector;
950 
951         if ((thunk[0] == 0xb8) && (thunk[3] == 0xea))
952             selector = thunk[6] + (thunk[7] << 8);
953         else
954             selector = HIWORD( proc );
955 
956         pModule = NE_GetPtr( GlobalHandle16( selector ) );
957         pSeg = pModule? NE_SEG_TABLE( pModule ) : NULL;
958 
959         if ( pModule )
960             for ( segNr = 1; segNr <= pModule->ne_cseg; segNr++, pSeg++ )
961                 if ( GlobalHandleToSel16(pSeg->hSeg) == selector )
962                     break;
963 
964         if ( pModule && segNr > pModule->ne_cseg )
965             pSeg = NULL;
966     }
967 
968     /* Abort if segment not found */
969 
970     if ( !pModule || !pSeg )
971         return FALSE;
972 
973     /* Return segment data */
974 
975     if ( ppModule ) *ppModule = pModule;
976     if ( ppSeg    ) *ppSeg    = pSeg;
977     if ( pSegNr   ) *pSegNr   = segNr;
978 
979     return TRUE;
980 }
981 
982 /**********************************************************************
983  *          GetCodeHandle    (KERNEL.93)
984  */
985 HANDLE16 WINAPI GetCodeHandle16( FARPROC16 proc )
986 {
987     SEGTABLEENTRY *pSeg;
988 
989     if ( !TASK_GetCodeSegment( proc, NULL, &pSeg, NULL ) )
990         return (HANDLE16)0;
991 
992     return pSeg->hSeg;
993 }
994 
995 /**********************************************************************
996  *          GetCodeInfo    (KERNEL.104)
997  */
998 BOOL16 WINAPI GetCodeInfo16( FARPROC16 proc, SEGINFO *segInfo )
999 {
1000     NE_MODULE *pModule;
1001     SEGTABLEENTRY *pSeg;
1002     int segNr;
1003 
1004     if ( !TASK_GetCodeSegment( proc, &pModule, &pSeg, &segNr ) )
1005         return FALSE;
1006 
1007     /* Fill in segment information */
1008 
1009     segInfo->offSegment = pSeg->filepos;
1010     segInfo->cbSegment  = pSeg->size;
1011     segInfo->flags      = pSeg->flags;
1012     segInfo->cbAlloc    = pSeg->minsize;
1013     segInfo->h          = pSeg->hSeg;
1014     segInfo->alignShift = pModule->ne_align;
1015 
1016     if ( segNr == pModule->ne_autodata )
1017         segInfo->cbAlloc += pModule->ne_heap + pModule->ne_stack;
1018 
1019     /* Return module handle in %es */
1020 
1021     CURRENT_STACK16->es = GlobalHandleToSel16( pModule->self );
1022 
1023     return TRUE;
1024 }
1025 
1026 
1027 /**********************************************************************
1028  *          DefineHandleTable    (KERNEL.94)
1029  */
1030 BOOL16 WINAPI DefineHandleTable16( WORD wOffset )
1031 {
1032     FIXME("(%04x): stub ?\n", wOffset);
1033     return TRUE;
1034 }