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(toolhelp);
54 /* Segment containing MakeProcInstance() thunks */
57 WORD next; /* Selector of next segment */
58 WORD magic; /* Thunks signature */
60 WORD free; /* Head of the free list */
61 WORD thunks[4]; /* Each thunk is 4 words long */
66 #define THUNK_MAGIC ('P' | ('T' << 8))
68 /* Min. number of thunks allocated when creating a new segment */
71 #define TDB_MAGIC ('T' | ('D' << 8))
73 static THHOOK DefaultThhook;
74 THHOOK *pThhook = &DefaultThhook;
76 #define hFirstTask (pThhook->HeadTDB)
77 #define hLockedTask (pThhook->LockTDB)
79 static UINT16 nTaskCount = 0;
81 static HTASK16 initial_task, main_task;
83 /***********************************************************************
86 void TASK_InstallTHHook( THHOOK *pNewThhook )
88 THHOOK *pOldThhook = pThhook;
90 pThhook = pNewThhook? pNewThhook : &DefaultThhook;
92 *pThhook = *pOldThhook;
95 /***********************************************************************
98 static TDB *TASK_GetPtr( HTASK16 hTask )
100 return GlobalLock16( hTask );
104 /***********************************************************************
107 TDB *TASK_GetCurrent(void)
109 return TASK_GetPtr( GetCurrentTask() );
113 /***********************************************************************
116 static void TASK_LinkTask( HTASK16 hTask )
121 if (!(pTask = TASK_GetPtr( hTask ))) return;
122 prevTask = &hFirstTask;
125 TDB *prevTaskPtr = TASK_GetPtr( *prevTask );
126 if (prevTaskPtr->priority >= pTask->priority) break;
127 prevTask = &prevTaskPtr->hNext;
129 pTask->hNext = *prevTask;
135 /***********************************************************************
138 static void TASK_UnlinkTask( HTASK16 hTask )
143 prevTask = &hFirstTask;
144 while (*prevTask && (*prevTask != hTask))
146 pTask = TASK_GetPtr( *prevTask );
147 prevTask = &pTask->hNext;
151 pTask = TASK_GetPtr( *prevTask );
152 *prevTask = pTask->hNext;
159 /***********************************************************************
162 * Create a thunk free-list in segment 'handle', starting from offset 'offset'
163 * and containing 'count' entries.
165 static void TASK_CreateThunks( HGLOBAL16 handle, WORD offset, WORD count )
171 pThunk = (THUNKS *)((BYTE *)GlobalLock16( handle ) + offset);
173 pThunk->magic = THUNK_MAGIC;
174 pThunk->free = (int)&pThunk->thunks - (int)pThunk;
176 for (i = 0; i < count-1; i++)
178 free += 8; /* Offset of next thunk */
179 pThunk->thunks[4*i] = free;
181 pThunk->thunks[4*i] = 0; /* Last thunk */
185 /***********************************************************************
188 * Allocate a thunk for MakeProcInstance().
190 static SEGPTR TASK_AllocThunk(void)
196 if (!(pTask = TASK_GetCurrent())) return 0;
197 sel = pTask->hCSAlias;
198 pThunk = (THUNKS *)&pTask->thunks;
199 base = (char *)pThunk - (char *)pTask;
200 while (!pThunk->free)
203 if (!sel) /* Allocate a new segment */
205 sel = GLOBAL_Alloc( GMEM_FIXED, sizeof(THUNKS) + (MIN_THUNKS-1)*8,
206 pTask->hPDB, WINE_LDT_FLAGS_CODE );
207 if (!sel) return (SEGPTR)0;
208 TASK_CreateThunks( sel, 0, MIN_THUNKS );
211 pThunk = (THUNKS *)GlobalLock16( sel );
214 base += pThunk->free;
215 pThunk->free = *(WORD *)((BYTE *)pThunk + pThunk->free);
216 return MAKESEGPTR( sel, base );
220 /***********************************************************************
223 * Free a MakeProcInstance() thunk.
225 static BOOL TASK_FreeThunk( SEGPTR thunk )
231 if (!(pTask = TASK_GetCurrent())) return 0;
232 sel = pTask->hCSAlias;
233 pThunk = (THUNKS *)&pTask->thunks;
234 base = (char *)pThunk - (char *)pTask;
235 while (sel && (sel != HIWORD(thunk)))
238 pThunk = (THUNKS *)GlobalLock16( sel );
241 if (!sel) return FALSE;
242 *(WORD *)((BYTE *)pThunk + LOWORD(thunk) - base) = pThunk->free;
243 pThunk->free = LOWORD(thunk) - base;
248 /***********************************************************************
251 * NOTE: This routine might be called by a Win32 thread. Thus, we need
252 * to be careful to protect global data structures. We do this
253 * by entering the Win16Lock while linking the task into the
256 static TDB *TASK_Create( NE_MODULE *pModule, UINT16 cmdShow, LPCSTR cmdline, BYTE len )
261 char curdir[MAX_PATH];
262 HMODULE16 hModule = pModule ? pModule->self : 0;
264 /* Allocate the task structure */
266 hTask = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, sizeof(TDB) );
267 if (!hTask) return NULL;
268 pTask = TASK_GetPtr( hTask );
269 FarSetOwner16( hTask, hModule );
271 /* Fill the task structure */
273 pTask->hSelf = hTask;
275 pTask->version = pModule ? pModule->ne_expver : 0x0400;
276 pTask->hModule = hModule;
277 pTask->hParent = GetCurrentTask();
278 pTask->magic = TDB_MAGIC;
279 pTask->nCmdShow = cmdShow;
281 GetCurrentDirectoryA( sizeof(curdir), curdir );
282 GetShortPathNameA( curdir, curdir, sizeof(curdir) );
283 pTask->curdrive = (curdir[0] - 'A') | 0x80;
284 lstrcpynA( pTask->curdir, curdir + 2, sizeof(pTask->curdir) );
286 /* Create the thunks block */
288 TASK_CreateThunks( hTask, (char *)&pTask->thunks - (char *)pTask, 7 );
290 /* Copy the module name */
294 char name[sizeof(pTask->module_name)+1];
296 GetModuleName16( hModule, name, sizeof(name) );
297 len = strlen(name) + 1;
298 memcpy(pTask->module_name, name, min(len,sizeof(pTask->module_name)));
299 pTask->compat_flags = GetProfileIntA( "Compatibility", name, 0 );
302 /* Allocate a selector for the PDB */
304 pTask->hPDB = GLOBAL_CreateBlock( GMEM_FIXED, &pTask->pdb, sizeof(PDB16),
305 hModule, WINE_LDT_FLAGS_DATA );
309 pTask->pdb.int20 = 0x20cd;
310 pTask->pdb.dispatcher[0] = 0x9a; /* ljmp */
311 proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DOS3Call" );
312 memcpy( &pTask->pdb.dispatcher[1], &proc, sizeof(proc) );
313 pTask->pdb.savedint22 = 0;
314 pTask->pdb.savedint23 = 0;
315 pTask->pdb.savedint24 = 0;
316 pTask->pdb.fileHandlesPtr =
317 MAKESEGPTR( GlobalHandleToSel16(pTask->hPDB), (int)&((PDB16 *)0)->fileHandles );
318 pTask->pdb.hFileHandles = 0;
319 memset( pTask->pdb.fileHandles, 0xff, sizeof(pTask->pdb.fileHandles) );
320 /* FIXME: should we make a copy of the environment? */
321 pTask->pdb.environment = SELECTOROF(GetDOSEnvironment16());
322 pTask->pdb.nbFiles = 20;
324 /* Fill the command line */
328 cmdline = GetCommandLineA();
329 /* remove the first word (program name) */
331 if (!(cmdline = strchr( cmdline+1, '"' ))) cmdline = GetCommandLineA();
332 while (*cmdline && (*cmdline != ' ') && (*cmdline != '\t')) cmdline++;
333 while ((*cmdline == ' ') || (*cmdline == '\t')) cmdline++;
334 len = strlen(cmdline);
336 if (len >= sizeof(pTask->pdb.cmdLine)) len = sizeof(pTask->pdb.cmdLine)-1;
337 pTask->pdb.cmdLine[0] = len;
338 memcpy( pTask->pdb.cmdLine + 1, cmdline, len );
339 /* pTask->pdb.cmdLine[len+1] = 0; */
341 TRACE("cmdline='%.*s' task=%04x\n", len, cmdline, hTask );
343 /* Allocate a code segment alias for the TDB */
345 pTask->hCSAlias = GLOBAL_CreateBlock( GMEM_FIXED, (void *)pTask,
346 sizeof(TDB), pTask->hPDB, WINE_LDT_FLAGS_CODE );
348 /* Default DTA overwrites command line */
350 pTask->dta = MAKESEGPTR( pTask->hPDB, (int)&pTask->pdb.cmdLine - (int)&pTask->pdb );
352 /* Create scheduler event for 16-bit tasks */
354 if ( !(pTask->flags & TDBF_WIN32) )
355 NtCreateEvent( &pTask->hEvent, EVENT_ALL_ACCESS, NULL, TRUE, FALSE );
357 if (!initial_task) initial_task = hTask;
363 /***********************************************************************
366 static void TASK_DeleteTask( HTASK16 hTask )
371 if (!(pTask = TASK_GetPtr( hTask ))) return;
374 pTask->magic = 0xdead; /* invalidate signature */
376 /* Free the selector aliases */
378 GLOBAL_FreeBlock( pTask->hCSAlias );
379 GLOBAL_FreeBlock( pTask->hPDB );
381 /* Free the task module */
383 FreeModule16( pTask->hModule );
385 /* Free the task structure itself */
387 GlobalFree16( hTask );
389 /* Free all memory used by this task (including the 32-bit stack, */
390 /* the environment block and the thunk segments). */
392 GlobalFreeAll16( hPDB );
396 /***********************************************************************
397 * TASK_CreateMainTask
399 * Create a task for the main (32-bit) process.
401 void TASK_CreateMainTask(void)
404 STARTUPINFOA startup_info;
405 UINT cmdShow = 1; /* SW_SHOWNORMAL but we don't want to include winuser.h here */
407 GetStartupInfoA( &startup_info );
408 if (startup_info.dwFlags & STARTF_USESHOWWINDOW) cmdShow = startup_info.wShowWindow;
409 pTask = TASK_Create( NULL, cmdShow, NULL, 0 );
412 ERR("could not create task for main process\n");
416 pTask->flags |= TDBF_WIN32;
417 pTask->hInstance = 0;
418 pTask->hPrevInstance = 0;
419 pTask->teb = NtCurrentTeb();
421 /* Add the task to the linked list */
422 /* (no need to get the win16 lock, we are the only thread at this point) */
423 TASK_LinkTask( pTask->hSelf );
424 main_task = pTask->hSelf;
431 WIN16_SUBSYSTEM_TIB *tib;
434 /* allocate the win16 TIB for a new 16-bit task */
435 static WIN16_SUBSYSTEM_TIB *allocate_win16_tib( TDB *pTask )
437 WCHAR path[MAX_PATH];
438 WIN16_SUBSYSTEM_TIB *tib;
439 UNICODE_STRING *curdir;
440 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
442 if (!(tib = HeapAlloc( GetProcessHeap(), 0, sizeof(*tib) ))) return NULL;
443 MultiByteToWideChar( CP_ACP, 0, NE_MODULE_NAME(pModule), -1, path, MAX_PATH );
444 GetLongPathNameW( path, path, MAX_PATH );
445 if (RtlCreateUnicodeString( &tib->exe_str, path )) tib->exe_name = &tib->exe_str;
446 else tib->exe_name = NULL;
449 if (NtCurrentTeb()->Tib.SubSystemTib)
450 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
452 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
453 tib->curdir.DosPath.MaximumLength = sizeof(tib->curdir_buffer);
454 tib->curdir.DosPath.Length = min( curdir->Length, tib->curdir.DosPath.MaximumLength-sizeof(WCHAR) );
455 tib->curdir.DosPath.Buffer = tib->curdir_buffer;
456 tib->curdir.Handle = 0;
457 memcpy( tib->curdir_buffer, curdir->Buffer, tib->curdir.DosPath.Length );
458 tib->curdir_buffer[tib->curdir.DosPath.Length/sizeof(WCHAR)] = 0;
463 static inline void free_win16_tib( WIN16_SUBSYSTEM_TIB *tib )
465 if (tib->exe_name) RtlFreeUnicodeString( tib->exe_name );
466 HeapFree( GetProcessHeap(), 0, tib );
469 /* startup routine for a new 16-bit thread */
470 static DWORD CALLBACK task_start( LPVOID p )
472 struct create_data *data = p;
473 TDB *pTask = data->task;
476 kernel_get_thread_data()->htask16 = pTask->hSelf;
477 NtCurrentTeb()->Tib.SubSystemTib = data->tib;
478 HeapFree( GetProcessHeap(), 0, data );
481 TASK_LinkTask( pTask->hSelf );
482 pTask->teb = NtCurrentTeb();
483 ret = NE_StartTask();
489 /***********************************************************************
492 * Spawn a new 16-bit task.
494 HTASK16 TASK_SpawnTask( NE_MODULE *pModule, WORD cmdShow,
495 LPCSTR cmdline, BYTE len, HANDLE *hThread )
497 struct create_data *data = NULL;
498 WIN16_SUBSYSTEM_TIB *tib;
501 if (!(pTask = TASK_Create( pModule, cmdShow, cmdline, len ))) return 0;
502 if (!(tib = allocate_win16_tib( pTask ))) goto failed;
503 if (!(data = HeapAlloc( GetProcessHeap(), 0, sizeof(*data)))) goto failed;
506 if (!(*hThread = CreateThread( NULL, 0, task_start, data, 0, NULL ))) goto failed;
510 if (tib) free_win16_tib( tib );
511 HeapFree( GetProcessHeap(), 0, data );
512 TASK_DeleteTask( pTask->hSelf );
517 /***********************************************************************
518 * TASK_GetTaskFromThread
520 HTASK16 TASK_GetTaskFromThread( DWORD thread )
522 TDB *p = TASK_GetPtr( hFirstTask );
525 if (p->teb->ClientId.UniqueThread == (HANDLE)thread) return p->hSelf;
526 p = TASK_GetPtr( p->hNext );
532 /***********************************************************************
533 * TASK_CallTaskSignalProc
535 static void TASK_CallTaskSignalProc( UINT16 uCode, HANDLE16 hTaskOrModule )
538 TDB *pTask = TASK_GetCurrent();
540 if ( !pTask || !pTask->userhandler ) return;
542 args[4] = hTaskOrModule;
545 args[1] = pTask->hInstance;
546 args[0] = pTask->hQueue;
547 WOWCallback16Ex( (DWORD)pTask->userhandler, WCB16_PASCAL, sizeof(args), args, NULL );
551 /***********************************************************************
554 void TASK_ExitTask(void)
556 WIN16_SUBSYSTEM_TIB *tib;
560 /* Enter the Win16Lock to protect global data structures */
563 pTask = TASK_GetCurrent();
570 TRACE("Killing task %04x\n", pTask->hSelf );
572 /* Perform USER cleanup */
574 TASK_CallTaskSignalProc( USIG16_TERMINATION, pTask->hSelf );
576 /* Remove the task from the list to be sure we never switch back to it */
577 TASK_UnlinkTask( pTask->hSelf );
579 if (!nTaskCount || (nTaskCount == 1 && hFirstTask == initial_task))
581 TRACE("this is the last task, exiting\n" );
587 if ( hLockedTask == pTask->hSelf )
590 TASK_DeleteTask( pTask->hSelf );
592 if ((tib = NtCurrentTeb()->Tib.SubSystemTib))
594 free_win16_tib( tib );
595 NtCurrentTeb()->Tib.SubSystemTib = NULL;
598 /* ... and completely release the Win16Lock, just in case. */
599 ReleaseThunkLock( &lockCount );
603 /***********************************************************************
604 * ExitKernel (KERNEL.2)
606 * Clean-up everything and exit the Wine process.
608 void WINAPI ExitKernel16(void)
610 WriteOutProfiles16();
611 TerminateProcess( GetCurrentProcess(), 0 );
615 /***********************************************************************
616 * InitTask (KERNEL.91)
618 * Called by the application startup code.
620 void WINAPI InitTask16( CONTEXT86 *context )
623 INSTANCEDATA *pinstance;
627 if (!(pTask = TASK_GetCurrent())) return;
629 /* Note: we need to trust that BX/CX contain the stack/heap sizes,
630 as some apps, notably Visual Basic apps, *modify* the heap/stack
631 size of the instance data segment before calling InitTask() */
633 /* Initialize the INSTANCEDATA structure */
634 pinstance = MapSL( MAKESEGPTR(CURRENT_DS, 0) );
635 pinstance->stackmin = OFFSETOF(NtCurrentTeb()->WOW32Reserved) + sizeof( STACK16FRAME );
636 pinstance->stackbottom = pinstance->stackmin; /* yup, that's right. Confused me too. */
637 pinstance->stacktop = ( pinstance->stackmin > LOWORD(context->Ebx) ?
638 pinstance->stackmin - LOWORD(context->Ebx) : 0 ) + 150;
640 /* Initialize the local heap */
641 if (LOWORD(context->Ecx))
642 LocalInit16( GlobalHandleToSel16(pTask->hInstance), 0, LOWORD(context->Ecx) );
644 /* Initialize implicitly loaded DLLs */
645 NE_InitializeDLLs( pTask->hModule );
646 NE_DllProcessAttach( pTask->hModule );
648 /* Registers on return are:
649 * ax 1 if OK, 0 on error
650 * cx stack limit in bytes
651 * dx cmdShow parameter
652 * si instance handle of the previous instance
653 * di instance handle of the new task
654 * es:bx pointer to command line inside PSP
656 * 0 (=%bp) is pushed on the stack
658 ptr = stack16_push( sizeof(WORD) );
659 *(WORD *)MapSL(ptr) = 0;
664 if (!pTask->pdb.cmdLine[0]) context->Ebx = 0x80;
667 LPBYTE p = &pTask->pdb.cmdLine[1];
668 while ((*p == ' ') || (*p == '\t')) p++;
669 context->Ebx = 0x80 + (p - pTask->pdb.cmdLine);
671 context->Ecx = pinstance->stacktop;
672 context->Edx = pTask->nCmdShow;
673 context->Esi = (DWORD)pTask->hPrevInstance;
674 context->Edi = (DWORD)pTask->hInstance;
675 context->SegEs = (WORD)pTask->hPDB;
679 /***********************************************************************
680 * WaitEvent (KERNEL.30)
682 BOOL16 WINAPI WaitEvent16( HTASK16 hTask )
686 if (!hTask) hTask = GetCurrentTask();
687 pTask = TASK_GetPtr( hTask );
689 if (pTask->flags & TDBF_WIN32)
691 FIXME("called for Win32 thread (%04lx)!\n", GetCurrentThreadId());
695 if (pTask->nEvents > 0)
701 if (pTask->teb == NtCurrentTeb())
705 NtResetEvent( pTask->hEvent, NULL );
706 ReleaseThunkLock( &lockCount );
707 SYSLEVEL_CheckNotLevel( 1 );
708 WaitForSingleObject( pTask->hEvent, INFINITE );
709 RestoreThunkLock( lockCount );
710 if (pTask->nEvents > 0) pTask->nEvents--;
712 else FIXME("for other task %04x cur=%04x\n",pTask->hSelf,GetCurrentTask());
718 /***********************************************************************
719 * PostEvent (KERNEL.31)
721 void WINAPI PostEvent16( HTASK16 hTask )
725 if (!hTask) hTask = GetCurrentTask();
726 if (!(pTask = TASK_GetPtr( hTask ))) return;
728 if (pTask->flags & TDBF_WIN32)
730 FIXME("called for Win32 thread (%04lx)!\n", (DWORD)pTask->teb->ClientId.UniqueThread );
736 if (pTask->nEvents == 1) NtSetEvent( pTask->hEvent, NULL );
740 /***********************************************************************
741 * SetPriority (KERNEL.32)
743 void WINAPI SetPriority16( HTASK16 hTask, INT16 delta )
748 if (!hTask) hTask = GetCurrentTask();
749 if (!(pTask = TASK_GetPtr( hTask ))) return;
750 newpriority = pTask->priority + delta;
751 if (newpriority < -32) newpriority = -32;
752 else if (newpriority > 15) newpriority = 15;
754 pTask->priority = newpriority + 1;
755 TASK_UnlinkTask( pTask->hSelf );
756 TASK_LinkTask( pTask->hSelf );
761 /***********************************************************************
762 * LockCurrentTask (KERNEL.33)
764 HTASK16 WINAPI LockCurrentTask16( BOOL16 bLock )
766 if (bLock) hLockedTask = GetCurrentTask();
767 else hLockedTask = 0;
772 /***********************************************************************
773 * IsTaskLocked (KERNEL.122)
775 HTASK16 WINAPI IsTaskLocked16(void)
781 /***********************************************************************
782 * OldYield (KERNEL.117)
784 void WINAPI OldYield16(void)
788 ReleaseThunkLock(&count);
789 RestoreThunkLock(count);
792 /***********************************************************************
793 * WIN32_OldYield (KERNEL.447)
795 void WINAPI WIN32_OldYield16(void)
799 ReleaseThunkLock(&count);
800 RestoreThunkLock(count);
803 /***********************************************************************
804 * DirectedYield (KERNEL.150)
806 void WINAPI DirectedYield16( HTASK16 hTask )
811 /***********************************************************************
814 void WINAPI Yield16(void)
816 TDB *pCurTask = TASK_GetCurrent();
818 if (pCurTask && pCurTask->hQueue)
820 HMODULE mod = GetModuleHandleA( "user32.dll" );
823 FARPROC proc = GetProcAddress( mod, "UserYield16" );
834 /***********************************************************************
835 * KERNEL_490 (KERNEL.490)
837 HTASK16 WINAPI KERNEL_490( HTASK16 someTask )
839 if ( !someTask ) return 0;
841 FIXME("(%04x): stub\n", someTask );
845 /***********************************************************************
846 * MakeProcInstance (KERNEL.51)
848 FARPROC16 WINAPI MakeProcInstance16( FARPROC16 func, HANDLE16 hInstance )
852 WORD hInstanceSelector;
854 hInstanceSelector = GlobalHandleToSel16(hInstance);
856 TRACE("(%p, %04x);\n", func, hInstance);
859 /* Win95 actually protects via SEH, but this is better for debugging */
860 WARN("Ouch ! Called with invalid func %p !\n", func);
864 if ( (GlobalHandleToSel16(CURRENT_DS) != hInstanceSelector)
866 && (hInstance != 0xffff) )
868 /* calling MPI with a foreign DSEG is invalid ! */
869 WARN("Problem with hInstance? Got %04x, using %04x instead\n",
870 hInstance,CURRENT_DS);
873 /* Always use the DSEG that MPI was entered with.
874 * We used to set hInstance to GetTaskDS16(), but this should be wrong
875 * as CURRENT_DS provides the DSEG value we need.
876 * ("calling" DS, *not* "task" DS !) */
877 hInstanceSelector = CURRENT_DS;
878 hInstance = GlobalHandle16(hInstanceSelector);
880 /* no thunking for DLLs */
881 if (NE_GetPtr(FarGetOwner16(hInstance))->ne_flags & NE_FFLAGS_LIBMODULE)
884 thunkaddr = TASK_AllocThunk();
885 if (!thunkaddr) return (FARPROC16)0;
886 thunk = MapSL( thunkaddr );
887 lfunc = MapSL( (SEGPTR)func );
889 TRACE("(%p,%04x): got thunk %08lx\n", func, hInstance, thunkaddr );
890 if (((lfunc[0]==0x8c) && (lfunc[1]==0xd8)) || /* movw %ds, %ax */
891 ((lfunc[0]==0x1e) && (lfunc[1]==0x58)) /* pushw %ds, popw %ax */
893 WARN("This was the (in)famous \"thunk useless\" warning. We thought we have to overwrite with nop;nop;, but this isn't true.\n");
896 *thunk++ = 0xb8; /* movw instance, %ax */
897 *thunk++ = (BYTE)(hInstanceSelector & 0xff);
898 *thunk++ = (BYTE)(hInstanceSelector >> 8);
899 *thunk++ = 0xea; /* ljmp func */
900 *(DWORD *)thunk = (DWORD)func;
901 return (FARPROC16)thunkaddr;
902 /* CX reg indicates if thunkaddr != NULL, implement if needed */
906 /***********************************************************************
907 * FreeProcInstance (KERNEL.52)
909 void WINAPI FreeProcInstance16( FARPROC16 func )
911 TRACE("(%p)\n", func );
912 TASK_FreeThunk( (SEGPTR)func );
915 /**********************************************************************
916 * TASK_GetCodeSegment
918 * Helper function for GetCodeHandle/GetCodeInfo: Retrieve the module
919 * and logical segment number of a given code segment.
921 * 'proc' either *is* already a pair of module handle and segment number,
922 * in which case there's nothing to do. Otherwise, it is a pointer to
923 * a function, and we need to retrieve the code segment. If the pointer
924 * happens to point to a thunk, we'll retrieve info about the code segment
925 * where the function pointed to by the thunk resides, not the thunk itself.
927 * FIXME: if 'proc' is a SNOOP16 return stub, we should retrieve info about
928 * the function the snoop code will return to ...
931 static BOOL TASK_GetCodeSegment( FARPROC16 proc, NE_MODULE **ppModule,
932 SEGTABLEENTRY **ppSeg, int *pSegNr )
934 NE_MODULE *pModule = NULL;
935 SEGTABLEENTRY *pSeg = NULL;
938 /* Try pair of module handle / segment number */
939 pModule = (NE_MODULE *) GlobalLock16( HIWORD( proc ) );
940 if ( pModule && pModule->ne_magic == IMAGE_OS2_SIGNATURE )
942 segNr = LOWORD( proc );
943 if ( segNr && segNr <= pModule->ne_cseg )
944 pSeg = NE_SEG_TABLE( pModule ) + segNr-1;
947 /* Try thunk or function */
950 BYTE *thunk = MapSL( (SEGPTR)proc );
953 if ((thunk[0] == 0xb8) && (thunk[3] == 0xea))
954 selector = thunk[6] + (thunk[7] << 8);
956 selector = HIWORD( proc );
958 pModule = NE_GetPtr( GlobalHandle16( selector ) );
959 pSeg = pModule? NE_SEG_TABLE( pModule ) : NULL;
962 for ( segNr = 1; segNr <= pModule->ne_cseg; segNr++, pSeg++ )
963 if ( GlobalHandleToSel16(pSeg->hSeg) == selector )
966 if ( pModule && segNr > pModule->ne_cseg )
970 /* Abort if segment not found */
972 if ( !pModule || !pSeg )
975 /* Return segment data */
977 if ( ppModule ) *ppModule = pModule;
978 if ( ppSeg ) *ppSeg = pSeg;
979 if ( pSegNr ) *pSegNr = segNr;
984 /**********************************************************************
985 * GetCodeHandle (KERNEL.93)
987 HANDLE16 WINAPI GetCodeHandle16( FARPROC16 proc )
991 if ( !TASK_GetCodeSegment( proc, NULL, &pSeg, NULL ) )
997 /**********************************************************************
998 * GetCodeInfo (KERNEL.104)
1000 BOOL16 WINAPI GetCodeInfo16( FARPROC16 proc, SEGINFO *segInfo )
1003 SEGTABLEENTRY *pSeg;
1006 if ( !TASK_GetCodeSegment( proc, &pModule, &pSeg, &segNr ) )
1009 /* Fill in segment information */
1011 segInfo->offSegment = pSeg->filepos;
1012 segInfo->cbSegment = pSeg->size;
1013 segInfo->flags = pSeg->flags;
1014 segInfo->cbAlloc = pSeg->minsize;
1015 segInfo->h = pSeg->hSeg;
1016 segInfo->alignShift = pModule->ne_align;
1018 if ( segNr == pModule->ne_autodata )
1019 segInfo->cbAlloc += pModule->ne_heap + pModule->ne_stack;
1021 /* Return module handle in %es */
1023 CURRENT_STACK16->es = GlobalHandleToSel16( pModule->self );
1029 /**********************************************************************
1030 * DefineHandleTable (KERNEL.94)
1032 BOOL16 WINAPI DefineHandleTable16( WORD wOffset )
1034 FIXME("(%04x): stub ?\n", wOffset);
1039 /***********************************************************************
1040 * SetTaskQueue (KERNEL.34)
1042 HQUEUE16 WINAPI SetTaskQueue16( HTASK16 hTask, HQUEUE16 hQueue )
1044 FIXME( "stub, should not get called\n" );
1049 /***********************************************************************
1050 * GetTaskQueue (KERNEL.35)
1052 HQUEUE16 WINAPI GetTaskQueue16( HTASK16 hTask )
1054 FIXME( "stub, should not get called\n" );
1058 /***********************************************************************
1059 * SetThreadQueue (KERNEL.463)
1061 HQUEUE16 WINAPI SetThreadQueue16( DWORD thread, HQUEUE16 hQueue )
1063 FIXME( "stub, should not get called\n" );
1067 /***********************************************************************
1068 * GetThreadQueue (KERNEL.464)
1070 HQUEUE16 WINAPI GetThreadQueue16( DWORD thread )
1072 FIXME( "stub, should not get called\n" );
1076 /***********************************************************************
1077 * SetFastQueue (KERNEL.624)
1079 VOID WINAPI SetFastQueue16( DWORD thread, HQUEUE16 hQueue )
1081 FIXME( "stub, should not get called\n" );
1084 /***********************************************************************
1085 * GetFastQueue (KERNEL.625)
1087 HQUEUE16 WINAPI GetFastQueue16( void )
1089 FIXME( "stub, should not get called\n" );
1093 /***********************************************************************
1094 * SwitchStackTo (KERNEL.108)
1096 void WINAPI SwitchStackTo16( WORD seg, WORD ptr, WORD top )
1098 STACK16FRAME *oldFrame, *newFrame;
1099 INSTANCEDATA *pData;
1102 if (!(pData = (INSTANCEDATA *)GlobalLock16( seg ))) return;
1103 TRACE("old=%04x:%04x new=%04x:%04x\n",
1104 SELECTOROF( NtCurrentTeb()->WOW32Reserved ),
1105 OFFSETOF( NtCurrentTeb()->WOW32Reserved ), seg, ptr );
1107 /* Save the old stack */
1109 oldFrame = CURRENT_STACK16;
1110 /* pop frame + args and push bp */
1111 pData->old_ss_sp = (SEGPTR)NtCurrentTeb()->WOW32Reserved + sizeof(STACK16FRAME)
1113 *(WORD *)MapSL(pData->old_ss_sp) = oldFrame->bp;
1114 pData->stacktop = top;
1115 pData->stackmin = ptr;
1116 pData->stackbottom = ptr;
1118 /* Switch to the new stack */
1120 /* Note: we need to take the 3 arguments into account; otherwise,
1121 * the stack will underflow upon return from this function.
1123 copySize = oldFrame->bp - OFFSETOF(pData->old_ss_sp);
1124 copySize += 3 * sizeof(WORD) + sizeof(STACK16FRAME);
1125 NtCurrentTeb()->WOW32Reserved = (void *)MAKESEGPTR( seg, ptr - copySize );
1126 newFrame = CURRENT_STACK16;
1128 /* Copy the stack frame and the local variables to the new stack */
1130 memmove( newFrame, oldFrame, copySize );
1132 *(WORD *)MapSL( MAKESEGPTR( seg, ptr ) ) = 0; /* clear previous bp */
1136 /***********************************************************************
1137 * SwitchStackBack (KERNEL.109)
1139 void WINAPI SwitchStackBack16( CONTEXT86 *context )
1141 STACK16FRAME *oldFrame, *newFrame;
1142 INSTANCEDATA *pData;
1144 if (!(pData = (INSTANCEDATA *)GlobalLock16(SELECTOROF(NtCurrentTeb()->WOW32Reserved))))
1146 if (!pData->old_ss_sp)
1148 WARN("No previous SwitchStackTo\n" );
1151 TRACE("restoring stack %04x:%04x\n",
1152 SELECTOROF(pData->old_ss_sp), OFFSETOF(pData->old_ss_sp) );
1154 oldFrame = CURRENT_STACK16;
1156 /* Pop bp from the previous stack */
1158 context->Ebp = (context->Ebp & ~0xffff) | *(WORD *)MapSL(pData->old_ss_sp);
1159 pData->old_ss_sp += sizeof(WORD);
1161 /* Switch back to the old stack */
1163 NtCurrentTeb()->WOW32Reserved = (void *)(pData->old_ss_sp - sizeof(STACK16FRAME));
1164 context->SegSs = SELECTOROF(pData->old_ss_sp);
1165 context->Esp = OFFSETOF(pData->old_ss_sp) - sizeof(DWORD); /*ret addr*/
1166 pData->old_ss_sp = 0;
1168 /* Build a stack frame for the return */
1170 newFrame = CURRENT_STACK16;
1171 newFrame->frame32 = oldFrame->frame32;
1172 newFrame->module_cs = oldFrame->module_cs;
1173 newFrame->callfrom_ip = oldFrame->callfrom_ip;
1174 newFrame->entry_ip = oldFrame->entry_ip;
1178 /***********************************************************************
1179 * GetTaskQueueDS (KERNEL.118)
1181 void WINAPI GetTaskQueueDS16(void)
1183 CURRENT_STACK16->ds = GlobalHandleToSel16( GetTaskQueue16(0) );
1187 /***********************************************************************
1188 * GetTaskQueueES (KERNEL.119)
1190 void WINAPI GetTaskQueueES16(void)
1192 CURRENT_STACK16->es = GlobalHandleToSel16( GetTaskQueue16(0) );
1196 /***********************************************************************
1197 * GetCurrentTask (KERNEL32.@)
1199 HTASK16 WINAPI GetCurrentTask(void)
1201 HTASK16 ret = kernel_get_thread_data()->htask16;
1202 if (!ret) ret = main_task;
1206 /***********************************************************************
1207 * GetCurrentTask (KERNEL.36)
1209 DWORD WINAPI WIN16_GetCurrentTask(void)
1211 /* This is the version used by relay code; the first task is */
1212 /* returned in the high word of the result */
1213 return MAKELONG( GetCurrentTask(), hFirstTask );
1217 /***********************************************************************
1218 * GetCurrentPDB (KERNEL.37)
1220 * UNDOC: returns PSP of KERNEL in high word
1222 DWORD WINAPI GetCurrentPDB16(void)
1226 if (!(pTask = TASK_GetCurrent())) return 0;
1227 return MAKELONG(pTask->hPDB, 0); /* FIXME */
1231 /***********************************************************************
1232 * GetCurPID (KERNEL.157)
1234 DWORD WINAPI GetCurPID16( DWORD unused )
1240 /***********************************************************************
1241 * GetInstanceData (KERNEL.54)
1243 INT16 WINAPI GetInstanceData16( HINSTANCE16 instance, WORD buffer, INT16 len )
1245 char *ptr = (char *)GlobalLock16( instance );
1246 if (!ptr || !len) return 0;
1247 if ((int)buffer + len >= 0x10000) len = 0x10000 - buffer;
1248 memcpy( (char *)GlobalLock16(CURRENT_DS) + buffer, ptr + buffer, len );
1253 /***********************************************************************
1254 * GetExeVersion (KERNEL.105)
1256 WORD WINAPI GetExeVersion16(void)
1260 if (!(pTask = TASK_GetCurrent())) return 0;
1261 return pTask->version;
1265 /***********************************************************************
1266 * SetErrorMode (KERNEL.107)
1268 UINT16 WINAPI SetErrorMode16( UINT16 mode )
1271 if (!(pTask = TASK_GetCurrent())) return 0;
1272 pTask->error_mode = mode;
1273 return SetErrorMode( mode );
1277 /***********************************************************************
1278 * GetNumTasks (KERNEL.152)
1280 UINT16 WINAPI GetNumTasks16(void)
1286 /***********************************************************************
1287 * GetTaskDS (KERNEL.155)
1289 * Note: this function apparently returns a DWORD with LOWORD == HIWORD.
1290 * I don't think we need to bother with this.
1292 HINSTANCE16 WINAPI GetTaskDS16(void)
1296 if (!(pTask = TASK_GetCurrent())) return 0;
1297 return GlobalHandleToSel16(pTask->hInstance);
1300 /***********************************************************************
1301 * GetDummyModuleHandleDS (KERNEL.602)
1303 WORD WINAPI GetDummyModuleHandleDS16(void)
1308 if (!(pTask = TASK_GetCurrent())) return 0;
1309 if (!(pTask->flags & TDBF_WIN32)) return 0;
1310 selector = GlobalHandleToSel16( pTask->hModule );
1311 CURRENT_DS = selector;
1315 /***********************************************************************
1316 * IsTask (KERNEL.320)
1318 BOOL16 WINAPI IsTask16( HTASK16 hTask )
1322 if (!(pTask = TASK_GetPtr( hTask ))) return FALSE;
1323 if (GlobalSize16( hTask ) < sizeof(TDB)) return FALSE;
1324 return (pTask->magic == TDB_MAGIC);
1328 /***********************************************************************
1329 * IsWinOldApTask (KERNEL.158)
1331 BOOL16 WINAPI IsWinOldApTask16( HTASK16 hTask )
1333 /* should return bit 0 of byte 0x48 in PSP */
1337 /***********************************************************************
1338 * SetTaskSignalProc (KERNEL.38)
1340 FARPROC16 WINAPI SetTaskSignalProc( HTASK16 hTask, FARPROC16 proc )
1345 if (!hTask) hTask = GetCurrentTask();
1346 if (!(pTask = TASK_GetPtr( hTask ))) return NULL;
1347 oldProc = pTask->userhandler;
1348 pTask->userhandler = proc;
1352 /***********************************************************************
1353 * SetSigHandler (KERNEL.140)
1355 WORD WINAPI SetSigHandler16( FARPROC16 newhandler, FARPROC16* oldhandler,
1356 UINT16 *oldmode, UINT16 newmode, UINT16 flag )
1358 FIXME("(%p,%p,%p,%d,%d), unimplemented.\n",
1359 newhandler,oldhandler,oldmode,newmode,flag );
1361 if (flag != 1) return 0;
1362 if (!newmode) newhandler = NULL; /* Default handler */
1367 if (!(pTask = TASK_GetCurrent())) return 0;
1368 if (oldmode) *oldmode = pTask->signal_flags;
1369 pTask->signal_flags = newmode;
1370 if (oldhandler) *oldhandler = pTask->sighandler;
1371 pTask->sighandler = newhandler;
1377 /***********************************************************************
1378 * GlobalNotify (KERNEL.154)
1380 * Note that GlobalNotify does _not_ return the old NotifyProc
1381 * -- contrary to LocalNotify !!
1383 VOID WINAPI GlobalNotify16( FARPROC16 proc )
1387 if (!(pTask = TASK_GetCurrent())) return;
1388 pTask->discardhandler = proc;
1392 /***********************************************************************
1395 static inline HMODULE16 GetExePtrHelper( HANDLE16 handle, HTASK16 *hTask )
1400 /* Check for module handle */
1402 if (!(ptr = GlobalLock16( handle ))) return 0;
1403 if (((NE_MODULE *)ptr)->ne_magic == IMAGE_OS2_SIGNATURE) return handle;
1405 /* Search for this handle inside all tasks */
1407 *hTask = hFirstTask;
1410 TDB *pTask = TASK_GetPtr( *hTask );
1411 if ((*hTask == handle) ||
1412 (pTask->hInstance == handle) ||
1413 (pTask->hQueue == handle) ||
1414 (pTask->hPDB == handle)) return pTask->hModule;
1415 *hTask = pTask->hNext;
1418 /* Check the owner for module handle */
1420 owner = FarGetOwner16( handle );
1421 if (!(ptr = GlobalLock16( owner ))) return 0;
1422 if (((NE_MODULE *)ptr)->ne_magic == IMAGE_OS2_SIGNATURE) return owner;
1424 /* Search for the owner inside all tasks */
1426 *hTask = hFirstTask;
1429 TDB *pTask = TASK_GetPtr( *hTask );
1430 if ((*hTask == owner) ||
1431 (pTask->hInstance == owner) ||
1432 (pTask->hQueue == owner) ||
1433 (pTask->hPDB == owner)) return pTask->hModule;
1434 *hTask = pTask->hNext;
1440 /***********************************************************************
1441 * GetExePtr (KERNEL.133)
1443 HMODULE16 WINAPI WIN16_GetExePtr( HANDLE16 handle )
1446 HMODULE16 hModule = GetExePtrHelper( handle, &hTask );
1447 STACK16FRAME *frame = CURRENT_STACK16;
1448 frame->ecx = hModule;
1449 if (hTask) frame->es = hTask;
1454 /***********************************************************************
1457 HMODULE16 WINAPI GetExePtr( HANDLE16 handle )
1460 return GetExePtrHelper( handle, &hTask );
1464 /***********************************************************************
1465 * TaskFirst (TOOLHELP.63)
1467 BOOL16 WINAPI TaskFirst16( TASKENTRY *lpte )
1469 lpte->hNext = hFirstTask;
1470 return TaskNext16( lpte );
1474 /***********************************************************************
1475 * TaskNext (TOOLHELP.64)
1477 BOOL16 WINAPI TaskNext16( TASKENTRY *lpte )
1480 INSTANCEDATA *pInstData;
1482 TRACE_(toolhelp)("(%p): task=%04x\n", lpte, lpte->hNext );
1483 if (!lpte->hNext) return FALSE;
1485 /* make sure that task and hInstance are valid (skip initial Wine task !) */
1487 pTask = TASK_GetPtr( lpte->hNext );
1488 if (!pTask || pTask->magic != TDB_MAGIC) return FALSE;
1489 if (pTask->hInstance)
1491 lpte->hNext = pTask->hNext;
1493 pInstData = MapSL( MAKESEGPTR( GlobalHandleToSel16(pTask->hInstance), 0 ) );
1494 lpte->hTask = lpte->hNext;
1495 lpte->hTaskParent = pTask->hParent;
1496 lpte->hInst = pTask->hInstance;
1497 lpte->hModule = pTask->hModule;
1498 lpte->wSS = SELECTOROF( pTask->teb->WOW32Reserved );
1499 lpte->wSP = OFFSETOF( pTask->teb->WOW32Reserved );
1500 lpte->wStackTop = pInstData->stacktop;
1501 lpte->wStackMinimum = pInstData->stackmin;
1502 lpte->wStackBottom = pInstData->stackbottom;
1503 lpte->wcEvents = pTask->nEvents;
1504 lpte->hQueue = pTask->hQueue;
1505 lstrcpynA( lpte->szModule, pTask->module_name, sizeof(lpte->szModule) );
1506 lpte->wPSPOffset = 0x100; /*??*/
1507 lpte->hNext = pTask->hNext;
1512 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND hWnd, LPCSTR text, LPCSTR title, UINT type);
1514 /**************************************************************************
1515 * FatalAppExit (KERNEL.137)
1517 void WINAPI FatalAppExit16( UINT16 action, LPCSTR str )
1519 TDB *pTask = TASK_GetCurrent();
1521 if (!pTask || !(pTask->error_mode & SEM_NOGPFAULTERRORBOX))
1523 HMODULE mod = GetModuleHandleA( "user32.dll" );
1526 MessageBoxA_funcptr pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
1529 pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
1533 ERR( "%s\n", debugstr_a(str) );
1540 /***********************************************************************
1541 * TerminateApp (TOOLHELP.77)
1543 * See "Undocumented Windows".
1545 void WINAPI TerminateApp16(HTASK16 hTask, WORD wFlags)
1547 if (hTask && hTask != GetCurrentTask())
1549 FIXME("cannot terminate task %x\n", hTask);
1553 if (wFlags & NO_UAE_BOX)
1556 old_mode = SetErrorMode16(0);
1557 SetErrorMode16(old_mode|SEM_NOGPFAULTERRORBOX);
1559 FatalAppExit16( 0, NULL );
1561 /* hmm, we're still alive ?? */
1563 /* check undocumented flag */
1564 if (!(wFlags & 0x8000))
1565 TASK_CallTaskSignalProc( USIG16_TERMINATION, hTask );
1567 /* UndocWin says to call int 0x21/0x4c exit=0xff here,
1568 but let's just call ExitThread */
1573 /***********************************************************************
1574 * GetAppCompatFlags (KERNEL.354)
1576 DWORD WINAPI GetAppCompatFlags16( HTASK16 hTask )
1580 if (!hTask) hTask = GetCurrentTask();
1581 if (!(pTask=TASK_GetPtr( hTask ))) return 0;
1582 if (GlobalSize16(hTask) < sizeof(TDB)) return 0;
1583 return pTask->compat_flags;
1587 /***********************************************************************
1588 * GetDOSEnvironment (KERNEL.131)
1590 * Note: the environment is allocated once, it doesn't track changes
1591 * made using the Win32 API. This shouldn't matter.
1593 * Format of a 16-bit environment block:
1594 * ASCIIZ string 1 (xx=yy format)
1599 * ASCIIZ program name (e.g. C:\WINDOWS\SYSTEM\KRNL386.EXE)
1601 SEGPTR WINAPI GetDOSEnvironment16(void)
1603 static const char ENV_program_name[] = "C:\\WINDOWS\\SYSTEM\\KRNL386.EXE";
1604 static HGLOBAL16 handle; /* handle to the 16 bit environment */
1611 p = env = GetEnvironmentStringsA();
1612 while (*p) p += strlen(p) + 1;
1613 p++; /* skip last null */
1614 size = (p - env) + sizeof(WORD) + sizeof(ENV_program_name);
1615 handle = GlobalAlloc16( GMEM_FIXED, size );
1619 LPSTR env16 = GlobalLock16( handle );
1620 memcpy( env16, env, p - env );
1621 memcpy( env16 + (p - env), &one, sizeof(one));
1622 memcpy( env16 + (p - env) + sizeof(WORD), ENV_program_name, sizeof(ENV_program_name));
1623 GlobalUnlock16( handle );
1625 FreeEnvironmentStringsA( env );
1627 return WOWGlobalLock16( handle );