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"
46 #include "selectors.h"
47 #include "wine/server.h"
48 #include "stackframe.h"
52 #include "kernel_private.h"
54 #include "wine/debug.h"
56 WINE_DEFAULT_DEBUG_CHANNEL(task);
57 WINE_DECLARE_DEBUG_CHANNEL(relay);
58 WINE_DECLARE_DEBUG_CHANNEL(toolhelp);
60 /* Min. number of thunks allocated when creating a new segment */
63 static THHOOK DefaultThhook;
65 #define hFirstTask (pThhook->HeadTDB)
66 #define hLockedTask (pThhook->LockTDB)
68 static UINT16 nTaskCount = 0;
70 static HTASK16 initial_task;
72 /***********************************************************************
75 void TASK_InstallTHHook( THHOOK *pNewThhook )
77 THHOOK *pOldThhook = pThhook;
79 pThhook = pNewThhook? pNewThhook : &DefaultThhook;
81 *pThhook = *pOldThhook;
84 /***********************************************************************
87 static TDB *TASK_GetPtr( HTASK16 hTask )
89 return GlobalLock16( hTask );
93 /***********************************************************************
96 TDB *TASK_GetCurrent(void)
98 return TASK_GetPtr( GetCurrentTask() );
102 /***********************************************************************
105 static void TASK_LinkTask( HTASK16 hTask )
110 if (!(pTask = TASK_GetPtr( hTask ))) return;
111 prevTask = &hFirstTask;
114 TDB *prevTaskPtr = TASK_GetPtr( *prevTask );
115 if (prevTaskPtr->priority >= pTask->priority) break;
116 prevTask = &prevTaskPtr->hNext;
118 pTask->hNext = *prevTask;
124 /***********************************************************************
127 static void TASK_UnlinkTask( HTASK16 hTask )
132 prevTask = &hFirstTask;
133 while (*prevTask && (*prevTask != hTask))
135 pTask = TASK_GetPtr( *prevTask );
136 prevTask = &pTask->hNext;
140 pTask = TASK_GetPtr( *prevTask );
141 *prevTask = pTask->hNext;
148 /***********************************************************************
151 * Create a thunk free-list in segment 'handle', starting from offset 'offset'
152 * and containing 'count' entries.
154 static void TASK_CreateThunks( HGLOBAL16 handle, WORD offset, WORD count )
160 pThunk = (THUNKS *)((BYTE *)GlobalLock16( handle ) + offset);
162 pThunk->magic = THUNK_MAGIC;
163 pThunk->free = (int)&pThunk->thunks - (int)pThunk;
165 for (i = 0; i < count-1; i++)
167 free += 8; /* Offset of next thunk */
168 pThunk->thunks[4*i] = free;
170 pThunk->thunks[4*i] = 0; /* Last thunk */
174 /***********************************************************************
177 * Allocate a thunk for MakeProcInstance().
179 static SEGPTR TASK_AllocThunk(void)
185 if (!(pTask = TASK_GetCurrent())) return 0;
186 sel = pTask->hCSAlias;
187 pThunk = &pTask->thunks;
188 base = (int)pThunk - (int)pTask;
189 while (!pThunk->free)
192 if (!sel) /* Allocate a new segment */
194 sel = GLOBAL_Alloc( GMEM_FIXED, sizeof(THUNKS) + (MIN_THUNKS-1)*8,
195 pTask->hPDB, WINE_LDT_FLAGS_CODE );
196 if (!sel) return (SEGPTR)0;
197 TASK_CreateThunks( sel, 0, MIN_THUNKS );
200 pThunk = (THUNKS *)GlobalLock16( sel );
203 base += pThunk->free;
204 pThunk->free = *(WORD *)((BYTE *)pThunk + pThunk->free);
205 return MAKESEGPTR( sel, base );
209 /***********************************************************************
212 * Free a MakeProcInstance() thunk.
214 static BOOL TASK_FreeThunk( SEGPTR thunk )
220 if (!(pTask = TASK_GetCurrent())) return 0;
221 sel = pTask->hCSAlias;
222 pThunk = &pTask->thunks;
223 base = (int)pThunk - (int)pTask;
224 while (sel && (sel != HIWORD(thunk)))
227 pThunk = (THUNKS *)GlobalLock16( sel );
230 if (!sel) return FALSE;
231 *(WORD *)((BYTE *)pThunk + LOWORD(thunk) - base) = pThunk->free;
232 pThunk->free = LOWORD(thunk) - base;
237 /***********************************************************************
240 * NOTE: This routine might be called by a Win32 thread. Thus, we need
241 * to be careful to protect global data structures. We do this
242 * by entering the Win16Lock while linking the task into the
245 static TDB *TASK_Create( NE_MODULE *pModule, UINT16 cmdShow, TEB *teb, LPCSTR cmdline, BYTE len )
250 HMODULE16 hModule = pModule ? pModule->self : 0;
252 /* Allocate the task structure */
254 hTask = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, sizeof(TDB) );
255 if (!hTask) return NULL;
256 pTask = TASK_GetPtr( hTask );
257 FarSetOwner16( hTask, hModule );
259 /* Fill the task structure */
261 pTask->hSelf = hTask;
263 if (teb && teb->tibflags & TEBF_WIN32)
265 pTask->flags |= TDBF_WIN32;
266 pTask->hInstance = hModule;
267 pTask->hPrevInstance = 0;
268 /* NOTE: for 16-bit tasks, the instance handles are updated later on
272 pTask->version = pModule ? pModule->expected_version : 0x0400;
273 pTask->hModule = hModule;
274 pTask->hParent = GetCurrentTask();
275 pTask->magic = TDB_MAGIC;
276 pTask->nCmdShow = cmdShow;
278 pTask->curdrive = DRIVE_GetCurrentDrive() | 0x80;
279 strcpy( pTask->curdir, "\\" );
280 WideCharToMultiByte(CP_ACP, 0, DRIVE_GetDosCwd(DRIVE_GetCurrentDrive()), -1,
281 pTask->curdir + 1, sizeof(pTask->curdir) - 1, NULL, NULL);
282 pTask->curdir[sizeof(pTask->curdir) - 1] = 0; /* ensure 0 termination */
284 /* Create the thunks block */
286 TASK_CreateThunks( hTask, (int)&pTask->thunks - (int)pTask, 7 );
288 /* Copy the module name */
293 GetModuleName16( hModule, name, sizeof(name) );
294 strncpy( pTask->module_name, name, sizeof(pTask->module_name) );
295 pTask->compat_flags = GetProfileIntA( "Compatibility", name, 0 );
298 /* Allocate a selector for the PDB */
300 pTask->hPDB = GLOBAL_CreateBlock( GMEM_FIXED, &pTask->pdb, sizeof(PDB16),
301 hModule, WINE_LDT_FLAGS_DATA );
305 pTask->pdb.int20 = 0x20cd;
306 pTask->pdb.dispatcher[0] = 0x9a; /* ljmp */
307 proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DOS3Call" );
308 memcpy( &pTask->pdb.dispatcher[1], &proc, sizeof(proc) );
309 pTask->pdb.savedint22 = 0;
310 pTask->pdb.savedint23 = 0;
311 pTask->pdb.savedint24 = 0;
312 pTask->pdb.fileHandlesPtr =
313 MAKESEGPTR( GlobalHandleToSel16(pTask->hPDB), (int)&((PDB16 *)0)->fileHandles );
314 pTask->pdb.hFileHandles = 0;
315 memset( pTask->pdb.fileHandles, 0xff, sizeof(pTask->pdb.fileHandles) );
316 /* FIXME: should we make a copy of the environment? */
317 pTask->pdb.environment = SELECTOROF(GetDOSEnvironment16());
318 pTask->pdb.nbFiles = 20;
320 /* Fill the command line */
324 cmdline = GetCommandLineA();
325 /* remove the first word (program name) */
327 if (!(cmdline = strchr( cmdline+1, '"' ))) cmdline = GetCommandLineA();
328 while (*cmdline && (*cmdline != ' ') && (*cmdline != '\t')) cmdline++;
329 while ((*cmdline == ' ') || (*cmdline == '\t')) cmdline++;
330 len = strlen(cmdline);
332 if (len >= sizeof(pTask->pdb.cmdLine)) len = sizeof(pTask->pdb.cmdLine)-1;
333 pTask->pdb.cmdLine[0] = len;
334 memcpy( pTask->pdb.cmdLine + 1, cmdline, len );
335 /* pTask->pdb.cmdLine[len+1] = 0; */
337 TRACE("cmdline='%.*s' task=%04x\n", len, cmdline, hTask );
339 /* Allocate a code segment alias for the TDB */
341 pTask->hCSAlias = GLOBAL_CreateBlock( GMEM_FIXED, (void *)pTask,
342 sizeof(TDB), pTask->hPDB, WINE_LDT_FLAGS_CODE );
344 /* Default DTA overwrites command line */
346 pTask->dta = MAKESEGPTR( pTask->hPDB, (int)&pTask->pdb.cmdLine - (int)&pTask->pdb );
348 /* Create scheduler event for 16-bit tasks */
350 if ( !(pTask->flags & TDBF_WIN32) )
351 NtCreateEvent( &pTask->hEvent, EVENT_ALL_ACCESS, NULL, TRUE, FALSE );
353 /* Enter task handle into thread */
355 if (teb) teb->htask16 = hTask;
356 if (!initial_task) initial_task = hTask;
362 /***********************************************************************
365 static void TASK_DeleteTask( HTASK16 hTask )
370 if (!(pTask = TASK_GetPtr( hTask ))) return;
373 pTask->magic = 0xdead; /* invalidate signature */
375 /* Free the selector aliases */
377 GLOBAL_FreeBlock( pTask->hCSAlias );
378 GLOBAL_FreeBlock( pTask->hPDB );
380 /* Free the task module */
382 FreeModule16( pTask->hModule );
384 /* Free the task structure itself */
386 GlobalFree16( hTask );
388 /* Free all memory used by this task (including the 32-bit stack, */
389 /* the environment block and the thunk segments). */
391 GlobalFreeAll16( hPDB );
395 /***********************************************************************
396 * TASK_CreateMainTask
398 * Create a task for the main (32-bit) process.
400 void TASK_CreateMainTask(void)
403 STARTUPINFOA startup_info;
404 UINT cmdShow = 1; /* SW_SHOWNORMAL but we don't want to include winuser.h here */
406 GetStartupInfoA( &startup_info );
407 if (startup_info.dwFlags & STARTF_USESHOWWINDOW) cmdShow = startup_info.wShowWindow;
408 pTask = TASK_Create( NULL, cmdShow, NtCurrentTeb(), NULL, 0 );
411 ERR("could not create task for main process\n");
415 /* Add the task to the linked list */
416 /* (no need to get the win16 lock, we are the only thread at this point) */
417 TASK_LinkTask( pTask->hSelf );
421 /* startup routine for a new 16-bit thread */
422 static DWORD CALLBACK task_start( TDB *pTask )
426 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
427 NtCurrentTeb()->htask16 = pTask->hSelf;
430 TASK_LinkTask( pTask->hSelf );
431 pTask->teb = NtCurrentTeb();
432 ret = NE_StartTask();
438 /***********************************************************************
441 * Spawn a new 16-bit task.
443 HTASK16 TASK_SpawnTask( NE_MODULE *pModule, WORD cmdShow,
444 LPCSTR cmdline, BYTE len, HANDLE *hThread )
448 if (!(pTask = TASK_Create( pModule, cmdShow, NULL, cmdline, len ))) return 0;
449 if (!(*hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)task_start, pTask, 0, NULL )))
451 TASK_DeleteTask( pTask->hSelf );
458 /***********************************************************************
459 * TASK_GetTaskFromThread
461 HTASK16 TASK_GetTaskFromThread( DWORD thread )
463 TDB *p = TASK_GetPtr( hFirstTask );
466 if (p->teb->ClientId.UniqueThread == (HANDLE)thread) return p->hSelf;
467 p = TASK_GetPtr( p->hNext );
473 /***********************************************************************
474 * TASK_CallTaskSignalProc
476 static void TASK_CallTaskSignalProc( UINT16 uCode, HANDLE16 hTaskOrModule )
479 TDB *pTask = TASK_GetCurrent();
481 if ( !pTask || !pTask->userhandler ) return;
483 args[4] = hTaskOrModule;
486 args[1] = pTask->hInstance;
487 args[0] = pTask->hQueue;
488 WOWCallback16Ex( (DWORD)pTask->userhandler, WCB16_PASCAL, sizeof(args), args, NULL );
492 /***********************************************************************
495 void TASK_ExitTask(void)
500 /* Enter the Win16Lock to protect global data structures */
503 pTask = TASK_GetCurrent();
510 TRACE("Killing task %04x\n", pTask->hSelf );
512 /* Perform USER cleanup */
514 TASK_CallTaskSignalProc( USIG16_TERMINATION, pTask->hSelf );
516 /* Remove the task from the list to be sure we never switch back to it */
517 TASK_UnlinkTask( pTask->hSelf );
519 if (!nTaskCount || (nTaskCount == 1 && hFirstTask == initial_task))
521 TRACE("this is the last task, exiting\n" );
527 if ( hLockedTask == pTask->hSelf )
530 TASK_DeleteTask( pTask->hSelf );
532 /* ... and completely release the Win16Lock, just in case. */
533 ReleaseThunkLock( &lockCount );
537 /***********************************************************************
538 * ExitKernel (KERNEL.2)
540 * Clean-up everything and exit the Wine process.
542 void WINAPI ExitKernel16(void)
544 WriteOutProfiles16();
545 TerminateProcess( GetCurrentProcess(), 0 );
549 /***********************************************************************
550 * InitTask (KERNEL.91)
552 * Called by the application startup code.
554 void WINAPI InitTask16( CONTEXT86 *context )
557 INSTANCEDATA *pinstance;
561 if (!(pTask = TASK_GetCurrent())) return;
563 /* Note: we need to trust that BX/CX contain the stack/heap sizes,
564 as some apps, notably Visual Basic apps, *modify* the heap/stack
565 size of the instance data segment before calling InitTask() */
567 /* Initialize the INSTANCEDATA structure */
568 pinstance = MapSL( MAKESEGPTR(CURRENT_DS, 0) );
569 pinstance->stackmin = OFFSETOF( NtCurrentTeb()->cur_stack ) + sizeof( STACK16FRAME );
570 pinstance->stackbottom = pinstance->stackmin; /* yup, that's right. Confused me too. */
571 pinstance->stacktop = ( pinstance->stackmin > LOWORD(context->Ebx) ?
572 pinstance->stackmin - LOWORD(context->Ebx) : 0 ) + 150;
574 /* Initialize the local heap */
575 if (LOWORD(context->Ecx))
576 LocalInit16( GlobalHandleToSel16(pTask->hInstance), 0, LOWORD(context->Ecx) );
578 /* Initialize implicitly loaded DLLs */
579 NE_InitializeDLLs( pTask->hModule );
580 NE_DllProcessAttach( pTask->hModule );
582 /* Registers on return are:
583 * ax 1 if OK, 0 on error
584 * cx stack limit in bytes
585 * dx cmdShow parameter
586 * si instance handle of the previous instance
587 * di instance handle of the new task
588 * es:bx pointer to command line inside PSP
590 * 0 (=%bp) is pushed on the stack
592 ptr = stack16_push( sizeof(WORD) );
593 *(WORD *)MapSL(ptr) = 0;
598 if (!pTask->pdb.cmdLine[0]) context->Ebx = 0x80;
601 LPBYTE p = &pTask->pdb.cmdLine[1];
602 while ((*p == ' ') || (*p == '\t')) p++;
603 context->Ebx = 0x80 + (p - pTask->pdb.cmdLine);
605 context->Ecx = pinstance->stacktop;
606 context->Edx = pTask->nCmdShow;
607 context->Esi = (DWORD)pTask->hPrevInstance;
608 context->Edi = (DWORD)pTask->hInstance;
609 context->SegEs = (WORD)pTask->hPDB;
613 /***********************************************************************
614 * WaitEvent (KERNEL.30)
616 BOOL16 WINAPI WaitEvent16( HTASK16 hTask )
620 if (!hTask) hTask = GetCurrentTask();
621 pTask = TASK_GetPtr( hTask );
623 if (pTask->flags & TDBF_WIN32)
625 FIXME("called for Win32 thread (%04lx)!\n", GetCurrentThreadId());
629 if (pTask->nEvents > 0)
635 if (pTask->teb == NtCurrentTeb())
639 NtResetEvent( pTask->hEvent, NULL );
640 ReleaseThunkLock( &lockCount );
641 SYSLEVEL_CheckNotLevel( 1 );
642 WaitForSingleObject( pTask->hEvent, INFINITE );
643 RestoreThunkLock( lockCount );
644 if (pTask->nEvents > 0) pTask->nEvents--;
646 else FIXME("for other task %04x cur=%04x\n",pTask->hSelf,GetCurrentTask());
652 /***********************************************************************
653 * PostEvent (KERNEL.31)
655 void WINAPI PostEvent16( HTASK16 hTask )
659 if (!hTask) hTask = GetCurrentTask();
660 if (!(pTask = TASK_GetPtr( hTask ))) return;
662 if (pTask->flags & TDBF_WIN32)
664 FIXME("called for Win32 thread (%04lx)!\n", (DWORD)pTask->teb->ClientId.UniqueThread );
670 if (pTask->nEvents == 1) NtSetEvent( pTask->hEvent, NULL );
674 /***********************************************************************
675 * SetPriority (KERNEL.32)
677 void WINAPI SetPriority16( HTASK16 hTask, INT16 delta )
682 if (!hTask) hTask = GetCurrentTask();
683 if (!(pTask = TASK_GetPtr( hTask ))) return;
684 newpriority = pTask->priority + delta;
685 if (newpriority < -32) newpriority = -32;
686 else if (newpriority > 15) newpriority = 15;
688 pTask->priority = newpriority + 1;
689 TASK_UnlinkTask( pTask->hSelf );
690 TASK_LinkTask( pTask->hSelf );
695 /***********************************************************************
696 * LockCurrentTask (KERNEL.33)
698 HTASK16 WINAPI LockCurrentTask16( BOOL16 bLock )
700 if (bLock) hLockedTask = GetCurrentTask();
701 else hLockedTask = 0;
706 /***********************************************************************
707 * IsTaskLocked (KERNEL.122)
709 HTASK16 WINAPI IsTaskLocked16(void)
715 /***********************************************************************
716 * OldYield (KERNEL.117)
718 void WINAPI OldYield16(void)
722 ReleaseThunkLock(&count);
723 RestoreThunkLock(count);
726 /***********************************************************************
727 * WIN32_OldYield (KERNEL.447)
729 void WINAPI WIN32_OldYield16(void)
733 ReleaseThunkLock(&count);
734 RestoreThunkLock(count);
737 /***********************************************************************
738 * DirectedYield (KERNEL.150)
740 void WINAPI DirectedYield16( HTASK16 hTask )
745 /***********************************************************************
748 void WINAPI Yield16(void)
750 TDB *pCurTask = TASK_GetCurrent();
752 if (pCurTask && pCurTask->hQueue)
754 HMODULE mod = GetModuleHandleA( "user32.dll" );
757 FARPROC proc = GetProcAddress( mod, "UserYield16" );
768 /***********************************************************************
769 * KERNEL_490 (KERNEL.490)
771 HTASK16 WINAPI KERNEL_490( HTASK16 someTask )
773 if ( !someTask ) return 0;
775 FIXME("(%04x): stub\n", someTask );
779 /***********************************************************************
780 * MakeProcInstance (KERNEL.51)
782 FARPROC16 WINAPI MakeProcInstance16( FARPROC16 func, HANDLE16 hInstance )
786 WORD hInstanceSelector;
788 hInstanceSelector = GlobalHandleToSel16(hInstance);
790 TRACE("(%08lx, %04x);\n", (DWORD)func, hInstance);
793 /* Win95 actually protects via SEH, but this is better for debugging */
794 WARN("Ouch ! Called with invalid func 0x%08lx !\n", (DWORD)func);
798 if ( (GlobalHandleToSel16(CURRENT_DS) != hInstanceSelector)
800 && (hInstance != 0xffff) )
802 /* calling MPI with a foreign DSEG is invalid ! */
803 WARN("Problem with hInstance? Got %04x, using %04x instead\n",
804 hInstance,CURRENT_DS);
807 /* Always use the DSEG that MPI was entered with.
808 * We used to set hInstance to GetTaskDS16(), but this should be wrong
809 * as CURRENT_DS provides the DSEG value we need.
810 * ("calling" DS, *not* "task" DS !) */
811 hInstanceSelector = CURRENT_DS;
812 hInstance = GlobalHandle16(hInstanceSelector);
814 /* no thunking for DLLs */
815 if (NE_GetPtr(FarGetOwner16(hInstance))->flags & NE_FFLAGS_LIBMODULE)
818 thunkaddr = TASK_AllocThunk();
819 if (!thunkaddr) return (FARPROC16)0;
820 thunk = MapSL( thunkaddr );
821 lfunc = MapSL( (SEGPTR)func );
823 TRACE("(%08lx,%04x): got thunk %08lx\n",
824 (DWORD)func, hInstance, (DWORD)thunkaddr );
825 if (((lfunc[0]==0x8c) && (lfunc[1]==0xd8)) || /* movw %ds, %ax */
826 ((lfunc[0]==0x1e) && (lfunc[1]==0x58)) /* pushw %ds, popw %ax */
828 WARN("This was the (in)famous \"thunk useless\" warning. We thought we have to overwrite with nop;nop;, but this isn't true.\n");
831 *thunk++ = 0xb8; /* movw instance, %ax */
832 *thunk++ = (BYTE)(hInstanceSelector & 0xff);
833 *thunk++ = (BYTE)(hInstanceSelector >> 8);
834 *thunk++ = 0xea; /* ljmp func */
835 *(DWORD *)thunk = (DWORD)func;
836 return (FARPROC16)thunkaddr;
837 /* CX reg indicates if thunkaddr != NULL, implement if needed */
841 /***********************************************************************
842 * FreeProcInstance (KERNEL.52)
844 void WINAPI FreeProcInstance16( FARPROC16 func )
846 TRACE("(%08lx)\n", (DWORD)func );
847 TASK_FreeThunk( (SEGPTR)func );
850 /**********************************************************************
851 * TASK_GetCodeSegment
853 * Helper function for GetCodeHandle/GetCodeInfo: Retrieve the module
854 * and logical segment number of a given code segment.
856 * 'proc' either *is* already a pair of module handle and segment number,
857 * in which case there's nothing to do. Otherwise, it is a pointer to
858 * a function, and we need to retrieve the code segment. If the pointer
859 * happens to point to a thunk, we'll retrieve info about the code segment
860 * where the function pointed to by the thunk resides, not the thunk itself.
862 * FIXME: if 'proc' is a SNOOP16 return stub, we should retrieve info about
863 * the function the snoop code will return to ...
866 static BOOL TASK_GetCodeSegment( FARPROC16 proc, NE_MODULE **ppModule,
867 SEGTABLEENTRY **ppSeg, int *pSegNr )
869 NE_MODULE *pModule = NULL;
870 SEGTABLEENTRY *pSeg = NULL;
873 /* Try pair of module handle / segment number */
874 pModule = (NE_MODULE *) GlobalLock16( HIWORD( proc ) );
875 if ( pModule && pModule->magic == IMAGE_OS2_SIGNATURE )
877 segNr = LOWORD( proc );
878 if ( segNr && segNr <= pModule->seg_count )
879 pSeg = NE_SEG_TABLE( pModule ) + segNr-1;
882 /* Try thunk or function */
885 BYTE *thunk = MapSL( (SEGPTR)proc );
888 if ((thunk[0] == 0xb8) && (thunk[3] == 0xea))
889 selector = thunk[6] + (thunk[7] << 8);
891 selector = HIWORD( proc );
893 pModule = NE_GetPtr( GlobalHandle16( selector ) );
894 pSeg = pModule? NE_SEG_TABLE( pModule ) : NULL;
897 for ( segNr = 1; segNr <= pModule->seg_count; segNr++, pSeg++ )
898 if ( GlobalHandleToSel16(pSeg->hSeg) == selector )
901 if ( pModule && segNr > pModule->seg_count )
905 /* Abort if segment not found */
907 if ( !pModule || !pSeg )
910 /* Return segment data */
912 if ( ppModule ) *ppModule = pModule;
913 if ( ppSeg ) *ppSeg = pSeg;
914 if ( pSegNr ) *pSegNr = segNr;
919 /**********************************************************************
920 * GetCodeHandle (KERNEL.93)
922 HANDLE16 WINAPI GetCodeHandle16( FARPROC16 proc )
926 if ( !TASK_GetCodeSegment( proc, NULL, &pSeg, NULL ) )
932 /**********************************************************************
933 * GetCodeInfo (KERNEL.104)
935 BOOL16 WINAPI GetCodeInfo16( FARPROC16 proc, SEGINFO *segInfo )
941 if ( !TASK_GetCodeSegment( proc, &pModule, &pSeg, &segNr ) )
944 /* Fill in segment information */
946 segInfo->offSegment = pSeg->filepos;
947 segInfo->cbSegment = pSeg->size;
948 segInfo->flags = pSeg->flags;
949 segInfo->cbAlloc = pSeg->minsize;
950 segInfo->h = pSeg->hSeg;
951 segInfo->alignShift = pModule->alignment;
953 if ( segNr == pModule->dgroup )
954 segInfo->cbAlloc += pModule->heap_size + pModule->stack_size;
956 /* Return module handle in %es */
958 CURRENT_STACK16->es = GlobalHandleToSel16( pModule->self );
964 /**********************************************************************
965 * DefineHandleTable (KERNEL.94)
967 BOOL16 WINAPI DefineHandleTable16( WORD wOffset )
969 FIXME("(%04x): stub ?\n", wOffset);
974 /***********************************************************************
975 * SetTaskQueue (KERNEL.34)
977 HQUEUE16 WINAPI SetTaskQueue16( HTASK16 hTask, HQUEUE16 hQueue )
982 if (!hTask) hTask = GetCurrentTask();
983 if (!(pTask = TASK_GetPtr( hTask ))) return 0;
985 hPrev = pTask->hQueue;
986 pTask->hQueue = hQueue;
992 /***********************************************************************
993 * GetTaskQueue (KERNEL.35)
995 HQUEUE16 WINAPI GetTaskQueue16( HTASK16 hTask )
999 if (!hTask) hTask = GetCurrentTask();
1000 if (!(pTask = TASK_GetPtr( hTask ))) return 0;
1001 return pTask->hQueue;
1004 /***********************************************************************
1005 * SetThreadQueue (KERNEL.463)
1007 HQUEUE16 WINAPI SetThreadQueue16( DWORD thread, HQUEUE16 hQueue )
1009 HQUEUE16 oldQueue = NtCurrentTeb()->queue;
1011 if (thread && thread != GetCurrentThreadId())
1013 FIXME( "not supported on other thread %04lx\n", thread );
1016 NtCurrentTeb()->queue = hQueue;
1017 if ( GetTaskQueue16( NtCurrentTeb()->htask16 ) == oldQueue )
1018 SetTaskQueue16( NtCurrentTeb()->htask16, hQueue );
1022 /***********************************************************************
1023 * GetThreadQueue (KERNEL.464)
1025 HQUEUE16 WINAPI GetThreadQueue16( DWORD thread )
1027 if (thread && thread != GetCurrentThreadId())
1029 FIXME( "not supported on other thread %04lx\n", thread );
1032 return NtCurrentTeb()->queue;
1035 /***********************************************************************
1036 * SetFastQueue (KERNEL.624)
1038 VOID WINAPI SetFastQueue16( DWORD thread, HQUEUE16 hQueue )
1040 if (!thread || thread == GetCurrentThreadId())
1041 NtCurrentTeb()->queue = hQueue;
1043 FIXME( "not supported on other thread %04lx\n", thread );
1046 /***********************************************************************
1047 * GetFastQueue (KERNEL.625)
1049 HQUEUE16 WINAPI GetFastQueue16( void )
1051 HQUEUE16 ret = NtCurrentTeb()->queue;
1053 if (!ret) FIXME("(): should initialize thread-local queue, expect failure!\n" );
1057 /***********************************************************************
1058 * SwitchStackTo (KERNEL.108)
1060 void WINAPI SwitchStackTo16( WORD seg, WORD ptr, WORD top )
1062 STACK16FRAME *oldFrame, *newFrame;
1063 INSTANCEDATA *pData;
1066 if (!(pData = (INSTANCEDATA *)GlobalLock16( seg ))) return;
1067 TRACE("old=%04x:%04x new=%04x:%04x\n",
1068 SELECTOROF( NtCurrentTeb()->cur_stack ),
1069 OFFSETOF( NtCurrentTeb()->cur_stack ), seg, ptr );
1071 /* Save the old stack */
1073 oldFrame = CURRENT_STACK16;
1074 /* pop frame + args and push bp */
1075 pData->old_ss_sp = NtCurrentTeb()->cur_stack + sizeof(STACK16FRAME)
1077 *(WORD *)MapSL(pData->old_ss_sp) = oldFrame->bp;
1078 pData->stacktop = top;
1079 pData->stackmin = ptr;
1080 pData->stackbottom = ptr;
1082 /* Switch to the new stack */
1084 /* Note: we need to take the 3 arguments into account; otherwise,
1085 * the stack will underflow upon return from this function.
1087 copySize = oldFrame->bp - OFFSETOF(pData->old_ss_sp);
1088 copySize += 3 * sizeof(WORD) + sizeof(STACK16FRAME);
1089 NtCurrentTeb()->cur_stack = MAKESEGPTR( seg, ptr - copySize );
1090 newFrame = CURRENT_STACK16;
1092 /* Copy the stack frame and the local variables to the new stack */
1094 memmove( newFrame, oldFrame, copySize );
1096 *(WORD *)MapSL( MAKESEGPTR( seg, ptr ) ) = 0; /* clear previous bp */
1100 /***********************************************************************
1101 * SwitchStackBack (KERNEL.109)
1103 void WINAPI SwitchStackBack16( CONTEXT86 *context )
1105 STACK16FRAME *oldFrame, *newFrame;
1106 INSTANCEDATA *pData;
1108 if (!(pData = (INSTANCEDATA *)GlobalLock16(SELECTOROF(NtCurrentTeb()->cur_stack))))
1110 if (!pData->old_ss_sp)
1112 WARN("No previous SwitchStackTo\n" );
1115 TRACE("restoring stack %04x:%04x\n",
1116 SELECTOROF(pData->old_ss_sp), OFFSETOF(pData->old_ss_sp) );
1118 oldFrame = CURRENT_STACK16;
1120 /* Pop bp from the previous stack */
1122 context->Ebp = (context->Ebp & ~0xffff) | *(WORD *)MapSL(pData->old_ss_sp);
1123 pData->old_ss_sp += sizeof(WORD);
1125 /* Switch back to the old stack */
1127 NtCurrentTeb()->cur_stack = pData->old_ss_sp - sizeof(STACK16FRAME);
1128 context->SegSs = SELECTOROF(pData->old_ss_sp);
1129 context->Esp = OFFSETOF(pData->old_ss_sp) - sizeof(DWORD); /*ret addr*/
1130 pData->old_ss_sp = 0;
1132 /* Build a stack frame for the return */
1134 newFrame = CURRENT_STACK16;
1135 newFrame->frame32 = oldFrame->frame32;
1136 newFrame->module_cs = oldFrame->module_cs;
1137 newFrame->callfrom_ip = oldFrame->callfrom_ip;
1138 newFrame->entry_ip = oldFrame->entry_ip;
1142 /***********************************************************************
1143 * GetTaskQueueDS (KERNEL.118)
1145 void WINAPI GetTaskQueueDS16(void)
1147 CURRENT_STACK16->ds = GlobalHandleToSel16( GetTaskQueue16(0) );
1151 /***********************************************************************
1152 * GetTaskQueueES (KERNEL.119)
1154 void WINAPI GetTaskQueueES16(void)
1156 CURRENT_STACK16->es = GlobalHandleToSel16( GetTaskQueue16(0) );
1160 /***********************************************************************
1161 * GetCurrentTask (KERNEL32.@)
1163 HTASK16 WINAPI GetCurrentTask(void)
1165 return NtCurrentTeb()->htask16;
1168 /***********************************************************************
1169 * GetCurrentTask (KERNEL.36)
1171 DWORD WINAPI WIN16_GetCurrentTask(void)
1173 /* This is the version used by relay code; the first task is */
1174 /* returned in the high word of the result */
1175 return MAKELONG( GetCurrentTask(), hFirstTask );
1179 /***********************************************************************
1180 * GetCurrentPDB (KERNEL.37)
1182 * UNDOC: returns PSP of KERNEL in high word
1184 DWORD WINAPI GetCurrentPDB16(void)
1188 if (!(pTask = TASK_GetCurrent())) return 0;
1189 return MAKELONG(pTask->hPDB, 0); /* FIXME */
1193 /***********************************************************************
1194 * GetCurPID (KERNEL.157)
1196 DWORD WINAPI GetCurPID16( DWORD unused )
1202 /***********************************************************************
1203 * GetInstanceData (KERNEL.54)
1205 INT16 WINAPI GetInstanceData16( HINSTANCE16 instance, WORD buffer, INT16 len )
1207 char *ptr = (char *)GlobalLock16( instance );
1208 if (!ptr || !len) return 0;
1209 if ((int)buffer + len >= 0x10000) len = 0x10000 - buffer;
1210 memcpy( (char *)GlobalLock16(CURRENT_DS) + buffer, ptr + buffer, len );
1215 /***********************************************************************
1216 * GetExeVersion (KERNEL.105)
1218 WORD WINAPI GetExeVersion16(void)
1222 if (!(pTask = TASK_GetCurrent())) return 0;
1223 return pTask->version;
1227 /***********************************************************************
1228 * SetErrorMode (KERNEL.107)
1230 UINT16 WINAPI SetErrorMode16( UINT16 mode )
1233 if (!(pTask = TASK_GetCurrent())) return 0;
1234 pTask->error_mode = mode;
1235 return SetErrorMode( mode );
1239 /***********************************************************************
1240 * GetNumTasks (KERNEL.152)
1242 UINT16 WINAPI GetNumTasks16(void)
1248 /***********************************************************************
1249 * GetTaskDS (KERNEL.155)
1251 * Note: this function apparently returns a DWORD with LOWORD == HIWORD.
1252 * I don't think we need to bother with this.
1254 HINSTANCE16 WINAPI GetTaskDS16(void)
1258 if (!(pTask = TASK_GetCurrent())) return 0;
1259 return GlobalHandleToSel16(pTask->hInstance);
1262 /***********************************************************************
1263 * GetDummyModuleHandleDS (KERNEL.602)
1265 WORD WINAPI GetDummyModuleHandleDS16(void)
1270 if (!(pTask = TASK_GetCurrent())) return 0;
1271 if (!(pTask->flags & TDBF_WIN32)) return 0;
1272 selector = GlobalHandleToSel16( pTask->hModule );
1273 CURRENT_DS = selector;
1277 /***********************************************************************
1278 * IsTask (KERNEL.320)
1280 BOOL16 WINAPI IsTask16( HTASK16 hTask )
1284 if (!(pTask = TASK_GetPtr( hTask ))) return FALSE;
1285 if (GlobalSize16( hTask ) < sizeof(TDB)) return FALSE;
1286 return (pTask->magic == TDB_MAGIC);
1290 /***********************************************************************
1291 * IsWinOldApTask (KERNEL.158)
1293 BOOL16 WINAPI IsWinOldApTask16( HTASK16 hTask )
1295 /* should return bit 0 of byte 0x48 in PSP */
1299 /***********************************************************************
1300 * SetTaskSignalProc (KERNEL.38)
1302 FARPROC16 WINAPI SetTaskSignalProc( HTASK16 hTask, FARPROC16 proc )
1307 if (!hTask) hTask = GetCurrentTask();
1308 if (!(pTask = TASK_GetPtr( hTask ))) return NULL;
1309 oldProc = pTask->userhandler;
1310 pTask->userhandler = proc;
1314 /***********************************************************************
1315 * SetSigHandler (KERNEL.140)
1317 WORD WINAPI SetSigHandler16( FARPROC16 newhandler, FARPROC16* oldhandler,
1318 UINT16 *oldmode, UINT16 newmode, UINT16 flag )
1320 FIXME("(%p,%p,%p,%d,%d), unimplemented.\n",
1321 newhandler,oldhandler,oldmode,newmode,flag );
1323 if (flag != 1) return 0;
1324 if (!newmode) newhandler = NULL; /* Default handler */
1329 if (!(pTask = TASK_GetCurrent())) return 0;
1330 if (oldmode) *oldmode = pTask->signal_flags;
1331 pTask->signal_flags = newmode;
1332 if (oldhandler) *oldhandler = pTask->sighandler;
1333 pTask->sighandler = newhandler;
1339 /***********************************************************************
1340 * GlobalNotify (KERNEL.154)
1342 * Note that GlobalNotify does _not_ return the old NotifyProc
1343 * -- contrary to LocalNotify !!
1345 VOID WINAPI GlobalNotify16( FARPROC16 proc )
1349 if (!(pTask = TASK_GetCurrent())) return;
1350 pTask->discardhandler = proc;
1354 /***********************************************************************
1357 static inline HMODULE16 GetExePtrHelper( HANDLE16 handle, HTASK16 *hTask )
1362 /* Check for module handle */
1364 if (!(ptr = GlobalLock16( handle ))) return 0;
1365 if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return handle;
1367 /* Search for this handle inside all tasks */
1369 *hTask = hFirstTask;
1372 TDB *pTask = TASK_GetPtr( *hTask );
1373 if ((*hTask == handle) ||
1374 (pTask->hInstance == handle) ||
1375 (pTask->hQueue == handle) ||
1376 (pTask->hPDB == handle)) return pTask->hModule;
1377 *hTask = pTask->hNext;
1380 /* Check the owner for module handle */
1382 owner = FarGetOwner16( handle );
1383 if (!(ptr = GlobalLock16( owner ))) return 0;
1384 if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return owner;
1386 /* Search for the owner inside all tasks */
1388 *hTask = hFirstTask;
1391 TDB *pTask = TASK_GetPtr( *hTask );
1392 if ((*hTask == owner) ||
1393 (pTask->hInstance == owner) ||
1394 (pTask->hQueue == owner) ||
1395 (pTask->hPDB == owner)) return pTask->hModule;
1396 *hTask = pTask->hNext;
1402 /***********************************************************************
1403 * GetExePtr (KERNEL.133)
1405 HMODULE16 WINAPI WIN16_GetExePtr( HANDLE16 handle )
1408 HMODULE16 hModule = GetExePtrHelper( handle, &hTask );
1409 STACK16FRAME *frame = CURRENT_STACK16;
1410 frame->ecx = hModule;
1411 if (hTask) frame->es = hTask;
1416 /***********************************************************************
1419 HMODULE16 WINAPI GetExePtr( HANDLE16 handle )
1422 return GetExePtrHelper( handle, &hTask );
1426 /***********************************************************************
1427 * TaskFirst (TOOLHELP.63)
1429 BOOL16 WINAPI TaskFirst16( TASKENTRY *lpte )
1431 lpte->hNext = hFirstTask;
1432 return TaskNext16( lpte );
1436 /***********************************************************************
1437 * TaskNext (TOOLHELP.64)
1439 BOOL16 WINAPI TaskNext16( TASKENTRY *lpte )
1442 INSTANCEDATA *pInstData;
1444 TRACE_(toolhelp)("(%p): task=%04x\n", lpte, lpte->hNext );
1445 if (!lpte->hNext) return FALSE;
1447 /* make sure that task and hInstance are valid (skip initial Wine task !) */
1449 pTask = TASK_GetPtr( lpte->hNext );
1450 if (!pTask || pTask->magic != TDB_MAGIC) return FALSE;
1451 if (pTask->hInstance)
1453 lpte->hNext = pTask->hNext;
1455 pInstData = MapSL( MAKESEGPTR( GlobalHandleToSel16(pTask->hInstance), 0 ) );
1456 lpte->hTask = lpte->hNext;
1457 lpte->hTaskParent = pTask->hParent;
1458 lpte->hInst = pTask->hInstance;
1459 lpte->hModule = pTask->hModule;
1460 lpte->wSS = SELECTOROF( pTask->teb->cur_stack );
1461 lpte->wSP = OFFSETOF( pTask->teb->cur_stack );
1462 lpte->wStackTop = pInstData->stacktop;
1463 lpte->wStackMinimum = pInstData->stackmin;
1464 lpte->wStackBottom = pInstData->stackbottom;
1465 lpte->wcEvents = pTask->nEvents;
1466 lpte->hQueue = pTask->hQueue;
1467 lstrcpynA( lpte->szModule, pTask->module_name, sizeof(lpte->szModule) );
1468 lpte->wPSPOffset = 0x100; /*??*/
1469 lpte->hNext = pTask->hNext;
1474 /***********************************************************************
1475 * TaskFindHandle (TOOLHELP.65)
1477 BOOL16 WINAPI TaskFindHandle16( TASKENTRY *lpte, HTASK16 hTask )
1479 lpte->hNext = hTask;
1480 return TaskNext16( lpte );
1484 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND hWnd, LPCSTR text, LPCSTR title, UINT type);
1486 /**************************************************************************
1487 * FatalAppExit (KERNEL.137)
1489 void WINAPI FatalAppExit16( UINT16 action, LPCSTR str )
1491 TDB *pTask = TASK_GetCurrent();
1493 if (!pTask || !(pTask->error_mode & SEM_NOGPFAULTERRORBOX))
1495 HMODULE mod = GetModuleHandleA( "user32.dll" );
1498 MessageBoxA_funcptr pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
1501 pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
1505 ERR( "%s\n", debugstr_a(str) );
1512 /***********************************************************************
1513 * TerminateApp (TOOLHELP.77)
1515 * See "Undocumented Windows".
1517 void WINAPI TerminateApp16(HTASK16 hTask, WORD wFlags)
1519 if (hTask && hTask != GetCurrentTask())
1521 FIXME("cannot terminate task %x\n", hTask);
1525 if (wFlags & NO_UAE_BOX)
1528 old_mode = SetErrorMode16(0);
1529 SetErrorMode16(old_mode|SEM_NOGPFAULTERRORBOX);
1531 FatalAppExit16( 0, NULL );
1533 /* hmm, we're still alive ?? */
1535 /* check undocumented flag */
1536 if (!(wFlags & 0x8000))
1537 TASK_CallTaskSignalProc( USIG16_TERMINATION, hTask );
1539 /* UndocWin says to call int 0x21/0x4c exit=0xff here,
1540 but let's just call ExitThread */
1545 /***********************************************************************
1546 * GetAppCompatFlags (KERNEL.354)
1548 DWORD WINAPI GetAppCompatFlags16( HTASK16 hTask )
1552 if (!hTask) hTask = GetCurrentTask();
1553 if (!(pTask=TASK_GetPtr( hTask ))) return 0;
1554 if (GlobalSize16(hTask) < sizeof(TDB)) return 0;
1555 return pTask->compat_flags;
1559 /***********************************************************************
1560 * GetDOSEnvironment (KERNEL.131)
1562 * Note: the environment is allocated once, it doesn't track changes
1563 * made using the Win32 API. This shouldn't matter.
1565 * Format of a 16-bit environment block:
1566 * ASCIIZ string 1 (xx=yy format)
1571 * ASCIIZ program name (e.g. C:\WINDOWS\SYSTEM\KRNL386.EXE)
1573 SEGPTR WINAPI GetDOSEnvironment16(void)
1575 static const char ENV_program_name[] = "C:\\WINDOWS\\SYSTEM\\KRNL386.EXE";
1576 static HGLOBAL16 handle; /* handle to the 16 bit environment */
1583 p = env = GetEnvironmentStringsA();
1584 while (*p) p += strlen(p) + 1;
1585 p++; /* skip last null */
1586 size = (p - env) + sizeof(WORD) + sizeof(ENV_program_name);
1587 handle = GlobalAlloc16( GMEM_FIXED, size );
1591 LPSTR env16 = GlobalLock16( handle );
1592 memcpy( env16, env, p - env );
1593 memcpy( env16 + (p - env), &one, sizeof(one));
1594 memcpy( env16 + (p - env) + sizeof(WORD), ENV_program_name, sizeof(ENV_program_name));
1595 GlobalUnlock16( handle );
1597 FreeEnvironmentStringsA( env );
1599 return K32WOWGlobalLock16( handle );