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"
43 #include "stackframe.h"
46 #include "kernel_private.h"
48 #include "wine/debug.h"
50 WINE_DEFAULT_DEBUG_CHANNEL(task);
51 WINE_DECLARE_DEBUG_CHANNEL(relay);
52 WINE_DECLARE_DEBUG_CHANNEL(toolhelp);
56 /* Segment containing MakeProcInstance() thunks */
59 WORD next; /* Selector of next segment */
60 WORD magic; /* Thunks signature */
62 WORD free; /* Head of the free list */
63 WORD thunks[4]; /* Each thunk is 4 words long */
68 #define THUNK_MAGIC ('P' | ('T' << 8))
70 /* Min. number of thunks allocated when creating a new segment */
73 #define TDB_MAGIC ('T' | ('D' << 8))
75 static THHOOK DefaultThhook;
76 THHOOK *pThhook = &DefaultThhook;
78 #define hFirstTask (pThhook->HeadTDB)
79 #define hLockedTask (pThhook->LockTDB)
81 static UINT16 nTaskCount = 0;
83 static HTASK16 initial_task;
85 /***********************************************************************
88 void TASK_InstallTHHook( THHOOK *pNewThhook )
90 THHOOK *pOldThhook = pThhook;
92 pThhook = pNewThhook? pNewThhook : &DefaultThhook;
94 *pThhook = *pOldThhook;
97 /***********************************************************************
100 static TDB *TASK_GetPtr( HTASK16 hTask )
102 return GlobalLock16( hTask );
106 /***********************************************************************
109 TDB *TASK_GetCurrent(void)
111 return TASK_GetPtr( GetCurrentTask() );
115 /***********************************************************************
118 static void TASK_LinkTask( HTASK16 hTask )
123 if (!(pTask = TASK_GetPtr( hTask ))) return;
124 prevTask = &hFirstTask;
127 TDB *prevTaskPtr = TASK_GetPtr( *prevTask );
128 if (prevTaskPtr->priority >= pTask->priority) break;
129 prevTask = &prevTaskPtr->hNext;
131 pTask->hNext = *prevTask;
137 /***********************************************************************
140 static void TASK_UnlinkTask( HTASK16 hTask )
145 prevTask = &hFirstTask;
146 while (*prevTask && (*prevTask != hTask))
148 pTask = TASK_GetPtr( *prevTask );
149 prevTask = &pTask->hNext;
153 pTask = TASK_GetPtr( *prevTask );
154 *prevTask = pTask->hNext;
161 /***********************************************************************
164 * Create a thunk free-list in segment 'handle', starting from offset 'offset'
165 * and containing 'count' entries.
167 static void TASK_CreateThunks( HGLOBAL16 handle, WORD offset, WORD count )
173 pThunk = (THUNKS *)((BYTE *)GlobalLock16( handle ) + offset);
175 pThunk->magic = THUNK_MAGIC;
176 pThunk->free = (int)&pThunk->thunks - (int)pThunk;
178 for (i = 0; i < count-1; i++)
180 free += 8; /* Offset of next thunk */
181 pThunk->thunks[4*i] = free;
183 pThunk->thunks[4*i] = 0; /* Last thunk */
187 /***********************************************************************
190 * Allocate a thunk for MakeProcInstance().
192 static SEGPTR TASK_AllocThunk(void)
198 if (!(pTask = TASK_GetCurrent())) return 0;
199 sel = pTask->hCSAlias;
200 pThunk = (THUNKS *)&pTask->thunks;
201 base = (char *)pThunk - (char *)pTask;
202 while (!pThunk->free)
205 if (!sel) /* Allocate a new segment */
207 sel = GLOBAL_Alloc( GMEM_FIXED, sizeof(THUNKS) + (MIN_THUNKS-1)*8,
208 pTask->hPDB, WINE_LDT_FLAGS_CODE );
209 if (!sel) return (SEGPTR)0;
210 TASK_CreateThunks( sel, 0, MIN_THUNKS );
213 pThunk = (THUNKS *)GlobalLock16( sel );
216 base += pThunk->free;
217 pThunk->free = *(WORD *)((BYTE *)pThunk + pThunk->free);
218 return MAKESEGPTR( sel, base );
222 /***********************************************************************
225 * Free a MakeProcInstance() thunk.
227 static BOOL TASK_FreeThunk( SEGPTR thunk )
233 if (!(pTask = TASK_GetCurrent())) return 0;
234 sel = pTask->hCSAlias;
235 pThunk = (THUNKS *)&pTask->thunks;
236 base = (char *)pThunk - (char *)pTask;
237 while (sel && (sel != HIWORD(thunk)))
240 pThunk = (THUNKS *)GlobalLock16( sel );
243 if (!sel) return FALSE;
244 *(WORD *)((BYTE *)pThunk + LOWORD(thunk) - base) = pThunk->free;
245 pThunk->free = LOWORD(thunk) - base;
250 /***********************************************************************
253 * NOTE: This routine might be called by a Win32 thread. Thus, we need
254 * to be careful to protect global data structures. We do this
255 * by entering the Win16Lock while linking the task into the
258 static TDB *TASK_Create( NE_MODULE *pModule, UINT16 cmdShow, LPCSTR cmdline, BYTE len )
263 char curdir[MAX_PATH];
264 HMODULE16 hModule = pModule ? pModule->self : 0;
266 /* Allocate the task structure */
268 hTask = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, sizeof(TDB) );
269 if (!hTask) return NULL;
270 pTask = TASK_GetPtr( hTask );
271 FarSetOwner16( hTask, hModule );
273 /* Fill the task structure */
275 pTask->hSelf = hTask;
277 pTask->version = pModule ? pModule->expected_version : 0x0400;
278 pTask->hModule = hModule;
279 pTask->hParent = GetCurrentTask();
280 pTask->magic = TDB_MAGIC;
281 pTask->nCmdShow = cmdShow;
283 GetCurrentDirectoryA( sizeof(curdir), curdir );
284 GetShortPathNameA( curdir, curdir, sizeof(curdir) );
285 pTask->curdrive = (curdir[0] - 'A') | 0x80;
286 lstrcpynA( pTask->curdir, curdir + 2, sizeof(pTask->curdir) );
288 /* Create the thunks block */
290 TASK_CreateThunks( hTask, (char *)&pTask->thunks - (char *)pTask, 7 );
292 /* Copy the module name */
297 GetModuleName16( hModule, name, sizeof(name) );
298 strncpy( pTask->module_name, name, 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 NtCurrentTeb()->htask16 = pTask->hSelf;
423 /* Add the task to the linked list */
424 /* (no need to get the win16 lock, we are the only thread at this point) */
425 TASK_LinkTask( 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( TDB *pTask )
460 NtCurrentTeb()->htask16 = pTask->hSelf;
461 NtCurrentTeb()->Tib.SubSystemTib = allocate_win16_tib( pTask );
464 TASK_LinkTask( pTask->hSelf );
465 pTask->teb = NtCurrentTeb();
466 ret = NE_StartTask();
472 /***********************************************************************
475 * Spawn a new 16-bit task.
477 HTASK16 TASK_SpawnTask( NE_MODULE *pModule, WORD cmdShow,
478 LPCSTR cmdline, BYTE len, HANDLE *hThread )
482 if (!(pTask = TASK_Create( pModule, cmdShow, cmdline, len ))) return 0;
483 if (!(*hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)task_start, pTask, 0, NULL )))
485 TASK_DeleteTask( pTask->hSelf );
492 /***********************************************************************
493 * TASK_GetTaskFromThread
495 HTASK16 TASK_GetTaskFromThread( DWORD thread )
497 TDB *p = TASK_GetPtr( hFirstTask );
500 if (p->teb->ClientId.UniqueThread == (HANDLE)thread) return p->hSelf;
501 p = TASK_GetPtr( p->hNext );
507 /***********************************************************************
508 * TASK_CallTaskSignalProc
510 static void TASK_CallTaskSignalProc( UINT16 uCode, HANDLE16 hTaskOrModule )
513 TDB *pTask = TASK_GetCurrent();
515 if ( !pTask || !pTask->userhandler ) return;
517 args[4] = hTaskOrModule;
520 args[1] = pTask->hInstance;
521 args[0] = pTask->hQueue;
522 WOWCallback16Ex( (DWORD)pTask->userhandler, WCB16_PASCAL, sizeof(args), args, NULL );
526 /***********************************************************************
529 void TASK_ExitTask(void)
531 WIN16_SUBSYSTEM_TIB *tib;
535 /* Enter the Win16Lock to protect global data structures */
538 pTask = TASK_GetCurrent();
545 TRACE("Killing task %04x\n", pTask->hSelf );
547 /* Perform USER cleanup */
549 TASK_CallTaskSignalProc( USIG16_TERMINATION, pTask->hSelf );
551 /* Remove the task from the list to be sure we never switch back to it */
552 TASK_UnlinkTask( pTask->hSelf );
554 if (!nTaskCount || (nTaskCount == 1 && hFirstTask == initial_task))
556 TRACE("this is the last task, exiting\n" );
562 if ( hLockedTask == pTask->hSelf )
565 TASK_DeleteTask( pTask->hSelf );
567 if ((tib = NtCurrentTeb()->Tib.SubSystemTib))
569 if (tib->exe_name) RtlFreeUnicodeString( tib->exe_name );
570 HeapFree( GetProcessHeap(), 0, tib );
571 NtCurrentTeb()->Tib.SubSystemTib = NULL;
574 /* ... and completely release the Win16Lock, just in case. */
575 ReleaseThunkLock( &lockCount );
579 /***********************************************************************
580 * ExitKernel (KERNEL.2)
582 * Clean-up everything and exit the Wine process.
584 void WINAPI ExitKernel16(void)
586 WriteOutProfiles16();
587 TerminateProcess( GetCurrentProcess(), 0 );
591 /***********************************************************************
592 * InitTask (KERNEL.91)
594 * Called by the application startup code.
596 void WINAPI InitTask16( CONTEXT86 *context )
599 INSTANCEDATA *pinstance;
603 if (!(pTask = TASK_GetCurrent())) return;
605 /* Note: we need to trust that BX/CX contain the stack/heap sizes,
606 as some apps, notably Visual Basic apps, *modify* the heap/stack
607 size of the instance data segment before calling InitTask() */
609 /* Initialize the INSTANCEDATA structure */
610 pinstance = MapSL( MAKESEGPTR(CURRENT_DS, 0) );
611 pinstance->stackmin = OFFSETOF( NtCurrentTeb()->cur_stack ) + sizeof( STACK16FRAME );
612 pinstance->stackbottom = pinstance->stackmin; /* yup, that's right. Confused me too. */
613 pinstance->stacktop = ( pinstance->stackmin > LOWORD(context->Ebx) ?
614 pinstance->stackmin - LOWORD(context->Ebx) : 0 ) + 150;
616 /* Initialize the local heap */
617 if (LOWORD(context->Ecx))
618 LocalInit16( GlobalHandleToSel16(pTask->hInstance), 0, LOWORD(context->Ecx) );
620 /* Initialize implicitly loaded DLLs */
621 NE_InitializeDLLs( pTask->hModule );
622 NE_DllProcessAttach( pTask->hModule );
624 /* Registers on return are:
625 * ax 1 if OK, 0 on error
626 * cx stack limit in bytes
627 * dx cmdShow parameter
628 * si instance handle of the previous instance
629 * di instance handle of the new task
630 * es:bx pointer to command line inside PSP
632 * 0 (=%bp) is pushed on the stack
634 ptr = stack16_push( sizeof(WORD) );
635 *(WORD *)MapSL(ptr) = 0;
640 if (!pTask->pdb.cmdLine[0]) context->Ebx = 0x80;
643 LPBYTE p = &pTask->pdb.cmdLine[1];
644 while ((*p == ' ') || (*p == '\t')) p++;
645 context->Ebx = 0x80 + (p - pTask->pdb.cmdLine);
647 context->Ecx = pinstance->stacktop;
648 context->Edx = pTask->nCmdShow;
649 context->Esi = (DWORD)pTask->hPrevInstance;
650 context->Edi = (DWORD)pTask->hInstance;
651 context->SegEs = (WORD)pTask->hPDB;
655 /***********************************************************************
656 * WaitEvent (KERNEL.30)
658 BOOL16 WINAPI WaitEvent16( HTASK16 hTask )
662 if (!hTask) hTask = GetCurrentTask();
663 pTask = TASK_GetPtr( hTask );
665 if (pTask->flags & TDBF_WIN32)
667 FIXME("called for Win32 thread (%04lx)!\n", GetCurrentThreadId());
671 if (pTask->nEvents > 0)
677 if (pTask->teb == NtCurrentTeb())
681 NtResetEvent( pTask->hEvent, NULL );
682 ReleaseThunkLock( &lockCount );
683 SYSLEVEL_CheckNotLevel( 1 );
684 WaitForSingleObject( pTask->hEvent, INFINITE );
685 RestoreThunkLock( lockCount );
686 if (pTask->nEvents > 0) pTask->nEvents--;
688 else FIXME("for other task %04x cur=%04x\n",pTask->hSelf,GetCurrentTask());
694 /***********************************************************************
695 * PostEvent (KERNEL.31)
697 void WINAPI PostEvent16( HTASK16 hTask )
701 if (!hTask) hTask = GetCurrentTask();
702 if (!(pTask = TASK_GetPtr( hTask ))) return;
704 if (pTask->flags & TDBF_WIN32)
706 FIXME("called for Win32 thread (%04lx)!\n", (DWORD)pTask->teb->ClientId.UniqueThread );
712 if (pTask->nEvents == 1) NtSetEvent( pTask->hEvent, NULL );
716 /***********************************************************************
717 * SetPriority (KERNEL.32)
719 void WINAPI SetPriority16( HTASK16 hTask, INT16 delta )
724 if (!hTask) hTask = GetCurrentTask();
725 if (!(pTask = TASK_GetPtr( hTask ))) return;
726 newpriority = pTask->priority + delta;
727 if (newpriority < -32) newpriority = -32;
728 else if (newpriority > 15) newpriority = 15;
730 pTask->priority = newpriority + 1;
731 TASK_UnlinkTask( pTask->hSelf );
732 TASK_LinkTask( pTask->hSelf );
737 /***********************************************************************
738 * LockCurrentTask (KERNEL.33)
740 HTASK16 WINAPI LockCurrentTask16( BOOL16 bLock )
742 if (bLock) hLockedTask = GetCurrentTask();
743 else hLockedTask = 0;
748 /***********************************************************************
749 * IsTaskLocked (KERNEL.122)
751 HTASK16 WINAPI IsTaskLocked16(void)
757 /***********************************************************************
758 * OldYield (KERNEL.117)
760 void WINAPI OldYield16(void)
764 ReleaseThunkLock(&count);
765 RestoreThunkLock(count);
768 /***********************************************************************
769 * WIN32_OldYield (KERNEL.447)
771 void WINAPI WIN32_OldYield16(void)
775 ReleaseThunkLock(&count);
776 RestoreThunkLock(count);
779 /***********************************************************************
780 * DirectedYield (KERNEL.150)
782 void WINAPI DirectedYield16( HTASK16 hTask )
787 /***********************************************************************
790 void WINAPI Yield16(void)
792 TDB *pCurTask = TASK_GetCurrent();
794 if (pCurTask && pCurTask->hQueue)
796 HMODULE mod = GetModuleHandleA( "user32.dll" );
799 FARPROC proc = GetProcAddress( mod, "UserYield16" );
810 /***********************************************************************
811 * KERNEL_490 (KERNEL.490)
813 HTASK16 WINAPI KERNEL_490( HTASK16 someTask )
815 if ( !someTask ) return 0;
817 FIXME("(%04x): stub\n", someTask );
821 /***********************************************************************
822 * MakeProcInstance (KERNEL.51)
824 FARPROC16 WINAPI MakeProcInstance16( FARPROC16 func, HANDLE16 hInstance )
828 WORD hInstanceSelector;
830 hInstanceSelector = GlobalHandleToSel16(hInstance);
832 TRACE("(%08lx, %04x);\n", (DWORD)func, hInstance);
835 /* Win95 actually protects via SEH, but this is better for debugging */
836 WARN("Ouch ! Called with invalid func 0x%08lx !\n", (DWORD)func);
840 if ( (GlobalHandleToSel16(CURRENT_DS) != hInstanceSelector)
842 && (hInstance != 0xffff) )
844 /* calling MPI with a foreign DSEG is invalid ! */
845 WARN("Problem with hInstance? Got %04x, using %04x instead\n",
846 hInstance,CURRENT_DS);
849 /* Always use the DSEG that MPI was entered with.
850 * We used to set hInstance to GetTaskDS16(), but this should be wrong
851 * as CURRENT_DS provides the DSEG value we need.
852 * ("calling" DS, *not* "task" DS !) */
853 hInstanceSelector = CURRENT_DS;
854 hInstance = GlobalHandle16(hInstanceSelector);
856 /* no thunking for DLLs */
857 if (NE_GetPtr(FarGetOwner16(hInstance))->flags & NE_FFLAGS_LIBMODULE)
860 thunkaddr = TASK_AllocThunk();
861 if (!thunkaddr) return (FARPROC16)0;
862 thunk = MapSL( thunkaddr );
863 lfunc = MapSL( (SEGPTR)func );
865 TRACE("(%08lx,%04x): got thunk %08lx\n",
866 (DWORD)func, hInstance, (DWORD)thunkaddr );
867 if (((lfunc[0]==0x8c) && (lfunc[1]==0xd8)) || /* movw %ds, %ax */
868 ((lfunc[0]==0x1e) && (lfunc[1]==0x58)) /* pushw %ds, popw %ax */
870 WARN("This was the (in)famous \"thunk useless\" warning. We thought we have to overwrite with nop;nop;, but this isn't true.\n");
873 *thunk++ = 0xb8; /* movw instance, %ax */
874 *thunk++ = (BYTE)(hInstanceSelector & 0xff);
875 *thunk++ = (BYTE)(hInstanceSelector >> 8);
876 *thunk++ = 0xea; /* ljmp func */
877 *(DWORD *)thunk = (DWORD)func;
878 return (FARPROC16)thunkaddr;
879 /* CX reg indicates if thunkaddr != NULL, implement if needed */
883 /***********************************************************************
884 * FreeProcInstance (KERNEL.52)
886 void WINAPI FreeProcInstance16( FARPROC16 func )
888 TRACE("(%08lx)\n", (DWORD)func );
889 TASK_FreeThunk( (SEGPTR)func );
892 /**********************************************************************
893 * TASK_GetCodeSegment
895 * Helper function for GetCodeHandle/GetCodeInfo: Retrieve the module
896 * and logical segment number of a given code segment.
898 * 'proc' either *is* already a pair of module handle and segment number,
899 * in which case there's nothing to do. Otherwise, it is a pointer to
900 * a function, and we need to retrieve the code segment. If the pointer
901 * happens to point to a thunk, we'll retrieve info about the code segment
902 * where the function pointed to by the thunk resides, not the thunk itself.
904 * FIXME: if 'proc' is a SNOOP16 return stub, we should retrieve info about
905 * the function the snoop code will return to ...
908 static BOOL TASK_GetCodeSegment( FARPROC16 proc, NE_MODULE **ppModule,
909 SEGTABLEENTRY **ppSeg, int *pSegNr )
911 NE_MODULE *pModule = NULL;
912 SEGTABLEENTRY *pSeg = NULL;
915 /* Try pair of module handle / segment number */
916 pModule = (NE_MODULE *) GlobalLock16( HIWORD( proc ) );
917 if ( pModule && pModule->magic == IMAGE_OS2_SIGNATURE )
919 segNr = LOWORD( proc );
920 if ( segNr && segNr <= pModule->seg_count )
921 pSeg = NE_SEG_TABLE( pModule ) + segNr-1;
924 /* Try thunk or function */
927 BYTE *thunk = MapSL( (SEGPTR)proc );
930 if ((thunk[0] == 0xb8) && (thunk[3] == 0xea))
931 selector = thunk[6] + (thunk[7] << 8);
933 selector = HIWORD( proc );
935 pModule = NE_GetPtr( GlobalHandle16( selector ) );
936 pSeg = pModule? NE_SEG_TABLE( pModule ) : NULL;
939 for ( segNr = 1; segNr <= pModule->seg_count; segNr++, pSeg++ )
940 if ( GlobalHandleToSel16(pSeg->hSeg) == selector )
943 if ( pModule && segNr > pModule->seg_count )
947 /* Abort if segment not found */
949 if ( !pModule || !pSeg )
952 /* Return segment data */
954 if ( ppModule ) *ppModule = pModule;
955 if ( ppSeg ) *ppSeg = pSeg;
956 if ( pSegNr ) *pSegNr = segNr;
961 /**********************************************************************
962 * GetCodeHandle (KERNEL.93)
964 HANDLE16 WINAPI GetCodeHandle16( FARPROC16 proc )
968 if ( !TASK_GetCodeSegment( proc, NULL, &pSeg, NULL ) )
974 /**********************************************************************
975 * GetCodeInfo (KERNEL.104)
977 BOOL16 WINAPI GetCodeInfo16( FARPROC16 proc, SEGINFO *segInfo )
983 if ( !TASK_GetCodeSegment( proc, &pModule, &pSeg, &segNr ) )
986 /* Fill in segment information */
988 segInfo->offSegment = pSeg->filepos;
989 segInfo->cbSegment = pSeg->size;
990 segInfo->flags = pSeg->flags;
991 segInfo->cbAlloc = pSeg->minsize;
992 segInfo->h = pSeg->hSeg;
993 segInfo->alignShift = pModule->alignment;
995 if ( segNr == pModule->dgroup )
996 segInfo->cbAlloc += pModule->heap_size + pModule->stack_size;
998 /* Return module handle in %es */
1000 CURRENT_STACK16->es = GlobalHandleToSel16( pModule->self );
1006 /**********************************************************************
1007 * DefineHandleTable (KERNEL.94)
1009 BOOL16 WINAPI DefineHandleTable16( WORD wOffset )
1011 FIXME("(%04x): stub ?\n", wOffset);
1016 /***********************************************************************
1017 * SetTaskQueue (KERNEL.34)
1019 HQUEUE16 WINAPI SetTaskQueue16( HTASK16 hTask, HQUEUE16 hQueue )
1024 if (!hTask) hTask = GetCurrentTask();
1025 if (!(pTask = TASK_GetPtr( hTask ))) return 0;
1027 hPrev = pTask->hQueue;
1028 pTask->hQueue = hQueue;
1034 /***********************************************************************
1035 * GetTaskQueue (KERNEL.35)
1037 HQUEUE16 WINAPI GetTaskQueue16( HTASK16 hTask )
1041 if (!hTask) hTask = GetCurrentTask();
1042 if (!(pTask = TASK_GetPtr( hTask ))) return 0;
1043 return pTask->hQueue;
1046 /***********************************************************************
1047 * SetThreadQueue (KERNEL.463)
1049 HQUEUE16 WINAPI SetThreadQueue16( DWORD thread, HQUEUE16 hQueue )
1051 HQUEUE16 oldQueue = NtCurrentTeb()->queue;
1053 if (thread && thread != GetCurrentThreadId())
1055 FIXME( "not supported on other thread %04lx\n", thread );
1058 NtCurrentTeb()->queue = hQueue;
1059 if ( GetTaskQueue16( NtCurrentTeb()->htask16 ) == oldQueue )
1060 SetTaskQueue16( NtCurrentTeb()->htask16, hQueue );
1064 /***********************************************************************
1065 * GetThreadQueue (KERNEL.464)
1067 HQUEUE16 WINAPI GetThreadQueue16( DWORD thread )
1069 if (thread && thread != GetCurrentThreadId())
1071 FIXME( "not supported on other thread %04lx\n", thread );
1074 return NtCurrentTeb()->queue;
1077 /***********************************************************************
1078 * SetFastQueue (KERNEL.624)
1080 VOID WINAPI SetFastQueue16( DWORD thread, HQUEUE16 hQueue )
1082 if (!thread || thread == GetCurrentThreadId())
1083 NtCurrentTeb()->queue = hQueue;
1085 FIXME( "not supported on other thread %04lx\n", thread );
1088 /***********************************************************************
1089 * GetFastQueue (KERNEL.625)
1091 HQUEUE16 WINAPI GetFastQueue16( void )
1093 HQUEUE16 ret = NtCurrentTeb()->queue;
1095 if (!ret) FIXME("(): should initialize thread-local queue, expect failure!\n" );
1099 /***********************************************************************
1100 * SwitchStackTo (KERNEL.108)
1102 void WINAPI SwitchStackTo16( WORD seg, WORD ptr, WORD top )
1104 STACK16FRAME *oldFrame, *newFrame;
1105 INSTANCEDATA *pData;
1108 if (!(pData = (INSTANCEDATA *)GlobalLock16( seg ))) return;
1109 TRACE("old=%04x:%04x new=%04x:%04x\n",
1110 SELECTOROF( NtCurrentTeb()->cur_stack ),
1111 OFFSETOF( NtCurrentTeb()->cur_stack ), seg, ptr );
1113 /* Save the old stack */
1115 oldFrame = CURRENT_STACK16;
1116 /* pop frame + args and push bp */
1117 pData->old_ss_sp = NtCurrentTeb()->cur_stack + sizeof(STACK16FRAME)
1119 *(WORD *)MapSL(pData->old_ss_sp) = oldFrame->bp;
1120 pData->stacktop = top;
1121 pData->stackmin = ptr;
1122 pData->stackbottom = ptr;
1124 /* Switch to the new stack */
1126 /* Note: we need to take the 3 arguments into account; otherwise,
1127 * the stack will underflow upon return from this function.
1129 copySize = oldFrame->bp - OFFSETOF(pData->old_ss_sp);
1130 copySize += 3 * sizeof(WORD) + sizeof(STACK16FRAME);
1131 NtCurrentTeb()->cur_stack = MAKESEGPTR( seg, ptr - copySize );
1132 newFrame = CURRENT_STACK16;
1134 /* Copy the stack frame and the local variables to the new stack */
1136 memmove( newFrame, oldFrame, copySize );
1138 *(WORD *)MapSL( MAKESEGPTR( seg, ptr ) ) = 0; /* clear previous bp */
1142 /***********************************************************************
1143 * SwitchStackBack (KERNEL.109)
1145 void WINAPI SwitchStackBack16( CONTEXT86 *context )
1147 STACK16FRAME *oldFrame, *newFrame;
1148 INSTANCEDATA *pData;
1150 if (!(pData = (INSTANCEDATA *)GlobalLock16(SELECTOROF(NtCurrentTeb()->cur_stack))))
1152 if (!pData->old_ss_sp)
1154 WARN("No previous SwitchStackTo\n" );
1157 TRACE("restoring stack %04x:%04x\n",
1158 SELECTOROF(pData->old_ss_sp), OFFSETOF(pData->old_ss_sp) );
1160 oldFrame = CURRENT_STACK16;
1162 /* Pop bp from the previous stack */
1164 context->Ebp = (context->Ebp & ~0xffff) | *(WORD *)MapSL(pData->old_ss_sp);
1165 pData->old_ss_sp += sizeof(WORD);
1167 /* Switch back to the old stack */
1169 NtCurrentTeb()->cur_stack = pData->old_ss_sp - sizeof(STACK16FRAME);
1170 context->SegSs = SELECTOROF(pData->old_ss_sp);
1171 context->Esp = OFFSETOF(pData->old_ss_sp) - sizeof(DWORD); /*ret addr*/
1172 pData->old_ss_sp = 0;
1174 /* Build a stack frame for the return */
1176 newFrame = CURRENT_STACK16;
1177 newFrame->frame32 = oldFrame->frame32;
1178 newFrame->module_cs = oldFrame->module_cs;
1179 newFrame->callfrom_ip = oldFrame->callfrom_ip;
1180 newFrame->entry_ip = oldFrame->entry_ip;
1184 /***********************************************************************
1185 * GetTaskQueueDS (KERNEL.118)
1187 void WINAPI GetTaskQueueDS16(void)
1189 CURRENT_STACK16->ds = GlobalHandleToSel16( GetTaskQueue16(0) );
1193 /***********************************************************************
1194 * GetTaskQueueES (KERNEL.119)
1196 void WINAPI GetTaskQueueES16(void)
1198 CURRENT_STACK16->es = GlobalHandleToSel16( GetTaskQueue16(0) );
1202 /***********************************************************************
1203 * GetCurrentTask (KERNEL32.@)
1205 HTASK16 WINAPI GetCurrentTask(void)
1207 return NtCurrentTeb()->htask16;
1210 /***********************************************************************
1211 * GetCurrentTask (KERNEL.36)
1213 DWORD WINAPI WIN16_GetCurrentTask(void)
1215 /* This is the version used by relay code; the first task is */
1216 /* returned in the high word of the result */
1217 return MAKELONG( GetCurrentTask(), hFirstTask );
1221 /***********************************************************************
1222 * GetCurrentPDB (KERNEL.37)
1224 * UNDOC: returns PSP of KERNEL in high word
1226 DWORD WINAPI GetCurrentPDB16(void)
1230 if (!(pTask = TASK_GetCurrent())) return 0;
1231 return MAKELONG(pTask->hPDB, 0); /* FIXME */
1235 /***********************************************************************
1236 * GetCurPID (KERNEL.157)
1238 DWORD WINAPI GetCurPID16( DWORD unused )
1244 /***********************************************************************
1245 * GetInstanceData (KERNEL.54)
1247 INT16 WINAPI GetInstanceData16( HINSTANCE16 instance, WORD buffer, INT16 len )
1249 char *ptr = (char *)GlobalLock16( instance );
1250 if (!ptr || !len) return 0;
1251 if ((int)buffer + len >= 0x10000) len = 0x10000 - buffer;
1252 memcpy( (char *)GlobalLock16(CURRENT_DS) + buffer, ptr + buffer, len );
1257 /***********************************************************************
1258 * GetExeVersion (KERNEL.105)
1260 WORD WINAPI GetExeVersion16(void)
1264 if (!(pTask = TASK_GetCurrent())) return 0;
1265 return pTask->version;
1269 /***********************************************************************
1270 * SetErrorMode (KERNEL.107)
1272 UINT16 WINAPI SetErrorMode16( UINT16 mode )
1275 if (!(pTask = TASK_GetCurrent())) return 0;
1276 pTask->error_mode = mode;
1277 return SetErrorMode( mode );
1281 /***********************************************************************
1282 * GetNumTasks (KERNEL.152)
1284 UINT16 WINAPI GetNumTasks16(void)
1290 /***********************************************************************
1291 * GetTaskDS (KERNEL.155)
1293 * Note: this function apparently returns a DWORD with LOWORD == HIWORD.
1294 * I don't think we need to bother with this.
1296 HINSTANCE16 WINAPI GetTaskDS16(void)
1300 if (!(pTask = TASK_GetCurrent())) return 0;
1301 return GlobalHandleToSel16(pTask->hInstance);
1304 /***********************************************************************
1305 * GetDummyModuleHandleDS (KERNEL.602)
1307 WORD WINAPI GetDummyModuleHandleDS16(void)
1312 if (!(pTask = TASK_GetCurrent())) return 0;
1313 if (!(pTask->flags & TDBF_WIN32)) return 0;
1314 selector = GlobalHandleToSel16( pTask->hModule );
1315 CURRENT_DS = selector;
1319 /***********************************************************************
1320 * IsTask (KERNEL.320)
1322 BOOL16 WINAPI IsTask16( HTASK16 hTask )
1326 if (!(pTask = TASK_GetPtr( hTask ))) return FALSE;
1327 if (GlobalSize16( hTask ) < sizeof(TDB)) return FALSE;
1328 return (pTask->magic == TDB_MAGIC);
1332 /***********************************************************************
1333 * IsWinOldApTask (KERNEL.158)
1335 BOOL16 WINAPI IsWinOldApTask16( HTASK16 hTask )
1337 /* should return bit 0 of byte 0x48 in PSP */
1341 /***********************************************************************
1342 * SetTaskSignalProc (KERNEL.38)
1344 FARPROC16 WINAPI SetTaskSignalProc( HTASK16 hTask, FARPROC16 proc )
1349 if (!hTask) hTask = GetCurrentTask();
1350 if (!(pTask = TASK_GetPtr( hTask ))) return NULL;
1351 oldProc = pTask->userhandler;
1352 pTask->userhandler = proc;
1356 /***********************************************************************
1357 * SetSigHandler (KERNEL.140)
1359 WORD WINAPI SetSigHandler16( FARPROC16 newhandler, FARPROC16* oldhandler,
1360 UINT16 *oldmode, UINT16 newmode, UINT16 flag )
1362 FIXME("(%p,%p,%p,%d,%d), unimplemented.\n",
1363 newhandler,oldhandler,oldmode,newmode,flag );
1365 if (flag != 1) return 0;
1366 if (!newmode) newhandler = NULL; /* Default handler */
1371 if (!(pTask = TASK_GetCurrent())) return 0;
1372 if (oldmode) *oldmode = pTask->signal_flags;
1373 pTask->signal_flags = newmode;
1374 if (oldhandler) *oldhandler = pTask->sighandler;
1375 pTask->sighandler = newhandler;
1381 /***********************************************************************
1382 * GlobalNotify (KERNEL.154)
1384 * Note that GlobalNotify does _not_ return the old NotifyProc
1385 * -- contrary to LocalNotify !!
1387 VOID WINAPI GlobalNotify16( FARPROC16 proc )
1391 if (!(pTask = TASK_GetCurrent())) return;
1392 pTask->discardhandler = proc;
1396 /***********************************************************************
1399 static inline HMODULE16 GetExePtrHelper( HANDLE16 handle, HTASK16 *hTask )
1404 /* Check for module handle */
1406 if (!(ptr = GlobalLock16( handle ))) return 0;
1407 if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return handle;
1409 /* Search for this handle inside all tasks */
1411 *hTask = hFirstTask;
1414 TDB *pTask = TASK_GetPtr( *hTask );
1415 if ((*hTask == handle) ||
1416 (pTask->hInstance == handle) ||
1417 (pTask->hQueue == handle) ||
1418 (pTask->hPDB == handle)) return pTask->hModule;
1419 *hTask = pTask->hNext;
1422 /* Check the owner for module handle */
1424 owner = FarGetOwner16( handle );
1425 if (!(ptr = GlobalLock16( owner ))) return 0;
1426 if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return owner;
1428 /* Search for the owner inside all tasks */
1430 *hTask = hFirstTask;
1433 TDB *pTask = TASK_GetPtr( *hTask );
1434 if ((*hTask == owner) ||
1435 (pTask->hInstance == owner) ||
1436 (pTask->hQueue == owner) ||
1437 (pTask->hPDB == owner)) return pTask->hModule;
1438 *hTask = pTask->hNext;
1444 /***********************************************************************
1445 * GetExePtr (KERNEL.133)
1447 HMODULE16 WINAPI WIN16_GetExePtr( HANDLE16 handle )
1450 HMODULE16 hModule = GetExePtrHelper( handle, &hTask );
1451 STACK16FRAME *frame = CURRENT_STACK16;
1452 frame->ecx = hModule;
1453 if (hTask) frame->es = hTask;
1458 /***********************************************************************
1461 HMODULE16 WINAPI GetExePtr( HANDLE16 handle )
1464 return GetExePtrHelper( handle, &hTask );
1468 /***********************************************************************
1469 * TaskFirst (TOOLHELP.63)
1471 BOOL16 WINAPI TaskFirst16( TASKENTRY *lpte )
1473 lpte->hNext = hFirstTask;
1474 return TaskNext16( lpte );
1478 /***********************************************************************
1479 * TaskNext (TOOLHELP.64)
1481 BOOL16 WINAPI TaskNext16( TASKENTRY *lpte )
1484 INSTANCEDATA *pInstData;
1486 TRACE_(toolhelp)("(%p): task=%04x\n", lpte, lpte->hNext );
1487 if (!lpte->hNext) return FALSE;
1489 /* make sure that task and hInstance are valid (skip initial Wine task !) */
1491 pTask = TASK_GetPtr( lpte->hNext );
1492 if (!pTask || pTask->magic != TDB_MAGIC) return FALSE;
1493 if (pTask->hInstance)
1495 lpte->hNext = pTask->hNext;
1497 pInstData = MapSL( MAKESEGPTR( GlobalHandleToSel16(pTask->hInstance), 0 ) );
1498 lpte->hTask = lpte->hNext;
1499 lpte->hTaskParent = pTask->hParent;
1500 lpte->hInst = pTask->hInstance;
1501 lpte->hModule = pTask->hModule;
1502 lpte->wSS = SELECTOROF( pTask->teb->cur_stack );
1503 lpte->wSP = OFFSETOF( pTask->teb->cur_stack );
1504 lpte->wStackTop = pInstData->stacktop;
1505 lpte->wStackMinimum = pInstData->stackmin;
1506 lpte->wStackBottom = pInstData->stackbottom;
1507 lpte->wcEvents = pTask->nEvents;
1508 lpte->hQueue = pTask->hQueue;
1509 lstrcpynA( lpte->szModule, pTask->module_name, sizeof(lpte->szModule) );
1510 lpte->wPSPOffset = 0x100; /*??*/
1511 lpte->hNext = pTask->hNext;
1516 /***********************************************************************
1517 * TaskFindHandle (TOOLHELP.65)
1519 BOOL16 WINAPI TaskFindHandle16( TASKENTRY *lpte, HTASK16 hTask )
1521 lpte->hNext = hTask;
1522 return TaskNext16( lpte );
1526 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND hWnd, LPCSTR text, LPCSTR title, UINT type);
1528 /**************************************************************************
1529 * FatalAppExit (KERNEL.137)
1531 void WINAPI FatalAppExit16( UINT16 action, LPCSTR str )
1533 TDB *pTask = TASK_GetCurrent();
1535 if (!pTask || !(pTask->error_mode & SEM_NOGPFAULTERRORBOX))
1537 HMODULE mod = GetModuleHandleA( "user32.dll" );
1540 MessageBoxA_funcptr pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
1543 pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
1547 ERR( "%s\n", debugstr_a(str) );
1554 /***********************************************************************
1555 * TerminateApp (TOOLHELP.77)
1557 * See "Undocumented Windows".
1559 void WINAPI TerminateApp16(HTASK16 hTask, WORD wFlags)
1561 if (hTask && hTask != GetCurrentTask())
1563 FIXME("cannot terminate task %x\n", hTask);
1567 if (wFlags & NO_UAE_BOX)
1570 old_mode = SetErrorMode16(0);
1571 SetErrorMode16(old_mode|SEM_NOGPFAULTERRORBOX);
1573 FatalAppExit16( 0, NULL );
1575 /* hmm, we're still alive ?? */
1577 /* check undocumented flag */
1578 if (!(wFlags & 0x8000))
1579 TASK_CallTaskSignalProc( USIG16_TERMINATION, hTask );
1581 /* UndocWin says to call int 0x21/0x4c exit=0xff here,
1582 but let's just call ExitThread */
1587 /***********************************************************************
1588 * GetAppCompatFlags (KERNEL.354)
1590 DWORD WINAPI GetAppCompatFlags16( HTASK16 hTask )
1594 if (!hTask) hTask = GetCurrentTask();
1595 if (!(pTask=TASK_GetPtr( hTask ))) return 0;
1596 if (GlobalSize16(hTask) < sizeof(TDB)) return 0;
1597 return pTask->compat_flags;
1601 /***********************************************************************
1602 * GetDOSEnvironment (KERNEL.131)
1604 * Note: the environment is allocated once, it doesn't track changes
1605 * made using the Win32 API. This shouldn't matter.
1607 * Format of a 16-bit environment block:
1608 * ASCIIZ string 1 (xx=yy format)
1613 * ASCIIZ program name (e.g. C:\WINDOWS\SYSTEM\KRNL386.EXE)
1615 SEGPTR WINAPI GetDOSEnvironment16(void)
1617 static const char ENV_program_name[] = "C:\\WINDOWS\\SYSTEM\\KRNL386.EXE";
1618 static HGLOBAL16 handle; /* handle to the 16 bit environment */
1625 p = env = GetEnvironmentStringsA();
1626 while (*p) p += strlen(p) + 1;
1627 p++; /* skip last null */
1628 size = (p - env) + sizeof(WORD) + sizeof(ENV_program_name);
1629 handle = GlobalAlloc16( GMEM_FIXED, size );
1633 LPSTR env16 = GlobalLock16( handle );
1634 memcpy( env16, env, p - env );
1635 memcpy( env16 + (p - env), &one, sizeof(one));
1636 memcpy( env16 + (p - env) + sizeof(WORD), ENV_program_name, sizeof(ENV_program_name));
1637 GlobalUnlock16( handle );
1639 FreeEnvironmentStringsA( env );
1641 return K32WOWGlobalLock16( handle );