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"
45 #include "wine/server.h"
46 #include "stackframe.h"
50 #include "kernel_private.h"
52 #include "wine/debug.h"
54 WINE_DEFAULT_DEBUG_CHANNEL(task);
55 WINE_DECLARE_DEBUG_CHANNEL(relay);
56 WINE_DECLARE_DEBUG_CHANNEL(toolhelp);
58 /* Min. number of thunks allocated when creating a new segment */
61 static THHOOK DefaultThhook;
62 THHOOK *pThhook = &DefaultThhook;
64 #define hFirstTask (pThhook->HeadTDB)
65 #define hLockedTask (pThhook->LockTDB)
67 static UINT16 nTaskCount = 0;
69 static HTASK16 initial_task;
71 /***********************************************************************
74 void TASK_InstallTHHook( THHOOK *pNewThhook )
76 THHOOK *pOldThhook = pThhook;
78 pThhook = pNewThhook? pNewThhook : &DefaultThhook;
80 *pThhook = *pOldThhook;
83 /***********************************************************************
86 static TDB *TASK_GetPtr( HTASK16 hTask )
88 return GlobalLock16( hTask );
92 /***********************************************************************
95 TDB *TASK_GetCurrent(void)
97 return TASK_GetPtr( GetCurrentTask() );
101 /***********************************************************************
104 static void TASK_LinkTask( HTASK16 hTask )
109 if (!(pTask = TASK_GetPtr( hTask ))) return;
110 prevTask = &hFirstTask;
113 TDB *prevTaskPtr = TASK_GetPtr( *prevTask );
114 if (prevTaskPtr->priority >= pTask->priority) break;
115 prevTask = &prevTaskPtr->hNext;
117 pTask->hNext = *prevTask;
123 /***********************************************************************
126 static void TASK_UnlinkTask( HTASK16 hTask )
131 prevTask = &hFirstTask;
132 while (*prevTask && (*prevTask != hTask))
134 pTask = TASK_GetPtr( *prevTask );
135 prevTask = &pTask->hNext;
139 pTask = TASK_GetPtr( *prevTask );
140 *prevTask = pTask->hNext;
147 /***********************************************************************
150 * Create a thunk free-list in segment 'handle', starting from offset 'offset'
151 * and containing 'count' entries.
153 static void TASK_CreateThunks( HGLOBAL16 handle, WORD offset, WORD count )
159 pThunk = (THUNKS *)((BYTE *)GlobalLock16( handle ) + offset);
161 pThunk->magic = THUNK_MAGIC;
162 pThunk->free = (int)&pThunk->thunks - (int)pThunk;
164 for (i = 0; i < count-1; i++)
166 free += 8; /* Offset of next thunk */
167 pThunk->thunks[4*i] = free;
169 pThunk->thunks[4*i] = 0; /* Last thunk */
173 /***********************************************************************
176 * Allocate a thunk for MakeProcInstance().
178 static SEGPTR TASK_AllocThunk(void)
184 if (!(pTask = TASK_GetCurrent())) return 0;
185 sel = pTask->hCSAlias;
186 pThunk = &pTask->thunks;
187 base = (int)pThunk - (int)pTask;
188 while (!pThunk->free)
191 if (!sel) /* Allocate a new segment */
193 sel = GLOBAL_Alloc( GMEM_FIXED, sizeof(THUNKS) + (MIN_THUNKS-1)*8,
194 pTask->hPDB, WINE_LDT_FLAGS_CODE );
195 if (!sel) return (SEGPTR)0;
196 TASK_CreateThunks( sel, 0, MIN_THUNKS );
199 pThunk = (THUNKS *)GlobalLock16( sel );
202 base += pThunk->free;
203 pThunk->free = *(WORD *)((BYTE *)pThunk + pThunk->free);
204 return MAKESEGPTR( sel, base );
208 /***********************************************************************
211 * Free a MakeProcInstance() thunk.
213 static BOOL TASK_FreeThunk( SEGPTR thunk )
219 if (!(pTask = TASK_GetCurrent())) return 0;
220 sel = pTask->hCSAlias;
221 pThunk = &pTask->thunks;
222 base = (int)pThunk - (int)pTask;
223 while (sel && (sel != HIWORD(thunk)))
226 pThunk = (THUNKS *)GlobalLock16( sel );
229 if (!sel) return FALSE;
230 *(WORD *)((BYTE *)pThunk + LOWORD(thunk) - base) = pThunk->free;
231 pThunk->free = LOWORD(thunk) - base;
236 /***********************************************************************
239 * NOTE: This routine might be called by a Win32 thread. Thus, we need
240 * to be careful to protect global data structures. We do this
241 * by entering the Win16Lock while linking the task into the
244 static TDB *TASK_Create( NE_MODULE *pModule, UINT16 cmdShow, TEB *teb, LPCSTR cmdline, BYTE len )
249 HMODULE16 hModule = pModule ? pModule->self : 0;
251 /* Allocate the task structure */
253 hTask = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, sizeof(TDB) );
254 if (!hTask) return NULL;
255 pTask = TASK_GetPtr( hTask );
256 FarSetOwner16( hTask, hModule );
258 /* Fill the task structure */
260 pTask->hSelf = hTask;
262 if (teb && teb->tibflags & TEBF_WIN32)
264 pTask->flags |= TDBF_WIN32;
265 pTask->hInstance = hModule;
266 pTask->hPrevInstance = 0;
267 /* NOTE: for 16-bit tasks, the instance handles are updated later on
271 pTask->version = pModule ? pModule->expected_version : 0x0400;
272 pTask->hModule = hModule;
273 pTask->hParent = GetCurrentTask();
274 pTask->magic = TDB_MAGIC;
275 pTask->nCmdShow = cmdShow;
277 pTask->curdrive = DRIVE_GetCurrentDrive() | 0x80;
278 strcpy( pTask->curdir, "\\" );
279 WideCharToMultiByte(CP_ACP, 0, DRIVE_GetDosCwd(DRIVE_GetCurrentDrive()), -1,
280 pTask->curdir + 1, sizeof(pTask->curdir) - 1, NULL, NULL);
281 pTask->curdir[sizeof(pTask->curdir) - 1] = 0; /* ensure 0 termination */
283 /* Create the thunks block */
285 TASK_CreateThunks( hTask, (int)&pTask->thunks - (int)pTask, 7 );
287 /* Copy the module name */
292 GetModuleName16( hModule, name, sizeof(name) );
293 strncpy( pTask->module_name, name, sizeof(pTask->module_name) );
294 pTask->compat_flags = GetProfileIntA( "Compatibility", name, 0 );
297 /* Allocate a selector for the PDB */
299 pTask->hPDB = GLOBAL_CreateBlock( GMEM_FIXED, &pTask->pdb, sizeof(PDB16),
300 hModule, WINE_LDT_FLAGS_DATA );
304 pTask->pdb.int20 = 0x20cd;
305 pTask->pdb.dispatcher[0] = 0x9a; /* ljmp */
306 proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DOS3Call" );
307 memcpy( &pTask->pdb.dispatcher[1], &proc, sizeof(proc) );
308 pTask->pdb.savedint22 = 0;
309 pTask->pdb.savedint23 = 0;
310 pTask->pdb.savedint24 = 0;
311 pTask->pdb.fileHandlesPtr =
312 MAKESEGPTR( GlobalHandleToSel16(pTask->hPDB), (int)&((PDB16 *)0)->fileHandles );
313 pTask->pdb.hFileHandles = 0;
314 memset( pTask->pdb.fileHandles, 0xff, sizeof(pTask->pdb.fileHandles) );
315 /* FIXME: should we make a copy of the environment? */
316 pTask->pdb.environment = SELECTOROF(GetDOSEnvironment16());
317 pTask->pdb.nbFiles = 20;
319 /* Fill the command line */
323 cmdline = GetCommandLineA();
324 /* remove the first word (program name) */
326 if (!(cmdline = strchr( cmdline+1, '"' ))) cmdline = GetCommandLineA();
327 while (*cmdline && (*cmdline != ' ') && (*cmdline != '\t')) cmdline++;
328 while ((*cmdline == ' ') || (*cmdline == '\t')) cmdline++;
329 len = strlen(cmdline);
331 if (len >= sizeof(pTask->pdb.cmdLine)) len = sizeof(pTask->pdb.cmdLine)-1;
332 pTask->pdb.cmdLine[0] = len;
333 memcpy( pTask->pdb.cmdLine + 1, cmdline, len );
334 /* pTask->pdb.cmdLine[len+1] = 0; */
336 TRACE("cmdline='%.*s' task=%04x\n", len, cmdline, hTask );
338 /* Allocate a code segment alias for the TDB */
340 pTask->hCSAlias = GLOBAL_CreateBlock( GMEM_FIXED, (void *)pTask,
341 sizeof(TDB), pTask->hPDB, WINE_LDT_FLAGS_CODE );
343 /* Default DTA overwrites command line */
345 pTask->dta = MAKESEGPTR( pTask->hPDB, (int)&pTask->pdb.cmdLine - (int)&pTask->pdb );
347 /* Create scheduler event for 16-bit tasks */
349 if ( !(pTask->flags & TDBF_WIN32) )
350 NtCreateEvent( &pTask->hEvent, EVENT_ALL_ACCESS, NULL, TRUE, FALSE );
352 /* Enter task handle into thread */
354 if (teb) teb->htask16 = hTask;
355 if (!initial_task) initial_task = hTask;
361 /***********************************************************************
364 static void TASK_DeleteTask( HTASK16 hTask )
369 if (!(pTask = TASK_GetPtr( hTask ))) return;
372 pTask->magic = 0xdead; /* invalidate signature */
374 /* Free the selector aliases */
376 GLOBAL_FreeBlock( pTask->hCSAlias );
377 GLOBAL_FreeBlock( pTask->hPDB );
379 /* Free the task module */
381 FreeModule16( pTask->hModule );
383 /* Free the task structure itself */
385 GlobalFree16( hTask );
387 /* Free all memory used by this task (including the 32-bit stack, */
388 /* the environment block and the thunk segments). */
390 GlobalFreeAll16( hPDB );
394 /***********************************************************************
395 * TASK_CreateMainTask
397 * Create a task for the main (32-bit) process.
399 void TASK_CreateMainTask(void)
402 STARTUPINFOA startup_info;
403 UINT cmdShow = 1; /* SW_SHOWNORMAL but we don't want to include winuser.h here */
405 GetStartupInfoA( &startup_info );
406 if (startup_info.dwFlags & STARTF_USESHOWWINDOW) cmdShow = startup_info.wShowWindow;
407 pTask = TASK_Create( NULL, cmdShow, NtCurrentTeb(), NULL, 0 );
410 ERR("could not create task for main process\n");
414 /* Add the task to the linked list */
415 /* (no need to get the win16 lock, we are the only thread at this point) */
416 TASK_LinkTask( pTask->hSelf );
420 /* startup routine for a new 16-bit thread */
421 static DWORD CALLBACK task_start( TDB *pTask )
425 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
426 NtCurrentTeb()->htask16 = pTask->hSelf;
429 TASK_LinkTask( pTask->hSelf );
430 pTask->teb = NtCurrentTeb();
431 ret = NE_StartTask();
437 /***********************************************************************
440 * Spawn a new 16-bit task.
442 HTASK16 TASK_SpawnTask( NE_MODULE *pModule, WORD cmdShow,
443 LPCSTR cmdline, BYTE len, HANDLE *hThread )
447 if (!(pTask = TASK_Create( pModule, cmdShow, NULL, cmdline, len ))) return 0;
448 if (!(*hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)task_start, pTask, 0, NULL )))
450 TASK_DeleteTask( pTask->hSelf );
457 /***********************************************************************
458 * TASK_GetTaskFromThread
460 HTASK16 TASK_GetTaskFromThread( DWORD thread )
462 TDB *p = TASK_GetPtr( hFirstTask );
465 if (p->teb->ClientId.UniqueThread == (HANDLE)thread) return p->hSelf;
466 p = TASK_GetPtr( p->hNext );
472 /***********************************************************************
473 * TASK_CallTaskSignalProc
475 static void TASK_CallTaskSignalProc( UINT16 uCode, HANDLE16 hTaskOrModule )
478 TDB *pTask = TASK_GetCurrent();
480 if ( !pTask || !pTask->userhandler ) return;
482 args[4] = hTaskOrModule;
485 args[1] = pTask->hInstance;
486 args[0] = pTask->hQueue;
487 WOWCallback16Ex( (DWORD)pTask->userhandler, WCB16_PASCAL, sizeof(args), args, NULL );
491 /***********************************************************************
494 void TASK_ExitTask(void)
499 /* Enter the Win16Lock to protect global data structures */
502 pTask = TASK_GetCurrent();
509 TRACE("Killing task %04x\n", pTask->hSelf );
511 /* Perform USER cleanup */
513 TASK_CallTaskSignalProc( USIG16_TERMINATION, pTask->hSelf );
515 /* Remove the task from the list to be sure we never switch back to it */
516 TASK_UnlinkTask( pTask->hSelf );
518 if (!nTaskCount || (nTaskCount == 1 && hFirstTask == initial_task))
520 TRACE("this is the last task, exiting\n" );
526 if ( hLockedTask == pTask->hSelf )
529 TASK_DeleteTask( pTask->hSelf );
531 /* ... and completely release the Win16Lock, just in case. */
532 ReleaseThunkLock( &lockCount );
536 /***********************************************************************
537 * ExitKernel (KERNEL.2)
539 * Clean-up everything and exit the Wine process.
541 void WINAPI ExitKernel16(void)
543 WriteOutProfiles16();
544 TerminateProcess( GetCurrentProcess(), 0 );
548 /***********************************************************************
549 * InitTask (KERNEL.91)
551 * Called by the application startup code.
553 void WINAPI InitTask16( CONTEXT86 *context )
556 INSTANCEDATA *pinstance;
560 if (!(pTask = TASK_GetCurrent())) return;
562 /* Note: we need to trust that BX/CX contain the stack/heap sizes,
563 as some apps, notably Visual Basic apps, *modify* the heap/stack
564 size of the instance data segment before calling InitTask() */
566 /* Initialize the INSTANCEDATA structure */
567 pinstance = MapSL( MAKESEGPTR(CURRENT_DS, 0) );
568 pinstance->stackmin = OFFSETOF( NtCurrentTeb()->cur_stack ) + sizeof( STACK16FRAME );
569 pinstance->stackbottom = pinstance->stackmin; /* yup, that's right. Confused me too. */
570 pinstance->stacktop = ( pinstance->stackmin > LOWORD(context->Ebx) ?
571 pinstance->stackmin - LOWORD(context->Ebx) : 0 ) + 150;
573 /* Initialize the local heap */
574 if (LOWORD(context->Ecx))
575 LocalInit16( GlobalHandleToSel16(pTask->hInstance), 0, LOWORD(context->Ecx) );
577 /* Initialize implicitly loaded DLLs */
578 NE_InitializeDLLs( pTask->hModule );
579 NE_DllProcessAttach( pTask->hModule );
581 /* Registers on return are:
582 * ax 1 if OK, 0 on error
583 * cx stack limit in bytes
584 * dx cmdShow parameter
585 * si instance handle of the previous instance
586 * di instance handle of the new task
587 * es:bx pointer to command line inside PSP
589 * 0 (=%bp) is pushed on the stack
591 ptr = stack16_push( sizeof(WORD) );
592 *(WORD *)MapSL(ptr) = 0;
597 if (!pTask->pdb.cmdLine[0]) context->Ebx = 0x80;
600 LPBYTE p = &pTask->pdb.cmdLine[1];
601 while ((*p == ' ') || (*p == '\t')) p++;
602 context->Ebx = 0x80 + (p - pTask->pdb.cmdLine);
604 context->Ecx = pinstance->stacktop;
605 context->Edx = pTask->nCmdShow;
606 context->Esi = (DWORD)pTask->hPrevInstance;
607 context->Edi = (DWORD)pTask->hInstance;
608 context->SegEs = (WORD)pTask->hPDB;
612 /***********************************************************************
613 * WaitEvent (KERNEL.30)
615 BOOL16 WINAPI WaitEvent16( HTASK16 hTask )
619 if (!hTask) hTask = GetCurrentTask();
620 pTask = TASK_GetPtr( hTask );
622 if (pTask->flags & TDBF_WIN32)
624 FIXME("called for Win32 thread (%04lx)!\n", GetCurrentThreadId());
628 if (pTask->nEvents > 0)
634 if (pTask->teb == NtCurrentTeb())
638 NtResetEvent( pTask->hEvent, NULL );
639 ReleaseThunkLock( &lockCount );
640 SYSLEVEL_CheckNotLevel( 1 );
641 WaitForSingleObject( pTask->hEvent, INFINITE );
642 RestoreThunkLock( lockCount );
643 if (pTask->nEvents > 0) pTask->nEvents--;
645 else FIXME("for other task %04x cur=%04x\n",pTask->hSelf,GetCurrentTask());
651 /***********************************************************************
652 * PostEvent (KERNEL.31)
654 void WINAPI PostEvent16( HTASK16 hTask )
658 if (!hTask) hTask = GetCurrentTask();
659 if (!(pTask = TASK_GetPtr( hTask ))) return;
661 if (pTask->flags & TDBF_WIN32)
663 FIXME("called for Win32 thread (%04lx)!\n", (DWORD)pTask->teb->ClientId.UniqueThread );
669 if (pTask->nEvents == 1) NtSetEvent( pTask->hEvent, NULL );
673 /***********************************************************************
674 * SetPriority (KERNEL.32)
676 void WINAPI SetPriority16( HTASK16 hTask, INT16 delta )
681 if (!hTask) hTask = GetCurrentTask();
682 if (!(pTask = TASK_GetPtr( hTask ))) return;
683 newpriority = pTask->priority + delta;
684 if (newpriority < -32) newpriority = -32;
685 else if (newpriority > 15) newpriority = 15;
687 pTask->priority = newpriority + 1;
688 TASK_UnlinkTask( pTask->hSelf );
689 TASK_LinkTask( pTask->hSelf );
694 /***********************************************************************
695 * LockCurrentTask (KERNEL.33)
697 HTASK16 WINAPI LockCurrentTask16( BOOL16 bLock )
699 if (bLock) hLockedTask = GetCurrentTask();
700 else hLockedTask = 0;
705 /***********************************************************************
706 * IsTaskLocked (KERNEL.122)
708 HTASK16 WINAPI IsTaskLocked16(void)
714 /***********************************************************************
715 * OldYield (KERNEL.117)
717 void WINAPI OldYield16(void)
721 ReleaseThunkLock(&count);
722 RestoreThunkLock(count);
725 /***********************************************************************
726 * WIN32_OldYield (KERNEL.447)
728 void WINAPI WIN32_OldYield16(void)
732 ReleaseThunkLock(&count);
733 RestoreThunkLock(count);
736 /***********************************************************************
737 * DirectedYield (KERNEL.150)
739 void WINAPI DirectedYield16( HTASK16 hTask )
744 /***********************************************************************
747 void WINAPI Yield16(void)
749 TDB *pCurTask = TASK_GetCurrent();
751 if (pCurTask && pCurTask->hQueue)
753 HMODULE mod = GetModuleHandleA( "user32.dll" );
756 FARPROC proc = GetProcAddress( mod, "UserYield16" );
767 /***********************************************************************
768 * KERNEL_490 (KERNEL.490)
770 HTASK16 WINAPI KERNEL_490( HTASK16 someTask )
772 if ( !someTask ) return 0;
774 FIXME("(%04x): stub\n", someTask );
778 /***********************************************************************
779 * MakeProcInstance (KERNEL.51)
781 FARPROC16 WINAPI MakeProcInstance16( FARPROC16 func, HANDLE16 hInstance )
785 WORD hInstanceSelector;
787 hInstanceSelector = GlobalHandleToSel16(hInstance);
789 TRACE("(%08lx, %04x);\n", (DWORD)func, hInstance);
792 /* Win95 actually protects via SEH, but this is better for debugging */
793 WARN("Ouch ! Called with invalid func 0x%08lx !\n", (DWORD)func);
797 if ( (GlobalHandleToSel16(CURRENT_DS) != hInstanceSelector)
799 && (hInstance != 0xffff) )
801 /* calling MPI with a foreign DSEG is invalid ! */
802 WARN("Problem with hInstance? Got %04x, using %04x instead\n",
803 hInstance,CURRENT_DS);
806 /* Always use the DSEG that MPI was entered with.
807 * We used to set hInstance to GetTaskDS16(), but this should be wrong
808 * as CURRENT_DS provides the DSEG value we need.
809 * ("calling" DS, *not* "task" DS !) */
810 hInstanceSelector = CURRENT_DS;
811 hInstance = GlobalHandle16(hInstanceSelector);
813 /* no thunking for DLLs */
814 if (NE_GetPtr(FarGetOwner16(hInstance))->flags & NE_FFLAGS_LIBMODULE)
817 thunkaddr = TASK_AllocThunk();
818 if (!thunkaddr) return (FARPROC16)0;
819 thunk = MapSL( thunkaddr );
820 lfunc = MapSL( (SEGPTR)func );
822 TRACE("(%08lx,%04x): got thunk %08lx\n",
823 (DWORD)func, hInstance, (DWORD)thunkaddr );
824 if (((lfunc[0]==0x8c) && (lfunc[1]==0xd8)) || /* movw %ds, %ax */
825 ((lfunc[0]==0x1e) && (lfunc[1]==0x58)) /* pushw %ds, popw %ax */
827 WARN("This was the (in)famous \"thunk useless\" warning. We thought we have to overwrite with nop;nop;, but this isn't true.\n");
830 *thunk++ = 0xb8; /* movw instance, %ax */
831 *thunk++ = (BYTE)(hInstanceSelector & 0xff);
832 *thunk++ = (BYTE)(hInstanceSelector >> 8);
833 *thunk++ = 0xea; /* ljmp func */
834 *(DWORD *)thunk = (DWORD)func;
835 return (FARPROC16)thunkaddr;
836 /* CX reg indicates if thunkaddr != NULL, implement if needed */
840 /***********************************************************************
841 * FreeProcInstance (KERNEL.52)
843 void WINAPI FreeProcInstance16( FARPROC16 func )
845 TRACE("(%08lx)\n", (DWORD)func );
846 TASK_FreeThunk( (SEGPTR)func );
849 /**********************************************************************
850 * TASK_GetCodeSegment
852 * Helper function for GetCodeHandle/GetCodeInfo: Retrieve the module
853 * and logical segment number of a given code segment.
855 * 'proc' either *is* already a pair of module handle and segment number,
856 * in which case there's nothing to do. Otherwise, it is a pointer to
857 * a function, and we need to retrieve the code segment. If the pointer
858 * happens to point to a thunk, we'll retrieve info about the code segment
859 * where the function pointed to by the thunk resides, not the thunk itself.
861 * FIXME: if 'proc' is a SNOOP16 return stub, we should retrieve info about
862 * the function the snoop code will return to ...
865 static BOOL TASK_GetCodeSegment( FARPROC16 proc, NE_MODULE **ppModule,
866 SEGTABLEENTRY **ppSeg, int *pSegNr )
868 NE_MODULE *pModule = NULL;
869 SEGTABLEENTRY *pSeg = NULL;
872 /* Try pair of module handle / segment number */
873 pModule = (NE_MODULE *) GlobalLock16( HIWORD( proc ) );
874 if ( pModule && pModule->magic == IMAGE_OS2_SIGNATURE )
876 segNr = LOWORD( proc );
877 if ( segNr && segNr <= pModule->seg_count )
878 pSeg = NE_SEG_TABLE( pModule ) + segNr-1;
881 /* Try thunk or function */
884 BYTE *thunk = MapSL( (SEGPTR)proc );
887 if ((thunk[0] == 0xb8) && (thunk[3] == 0xea))
888 selector = thunk[6] + (thunk[7] << 8);
890 selector = HIWORD( proc );
892 pModule = NE_GetPtr( GlobalHandle16( selector ) );
893 pSeg = pModule? NE_SEG_TABLE( pModule ) : NULL;
896 for ( segNr = 1; segNr <= pModule->seg_count; segNr++, pSeg++ )
897 if ( GlobalHandleToSel16(pSeg->hSeg) == selector )
900 if ( pModule && segNr > pModule->seg_count )
904 /* Abort if segment not found */
906 if ( !pModule || !pSeg )
909 /* Return segment data */
911 if ( ppModule ) *ppModule = pModule;
912 if ( ppSeg ) *ppSeg = pSeg;
913 if ( pSegNr ) *pSegNr = segNr;
918 /**********************************************************************
919 * GetCodeHandle (KERNEL.93)
921 HANDLE16 WINAPI GetCodeHandle16( FARPROC16 proc )
925 if ( !TASK_GetCodeSegment( proc, NULL, &pSeg, NULL ) )
931 /**********************************************************************
932 * GetCodeInfo (KERNEL.104)
934 BOOL16 WINAPI GetCodeInfo16( FARPROC16 proc, SEGINFO *segInfo )
940 if ( !TASK_GetCodeSegment( proc, &pModule, &pSeg, &segNr ) )
943 /* Fill in segment information */
945 segInfo->offSegment = pSeg->filepos;
946 segInfo->cbSegment = pSeg->size;
947 segInfo->flags = pSeg->flags;
948 segInfo->cbAlloc = pSeg->minsize;
949 segInfo->h = pSeg->hSeg;
950 segInfo->alignShift = pModule->alignment;
952 if ( segNr == pModule->dgroup )
953 segInfo->cbAlloc += pModule->heap_size + pModule->stack_size;
955 /* Return module handle in %es */
957 CURRENT_STACK16->es = GlobalHandleToSel16( pModule->self );
963 /**********************************************************************
964 * DefineHandleTable (KERNEL.94)
966 BOOL16 WINAPI DefineHandleTable16( WORD wOffset )
968 FIXME("(%04x): stub ?\n", wOffset);
973 /***********************************************************************
974 * SetTaskQueue (KERNEL.34)
976 HQUEUE16 WINAPI SetTaskQueue16( HTASK16 hTask, HQUEUE16 hQueue )
981 if (!hTask) hTask = GetCurrentTask();
982 if (!(pTask = TASK_GetPtr( hTask ))) return 0;
984 hPrev = pTask->hQueue;
985 pTask->hQueue = hQueue;
991 /***********************************************************************
992 * GetTaskQueue (KERNEL.35)
994 HQUEUE16 WINAPI GetTaskQueue16( HTASK16 hTask )
998 if (!hTask) hTask = GetCurrentTask();
999 if (!(pTask = TASK_GetPtr( hTask ))) return 0;
1000 return pTask->hQueue;
1003 /***********************************************************************
1004 * SetThreadQueue (KERNEL.463)
1006 HQUEUE16 WINAPI SetThreadQueue16( DWORD thread, HQUEUE16 hQueue )
1008 HQUEUE16 oldQueue = NtCurrentTeb()->queue;
1010 if (thread && thread != GetCurrentThreadId())
1012 FIXME( "not supported on other thread %04lx\n", thread );
1015 NtCurrentTeb()->queue = hQueue;
1016 if ( GetTaskQueue16( NtCurrentTeb()->htask16 ) == oldQueue )
1017 SetTaskQueue16( NtCurrentTeb()->htask16, hQueue );
1021 /***********************************************************************
1022 * GetThreadQueue (KERNEL.464)
1024 HQUEUE16 WINAPI GetThreadQueue16( DWORD thread )
1026 if (thread && thread != GetCurrentThreadId())
1028 FIXME( "not supported on other thread %04lx\n", thread );
1031 return NtCurrentTeb()->queue;
1034 /***********************************************************************
1035 * SetFastQueue (KERNEL.624)
1037 VOID WINAPI SetFastQueue16( DWORD thread, HQUEUE16 hQueue )
1039 if (!thread || thread == GetCurrentThreadId())
1040 NtCurrentTeb()->queue = hQueue;
1042 FIXME( "not supported on other thread %04lx\n", thread );
1045 /***********************************************************************
1046 * GetFastQueue (KERNEL.625)
1048 HQUEUE16 WINAPI GetFastQueue16( void )
1050 HQUEUE16 ret = NtCurrentTeb()->queue;
1052 if (!ret) FIXME("(): should initialize thread-local queue, expect failure!\n" );
1056 /***********************************************************************
1057 * SwitchStackTo (KERNEL.108)
1059 void WINAPI SwitchStackTo16( WORD seg, WORD ptr, WORD top )
1061 STACK16FRAME *oldFrame, *newFrame;
1062 INSTANCEDATA *pData;
1065 if (!(pData = (INSTANCEDATA *)GlobalLock16( seg ))) return;
1066 TRACE("old=%04x:%04x new=%04x:%04x\n",
1067 SELECTOROF( NtCurrentTeb()->cur_stack ),
1068 OFFSETOF( NtCurrentTeb()->cur_stack ), seg, ptr );
1070 /* Save the old stack */
1072 oldFrame = CURRENT_STACK16;
1073 /* pop frame + args and push bp */
1074 pData->old_ss_sp = NtCurrentTeb()->cur_stack + sizeof(STACK16FRAME)
1076 *(WORD *)MapSL(pData->old_ss_sp) = oldFrame->bp;
1077 pData->stacktop = top;
1078 pData->stackmin = ptr;
1079 pData->stackbottom = ptr;
1081 /* Switch to the new stack */
1083 /* Note: we need to take the 3 arguments into account; otherwise,
1084 * the stack will underflow upon return from this function.
1086 copySize = oldFrame->bp - OFFSETOF(pData->old_ss_sp);
1087 copySize += 3 * sizeof(WORD) + sizeof(STACK16FRAME);
1088 NtCurrentTeb()->cur_stack = MAKESEGPTR( seg, ptr - copySize );
1089 newFrame = CURRENT_STACK16;
1091 /* Copy the stack frame and the local variables to the new stack */
1093 memmove( newFrame, oldFrame, copySize );
1095 *(WORD *)MapSL( MAKESEGPTR( seg, ptr ) ) = 0; /* clear previous bp */
1099 /***********************************************************************
1100 * SwitchStackBack (KERNEL.109)
1102 void WINAPI SwitchStackBack16( CONTEXT86 *context )
1104 STACK16FRAME *oldFrame, *newFrame;
1105 INSTANCEDATA *pData;
1107 if (!(pData = (INSTANCEDATA *)GlobalLock16(SELECTOROF(NtCurrentTeb()->cur_stack))))
1109 if (!pData->old_ss_sp)
1111 WARN("No previous SwitchStackTo\n" );
1114 TRACE("restoring stack %04x:%04x\n",
1115 SELECTOROF(pData->old_ss_sp), OFFSETOF(pData->old_ss_sp) );
1117 oldFrame = CURRENT_STACK16;
1119 /* Pop bp from the previous stack */
1121 context->Ebp = (context->Ebp & ~0xffff) | *(WORD *)MapSL(pData->old_ss_sp);
1122 pData->old_ss_sp += sizeof(WORD);
1124 /* Switch back to the old stack */
1126 NtCurrentTeb()->cur_stack = pData->old_ss_sp - sizeof(STACK16FRAME);
1127 context->SegSs = SELECTOROF(pData->old_ss_sp);
1128 context->Esp = OFFSETOF(pData->old_ss_sp) - sizeof(DWORD); /*ret addr*/
1129 pData->old_ss_sp = 0;
1131 /* Build a stack frame for the return */
1133 newFrame = CURRENT_STACK16;
1134 newFrame->frame32 = oldFrame->frame32;
1135 newFrame->module_cs = oldFrame->module_cs;
1136 newFrame->callfrom_ip = oldFrame->callfrom_ip;
1137 newFrame->entry_ip = oldFrame->entry_ip;
1141 /***********************************************************************
1142 * GetTaskQueueDS (KERNEL.118)
1144 void WINAPI GetTaskQueueDS16(void)
1146 CURRENT_STACK16->ds = GlobalHandleToSel16( GetTaskQueue16(0) );
1150 /***********************************************************************
1151 * GetTaskQueueES (KERNEL.119)
1153 void WINAPI GetTaskQueueES16(void)
1155 CURRENT_STACK16->es = GlobalHandleToSel16( GetTaskQueue16(0) );
1159 /***********************************************************************
1160 * GetCurrentTask (KERNEL32.@)
1162 HTASK16 WINAPI GetCurrentTask(void)
1164 return NtCurrentTeb()->htask16;
1167 /***********************************************************************
1168 * GetCurrentTask (KERNEL.36)
1170 DWORD WINAPI WIN16_GetCurrentTask(void)
1172 /* This is the version used by relay code; the first task is */
1173 /* returned in the high word of the result */
1174 return MAKELONG( GetCurrentTask(), hFirstTask );
1178 /***********************************************************************
1179 * GetCurrentPDB (KERNEL.37)
1181 * UNDOC: returns PSP of KERNEL in high word
1183 DWORD WINAPI GetCurrentPDB16(void)
1187 if (!(pTask = TASK_GetCurrent())) return 0;
1188 return MAKELONG(pTask->hPDB, 0); /* FIXME */
1192 /***********************************************************************
1193 * GetCurPID (KERNEL.157)
1195 DWORD WINAPI GetCurPID16( DWORD unused )
1201 /***********************************************************************
1202 * GetInstanceData (KERNEL.54)
1204 INT16 WINAPI GetInstanceData16( HINSTANCE16 instance, WORD buffer, INT16 len )
1206 char *ptr = (char *)GlobalLock16( instance );
1207 if (!ptr || !len) return 0;
1208 if ((int)buffer + len >= 0x10000) len = 0x10000 - buffer;
1209 memcpy( (char *)GlobalLock16(CURRENT_DS) + buffer, ptr + buffer, len );
1214 /***********************************************************************
1215 * GetExeVersion (KERNEL.105)
1217 WORD WINAPI GetExeVersion16(void)
1221 if (!(pTask = TASK_GetCurrent())) return 0;
1222 return pTask->version;
1226 /***********************************************************************
1227 * SetErrorMode (KERNEL.107)
1229 UINT16 WINAPI SetErrorMode16( UINT16 mode )
1232 if (!(pTask = TASK_GetCurrent())) return 0;
1233 pTask->error_mode = mode;
1234 return SetErrorMode( mode );
1238 /***********************************************************************
1239 * GetNumTasks (KERNEL.152)
1241 UINT16 WINAPI GetNumTasks16(void)
1247 /***********************************************************************
1248 * GetTaskDS (KERNEL.155)
1250 * Note: this function apparently returns a DWORD with LOWORD == HIWORD.
1251 * I don't think we need to bother with this.
1253 HINSTANCE16 WINAPI GetTaskDS16(void)
1257 if (!(pTask = TASK_GetCurrent())) return 0;
1258 return GlobalHandleToSel16(pTask->hInstance);
1261 /***********************************************************************
1262 * GetDummyModuleHandleDS (KERNEL.602)
1264 WORD WINAPI GetDummyModuleHandleDS16(void)
1269 if (!(pTask = TASK_GetCurrent())) return 0;
1270 if (!(pTask->flags & TDBF_WIN32)) return 0;
1271 selector = GlobalHandleToSel16( pTask->hModule );
1272 CURRENT_DS = selector;
1276 /***********************************************************************
1277 * IsTask (KERNEL.320)
1279 BOOL16 WINAPI IsTask16( HTASK16 hTask )
1283 if (!(pTask = TASK_GetPtr( hTask ))) return FALSE;
1284 if (GlobalSize16( hTask ) < sizeof(TDB)) return FALSE;
1285 return (pTask->magic == TDB_MAGIC);
1289 /***********************************************************************
1290 * IsWinOldApTask (KERNEL.158)
1292 BOOL16 WINAPI IsWinOldApTask16( HTASK16 hTask )
1294 /* should return bit 0 of byte 0x48 in PSP */
1298 /***********************************************************************
1299 * SetTaskSignalProc (KERNEL.38)
1301 FARPROC16 WINAPI SetTaskSignalProc( HTASK16 hTask, FARPROC16 proc )
1306 if (!hTask) hTask = GetCurrentTask();
1307 if (!(pTask = TASK_GetPtr( hTask ))) return NULL;
1308 oldProc = pTask->userhandler;
1309 pTask->userhandler = proc;
1313 /***********************************************************************
1314 * SetSigHandler (KERNEL.140)
1316 WORD WINAPI SetSigHandler16( FARPROC16 newhandler, FARPROC16* oldhandler,
1317 UINT16 *oldmode, UINT16 newmode, UINT16 flag )
1319 FIXME("(%p,%p,%p,%d,%d), unimplemented.\n",
1320 newhandler,oldhandler,oldmode,newmode,flag );
1322 if (flag != 1) return 0;
1323 if (!newmode) newhandler = NULL; /* Default handler */
1328 if (!(pTask = TASK_GetCurrent())) return 0;
1329 if (oldmode) *oldmode = pTask->signal_flags;
1330 pTask->signal_flags = newmode;
1331 if (oldhandler) *oldhandler = pTask->sighandler;
1332 pTask->sighandler = newhandler;
1338 /***********************************************************************
1339 * GlobalNotify (KERNEL.154)
1341 * Note that GlobalNotify does _not_ return the old NotifyProc
1342 * -- contrary to LocalNotify !!
1344 VOID WINAPI GlobalNotify16( FARPROC16 proc )
1348 if (!(pTask = TASK_GetCurrent())) return;
1349 pTask->discardhandler = proc;
1353 /***********************************************************************
1356 static inline HMODULE16 GetExePtrHelper( HANDLE16 handle, HTASK16 *hTask )
1361 /* Check for module handle */
1363 if (!(ptr = GlobalLock16( handle ))) return 0;
1364 if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return handle;
1366 /* Search for this handle inside all tasks */
1368 *hTask = hFirstTask;
1371 TDB *pTask = TASK_GetPtr( *hTask );
1372 if ((*hTask == handle) ||
1373 (pTask->hInstance == handle) ||
1374 (pTask->hQueue == handle) ||
1375 (pTask->hPDB == handle)) return pTask->hModule;
1376 *hTask = pTask->hNext;
1379 /* Check the owner for module handle */
1381 owner = FarGetOwner16( handle );
1382 if (!(ptr = GlobalLock16( owner ))) return 0;
1383 if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return owner;
1385 /* Search for the owner inside all tasks */
1387 *hTask = hFirstTask;
1390 TDB *pTask = TASK_GetPtr( *hTask );
1391 if ((*hTask == owner) ||
1392 (pTask->hInstance == owner) ||
1393 (pTask->hQueue == owner) ||
1394 (pTask->hPDB == owner)) return pTask->hModule;
1395 *hTask = pTask->hNext;
1401 /***********************************************************************
1402 * GetExePtr (KERNEL.133)
1404 HMODULE16 WINAPI WIN16_GetExePtr( HANDLE16 handle )
1407 HMODULE16 hModule = GetExePtrHelper( handle, &hTask );
1408 STACK16FRAME *frame = CURRENT_STACK16;
1409 frame->ecx = hModule;
1410 if (hTask) frame->es = hTask;
1415 /***********************************************************************
1418 HMODULE16 WINAPI GetExePtr( HANDLE16 handle )
1421 return GetExePtrHelper( handle, &hTask );
1425 /***********************************************************************
1426 * TaskFirst (TOOLHELP.63)
1428 BOOL16 WINAPI TaskFirst16( TASKENTRY *lpte )
1430 lpte->hNext = hFirstTask;
1431 return TaskNext16( lpte );
1435 /***********************************************************************
1436 * TaskNext (TOOLHELP.64)
1438 BOOL16 WINAPI TaskNext16( TASKENTRY *lpte )
1441 INSTANCEDATA *pInstData;
1443 TRACE_(toolhelp)("(%p): task=%04x\n", lpte, lpte->hNext );
1444 if (!lpte->hNext) return FALSE;
1446 /* make sure that task and hInstance are valid (skip initial Wine task !) */
1448 pTask = TASK_GetPtr( lpte->hNext );
1449 if (!pTask || pTask->magic != TDB_MAGIC) return FALSE;
1450 if (pTask->hInstance)
1452 lpte->hNext = pTask->hNext;
1454 pInstData = MapSL( MAKESEGPTR( GlobalHandleToSel16(pTask->hInstance), 0 ) );
1455 lpte->hTask = lpte->hNext;
1456 lpte->hTaskParent = pTask->hParent;
1457 lpte->hInst = pTask->hInstance;
1458 lpte->hModule = pTask->hModule;
1459 lpte->wSS = SELECTOROF( pTask->teb->cur_stack );
1460 lpte->wSP = OFFSETOF( pTask->teb->cur_stack );
1461 lpte->wStackTop = pInstData->stacktop;
1462 lpte->wStackMinimum = pInstData->stackmin;
1463 lpte->wStackBottom = pInstData->stackbottom;
1464 lpte->wcEvents = pTask->nEvents;
1465 lpte->hQueue = pTask->hQueue;
1466 lstrcpynA( lpte->szModule, pTask->module_name, sizeof(lpte->szModule) );
1467 lpte->wPSPOffset = 0x100; /*??*/
1468 lpte->hNext = pTask->hNext;
1473 /***********************************************************************
1474 * TaskFindHandle (TOOLHELP.65)
1476 BOOL16 WINAPI TaskFindHandle16( TASKENTRY *lpte, HTASK16 hTask )
1478 lpte->hNext = hTask;
1479 return TaskNext16( lpte );
1483 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND hWnd, LPCSTR text, LPCSTR title, UINT type);
1485 /**************************************************************************
1486 * FatalAppExit (KERNEL.137)
1488 void WINAPI FatalAppExit16( UINT16 action, LPCSTR str )
1490 TDB *pTask = TASK_GetCurrent();
1492 if (!pTask || !(pTask->error_mode & SEM_NOGPFAULTERRORBOX))
1494 HMODULE mod = GetModuleHandleA( "user32.dll" );
1497 MessageBoxA_funcptr pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
1500 pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
1504 ERR( "%s\n", debugstr_a(str) );
1511 /***********************************************************************
1512 * TerminateApp (TOOLHELP.77)
1514 * See "Undocumented Windows".
1516 void WINAPI TerminateApp16(HTASK16 hTask, WORD wFlags)
1518 if (hTask && hTask != GetCurrentTask())
1520 FIXME("cannot terminate task %x\n", hTask);
1524 if (wFlags & NO_UAE_BOX)
1527 old_mode = SetErrorMode16(0);
1528 SetErrorMode16(old_mode|SEM_NOGPFAULTERRORBOX);
1530 FatalAppExit16( 0, NULL );
1532 /* hmm, we're still alive ?? */
1534 /* check undocumented flag */
1535 if (!(wFlags & 0x8000))
1536 TASK_CallTaskSignalProc( USIG16_TERMINATION, hTask );
1538 /* UndocWin says to call int 0x21/0x4c exit=0xff here,
1539 but let's just call ExitThread */
1544 /***********************************************************************
1545 * GetAppCompatFlags (KERNEL.354)
1547 DWORD WINAPI GetAppCompatFlags16( HTASK16 hTask )
1551 if (!hTask) hTask = GetCurrentTask();
1552 if (!(pTask=TASK_GetPtr( hTask ))) return 0;
1553 if (GlobalSize16(hTask) < sizeof(TDB)) return 0;
1554 return pTask->compat_flags;
1558 /***********************************************************************
1559 * GetDOSEnvironment (KERNEL.131)
1561 * Note: the environment is allocated once, it doesn't track changes
1562 * made using the Win32 API. This shouldn't matter.
1564 * Format of a 16-bit environment block:
1565 * ASCIIZ string 1 (xx=yy format)
1570 * ASCIIZ program name (e.g. C:\WINDOWS\SYSTEM\KRNL386.EXE)
1572 SEGPTR WINAPI GetDOSEnvironment16(void)
1574 static const char ENV_program_name[] = "C:\\WINDOWS\\SYSTEM\\KRNL386.EXE";
1575 static HGLOBAL16 handle; /* handle to the 16 bit environment */
1582 p = env = GetEnvironmentStringsA();
1583 while (*p) p += strlen(p) + 1;
1584 p++; /* skip last null */
1585 size = (p - env) + sizeof(WORD) + sizeof(ENV_program_name);
1586 handle = GlobalAlloc16( GMEM_FIXED, size );
1590 LPSTR env16 = GlobalLock16( handle );
1591 memcpy( env16, env, p - env );
1592 memcpy( env16 + (p - env), &one, sizeof(one));
1593 memcpy( env16 + (p - env) + sizeof(WORD), ENV_program_name, sizeof(ENV_program_name));
1594 GlobalUnlock16( handle );
1596 FreeEnvironmentStringsA( env );
1598 return K32WOWGlobalLock16( handle );