4 * Copyright 1995 Alexandre Julliard
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.
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.
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
22 #include "wine/port.h"
39 #include "wine/winbase16.h"
42 #include "wine/server.h"
44 #include "kernel_private.h"
45 #include "kernel16_private.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(task);
50 WINE_DECLARE_DEBUG_CHANNEL(relay);
51 WINE_DECLARE_DEBUG_CHANNEL(toolhelp);
55 /* Segment containing MakeProcInstance() thunks */
58 WORD next; /* Selector of next segment */
59 WORD magic; /* Thunks signature */
61 WORD free; /* Head of the free list */
62 WORD thunks[4]; /* Each thunk is 4 words long */
67 #define THUNK_MAGIC ('P' | ('T' << 8))
69 /* Min. number of thunks allocated when creating a new segment */
72 #define TDB_MAGIC ('T' | ('D' << 8))
74 static THHOOK DefaultThhook;
75 THHOOK *pThhook = &DefaultThhook;
77 #define hFirstTask (pThhook->HeadTDB)
78 #define hLockedTask (pThhook->LockTDB)
80 static UINT16 nTaskCount = 0;
82 static HTASK16 initial_task, main_task;
84 /***********************************************************************
87 void TASK_InstallTHHook( THHOOK *pNewThhook )
89 THHOOK *pOldThhook = pThhook;
91 pThhook = pNewThhook? pNewThhook : &DefaultThhook;
93 *pThhook = *pOldThhook;
96 /***********************************************************************
99 static TDB *TASK_GetPtr( HTASK16 hTask )
101 return GlobalLock16( hTask );
105 /***********************************************************************
108 TDB *TASK_GetCurrent(void)
110 return TASK_GetPtr( GetCurrentTask() );
114 /***********************************************************************
117 static void TASK_LinkTask( HTASK16 hTask )
122 if (!(pTask = TASK_GetPtr( hTask ))) return;
123 prevTask = &hFirstTask;
126 TDB *prevTaskPtr = TASK_GetPtr( *prevTask );
127 if (prevTaskPtr->priority >= pTask->priority) break;
128 prevTask = &prevTaskPtr->hNext;
130 pTask->hNext = *prevTask;
136 /***********************************************************************
139 static void TASK_UnlinkTask( HTASK16 hTask )
144 prevTask = &hFirstTask;
145 while (*prevTask && (*prevTask != hTask))
147 pTask = TASK_GetPtr( *prevTask );
148 prevTask = &pTask->hNext;
152 pTask = TASK_GetPtr( *prevTask );
153 *prevTask = pTask->hNext;
160 /***********************************************************************
163 * Create a thunk free-list in segment 'handle', starting from offset 'offset'
164 * and containing 'count' entries.
166 static void TASK_CreateThunks( HGLOBAL16 handle, WORD offset, WORD count )
172 pThunk = (THUNKS *)((BYTE *)GlobalLock16( handle ) + offset);
174 pThunk->magic = THUNK_MAGIC;
175 pThunk->free = (int)&pThunk->thunks - (int)pThunk;
177 for (i = 0; i < count-1; i++)
179 free += 8; /* Offset of next thunk */
180 pThunk->thunks[4*i] = free;
182 pThunk->thunks[4*i] = 0; /* Last thunk */
186 /***********************************************************************
189 * Allocate a thunk for MakeProcInstance().
191 static SEGPTR TASK_AllocThunk(void)
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)
204 if (!sel) /* Allocate a new segment */
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 );
212 pThunk = (THUNKS *)GlobalLock16( sel );
215 base += pThunk->free;
216 pThunk->free = *(WORD *)((BYTE *)pThunk + pThunk->free);
217 return MAKESEGPTR( sel, base );
221 /***********************************************************************
224 * Free a MakeProcInstance() thunk.
226 static BOOL TASK_FreeThunk( SEGPTR thunk )
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)))
239 pThunk = (THUNKS *)GlobalLock16( sel );
242 if (!sel) return FALSE;
243 *(WORD *)((BYTE *)pThunk + LOWORD(thunk) - base) = pThunk->free;
244 pThunk->free = LOWORD(thunk) - base;
249 /***********************************************************************
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
257 static TDB *TASK_Create( NE_MODULE *pModule, UINT16 cmdShow, LPCSTR cmdline, BYTE len )
262 char curdir[MAX_PATH];
263 HMODULE16 hModule = pModule ? pModule->self : 0;
265 /* Allocate the task structure */
267 hTask = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, sizeof(TDB) );
268 if (!hTask) return NULL;
269 pTask = TASK_GetPtr( hTask );
270 FarSetOwner16( hTask, hModule );
272 /* Fill the task structure */
274 pTask->hSelf = hTask;
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;
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) );
287 /* Create the thunks block */
289 TASK_CreateThunks( hTask, (char *)&pTask->thunks - (char *)pTask, 7 );
291 /* Copy the module name */
295 char name[sizeof(pTask->module_name)+1];
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 );
303 /* Allocate a selector for the PDB */
305 pTask->hPDB = GLOBAL_CreateBlock( GMEM_FIXED, &pTask->pdb, sizeof(PDB16),
306 hModule, WINE_LDT_FLAGS_DATA );
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;
325 /* Fill the command line */
329 cmdline = GetCommandLineA();
330 /* remove the first word (program name) */
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);
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; */
342 TRACE("cmdline='%.*s' task=%04x\n", len, cmdline, hTask );
344 /* Allocate a code segment alias for the TDB */
346 pTask->hCSAlias = GLOBAL_CreateBlock( GMEM_FIXED, (void *)pTask,
347 sizeof(TDB), pTask->hPDB, WINE_LDT_FLAGS_CODE );
349 /* Default DTA overwrites command line */
351 pTask->dta = MAKESEGPTR( pTask->hPDB, (int)&pTask->pdb.cmdLine - (int)&pTask->pdb );
353 /* Create scheduler event for 16-bit tasks */
355 if ( !(pTask->flags & TDBF_WIN32) )
356 NtCreateEvent( &pTask->hEvent, EVENT_ALL_ACCESS, NULL, TRUE, FALSE );
358 if (!initial_task) initial_task = hTask;
364 /***********************************************************************
367 static void TASK_DeleteTask( HTASK16 hTask )
372 if (!(pTask = TASK_GetPtr( hTask ))) return;
375 pTask->magic = 0xdead; /* invalidate signature */
377 /* Free the selector aliases */
379 GLOBAL_FreeBlock( pTask->hCSAlias );
380 GLOBAL_FreeBlock( pTask->hPDB );
382 /* Free the task module */
384 FreeModule16( pTask->hModule );
386 /* Free the task structure itself */
388 GlobalFree16( hTask );
390 /* Free all memory used by this task (including the 32-bit stack, */
391 /* the environment block and the thunk segments). */
393 GlobalFreeAll16( hPDB );
397 /***********************************************************************
398 * TASK_CreateMainTask
400 * Create a task for the main (32-bit) process.
402 void TASK_CreateMainTask(void)
405 STARTUPINFOA startup_info;
406 UINT cmdShow = 1; /* SW_SHOWNORMAL but we don't want to include winuser.h here */
408 GetStartupInfoA( &startup_info );
409 if (startup_info.dwFlags & STARTF_USESHOWWINDOW) cmdShow = startup_info.wShowWindow;
410 pTask = TASK_Create( NULL, cmdShow, NULL, 0 );
413 ERR("could not create task for main process\n");
417 pTask->flags |= TDBF_WIN32;
418 pTask->hInstance = 0;
419 pTask->hPrevInstance = 0;
420 pTask->teb = NtCurrentTeb();
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;
429 /* allocate the win16 TIB for a new 16-bit task */
430 static WIN16_SUBSYSTEM_TIB *allocate_win16_tib( TDB *pTask )
432 WCHAR path[MAX_PATH];
433 WIN16_SUBSYSTEM_TIB *tib;
434 UNICODE_STRING *curdir;
435 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
437 if (!(tib = HeapAlloc( GetProcessHeap(), 0, sizeof(*tib) ))) return NULL;
438 MultiByteToWideChar( CP_ACP, 0, NE_MODULE_NAME(pModule), -1, path, MAX_PATH );
439 GetLongPathNameW( path, path, MAX_PATH );
440 if (RtlCreateUnicodeString( &tib->exe_str, path )) tib->exe_name = &tib->exe_str;
441 else tib->exe_name = NULL;
444 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
445 tib->curdir.DosPath.MaximumLength = sizeof(tib->curdir_buffer);
446 tib->curdir.DosPath.Length = min( curdir->Length, tib->curdir.DosPath.MaximumLength-sizeof(WCHAR) );
447 tib->curdir.DosPath.Buffer = tib->curdir_buffer;
448 tib->curdir.Handle = 0;
449 memcpy( tib->curdir_buffer, curdir->Buffer, tib->curdir.DosPath.Length );
450 tib->curdir_buffer[tib->curdir.DosPath.Length/sizeof(WCHAR)] = 0;
455 /* startup routine for a new 16-bit thread */
456 static DWORD CALLBACK task_start( LPVOID p )
458 TDB *pTask = (TDB *)p;
461 kernel_get_thread_data()->htask16 = pTask->hSelf;
462 NtCurrentTeb()->Tib.SubSystemTib = allocate_win16_tib( pTask );
465 TASK_LinkTask( pTask->hSelf );
466 pTask->teb = NtCurrentTeb();
467 ret = NE_StartTask();
473 /***********************************************************************
476 * Spawn a new 16-bit task.
478 HTASK16 TASK_SpawnTask( NE_MODULE *pModule, WORD cmdShow,
479 LPCSTR cmdline, BYTE len, HANDLE *hThread )
483 if (!(pTask = TASK_Create( pModule, cmdShow, cmdline, len ))) return 0;
484 if (!(*hThread = CreateThread( NULL, 0, task_start, pTask, 0, NULL )))
486 TASK_DeleteTask( pTask->hSelf );
493 /***********************************************************************
494 * TASK_GetTaskFromThread
496 HTASK16 TASK_GetTaskFromThread( DWORD thread )
498 TDB *p = TASK_GetPtr( hFirstTask );
501 if (p->teb->ClientId.UniqueThread == (HANDLE)thread) return p->hSelf;
502 p = TASK_GetPtr( p->hNext );
508 /***********************************************************************
509 * TASK_CallTaskSignalProc
511 static void TASK_CallTaskSignalProc( UINT16 uCode, HANDLE16 hTaskOrModule )
514 TDB *pTask = TASK_GetCurrent();
516 if ( !pTask || !pTask->userhandler ) return;
518 args[4] = hTaskOrModule;
521 args[1] = pTask->hInstance;
522 args[0] = pTask->hQueue;
523 WOWCallback16Ex( (DWORD)pTask->userhandler, WCB16_PASCAL, sizeof(args), args, NULL );
527 /***********************************************************************
530 void TASK_ExitTask(void)
532 WIN16_SUBSYSTEM_TIB *tib;
536 /* Enter the Win16Lock to protect global data structures */
539 pTask = TASK_GetCurrent();
546 TRACE("Killing task %04x\n", pTask->hSelf );
548 /* Perform USER cleanup */
550 TASK_CallTaskSignalProc( USIG16_TERMINATION, pTask->hSelf );
552 /* Remove the task from the list to be sure we never switch back to it */
553 TASK_UnlinkTask( pTask->hSelf );
555 if (!nTaskCount || (nTaskCount == 1 && hFirstTask == initial_task))
557 TRACE("this is the last task, exiting\n" );
563 if ( hLockedTask == pTask->hSelf )
566 TASK_DeleteTask( pTask->hSelf );
568 if ((tib = NtCurrentTeb()->Tib.SubSystemTib))
570 if (tib->exe_name) RtlFreeUnicodeString( tib->exe_name );
571 HeapFree( GetProcessHeap(), 0, tib );
572 NtCurrentTeb()->Tib.SubSystemTib = NULL;
575 /* ... and completely release the Win16Lock, just in case. */
576 ReleaseThunkLock( &lockCount );
580 /***********************************************************************
581 * ExitKernel (KERNEL.2)
583 * Clean-up everything and exit the Wine process.
585 void WINAPI ExitKernel16(void)
587 WriteOutProfiles16();
588 TerminateProcess( GetCurrentProcess(), 0 );
592 /***********************************************************************
593 * InitTask (KERNEL.91)
595 * Called by the application startup code.
597 void WINAPI InitTask16( CONTEXT86 *context )
600 INSTANCEDATA *pinstance;
604 if (!(pTask = TASK_GetCurrent())) return;
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() */
610 /* Initialize the INSTANCEDATA structure */
611 pinstance = MapSL( MAKESEGPTR(CURRENT_DS, 0) );
612 pinstance->stackmin = OFFSETOF(NtCurrentTeb()->WOW32Reserved) + 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;
617 /* Initialize the local heap */
618 if (LOWORD(context->Ecx))
619 LocalInit16( GlobalHandleToSel16(pTask->hInstance), 0, LOWORD(context->Ecx) );
621 /* Initialize implicitly loaded DLLs */
622 NE_InitializeDLLs( pTask->hModule );
623 NE_DllProcessAttach( pTask->hModule );
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
633 * 0 (=%bp) is pushed on the stack
635 ptr = stack16_push( sizeof(WORD) );
636 *(WORD *)MapSL(ptr) = 0;
641 if (!pTask->pdb.cmdLine[0]) context->Ebx = 0x80;
644 LPBYTE p = &pTask->pdb.cmdLine[1];
645 while ((*p == ' ') || (*p == '\t')) p++;
646 context->Ebx = 0x80 + (p - pTask->pdb.cmdLine);
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;
656 /***********************************************************************
657 * WaitEvent (KERNEL.30)
659 BOOL16 WINAPI WaitEvent16( HTASK16 hTask )
663 if (!hTask) hTask = GetCurrentTask();
664 pTask = TASK_GetPtr( hTask );
666 if (pTask->flags & TDBF_WIN32)
668 FIXME("called for Win32 thread (%04lx)!\n", GetCurrentThreadId());
672 if (pTask->nEvents > 0)
678 if (pTask->teb == NtCurrentTeb())
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--;
689 else FIXME("for other task %04x cur=%04x\n",pTask->hSelf,GetCurrentTask());
695 /***********************************************************************
696 * PostEvent (KERNEL.31)
698 void WINAPI PostEvent16( HTASK16 hTask )
702 if (!hTask) hTask = GetCurrentTask();
703 if (!(pTask = TASK_GetPtr( hTask ))) return;
705 if (pTask->flags & TDBF_WIN32)
707 FIXME("called for Win32 thread (%04lx)!\n", (DWORD)pTask->teb->ClientId.UniqueThread );
713 if (pTask->nEvents == 1) NtSetEvent( pTask->hEvent, NULL );
717 /***********************************************************************
718 * SetPriority (KERNEL.32)
720 void WINAPI SetPriority16( HTASK16 hTask, INT16 delta )
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;
731 pTask->priority = newpriority + 1;
732 TASK_UnlinkTask( pTask->hSelf );
733 TASK_LinkTask( pTask->hSelf );
738 /***********************************************************************
739 * LockCurrentTask (KERNEL.33)
741 HTASK16 WINAPI LockCurrentTask16( BOOL16 bLock )
743 if (bLock) hLockedTask = GetCurrentTask();
744 else hLockedTask = 0;
749 /***********************************************************************
750 * IsTaskLocked (KERNEL.122)
752 HTASK16 WINAPI IsTaskLocked16(void)
758 /***********************************************************************
759 * OldYield (KERNEL.117)
761 void WINAPI OldYield16(void)
765 ReleaseThunkLock(&count);
766 RestoreThunkLock(count);
769 /***********************************************************************
770 * WIN32_OldYield (KERNEL.447)
772 void WINAPI WIN32_OldYield16(void)
776 ReleaseThunkLock(&count);
777 RestoreThunkLock(count);
780 /***********************************************************************
781 * DirectedYield (KERNEL.150)
783 void WINAPI DirectedYield16( HTASK16 hTask )
788 /***********************************************************************
791 void WINAPI Yield16(void)
793 TDB *pCurTask = TASK_GetCurrent();
795 if (pCurTask && pCurTask->hQueue)
797 HMODULE mod = GetModuleHandleA( "user32.dll" );
800 FARPROC proc = GetProcAddress( mod, "UserYield16" );
811 /***********************************************************************
812 * KERNEL_490 (KERNEL.490)
814 HTASK16 WINAPI KERNEL_490( HTASK16 someTask )
816 if ( !someTask ) return 0;
818 FIXME("(%04x): stub\n", someTask );
822 /***********************************************************************
823 * MakeProcInstance (KERNEL.51)
825 FARPROC16 WINAPI MakeProcInstance16( FARPROC16 func, HANDLE16 hInstance )
829 WORD hInstanceSelector;
831 hInstanceSelector = GlobalHandleToSel16(hInstance);
833 TRACE("(%08lx, %04x);\n", (DWORD)func, hInstance);
836 /* Win95 actually protects via SEH, but this is better for debugging */
837 WARN("Ouch ! Called with invalid func 0x%08lx !\n", (DWORD)func);
841 if ( (GlobalHandleToSel16(CURRENT_DS) != hInstanceSelector)
843 && (hInstance != 0xffff) )
845 /* calling MPI with a foreign DSEG is invalid ! */
846 WARN("Problem with hInstance? Got %04x, using %04x instead\n",
847 hInstance,CURRENT_DS);
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);
857 /* no thunking for DLLs */
858 if (NE_GetPtr(FarGetOwner16(hInstance))->ne_flags & NE_FFLAGS_LIBMODULE)
861 thunkaddr = TASK_AllocThunk();
862 if (!thunkaddr) return (FARPROC16)0;
863 thunk = MapSL( thunkaddr );
864 lfunc = MapSL( (SEGPTR)func );
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 */
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");
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 */
884 /***********************************************************************
885 * FreeProcInstance (KERNEL.52)
887 void WINAPI FreeProcInstance16( FARPROC16 func )
889 TRACE("(%08lx)\n", (DWORD)func );
890 TASK_FreeThunk( (SEGPTR)func );
893 /**********************************************************************
894 * TASK_GetCodeSegment
896 * Helper function for GetCodeHandle/GetCodeInfo: Retrieve the module
897 * and logical segment number of a given code segment.
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.
905 * FIXME: if 'proc' is a SNOOP16 return stub, we should retrieve info about
906 * the function the snoop code will return to ...
909 static BOOL TASK_GetCodeSegment( FARPROC16 proc, NE_MODULE **ppModule,
910 SEGTABLEENTRY **ppSeg, int *pSegNr )
912 NE_MODULE *pModule = NULL;
913 SEGTABLEENTRY *pSeg = NULL;
916 /* Try pair of module handle / segment number */
917 pModule = (NE_MODULE *) GlobalLock16( HIWORD( proc ) );
918 if ( pModule && pModule->ne_magic == IMAGE_OS2_SIGNATURE )
920 segNr = LOWORD( proc );
921 if ( segNr && segNr <= pModule->ne_cseg )
922 pSeg = NE_SEG_TABLE( pModule ) + segNr-1;
925 /* Try thunk or function */
928 BYTE *thunk = MapSL( (SEGPTR)proc );
931 if ((thunk[0] == 0xb8) && (thunk[3] == 0xea))
932 selector = thunk[6] + (thunk[7] << 8);
934 selector = HIWORD( proc );
936 pModule = NE_GetPtr( GlobalHandle16( selector ) );
937 pSeg = pModule? NE_SEG_TABLE( pModule ) : NULL;
940 for ( segNr = 1; segNr <= pModule->ne_cseg; segNr++, pSeg++ )
941 if ( GlobalHandleToSel16(pSeg->hSeg) == selector )
944 if ( pModule && segNr > pModule->ne_cseg )
948 /* Abort if segment not found */
950 if ( !pModule || !pSeg )
953 /* Return segment data */
955 if ( ppModule ) *ppModule = pModule;
956 if ( ppSeg ) *ppSeg = pSeg;
957 if ( pSegNr ) *pSegNr = segNr;
962 /**********************************************************************
963 * GetCodeHandle (KERNEL.93)
965 HANDLE16 WINAPI GetCodeHandle16( FARPROC16 proc )
969 if ( !TASK_GetCodeSegment( proc, NULL, &pSeg, NULL ) )
975 /**********************************************************************
976 * GetCodeInfo (KERNEL.104)
978 BOOL16 WINAPI GetCodeInfo16( FARPROC16 proc, SEGINFO *segInfo )
984 if ( !TASK_GetCodeSegment( proc, &pModule, &pSeg, &segNr ) )
987 /* Fill in segment information */
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->ne_align;
996 if ( segNr == pModule->ne_autodata )
997 segInfo->cbAlloc += pModule->ne_heap + pModule->ne_stack;
999 /* Return module handle in %es */
1001 CURRENT_STACK16->es = GlobalHandleToSel16( pModule->self );
1007 /**********************************************************************
1008 * DefineHandleTable (KERNEL.94)
1010 BOOL16 WINAPI DefineHandleTable16( WORD wOffset )
1012 FIXME("(%04x): stub ?\n", wOffset);
1017 /***********************************************************************
1018 * SetTaskQueue (KERNEL.34)
1020 HQUEUE16 WINAPI SetTaskQueue16( HTASK16 hTask, HQUEUE16 hQueue )
1022 FIXME( "stub, should not get called\n" );
1027 /***********************************************************************
1028 * GetTaskQueue (KERNEL.35)
1030 HQUEUE16 WINAPI GetTaskQueue16( HTASK16 hTask )
1032 FIXME( "stub, should not get called\n" );
1036 /***********************************************************************
1037 * SetThreadQueue (KERNEL.463)
1039 HQUEUE16 WINAPI SetThreadQueue16( DWORD thread, HQUEUE16 hQueue )
1041 FIXME( "stub, should not get called\n" );
1045 /***********************************************************************
1046 * GetThreadQueue (KERNEL.464)
1048 HQUEUE16 WINAPI GetThreadQueue16( DWORD thread )
1050 FIXME( "stub, should not get called\n" );
1054 /***********************************************************************
1055 * SetFastQueue (KERNEL.624)
1057 VOID WINAPI SetFastQueue16( DWORD thread, HQUEUE16 hQueue )
1059 FIXME( "stub, should not get called\n" );
1062 /***********************************************************************
1063 * GetFastQueue (KERNEL.625)
1065 HQUEUE16 WINAPI GetFastQueue16( void )
1067 FIXME( "stub, should not get called\n" );
1071 /***********************************************************************
1072 * SwitchStackTo (KERNEL.108)
1074 void WINAPI SwitchStackTo16( WORD seg, WORD ptr, WORD top )
1076 STACK16FRAME *oldFrame, *newFrame;
1077 INSTANCEDATA *pData;
1080 if (!(pData = (INSTANCEDATA *)GlobalLock16( seg ))) return;
1081 TRACE("old=%04x:%04x new=%04x:%04x\n",
1082 SELECTOROF( NtCurrentTeb()->WOW32Reserved ),
1083 OFFSETOF( NtCurrentTeb()->WOW32Reserved ), seg, ptr );
1085 /* Save the old stack */
1087 oldFrame = CURRENT_STACK16;
1088 /* pop frame + args and push bp */
1089 pData->old_ss_sp = (SEGPTR)NtCurrentTeb()->WOW32Reserved + sizeof(STACK16FRAME)
1091 *(WORD *)MapSL(pData->old_ss_sp) = oldFrame->bp;
1092 pData->stacktop = top;
1093 pData->stackmin = ptr;
1094 pData->stackbottom = ptr;
1096 /* Switch to the new stack */
1098 /* Note: we need to take the 3 arguments into account; otherwise,
1099 * the stack will underflow upon return from this function.
1101 copySize = oldFrame->bp - OFFSETOF(pData->old_ss_sp);
1102 copySize += 3 * sizeof(WORD) + sizeof(STACK16FRAME);
1103 NtCurrentTeb()->WOW32Reserved = (void *)MAKESEGPTR( seg, ptr - copySize );
1104 newFrame = CURRENT_STACK16;
1106 /* Copy the stack frame and the local variables to the new stack */
1108 memmove( newFrame, oldFrame, copySize );
1110 *(WORD *)MapSL( MAKESEGPTR( seg, ptr ) ) = 0; /* clear previous bp */
1114 /***********************************************************************
1115 * SwitchStackBack (KERNEL.109)
1117 void WINAPI SwitchStackBack16( CONTEXT86 *context )
1119 STACK16FRAME *oldFrame, *newFrame;
1120 INSTANCEDATA *pData;
1122 if (!(pData = (INSTANCEDATA *)GlobalLock16(SELECTOROF(NtCurrentTeb()->WOW32Reserved))))
1124 if (!pData->old_ss_sp)
1126 WARN("No previous SwitchStackTo\n" );
1129 TRACE("restoring stack %04x:%04x\n",
1130 SELECTOROF(pData->old_ss_sp), OFFSETOF(pData->old_ss_sp) );
1132 oldFrame = CURRENT_STACK16;
1134 /* Pop bp from the previous stack */
1136 context->Ebp = (context->Ebp & ~0xffff) | *(WORD *)MapSL(pData->old_ss_sp);
1137 pData->old_ss_sp += sizeof(WORD);
1139 /* Switch back to the old stack */
1141 NtCurrentTeb()->WOW32Reserved = (void *)(pData->old_ss_sp - sizeof(STACK16FRAME));
1142 context->SegSs = SELECTOROF(pData->old_ss_sp);
1143 context->Esp = OFFSETOF(pData->old_ss_sp) - sizeof(DWORD); /*ret addr*/
1144 pData->old_ss_sp = 0;
1146 /* Build a stack frame for the return */
1148 newFrame = CURRENT_STACK16;
1149 newFrame->frame32 = oldFrame->frame32;
1150 newFrame->module_cs = oldFrame->module_cs;
1151 newFrame->callfrom_ip = oldFrame->callfrom_ip;
1152 newFrame->entry_ip = oldFrame->entry_ip;
1156 /***********************************************************************
1157 * GetTaskQueueDS (KERNEL.118)
1159 void WINAPI GetTaskQueueDS16(void)
1161 CURRENT_STACK16->ds = GlobalHandleToSel16( GetTaskQueue16(0) );
1165 /***********************************************************************
1166 * GetTaskQueueES (KERNEL.119)
1168 void WINAPI GetTaskQueueES16(void)
1170 CURRENT_STACK16->es = GlobalHandleToSel16( GetTaskQueue16(0) );
1174 /***********************************************************************
1175 * GetCurrentTask (KERNEL32.@)
1177 HTASK16 WINAPI GetCurrentTask(void)
1179 HTASK16 ret = kernel_get_thread_data()->htask16;
1180 if (!ret) ret = main_task;
1184 /***********************************************************************
1185 * GetCurrentTask (KERNEL.36)
1187 DWORD WINAPI WIN16_GetCurrentTask(void)
1189 /* This is the version used by relay code; the first task is */
1190 /* returned in the high word of the result */
1191 return MAKELONG( GetCurrentTask(), hFirstTask );
1195 /***********************************************************************
1196 * GetCurrentPDB (KERNEL.37)
1198 * UNDOC: returns PSP of KERNEL in high word
1200 DWORD WINAPI GetCurrentPDB16(void)
1204 if (!(pTask = TASK_GetCurrent())) return 0;
1205 return MAKELONG(pTask->hPDB, 0); /* FIXME */
1209 /***********************************************************************
1210 * GetCurPID (KERNEL.157)
1212 DWORD WINAPI GetCurPID16( DWORD unused )
1218 /***********************************************************************
1219 * GetInstanceData (KERNEL.54)
1221 INT16 WINAPI GetInstanceData16( HINSTANCE16 instance, WORD buffer, INT16 len )
1223 char *ptr = (char *)GlobalLock16( instance );
1224 if (!ptr || !len) return 0;
1225 if ((int)buffer + len >= 0x10000) len = 0x10000 - buffer;
1226 memcpy( (char *)GlobalLock16(CURRENT_DS) + buffer, ptr + buffer, len );
1231 /***********************************************************************
1232 * GetExeVersion (KERNEL.105)
1234 WORD WINAPI GetExeVersion16(void)
1238 if (!(pTask = TASK_GetCurrent())) return 0;
1239 return pTask->version;
1243 /***********************************************************************
1244 * SetErrorMode (KERNEL.107)
1246 UINT16 WINAPI SetErrorMode16( UINT16 mode )
1249 if (!(pTask = TASK_GetCurrent())) return 0;
1250 pTask->error_mode = mode;
1251 return SetErrorMode( mode );
1255 /***********************************************************************
1256 * GetNumTasks (KERNEL.152)
1258 UINT16 WINAPI GetNumTasks16(void)
1264 /***********************************************************************
1265 * GetTaskDS (KERNEL.155)
1267 * Note: this function apparently returns a DWORD with LOWORD == HIWORD.
1268 * I don't think we need to bother with this.
1270 HINSTANCE16 WINAPI GetTaskDS16(void)
1274 if (!(pTask = TASK_GetCurrent())) return 0;
1275 return GlobalHandleToSel16(pTask->hInstance);
1278 /***********************************************************************
1279 * GetDummyModuleHandleDS (KERNEL.602)
1281 WORD WINAPI GetDummyModuleHandleDS16(void)
1286 if (!(pTask = TASK_GetCurrent())) return 0;
1287 if (!(pTask->flags & TDBF_WIN32)) return 0;
1288 selector = GlobalHandleToSel16( pTask->hModule );
1289 CURRENT_DS = selector;
1293 /***********************************************************************
1294 * IsTask (KERNEL.320)
1296 BOOL16 WINAPI IsTask16( HTASK16 hTask )
1300 if (!(pTask = TASK_GetPtr( hTask ))) return FALSE;
1301 if (GlobalSize16( hTask ) < sizeof(TDB)) return FALSE;
1302 return (pTask->magic == TDB_MAGIC);
1306 /***********************************************************************
1307 * IsWinOldApTask (KERNEL.158)
1309 BOOL16 WINAPI IsWinOldApTask16( HTASK16 hTask )
1311 /* should return bit 0 of byte 0x48 in PSP */
1315 /***********************************************************************
1316 * SetTaskSignalProc (KERNEL.38)
1318 FARPROC16 WINAPI SetTaskSignalProc( HTASK16 hTask, FARPROC16 proc )
1323 if (!hTask) hTask = GetCurrentTask();
1324 if (!(pTask = TASK_GetPtr( hTask ))) return NULL;
1325 oldProc = pTask->userhandler;
1326 pTask->userhandler = proc;
1330 /***********************************************************************
1331 * SetSigHandler (KERNEL.140)
1333 WORD WINAPI SetSigHandler16( FARPROC16 newhandler, FARPROC16* oldhandler,
1334 UINT16 *oldmode, UINT16 newmode, UINT16 flag )
1336 FIXME("(%p,%p,%p,%d,%d), unimplemented.\n",
1337 newhandler,oldhandler,oldmode,newmode,flag );
1339 if (flag != 1) return 0;
1340 if (!newmode) newhandler = NULL; /* Default handler */
1345 if (!(pTask = TASK_GetCurrent())) return 0;
1346 if (oldmode) *oldmode = pTask->signal_flags;
1347 pTask->signal_flags = newmode;
1348 if (oldhandler) *oldhandler = pTask->sighandler;
1349 pTask->sighandler = newhandler;
1355 /***********************************************************************
1356 * GlobalNotify (KERNEL.154)
1358 * Note that GlobalNotify does _not_ return the old NotifyProc
1359 * -- contrary to LocalNotify !!
1361 VOID WINAPI GlobalNotify16( FARPROC16 proc )
1365 if (!(pTask = TASK_GetCurrent())) return;
1366 pTask->discardhandler = proc;
1370 /***********************************************************************
1373 static inline HMODULE16 GetExePtrHelper( HANDLE16 handle, HTASK16 *hTask )
1378 /* Check for module handle */
1380 if (!(ptr = GlobalLock16( handle ))) return 0;
1381 if (((NE_MODULE *)ptr)->ne_magic == IMAGE_OS2_SIGNATURE) return handle;
1383 /* Search for this handle inside all tasks */
1385 *hTask = hFirstTask;
1388 TDB *pTask = TASK_GetPtr( *hTask );
1389 if ((*hTask == handle) ||
1390 (pTask->hInstance == handle) ||
1391 (pTask->hQueue == handle) ||
1392 (pTask->hPDB == handle)) return pTask->hModule;
1393 *hTask = pTask->hNext;
1396 /* Check the owner for module handle */
1398 owner = FarGetOwner16( handle );
1399 if (!(ptr = GlobalLock16( owner ))) return 0;
1400 if (((NE_MODULE *)ptr)->ne_magic == IMAGE_OS2_SIGNATURE) return owner;
1402 /* Search for the owner inside all tasks */
1404 *hTask = hFirstTask;
1407 TDB *pTask = TASK_GetPtr( *hTask );
1408 if ((*hTask == owner) ||
1409 (pTask->hInstance == owner) ||
1410 (pTask->hQueue == owner) ||
1411 (pTask->hPDB == owner)) return pTask->hModule;
1412 *hTask = pTask->hNext;
1418 /***********************************************************************
1419 * GetExePtr (KERNEL.133)
1421 HMODULE16 WINAPI WIN16_GetExePtr( HANDLE16 handle )
1424 HMODULE16 hModule = GetExePtrHelper( handle, &hTask );
1425 STACK16FRAME *frame = CURRENT_STACK16;
1426 frame->ecx = hModule;
1427 if (hTask) frame->es = hTask;
1432 /***********************************************************************
1435 HMODULE16 WINAPI GetExePtr( HANDLE16 handle )
1438 return GetExePtrHelper( handle, &hTask );
1442 /***********************************************************************
1443 * TaskFirst (TOOLHELP.63)
1445 BOOL16 WINAPI TaskFirst16( TASKENTRY *lpte )
1447 lpte->hNext = hFirstTask;
1448 return TaskNext16( lpte );
1452 /***********************************************************************
1453 * TaskNext (TOOLHELP.64)
1455 BOOL16 WINAPI TaskNext16( TASKENTRY *lpte )
1458 INSTANCEDATA *pInstData;
1460 TRACE_(toolhelp)("(%p): task=%04x\n", lpte, lpte->hNext );
1461 if (!lpte->hNext) return FALSE;
1463 /* make sure that task and hInstance are valid (skip initial Wine task !) */
1465 pTask = TASK_GetPtr( lpte->hNext );
1466 if (!pTask || pTask->magic != TDB_MAGIC) return FALSE;
1467 if (pTask->hInstance)
1469 lpte->hNext = pTask->hNext;
1471 pInstData = MapSL( MAKESEGPTR( GlobalHandleToSel16(pTask->hInstance), 0 ) );
1472 lpte->hTask = lpte->hNext;
1473 lpte->hTaskParent = pTask->hParent;
1474 lpte->hInst = pTask->hInstance;
1475 lpte->hModule = pTask->hModule;
1476 lpte->wSS = SELECTOROF( pTask->teb->WOW32Reserved );
1477 lpte->wSP = OFFSETOF( pTask->teb->WOW32Reserved );
1478 lpte->wStackTop = pInstData->stacktop;
1479 lpte->wStackMinimum = pInstData->stackmin;
1480 lpte->wStackBottom = pInstData->stackbottom;
1481 lpte->wcEvents = pTask->nEvents;
1482 lpte->hQueue = pTask->hQueue;
1483 lstrcpynA( lpte->szModule, pTask->module_name, sizeof(lpte->szModule) );
1484 lpte->wPSPOffset = 0x100; /*??*/
1485 lpte->hNext = pTask->hNext;
1490 /***********************************************************************
1491 * TaskFindHandle (TOOLHELP.65)
1493 BOOL16 WINAPI TaskFindHandle16( TASKENTRY *lpte, HTASK16 hTask )
1495 lpte->hNext = hTask;
1496 return TaskNext16( lpte );
1500 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND hWnd, LPCSTR text, LPCSTR title, UINT type);
1502 /**************************************************************************
1503 * FatalAppExit (KERNEL.137)
1505 void WINAPI FatalAppExit16( UINT16 action, LPCSTR str )
1507 TDB *pTask = TASK_GetCurrent();
1509 if (!pTask || !(pTask->error_mode & SEM_NOGPFAULTERRORBOX))
1511 HMODULE mod = GetModuleHandleA( "user32.dll" );
1514 MessageBoxA_funcptr pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
1517 pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
1521 ERR( "%s\n", debugstr_a(str) );
1528 /***********************************************************************
1529 * TerminateApp (TOOLHELP.77)
1531 * See "Undocumented Windows".
1533 void WINAPI TerminateApp16(HTASK16 hTask, WORD wFlags)
1535 if (hTask && hTask != GetCurrentTask())
1537 FIXME("cannot terminate task %x\n", hTask);
1541 if (wFlags & NO_UAE_BOX)
1544 old_mode = SetErrorMode16(0);
1545 SetErrorMode16(old_mode|SEM_NOGPFAULTERRORBOX);
1547 FatalAppExit16( 0, NULL );
1549 /* hmm, we're still alive ?? */
1551 /* check undocumented flag */
1552 if (!(wFlags & 0x8000))
1553 TASK_CallTaskSignalProc( USIG16_TERMINATION, hTask );
1555 /* UndocWin says to call int 0x21/0x4c exit=0xff here,
1556 but let's just call ExitThread */
1561 /***********************************************************************
1562 * GetAppCompatFlags (KERNEL.354)
1564 DWORD WINAPI GetAppCompatFlags16( HTASK16 hTask )
1568 if (!hTask) hTask = GetCurrentTask();
1569 if (!(pTask=TASK_GetPtr( hTask ))) return 0;
1570 if (GlobalSize16(hTask) < sizeof(TDB)) return 0;
1571 return pTask->compat_flags;
1575 /***********************************************************************
1576 * GetDOSEnvironment (KERNEL.131)
1578 * Note: the environment is allocated once, it doesn't track changes
1579 * made using the Win32 API. This shouldn't matter.
1581 * Format of a 16-bit environment block:
1582 * ASCIIZ string 1 (xx=yy format)
1587 * ASCIIZ program name (e.g. C:\WINDOWS\SYSTEM\KRNL386.EXE)
1589 SEGPTR WINAPI GetDOSEnvironment16(void)
1591 static const char ENV_program_name[] = "C:\\WINDOWS\\SYSTEM\\KRNL386.EXE";
1592 static HGLOBAL16 handle; /* handle to the 16 bit environment */
1599 p = env = GetEnvironmentStringsA();
1600 while (*p) p += strlen(p) + 1;
1601 p++; /* skip last null */
1602 size = (p - env) + sizeof(WORD) + sizeof(ENV_program_name);
1603 handle = GlobalAlloc16( GMEM_FIXED, size );
1607 LPSTR env16 = GlobalLock16( handle );
1608 memcpy( env16, env, p - env );
1609 memcpy( env16 + (p - env), &one, sizeof(one));
1610 memcpy( env16 + (p - env) + sizeof(WORD), ENV_program_name, sizeof(ENV_program_name));
1611 GlobalUnlock16( handle );
1613 FreeEnvironmentStringsA( env );
1615 return K32WOWGlobalLock16( handle );