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"
44 #include "wine/server.h"
45 #include "stackframe.h"
48 #include "kernel_private.h"
50 #include "wine/debug.h"
52 WINE_DEFAULT_DEBUG_CHANNEL(task);
53 WINE_DECLARE_DEBUG_CHANNEL(relay);
54 WINE_DECLARE_DEBUG_CHANNEL(toolhelp);
58 /* Segment containing MakeProcInstance() thunks */
61 WORD next; /* Selector of next segment */
62 WORD magic; /* Thunks signature */
64 WORD free; /* Head of the free list */
65 WORD thunks[4]; /* Each thunk is 4 words long */
70 #define THUNK_MAGIC ('P' | ('T' << 8))
72 /* Min. number of thunks allocated when creating a new segment */
75 #define TDB_MAGIC ('T' | ('D' << 8))
77 static THHOOK DefaultThhook;
78 THHOOK *pThhook = &DefaultThhook;
80 #define hFirstTask (pThhook->HeadTDB)
81 #define hLockedTask (pThhook->LockTDB)
83 static UINT16 nTaskCount = 0;
85 static HTASK16 initial_task;
87 /***********************************************************************
90 void TASK_InstallTHHook( THHOOK *pNewThhook )
92 THHOOK *pOldThhook = pThhook;
94 pThhook = pNewThhook? pNewThhook : &DefaultThhook;
96 *pThhook = *pOldThhook;
99 /***********************************************************************
102 static TDB *TASK_GetPtr( HTASK16 hTask )
104 return GlobalLock16( hTask );
108 /***********************************************************************
111 TDB *TASK_GetCurrent(void)
113 return TASK_GetPtr( GetCurrentTask() );
117 /***********************************************************************
120 static void TASK_LinkTask( HTASK16 hTask )
125 if (!(pTask = TASK_GetPtr( hTask ))) return;
126 prevTask = &hFirstTask;
129 TDB *prevTaskPtr = TASK_GetPtr( *prevTask );
130 if (prevTaskPtr->priority >= pTask->priority) break;
131 prevTask = &prevTaskPtr->hNext;
133 pTask->hNext = *prevTask;
139 /***********************************************************************
142 static void TASK_UnlinkTask( HTASK16 hTask )
147 prevTask = &hFirstTask;
148 while (*prevTask && (*prevTask != hTask))
150 pTask = TASK_GetPtr( *prevTask );
151 prevTask = &pTask->hNext;
155 pTask = TASK_GetPtr( *prevTask );
156 *prevTask = pTask->hNext;
163 /***********************************************************************
166 * Create a thunk free-list in segment 'handle', starting from offset 'offset'
167 * and containing 'count' entries.
169 static void TASK_CreateThunks( HGLOBAL16 handle, WORD offset, WORD count )
175 pThunk = (THUNKS *)((BYTE *)GlobalLock16( handle ) + offset);
177 pThunk->magic = THUNK_MAGIC;
178 pThunk->free = (int)&pThunk->thunks - (int)pThunk;
180 for (i = 0; i < count-1; i++)
182 free += 8; /* Offset of next thunk */
183 pThunk->thunks[4*i] = free;
185 pThunk->thunks[4*i] = 0; /* Last thunk */
189 /***********************************************************************
192 * Allocate a thunk for MakeProcInstance().
194 static SEGPTR TASK_AllocThunk(void)
200 if (!(pTask = TASK_GetCurrent())) return 0;
201 sel = pTask->hCSAlias;
202 pThunk = (THUNKS *)&pTask->thunks;
203 base = (char *)pThunk - (char *)pTask;
204 while (!pThunk->free)
207 if (!sel) /* Allocate a new segment */
209 sel = GLOBAL_Alloc( GMEM_FIXED, sizeof(THUNKS) + (MIN_THUNKS-1)*8,
210 pTask->hPDB, WINE_LDT_FLAGS_CODE );
211 if (!sel) return (SEGPTR)0;
212 TASK_CreateThunks( sel, 0, MIN_THUNKS );
215 pThunk = (THUNKS *)GlobalLock16( sel );
218 base += pThunk->free;
219 pThunk->free = *(WORD *)((BYTE *)pThunk + pThunk->free);
220 return MAKESEGPTR( sel, base );
224 /***********************************************************************
227 * Free a MakeProcInstance() thunk.
229 static BOOL TASK_FreeThunk( SEGPTR thunk )
235 if (!(pTask = TASK_GetCurrent())) return 0;
236 sel = pTask->hCSAlias;
237 pThunk = (THUNKS *)&pTask->thunks;
238 base = (char *)pThunk - (char *)pTask;
239 while (sel && (sel != HIWORD(thunk)))
242 pThunk = (THUNKS *)GlobalLock16( sel );
245 if (!sel) return FALSE;
246 *(WORD *)((BYTE *)pThunk + LOWORD(thunk) - base) = pThunk->free;
247 pThunk->free = LOWORD(thunk) - base;
252 /***********************************************************************
255 * NOTE: This routine might be called by a Win32 thread. Thus, we need
256 * to be careful to protect global data structures. We do this
257 * by entering the Win16Lock while linking the task into the
260 static TDB *TASK_Create( NE_MODULE *pModule, UINT16 cmdShow, TEB *teb, LPCSTR cmdline, BYTE len )
265 HMODULE16 hModule = pModule ? pModule->self : 0;
267 /* Allocate the task structure */
269 hTask = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, sizeof(TDB) );
270 if (!hTask) return NULL;
271 pTask = TASK_GetPtr( hTask );
272 FarSetOwner16( hTask, hModule );
274 /* Fill the task structure */
276 pTask->hSelf = hTask;
278 if (teb && teb->tibflags & TEBF_WIN32)
280 pTask->flags |= TDBF_WIN32;
281 pTask->hInstance = hModule;
282 pTask->hPrevInstance = 0;
283 /* NOTE: for 16-bit tasks, the instance handles are updated later on
287 pTask->version = pModule ? pModule->expected_version : 0x0400;
288 pTask->hModule = hModule;
289 pTask->hParent = GetCurrentTask();
290 pTask->magic = TDB_MAGIC;
291 pTask->nCmdShow = cmdShow;
293 pTask->curdrive = DRIVE_GetCurrentDrive() | 0x80;
294 strcpy( pTask->curdir, "\\" );
295 WideCharToMultiByte(CP_ACP, 0, DRIVE_GetDosCwd(DRIVE_GetCurrentDrive()), -1,
296 pTask->curdir + 1, sizeof(pTask->curdir) - 1, NULL, NULL);
297 pTask->curdir[sizeof(pTask->curdir) - 1] = 0; /* ensure 0 termination */
299 /* Create the thunks block */
301 TASK_CreateThunks( hTask, (char *)&pTask->thunks - (char *)pTask, 7 );
303 /* Copy the module name */
308 GetModuleName16( hModule, name, sizeof(name) );
309 strncpy( pTask->module_name, name, sizeof(pTask->module_name) );
310 pTask->compat_flags = GetProfileIntA( "Compatibility", name, 0 );
313 /* Allocate a selector for the PDB */
315 pTask->hPDB = GLOBAL_CreateBlock( GMEM_FIXED, &pTask->pdb, sizeof(PDB16),
316 hModule, WINE_LDT_FLAGS_DATA );
320 pTask->pdb.int20 = 0x20cd;
321 pTask->pdb.dispatcher[0] = 0x9a; /* ljmp */
322 proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DOS3Call" );
323 memcpy( &pTask->pdb.dispatcher[1], &proc, sizeof(proc) );
324 pTask->pdb.savedint22 = 0;
325 pTask->pdb.savedint23 = 0;
326 pTask->pdb.savedint24 = 0;
327 pTask->pdb.fileHandlesPtr =
328 MAKESEGPTR( GlobalHandleToSel16(pTask->hPDB), (int)&((PDB16 *)0)->fileHandles );
329 pTask->pdb.hFileHandles = 0;
330 memset( pTask->pdb.fileHandles, 0xff, sizeof(pTask->pdb.fileHandles) );
331 /* FIXME: should we make a copy of the environment? */
332 pTask->pdb.environment = SELECTOROF(GetDOSEnvironment16());
333 pTask->pdb.nbFiles = 20;
335 /* Fill the command line */
339 cmdline = GetCommandLineA();
340 /* remove the first word (program name) */
342 if (!(cmdline = strchr( cmdline+1, '"' ))) cmdline = GetCommandLineA();
343 while (*cmdline && (*cmdline != ' ') && (*cmdline != '\t')) cmdline++;
344 while ((*cmdline == ' ') || (*cmdline == '\t')) cmdline++;
345 len = strlen(cmdline);
347 if (len >= sizeof(pTask->pdb.cmdLine)) len = sizeof(pTask->pdb.cmdLine)-1;
348 pTask->pdb.cmdLine[0] = len;
349 memcpy( pTask->pdb.cmdLine + 1, cmdline, len );
350 /* pTask->pdb.cmdLine[len+1] = 0; */
352 TRACE("cmdline='%.*s' task=%04x\n", len, cmdline, hTask );
354 /* Allocate a code segment alias for the TDB */
356 pTask->hCSAlias = GLOBAL_CreateBlock( GMEM_FIXED, (void *)pTask,
357 sizeof(TDB), pTask->hPDB, WINE_LDT_FLAGS_CODE );
359 /* Default DTA overwrites command line */
361 pTask->dta = MAKESEGPTR( pTask->hPDB, (int)&pTask->pdb.cmdLine - (int)&pTask->pdb );
363 /* Create scheduler event for 16-bit tasks */
365 if ( !(pTask->flags & TDBF_WIN32) )
366 NtCreateEvent( &pTask->hEvent, EVENT_ALL_ACCESS, NULL, TRUE, FALSE );
368 /* Enter task handle into thread */
370 if (teb) teb->htask16 = hTask;
371 if (!initial_task) initial_task = hTask;
377 /***********************************************************************
380 static void TASK_DeleteTask( HTASK16 hTask )
385 if (!(pTask = TASK_GetPtr( hTask ))) return;
388 pTask->magic = 0xdead; /* invalidate signature */
390 /* Free the selector aliases */
392 GLOBAL_FreeBlock( pTask->hCSAlias );
393 GLOBAL_FreeBlock( pTask->hPDB );
395 /* Free the task module */
397 FreeModule16( pTask->hModule );
399 /* Free the task structure itself */
401 GlobalFree16( hTask );
403 /* Free all memory used by this task (including the 32-bit stack, */
404 /* the environment block and the thunk segments). */
406 GlobalFreeAll16( hPDB );
410 /***********************************************************************
411 * TASK_CreateMainTask
413 * Create a task for the main (32-bit) process.
415 void TASK_CreateMainTask(void)
418 STARTUPINFOA startup_info;
419 UINT cmdShow = 1; /* SW_SHOWNORMAL but we don't want to include winuser.h here */
421 GetStartupInfoA( &startup_info );
422 if (startup_info.dwFlags & STARTF_USESHOWWINDOW) cmdShow = startup_info.wShowWindow;
423 pTask = TASK_Create( NULL, cmdShow, NtCurrentTeb(), NULL, 0 );
426 ERR("could not create task for main process\n");
430 /* Add the task to the linked list */
431 /* (no need to get the win16 lock, we are the only thread at this point) */
432 TASK_LinkTask( pTask->hSelf );
436 /* startup routine for a new 16-bit thread */
437 static DWORD CALLBACK task_start( TDB *pTask )
441 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
442 NtCurrentTeb()->htask16 = pTask->hSelf;
445 TASK_LinkTask( pTask->hSelf );
446 pTask->teb = NtCurrentTeb();
447 ret = NE_StartTask();
453 /***********************************************************************
456 * Spawn a new 16-bit task.
458 HTASK16 TASK_SpawnTask( NE_MODULE *pModule, WORD cmdShow,
459 LPCSTR cmdline, BYTE len, HANDLE *hThread )
463 if (!(pTask = TASK_Create( pModule, cmdShow, NULL, cmdline, len ))) return 0;
464 if (!(*hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)task_start, pTask, 0, NULL )))
466 TASK_DeleteTask( pTask->hSelf );
473 /***********************************************************************
474 * TASK_GetTaskFromThread
476 HTASK16 TASK_GetTaskFromThread( DWORD thread )
478 TDB *p = TASK_GetPtr( hFirstTask );
481 if (p->teb->ClientId.UniqueThread == (HANDLE)thread) return p->hSelf;
482 p = TASK_GetPtr( p->hNext );
488 /***********************************************************************
489 * TASK_CallTaskSignalProc
491 static void TASK_CallTaskSignalProc( UINT16 uCode, HANDLE16 hTaskOrModule )
494 TDB *pTask = TASK_GetCurrent();
496 if ( !pTask || !pTask->userhandler ) return;
498 args[4] = hTaskOrModule;
501 args[1] = pTask->hInstance;
502 args[0] = pTask->hQueue;
503 WOWCallback16Ex( (DWORD)pTask->userhandler, WCB16_PASCAL, sizeof(args), args, NULL );
507 /***********************************************************************
510 void TASK_ExitTask(void)
515 /* Enter the Win16Lock to protect global data structures */
518 pTask = TASK_GetCurrent();
525 TRACE("Killing task %04x\n", pTask->hSelf );
527 /* Perform USER cleanup */
529 TASK_CallTaskSignalProc( USIG16_TERMINATION, pTask->hSelf );
531 /* Remove the task from the list to be sure we never switch back to it */
532 TASK_UnlinkTask( pTask->hSelf );
534 if (!nTaskCount || (nTaskCount == 1 && hFirstTask == initial_task))
536 TRACE("this is the last task, exiting\n" );
542 if ( hLockedTask == pTask->hSelf )
545 TASK_DeleteTask( pTask->hSelf );
547 /* ... and completely release the Win16Lock, just in case. */
548 ReleaseThunkLock( &lockCount );
552 /***********************************************************************
553 * ExitKernel (KERNEL.2)
555 * Clean-up everything and exit the Wine process.
557 void WINAPI ExitKernel16(void)
559 WriteOutProfiles16();
560 TerminateProcess( GetCurrentProcess(), 0 );
564 /***********************************************************************
565 * InitTask (KERNEL.91)
567 * Called by the application startup code.
569 void WINAPI InitTask16( CONTEXT86 *context )
572 INSTANCEDATA *pinstance;
576 if (!(pTask = TASK_GetCurrent())) return;
578 /* Note: we need to trust that BX/CX contain the stack/heap sizes,
579 as some apps, notably Visual Basic apps, *modify* the heap/stack
580 size of the instance data segment before calling InitTask() */
582 /* Initialize the INSTANCEDATA structure */
583 pinstance = MapSL( MAKESEGPTR(CURRENT_DS, 0) );
584 pinstance->stackmin = OFFSETOF( NtCurrentTeb()->cur_stack ) + sizeof( STACK16FRAME );
585 pinstance->stackbottom = pinstance->stackmin; /* yup, that's right. Confused me too. */
586 pinstance->stacktop = ( pinstance->stackmin > LOWORD(context->Ebx) ?
587 pinstance->stackmin - LOWORD(context->Ebx) : 0 ) + 150;
589 /* Initialize the local heap */
590 if (LOWORD(context->Ecx))
591 LocalInit16( GlobalHandleToSel16(pTask->hInstance), 0, LOWORD(context->Ecx) );
593 /* Initialize implicitly loaded DLLs */
594 NE_InitializeDLLs( pTask->hModule );
595 NE_DllProcessAttach( pTask->hModule );
597 /* Registers on return are:
598 * ax 1 if OK, 0 on error
599 * cx stack limit in bytes
600 * dx cmdShow parameter
601 * si instance handle of the previous instance
602 * di instance handle of the new task
603 * es:bx pointer to command line inside PSP
605 * 0 (=%bp) is pushed on the stack
607 ptr = stack16_push( sizeof(WORD) );
608 *(WORD *)MapSL(ptr) = 0;
613 if (!pTask->pdb.cmdLine[0]) context->Ebx = 0x80;
616 LPBYTE p = &pTask->pdb.cmdLine[1];
617 while ((*p == ' ') || (*p == '\t')) p++;
618 context->Ebx = 0x80 + (p - pTask->pdb.cmdLine);
620 context->Ecx = pinstance->stacktop;
621 context->Edx = pTask->nCmdShow;
622 context->Esi = (DWORD)pTask->hPrevInstance;
623 context->Edi = (DWORD)pTask->hInstance;
624 context->SegEs = (WORD)pTask->hPDB;
628 /***********************************************************************
629 * WaitEvent (KERNEL.30)
631 BOOL16 WINAPI WaitEvent16( HTASK16 hTask )
635 if (!hTask) hTask = GetCurrentTask();
636 pTask = TASK_GetPtr( hTask );
638 if (pTask->flags & TDBF_WIN32)
640 FIXME("called for Win32 thread (%04lx)!\n", GetCurrentThreadId());
644 if (pTask->nEvents > 0)
650 if (pTask->teb == NtCurrentTeb())
654 NtResetEvent( pTask->hEvent, NULL );
655 ReleaseThunkLock( &lockCount );
656 SYSLEVEL_CheckNotLevel( 1 );
657 WaitForSingleObject( pTask->hEvent, INFINITE );
658 RestoreThunkLock( lockCount );
659 if (pTask->nEvents > 0) pTask->nEvents--;
661 else FIXME("for other task %04x cur=%04x\n",pTask->hSelf,GetCurrentTask());
667 /***********************************************************************
668 * PostEvent (KERNEL.31)
670 void WINAPI PostEvent16( HTASK16 hTask )
674 if (!hTask) hTask = GetCurrentTask();
675 if (!(pTask = TASK_GetPtr( hTask ))) return;
677 if (pTask->flags & TDBF_WIN32)
679 FIXME("called for Win32 thread (%04lx)!\n", (DWORD)pTask->teb->ClientId.UniqueThread );
685 if (pTask->nEvents == 1) NtSetEvent( pTask->hEvent, NULL );
689 /***********************************************************************
690 * SetPriority (KERNEL.32)
692 void WINAPI SetPriority16( HTASK16 hTask, INT16 delta )
697 if (!hTask) hTask = GetCurrentTask();
698 if (!(pTask = TASK_GetPtr( hTask ))) return;
699 newpriority = pTask->priority + delta;
700 if (newpriority < -32) newpriority = -32;
701 else if (newpriority > 15) newpriority = 15;
703 pTask->priority = newpriority + 1;
704 TASK_UnlinkTask( pTask->hSelf );
705 TASK_LinkTask( pTask->hSelf );
710 /***********************************************************************
711 * LockCurrentTask (KERNEL.33)
713 HTASK16 WINAPI LockCurrentTask16( BOOL16 bLock )
715 if (bLock) hLockedTask = GetCurrentTask();
716 else hLockedTask = 0;
721 /***********************************************************************
722 * IsTaskLocked (KERNEL.122)
724 HTASK16 WINAPI IsTaskLocked16(void)
730 /***********************************************************************
731 * OldYield (KERNEL.117)
733 void WINAPI OldYield16(void)
737 ReleaseThunkLock(&count);
738 RestoreThunkLock(count);
741 /***********************************************************************
742 * WIN32_OldYield (KERNEL.447)
744 void WINAPI WIN32_OldYield16(void)
748 ReleaseThunkLock(&count);
749 RestoreThunkLock(count);
752 /***********************************************************************
753 * DirectedYield (KERNEL.150)
755 void WINAPI DirectedYield16( HTASK16 hTask )
760 /***********************************************************************
763 void WINAPI Yield16(void)
765 TDB *pCurTask = TASK_GetCurrent();
767 if (pCurTask && pCurTask->hQueue)
769 HMODULE mod = GetModuleHandleA( "user32.dll" );
772 FARPROC proc = GetProcAddress( mod, "UserYield16" );
783 /***********************************************************************
784 * KERNEL_490 (KERNEL.490)
786 HTASK16 WINAPI KERNEL_490( HTASK16 someTask )
788 if ( !someTask ) return 0;
790 FIXME("(%04x): stub\n", someTask );
794 /***********************************************************************
795 * MakeProcInstance (KERNEL.51)
797 FARPROC16 WINAPI MakeProcInstance16( FARPROC16 func, HANDLE16 hInstance )
801 WORD hInstanceSelector;
803 hInstanceSelector = GlobalHandleToSel16(hInstance);
805 TRACE("(%08lx, %04x);\n", (DWORD)func, hInstance);
808 /* Win95 actually protects via SEH, but this is better for debugging */
809 WARN("Ouch ! Called with invalid func 0x%08lx !\n", (DWORD)func);
813 if ( (GlobalHandleToSel16(CURRENT_DS) != hInstanceSelector)
815 && (hInstance != 0xffff) )
817 /* calling MPI with a foreign DSEG is invalid ! */
818 WARN("Problem with hInstance? Got %04x, using %04x instead\n",
819 hInstance,CURRENT_DS);
822 /* Always use the DSEG that MPI was entered with.
823 * We used to set hInstance to GetTaskDS16(), but this should be wrong
824 * as CURRENT_DS provides the DSEG value we need.
825 * ("calling" DS, *not* "task" DS !) */
826 hInstanceSelector = CURRENT_DS;
827 hInstance = GlobalHandle16(hInstanceSelector);
829 /* no thunking for DLLs */
830 if (NE_GetPtr(FarGetOwner16(hInstance))->flags & NE_FFLAGS_LIBMODULE)
833 thunkaddr = TASK_AllocThunk();
834 if (!thunkaddr) return (FARPROC16)0;
835 thunk = MapSL( thunkaddr );
836 lfunc = MapSL( (SEGPTR)func );
838 TRACE("(%08lx,%04x): got thunk %08lx\n",
839 (DWORD)func, hInstance, (DWORD)thunkaddr );
840 if (((lfunc[0]==0x8c) && (lfunc[1]==0xd8)) || /* movw %ds, %ax */
841 ((lfunc[0]==0x1e) && (lfunc[1]==0x58)) /* pushw %ds, popw %ax */
843 WARN("This was the (in)famous \"thunk useless\" warning. We thought we have to overwrite with nop;nop;, but this isn't true.\n");
846 *thunk++ = 0xb8; /* movw instance, %ax */
847 *thunk++ = (BYTE)(hInstanceSelector & 0xff);
848 *thunk++ = (BYTE)(hInstanceSelector >> 8);
849 *thunk++ = 0xea; /* ljmp func */
850 *(DWORD *)thunk = (DWORD)func;
851 return (FARPROC16)thunkaddr;
852 /* CX reg indicates if thunkaddr != NULL, implement if needed */
856 /***********************************************************************
857 * FreeProcInstance (KERNEL.52)
859 void WINAPI FreeProcInstance16( FARPROC16 func )
861 TRACE("(%08lx)\n", (DWORD)func );
862 TASK_FreeThunk( (SEGPTR)func );
865 /**********************************************************************
866 * TASK_GetCodeSegment
868 * Helper function for GetCodeHandle/GetCodeInfo: Retrieve the module
869 * and logical segment number of a given code segment.
871 * 'proc' either *is* already a pair of module handle and segment number,
872 * in which case there's nothing to do. Otherwise, it is a pointer to
873 * a function, and we need to retrieve the code segment. If the pointer
874 * happens to point to a thunk, we'll retrieve info about the code segment
875 * where the function pointed to by the thunk resides, not the thunk itself.
877 * FIXME: if 'proc' is a SNOOP16 return stub, we should retrieve info about
878 * the function the snoop code will return to ...
881 static BOOL TASK_GetCodeSegment( FARPROC16 proc, NE_MODULE **ppModule,
882 SEGTABLEENTRY **ppSeg, int *pSegNr )
884 NE_MODULE *pModule = NULL;
885 SEGTABLEENTRY *pSeg = NULL;
888 /* Try pair of module handle / segment number */
889 pModule = (NE_MODULE *) GlobalLock16( HIWORD( proc ) );
890 if ( pModule && pModule->magic == IMAGE_OS2_SIGNATURE )
892 segNr = LOWORD( proc );
893 if ( segNr && segNr <= pModule->seg_count )
894 pSeg = NE_SEG_TABLE( pModule ) + segNr-1;
897 /* Try thunk or function */
900 BYTE *thunk = MapSL( (SEGPTR)proc );
903 if ((thunk[0] == 0xb8) && (thunk[3] == 0xea))
904 selector = thunk[6] + (thunk[7] << 8);
906 selector = HIWORD( proc );
908 pModule = NE_GetPtr( GlobalHandle16( selector ) );
909 pSeg = pModule? NE_SEG_TABLE( pModule ) : NULL;
912 for ( segNr = 1; segNr <= pModule->seg_count; segNr++, pSeg++ )
913 if ( GlobalHandleToSel16(pSeg->hSeg) == selector )
916 if ( pModule && segNr > pModule->seg_count )
920 /* Abort if segment not found */
922 if ( !pModule || !pSeg )
925 /* Return segment data */
927 if ( ppModule ) *ppModule = pModule;
928 if ( ppSeg ) *ppSeg = pSeg;
929 if ( pSegNr ) *pSegNr = segNr;
934 /**********************************************************************
935 * GetCodeHandle (KERNEL.93)
937 HANDLE16 WINAPI GetCodeHandle16( FARPROC16 proc )
941 if ( !TASK_GetCodeSegment( proc, NULL, &pSeg, NULL ) )
947 /**********************************************************************
948 * GetCodeInfo (KERNEL.104)
950 BOOL16 WINAPI GetCodeInfo16( FARPROC16 proc, SEGINFO *segInfo )
956 if ( !TASK_GetCodeSegment( proc, &pModule, &pSeg, &segNr ) )
959 /* Fill in segment information */
961 segInfo->offSegment = pSeg->filepos;
962 segInfo->cbSegment = pSeg->size;
963 segInfo->flags = pSeg->flags;
964 segInfo->cbAlloc = pSeg->minsize;
965 segInfo->h = pSeg->hSeg;
966 segInfo->alignShift = pModule->alignment;
968 if ( segNr == pModule->dgroup )
969 segInfo->cbAlloc += pModule->heap_size + pModule->stack_size;
971 /* Return module handle in %es */
973 CURRENT_STACK16->es = GlobalHandleToSel16( pModule->self );
979 /**********************************************************************
980 * DefineHandleTable (KERNEL.94)
982 BOOL16 WINAPI DefineHandleTable16( WORD wOffset )
984 FIXME("(%04x): stub ?\n", wOffset);
989 /***********************************************************************
990 * SetTaskQueue (KERNEL.34)
992 HQUEUE16 WINAPI SetTaskQueue16( HTASK16 hTask, HQUEUE16 hQueue )
997 if (!hTask) hTask = GetCurrentTask();
998 if (!(pTask = TASK_GetPtr( hTask ))) return 0;
1000 hPrev = pTask->hQueue;
1001 pTask->hQueue = hQueue;
1007 /***********************************************************************
1008 * GetTaskQueue (KERNEL.35)
1010 HQUEUE16 WINAPI GetTaskQueue16( HTASK16 hTask )
1014 if (!hTask) hTask = GetCurrentTask();
1015 if (!(pTask = TASK_GetPtr( hTask ))) return 0;
1016 return pTask->hQueue;
1019 /***********************************************************************
1020 * SetThreadQueue (KERNEL.463)
1022 HQUEUE16 WINAPI SetThreadQueue16( DWORD thread, HQUEUE16 hQueue )
1024 HQUEUE16 oldQueue = NtCurrentTeb()->queue;
1026 if (thread && thread != GetCurrentThreadId())
1028 FIXME( "not supported on other thread %04lx\n", thread );
1031 NtCurrentTeb()->queue = hQueue;
1032 if ( GetTaskQueue16( NtCurrentTeb()->htask16 ) == oldQueue )
1033 SetTaskQueue16( NtCurrentTeb()->htask16, hQueue );
1037 /***********************************************************************
1038 * GetThreadQueue (KERNEL.464)
1040 HQUEUE16 WINAPI GetThreadQueue16( DWORD thread )
1042 if (thread && thread != GetCurrentThreadId())
1044 FIXME( "not supported on other thread %04lx\n", thread );
1047 return NtCurrentTeb()->queue;
1050 /***********************************************************************
1051 * SetFastQueue (KERNEL.624)
1053 VOID WINAPI SetFastQueue16( DWORD thread, HQUEUE16 hQueue )
1055 if (!thread || thread == GetCurrentThreadId())
1056 NtCurrentTeb()->queue = hQueue;
1058 FIXME( "not supported on other thread %04lx\n", thread );
1061 /***********************************************************************
1062 * GetFastQueue (KERNEL.625)
1064 HQUEUE16 WINAPI GetFastQueue16( void )
1066 HQUEUE16 ret = NtCurrentTeb()->queue;
1068 if (!ret) FIXME("(): should initialize thread-local queue, expect failure!\n" );
1072 /***********************************************************************
1073 * SwitchStackTo (KERNEL.108)
1075 void WINAPI SwitchStackTo16( WORD seg, WORD ptr, WORD top )
1077 STACK16FRAME *oldFrame, *newFrame;
1078 INSTANCEDATA *pData;
1081 if (!(pData = (INSTANCEDATA *)GlobalLock16( seg ))) return;
1082 TRACE("old=%04x:%04x new=%04x:%04x\n",
1083 SELECTOROF( NtCurrentTeb()->cur_stack ),
1084 OFFSETOF( NtCurrentTeb()->cur_stack ), seg, ptr );
1086 /* Save the old stack */
1088 oldFrame = CURRENT_STACK16;
1089 /* pop frame + args and push bp */
1090 pData->old_ss_sp = NtCurrentTeb()->cur_stack + sizeof(STACK16FRAME)
1092 *(WORD *)MapSL(pData->old_ss_sp) = oldFrame->bp;
1093 pData->stacktop = top;
1094 pData->stackmin = ptr;
1095 pData->stackbottom = ptr;
1097 /* Switch to the new stack */
1099 /* Note: we need to take the 3 arguments into account; otherwise,
1100 * the stack will underflow upon return from this function.
1102 copySize = oldFrame->bp - OFFSETOF(pData->old_ss_sp);
1103 copySize += 3 * sizeof(WORD) + sizeof(STACK16FRAME);
1104 NtCurrentTeb()->cur_stack = MAKESEGPTR( seg, ptr - copySize );
1105 newFrame = CURRENT_STACK16;
1107 /* Copy the stack frame and the local variables to the new stack */
1109 memmove( newFrame, oldFrame, copySize );
1111 *(WORD *)MapSL( MAKESEGPTR( seg, ptr ) ) = 0; /* clear previous bp */
1115 /***********************************************************************
1116 * SwitchStackBack (KERNEL.109)
1118 void WINAPI SwitchStackBack16( CONTEXT86 *context )
1120 STACK16FRAME *oldFrame, *newFrame;
1121 INSTANCEDATA *pData;
1123 if (!(pData = (INSTANCEDATA *)GlobalLock16(SELECTOROF(NtCurrentTeb()->cur_stack))))
1125 if (!pData->old_ss_sp)
1127 WARN("No previous SwitchStackTo\n" );
1130 TRACE("restoring stack %04x:%04x\n",
1131 SELECTOROF(pData->old_ss_sp), OFFSETOF(pData->old_ss_sp) );
1133 oldFrame = CURRENT_STACK16;
1135 /* Pop bp from the previous stack */
1137 context->Ebp = (context->Ebp & ~0xffff) | *(WORD *)MapSL(pData->old_ss_sp);
1138 pData->old_ss_sp += sizeof(WORD);
1140 /* Switch back to the old stack */
1142 NtCurrentTeb()->cur_stack = pData->old_ss_sp - sizeof(STACK16FRAME);
1143 context->SegSs = SELECTOROF(pData->old_ss_sp);
1144 context->Esp = OFFSETOF(pData->old_ss_sp) - sizeof(DWORD); /*ret addr*/
1145 pData->old_ss_sp = 0;
1147 /* Build a stack frame for the return */
1149 newFrame = CURRENT_STACK16;
1150 newFrame->frame32 = oldFrame->frame32;
1151 newFrame->module_cs = oldFrame->module_cs;
1152 newFrame->callfrom_ip = oldFrame->callfrom_ip;
1153 newFrame->entry_ip = oldFrame->entry_ip;
1157 /***********************************************************************
1158 * GetTaskQueueDS (KERNEL.118)
1160 void WINAPI GetTaskQueueDS16(void)
1162 CURRENT_STACK16->ds = GlobalHandleToSel16( GetTaskQueue16(0) );
1166 /***********************************************************************
1167 * GetTaskQueueES (KERNEL.119)
1169 void WINAPI GetTaskQueueES16(void)
1171 CURRENT_STACK16->es = GlobalHandleToSel16( GetTaskQueue16(0) );
1175 /***********************************************************************
1176 * GetCurrentTask (KERNEL32.@)
1178 HTASK16 WINAPI GetCurrentTask(void)
1180 return NtCurrentTeb()->htask16;
1183 /***********************************************************************
1184 * GetCurrentTask (KERNEL.36)
1186 DWORD WINAPI WIN16_GetCurrentTask(void)
1188 /* This is the version used by relay code; the first task is */
1189 /* returned in the high word of the result */
1190 return MAKELONG( GetCurrentTask(), hFirstTask );
1194 /***********************************************************************
1195 * GetCurrentPDB (KERNEL.37)
1197 * UNDOC: returns PSP of KERNEL in high word
1199 DWORD WINAPI GetCurrentPDB16(void)
1203 if (!(pTask = TASK_GetCurrent())) return 0;
1204 return MAKELONG(pTask->hPDB, 0); /* FIXME */
1208 /***********************************************************************
1209 * GetCurPID (KERNEL.157)
1211 DWORD WINAPI GetCurPID16( DWORD unused )
1217 /***********************************************************************
1218 * GetInstanceData (KERNEL.54)
1220 INT16 WINAPI GetInstanceData16( HINSTANCE16 instance, WORD buffer, INT16 len )
1222 char *ptr = (char *)GlobalLock16( instance );
1223 if (!ptr || !len) return 0;
1224 if ((int)buffer + len >= 0x10000) len = 0x10000 - buffer;
1225 memcpy( (char *)GlobalLock16(CURRENT_DS) + buffer, ptr + buffer, len );
1230 /***********************************************************************
1231 * GetExeVersion (KERNEL.105)
1233 WORD WINAPI GetExeVersion16(void)
1237 if (!(pTask = TASK_GetCurrent())) return 0;
1238 return pTask->version;
1242 /***********************************************************************
1243 * SetErrorMode (KERNEL.107)
1245 UINT16 WINAPI SetErrorMode16( UINT16 mode )
1248 if (!(pTask = TASK_GetCurrent())) return 0;
1249 pTask->error_mode = mode;
1250 return SetErrorMode( mode );
1254 /***********************************************************************
1255 * GetNumTasks (KERNEL.152)
1257 UINT16 WINAPI GetNumTasks16(void)
1263 /***********************************************************************
1264 * GetTaskDS (KERNEL.155)
1266 * Note: this function apparently returns a DWORD with LOWORD == HIWORD.
1267 * I don't think we need to bother with this.
1269 HINSTANCE16 WINAPI GetTaskDS16(void)
1273 if (!(pTask = TASK_GetCurrent())) return 0;
1274 return GlobalHandleToSel16(pTask->hInstance);
1277 /***********************************************************************
1278 * GetDummyModuleHandleDS (KERNEL.602)
1280 WORD WINAPI GetDummyModuleHandleDS16(void)
1285 if (!(pTask = TASK_GetCurrent())) return 0;
1286 if (!(pTask->flags & TDBF_WIN32)) return 0;
1287 selector = GlobalHandleToSel16( pTask->hModule );
1288 CURRENT_DS = selector;
1292 /***********************************************************************
1293 * IsTask (KERNEL.320)
1295 BOOL16 WINAPI IsTask16( HTASK16 hTask )
1299 if (!(pTask = TASK_GetPtr( hTask ))) return FALSE;
1300 if (GlobalSize16( hTask ) < sizeof(TDB)) return FALSE;
1301 return (pTask->magic == TDB_MAGIC);
1305 /***********************************************************************
1306 * IsWinOldApTask (KERNEL.158)
1308 BOOL16 WINAPI IsWinOldApTask16( HTASK16 hTask )
1310 /* should return bit 0 of byte 0x48 in PSP */
1314 /***********************************************************************
1315 * SetTaskSignalProc (KERNEL.38)
1317 FARPROC16 WINAPI SetTaskSignalProc( HTASK16 hTask, FARPROC16 proc )
1322 if (!hTask) hTask = GetCurrentTask();
1323 if (!(pTask = TASK_GetPtr( hTask ))) return NULL;
1324 oldProc = pTask->userhandler;
1325 pTask->userhandler = proc;
1329 /***********************************************************************
1330 * SetSigHandler (KERNEL.140)
1332 WORD WINAPI SetSigHandler16( FARPROC16 newhandler, FARPROC16* oldhandler,
1333 UINT16 *oldmode, UINT16 newmode, UINT16 flag )
1335 FIXME("(%p,%p,%p,%d,%d), unimplemented.\n",
1336 newhandler,oldhandler,oldmode,newmode,flag );
1338 if (flag != 1) return 0;
1339 if (!newmode) newhandler = NULL; /* Default handler */
1344 if (!(pTask = TASK_GetCurrent())) return 0;
1345 if (oldmode) *oldmode = pTask->signal_flags;
1346 pTask->signal_flags = newmode;
1347 if (oldhandler) *oldhandler = pTask->sighandler;
1348 pTask->sighandler = newhandler;
1354 /***********************************************************************
1355 * GlobalNotify (KERNEL.154)
1357 * Note that GlobalNotify does _not_ return the old NotifyProc
1358 * -- contrary to LocalNotify !!
1360 VOID WINAPI GlobalNotify16( FARPROC16 proc )
1364 if (!(pTask = TASK_GetCurrent())) return;
1365 pTask->discardhandler = proc;
1369 /***********************************************************************
1372 static inline HMODULE16 GetExePtrHelper( HANDLE16 handle, HTASK16 *hTask )
1377 /* Check for module handle */
1379 if (!(ptr = GlobalLock16( handle ))) return 0;
1380 if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return handle;
1382 /* Search for this handle inside all tasks */
1384 *hTask = hFirstTask;
1387 TDB *pTask = TASK_GetPtr( *hTask );
1388 if ((*hTask == handle) ||
1389 (pTask->hInstance == handle) ||
1390 (pTask->hQueue == handle) ||
1391 (pTask->hPDB == handle)) return pTask->hModule;
1392 *hTask = pTask->hNext;
1395 /* Check the owner for module handle */
1397 owner = FarGetOwner16( handle );
1398 if (!(ptr = GlobalLock16( owner ))) return 0;
1399 if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return owner;
1401 /* Search for the owner inside all tasks */
1403 *hTask = hFirstTask;
1406 TDB *pTask = TASK_GetPtr( *hTask );
1407 if ((*hTask == owner) ||
1408 (pTask->hInstance == owner) ||
1409 (pTask->hQueue == owner) ||
1410 (pTask->hPDB == owner)) return pTask->hModule;
1411 *hTask = pTask->hNext;
1417 /***********************************************************************
1418 * GetExePtr (KERNEL.133)
1420 HMODULE16 WINAPI WIN16_GetExePtr( HANDLE16 handle )
1423 HMODULE16 hModule = GetExePtrHelper( handle, &hTask );
1424 STACK16FRAME *frame = CURRENT_STACK16;
1425 frame->ecx = hModule;
1426 if (hTask) frame->es = hTask;
1431 /***********************************************************************
1434 HMODULE16 WINAPI GetExePtr( HANDLE16 handle )
1437 return GetExePtrHelper( handle, &hTask );
1441 /***********************************************************************
1442 * TaskFirst (TOOLHELP.63)
1444 BOOL16 WINAPI TaskFirst16( TASKENTRY *lpte )
1446 lpte->hNext = hFirstTask;
1447 return TaskNext16( lpte );
1451 /***********************************************************************
1452 * TaskNext (TOOLHELP.64)
1454 BOOL16 WINAPI TaskNext16( TASKENTRY *lpte )
1457 INSTANCEDATA *pInstData;
1459 TRACE_(toolhelp)("(%p): task=%04x\n", lpte, lpte->hNext );
1460 if (!lpte->hNext) return FALSE;
1462 /* make sure that task and hInstance are valid (skip initial Wine task !) */
1464 pTask = TASK_GetPtr( lpte->hNext );
1465 if (!pTask || pTask->magic != TDB_MAGIC) return FALSE;
1466 if (pTask->hInstance)
1468 lpte->hNext = pTask->hNext;
1470 pInstData = MapSL( MAKESEGPTR( GlobalHandleToSel16(pTask->hInstance), 0 ) );
1471 lpte->hTask = lpte->hNext;
1472 lpte->hTaskParent = pTask->hParent;
1473 lpte->hInst = pTask->hInstance;
1474 lpte->hModule = pTask->hModule;
1475 lpte->wSS = SELECTOROF( pTask->teb->cur_stack );
1476 lpte->wSP = OFFSETOF( pTask->teb->cur_stack );
1477 lpte->wStackTop = pInstData->stacktop;
1478 lpte->wStackMinimum = pInstData->stackmin;
1479 lpte->wStackBottom = pInstData->stackbottom;
1480 lpte->wcEvents = pTask->nEvents;
1481 lpte->hQueue = pTask->hQueue;
1482 lstrcpynA( lpte->szModule, pTask->module_name, sizeof(lpte->szModule) );
1483 lpte->wPSPOffset = 0x100; /*??*/
1484 lpte->hNext = pTask->hNext;
1489 /***********************************************************************
1490 * TaskFindHandle (TOOLHELP.65)
1492 BOOL16 WINAPI TaskFindHandle16( TASKENTRY *lpte, HTASK16 hTask )
1494 lpte->hNext = hTask;
1495 return TaskNext16( lpte );
1499 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND hWnd, LPCSTR text, LPCSTR title, UINT type);
1501 /**************************************************************************
1502 * FatalAppExit (KERNEL.137)
1504 void WINAPI FatalAppExit16( UINT16 action, LPCSTR str )
1506 TDB *pTask = TASK_GetCurrent();
1508 if (!pTask || !(pTask->error_mode & SEM_NOGPFAULTERRORBOX))
1510 HMODULE mod = GetModuleHandleA( "user32.dll" );
1513 MessageBoxA_funcptr pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
1516 pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
1520 ERR( "%s\n", debugstr_a(str) );
1527 /***********************************************************************
1528 * TerminateApp (TOOLHELP.77)
1530 * See "Undocumented Windows".
1532 void WINAPI TerminateApp16(HTASK16 hTask, WORD wFlags)
1534 if (hTask && hTask != GetCurrentTask())
1536 FIXME("cannot terminate task %x\n", hTask);
1540 if (wFlags & NO_UAE_BOX)
1543 old_mode = SetErrorMode16(0);
1544 SetErrorMode16(old_mode|SEM_NOGPFAULTERRORBOX);
1546 FatalAppExit16( 0, NULL );
1548 /* hmm, we're still alive ?? */
1550 /* check undocumented flag */
1551 if (!(wFlags & 0x8000))
1552 TASK_CallTaskSignalProc( USIG16_TERMINATION, hTask );
1554 /* UndocWin says to call int 0x21/0x4c exit=0xff here,
1555 but let's just call ExitThread */
1560 /***********************************************************************
1561 * GetAppCompatFlags (KERNEL.354)
1563 DWORD WINAPI GetAppCompatFlags16( HTASK16 hTask )
1567 if (!hTask) hTask = GetCurrentTask();
1568 if (!(pTask=TASK_GetPtr( hTask ))) return 0;
1569 if (GlobalSize16(hTask) < sizeof(TDB)) return 0;
1570 return pTask->compat_flags;
1574 /***********************************************************************
1575 * GetDOSEnvironment (KERNEL.131)
1577 * Note: the environment is allocated once, it doesn't track changes
1578 * made using the Win32 API. This shouldn't matter.
1580 * Format of a 16-bit environment block:
1581 * ASCIIZ string 1 (xx=yy format)
1586 * ASCIIZ program name (e.g. C:\WINDOWS\SYSTEM\KRNL386.EXE)
1588 SEGPTR WINAPI GetDOSEnvironment16(void)
1590 static const char ENV_program_name[] = "C:\\WINDOWS\\SYSTEM\\KRNL386.EXE";
1591 static HGLOBAL16 handle; /* handle to the 16 bit environment */
1598 p = env = GetEnvironmentStringsA();
1599 while (*p) p += strlen(p) + 1;
1600 p++; /* skip last null */
1601 size = (p - env) + sizeof(WORD) + sizeof(ENV_program_name);
1602 handle = GlobalAlloc16( GMEM_FIXED, size );
1606 LPSTR env16 = GlobalLock16( handle );
1607 memcpy( env16, env, p - env );
1608 memcpy( env16 + (p - env), &one, sizeof(one));
1609 memcpy( env16 + (p - env) + sizeof(WORD), ENV_program_name, sizeof(ENV_program_name));
1610 GlobalUnlock16( handle );
1612 FreeEnvironmentStringsA( env );
1614 return K32WOWGlobalLock16( handle );