4 * Copyright 1995 Alexandre Julliard
12 #include "wine/winbase16.h"
27 #include "selectors.h"
28 #include "stackframe.h"
36 #include "debugtools.h"
41 DECLARE_DEBUG_CHANNEL(relay)
42 DECLARE_DEBUG_CHANNEL(task)
43 DECLARE_DEBUG_CHANNEL(toolhelp)
45 /* Min. number of thunks allocated when creating a new segment */
48 /* Pointer to function to switch to a larger stack */
49 int (*IF1632_CallLargeStack)( int (*func)(), void *arg ) = NULL;
51 /* Pointer to debugger callback routine */
52 void (*TASK_AddTaskEntryBreakpoint)( HTASK16 hTask ) = NULL;
54 static THHOOK DefaultThhook = { 0 };
55 THHOOK *pThhook = &DefaultThhook;
57 #define hCurrentTask (pThhook->CurTDB)
58 #define hFirstTask (pThhook->HeadTDB)
59 #define hLockedTask (pThhook->LockTDB)
61 static UINT16 nTaskCount = 0;
64 /***********************************************************************
67 void TASK_InstallTHHook( THHOOK *pNewThhook )
69 THHOOK *pOldThhook = pThhook;
71 pThhook = pNewThhook? pNewThhook : &DefaultThhook;
73 *pThhook = *pOldThhook;
76 /***********************************************************************
79 HTASK16 TASK_GetNextTask( HTASK16 hTask )
81 TDB* pTask = (TDB*)GlobalLock16(hTask);
83 if (pTask->hNext) return pTask->hNext;
84 return (hFirstTask != hTask) ? hFirstTask : 0;
87 /***********************************************************************
90 static void TASK_LinkTask( HTASK16 hTask )
95 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
96 prevTask = &hFirstTask;
99 TDB *prevTaskPtr = (TDB *)GlobalLock16( *prevTask );
100 if (prevTaskPtr->priority >= pTask->priority) break;
101 prevTask = &prevTaskPtr->hNext;
103 pTask->hNext = *prevTask;
109 /***********************************************************************
112 static void TASK_UnlinkTask( HTASK16 hTask )
117 prevTask = &hFirstTask;
118 while (*prevTask && (*prevTask != hTask))
120 pTask = (TDB *)GlobalLock16( *prevTask );
121 prevTask = &pTask->hNext;
125 pTask = (TDB *)GlobalLock16( *prevTask );
126 *prevTask = pTask->hNext;
133 /***********************************************************************
136 * Create a thunk free-list in segment 'handle', starting from offset 'offset'
137 * and containing 'count' entries.
139 static void TASK_CreateThunks( HGLOBAL16 handle, WORD offset, WORD count )
145 pThunk = (THUNKS *)((BYTE *)GlobalLock16( handle ) + offset);
147 pThunk->magic = THUNK_MAGIC;
148 pThunk->free = (int)&pThunk->thunks - (int)pThunk;
150 for (i = 0; i < count-1; i++)
152 free += 8; /* Offset of next thunk */
153 pThunk->thunks[4*i] = free;
155 pThunk->thunks[4*i] = 0; /* Last thunk */
159 /***********************************************************************
162 * Allocate a thunk for MakeProcInstance().
164 static SEGPTR TASK_AllocThunk( HTASK16 hTask )
170 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return 0;
171 sel = pTask->hCSAlias;
172 pThunk = &pTask->thunks;
173 base = (int)pThunk - (int)pTask;
174 while (!pThunk->free)
177 if (!sel) /* Allocate a new segment */
179 sel = GLOBAL_Alloc( GMEM_FIXED, sizeof(THUNKS) + (MIN_THUNKS-1)*8,
180 pTask->hPDB, TRUE, FALSE, FALSE );
181 if (!sel) return (SEGPTR)0;
182 TASK_CreateThunks( sel, 0, MIN_THUNKS );
185 pThunk = (THUNKS *)GlobalLock16( sel );
188 base += pThunk->free;
189 pThunk->free = *(WORD *)((BYTE *)pThunk + pThunk->free);
190 return PTR_SEG_OFF_TO_SEGPTR( sel, base );
194 /***********************************************************************
197 * Free a MakeProcInstance() thunk.
199 static BOOL TASK_FreeThunk( HTASK16 hTask, SEGPTR thunk )
205 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return 0;
206 sel = pTask->hCSAlias;
207 pThunk = &pTask->thunks;
208 base = (int)pThunk - (int)pTask;
209 while (sel && (sel != HIWORD(thunk)))
212 pThunk = (THUNKS *)GlobalLock16( sel );
215 if (!sel) return FALSE;
216 *(WORD *)((BYTE *)pThunk + LOWORD(thunk) - base) = pThunk->free;
217 pThunk->free = LOWORD(thunk) - base;
222 /***********************************************************************
225 * 32-bit entry point for a new task. This function is responsible for
226 * setting up the registers and jumping to the 16-bit entry point.
228 void TASK_CallToStart(void)
230 TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
231 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
232 SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
235 /* Add task to 16-bit scheduler pool */
238 /* Registers at initialization must be:
240 * bx stack size in bytes
241 * cx heap size in bytes
242 * si previous app instance
243 * di current app instance
245 * es selector to the PSP
246 * ds dgroup of the application
248 * sp top of the stack
251 memset( &context, 0, sizeof(context) );
252 CS_reg(&context) = GlobalHandleToSel16(pSegTable[pModule->cs - 1].hSeg);
253 DS_reg(&context) = GlobalHandleToSel16(pTask->hInstance);
254 ES_reg(&context) = pTask->hPDB;
255 EIP_reg(&context) = pModule->ip;
256 EBX_reg(&context) = pModule->stack_size;
257 ECX_reg(&context) = pModule->heap_size;
258 EDI_reg(&context) = pTask->hInstance;
259 ESI_reg(&context) = pTask->hPrevInstance;
261 TRACE_(task)("Starting main program: cs:ip=%04lx:%04x ds=%04lx ss:sp=%04x:%04x\n",
262 CS_reg(&context), IP_reg(&context), DS_reg(&context),
263 SELECTOROF(pTask->teb->cur_stack),
264 OFFSETOF(pTask->teb->cur_stack) );
266 Callbacks->CallRegisterShortProc( &context, 0 );
270 /***********************************************************************
273 * NOTE: This routine might be called by a Win32 thread. Thus, we need
274 * to be careful to protect global data structures. We do this
275 * by entering the Win16Lock while linking the task into the
278 BOOL TASK_Create( NE_MODULE *pModule, UINT16 cmdShow)
284 PDB *pdb32 = PROCESS_Current();
286 /* Allocate the task structure */
288 hTask = GLOBAL_Alloc( GMEM_FIXED | GMEM_ZEROINIT, sizeof(TDB),
289 pModule->self, FALSE, FALSE, FALSE );
290 if (!hTask) return FALSE;
291 pTask = (TDB *)GlobalLock16( hTask );
293 /* Fill the task structure */
296 pTask->hSelf = hTask;
299 if (pModule->flags & NE_FFLAGS_WIN32)
300 pTask->flags |= TDBF_WIN32;
301 if (pModule->lpDosTask)
302 pTask->flags |= TDBF_WINOLDAP;
304 pTask->hInstance = pModule->self;
305 pTask->hPrevInstance = 0;
306 /* NOTE: for 16-bit tasks, the instance handles are updated later on
309 pTask->version = pModule->expected_version;
310 pTask->hModule = pModule->self;
311 pTask->hParent = GetCurrentTask();
312 pTask->magic = TDB_MAGIC;
313 pTask->nCmdShow = cmdShow;
314 pTask->teb = NtCurrentTeb();
315 pTask->curdrive = DRIVE_GetCurrentDrive() | 0x80;
316 strcpy( pTask->curdir, "\\" );
317 lstrcpynA( pTask->curdir + 1, DRIVE_GetDosCwd( DRIVE_GetCurrentDrive() ),
318 sizeof(pTask->curdir) - 1 );
320 /* Create the thunks block */
322 TASK_CreateThunks( hTask, (int)&pTask->thunks - (int)pTask, 7 );
324 /* Copy the module name */
326 GetModuleName16( pModule->self, name, sizeof(name) );
327 strncpy( pTask->module_name, name, sizeof(pTask->module_name) );
329 /* Allocate a selector for the PDB */
331 pTask->hPDB = GLOBAL_CreateBlock( GMEM_FIXED, &pTask->pdb, sizeof(PDB16),
332 pModule->self, FALSE, FALSE, FALSE, NULL );
336 pTask->pdb.int20 = 0x20cd;
337 pTask->pdb.dispatcher[0] = 0x9a; /* ljmp */
338 PUT_DWORD(&pTask->pdb.dispatcher[1], (DWORD)NE_GetEntryPoint(
339 GetModuleHandle16("KERNEL"), 102 )); /* KERNEL.102 is DOS3Call() */
340 pTask->pdb.savedint22 = INT_GetPMHandler( 0x22 );
341 pTask->pdb.savedint23 = INT_GetPMHandler( 0x23 );
342 pTask->pdb.savedint24 = INT_GetPMHandler( 0x24 );
343 pTask->pdb.fileHandlesPtr =
344 PTR_SEG_OFF_TO_SEGPTR( GlobalHandleToSel16(pTask->hPDB),
345 (int)&((PDB16 *)0)->fileHandles );
346 pTask->pdb.hFileHandles = 0;
347 memset( pTask->pdb.fileHandles, 0xff, sizeof(pTask->pdb.fileHandles) );
348 pTask->pdb.environment = pdb32->env_db->env_sel;
349 pTask->pdb.nbFiles = 20;
351 /* Fill the command line */
353 cmd_line = pdb32->env_db->cmd_line;
354 while (*cmd_line && (*cmd_line != ' ') && (*cmd_line != '\t')) cmd_line++;
355 while ((*cmd_line == ' ') || (*cmd_line == '\t')) cmd_line++;
356 lstrcpynA( pTask->pdb.cmdLine+1, cmd_line, sizeof(pTask->pdb.cmdLine)-1);
357 pTask->pdb.cmdLine[0] = strlen( pTask->pdb.cmdLine + 1 );
359 /* Get the compatibility flags */
361 pTask->compat_flags = GetProfileIntA( "Compatibility", name, 0 );
363 /* Allocate a code segment alias for the TDB */
365 pTask->hCSAlias = GLOBAL_CreateBlock( GMEM_FIXED, (void *)pTask,
366 sizeof(TDB), pTask->hPDB, TRUE,
367 FALSE, FALSE, NULL );
369 /* Set the owner of the environment block */
371 FarSetOwner16( pTask->pdb.environment, pTask->hPDB );
373 /* Default DTA overwrites command-line */
375 pTask->dta = PTR_SEG_OFF_TO_SEGPTR( pTask->hPDB,
376 (int)&pTask->pdb.cmdLine - (int)&pTask->pdb );
378 /* Create scheduler event for 16-bit tasks */
380 if ( !(pTask->flags & TDBF_WIN32) )
382 pTask->hEvent = CreateEventA( NULL, TRUE, FALSE, NULL );
383 pTask->hEvent = ConvertToGlobalHandle( pTask->hEvent );
386 /* Enter task handle into thread and process */
388 pTask->teb->htask16 = pTask->teb->process->task = hTask;
389 TRACE_(task)("module='%s' cmdline='%s' task=%04x\n", name, cmd_line, hTask );
391 /* If requested, add entry point breakpoint */
393 if ( TASK_AddTaskEntryBreakpoint )
394 TASK_AddTaskEntryBreakpoint( hTask );
396 /* Add the task to the linked list */
398 SYSLEVEL_EnterWin16Lock();
399 TASK_LinkTask( hTask );
400 SYSLEVEL_LeaveWin16Lock();
405 /***********************************************************************
408 static void TASK_DeleteTask( HTASK16 hTask )
413 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
416 pTask->magic = 0xdead; /* invalidate signature */
418 /* Delete the Win32 part of the task */
420 /* PROCESS_FreePDB( pTask->teb->process ); FIXME */
421 /* K32OBJ_DecCount( &pTask->teb->header ); FIXME */
423 /* Free the selector aliases */
425 GLOBAL_FreeBlock( pTask->hCSAlias );
426 GLOBAL_FreeBlock( pTask->hPDB );
428 /* Free the task module */
430 FreeModule16( pTask->hModule );
432 /* Free the task structure itself */
434 GlobalFree16( hTask );
436 /* Free all memory used by this task (including the 32-bit stack, */
437 /* the environment block and the thunk segments). */
439 GlobalFreeAll16( hPDB );
442 /***********************************************************************
445 void TASK_KillTask( HTASK16 hTask )
449 /* Enter the Win16Lock to protect global data structures */
450 SYSLEVEL_EnterWin16Lock();
452 if ( !hTask ) hTask = GetCurrentTask();
453 pTask = (TDB *)GlobalLock16( hTask );
456 SYSLEVEL_LeaveWin16Lock();
460 TRACE_(task)("Killing task %04x\n", hTask );
462 /* Delete active sockets */
465 WINSOCK_DeleteTaskWSI( pTask, pTask->pwsi );
469 /* Kill DOS VM task */
470 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
471 if ( pModule->lpDosTask )
472 MZ_KillModule( pModule->lpDosTask );
476 /* Perform USER cleanup */
478 if (pTask->userhandler)
479 pTask->userhandler( hTask, USIG16_TERMINATION, 0,
480 pTask->hInstance, pTask->hQueue );
482 PROCESS_CallUserSignalProc( USIG_PROCESS_EXIT, 0 );
483 PROCESS_CallUserSignalProc( USIG_THREAD_EXIT, 0 ); /* FIXME */
484 PROCESS_CallUserSignalProc( USIG_PROCESS_DESTROY, 0 );
488 TRACE_(task)("this is the last task, exiting\n" );
492 /* FIXME: Hack! Send a message to the initial task so that
493 * the GetMessage wakes up and the initial task can check whether
494 * it is the only remaining one and terminate itself ...
495 * The initial task should probably install hooks or something
496 * to get informed about task termination :-/
498 Callout.PostAppMessage16( PROCESS_Initial()->task, WM_NULL, 0, 0 );
500 /* Remove the task from the list to be sure we never switch back to it */
501 TASK_UnlinkTask( hTask );
504 TDB* p = (TDB *)GlobalLock16( hFirstTask );
507 if( p->hYieldTo == hTask ) p->hYieldTo = 0;
508 p = (TDB *)GlobalLock16( p->hNext );
514 if ( hLockedTask == hTask )
517 TASK_DeleteTask( hTask );
519 /* When deleting the current task ... */
520 if ( hTask == hCurrentTask )
524 /* ... schedule another one ... */
527 /* ... and completely release the Win16Lock, just in case. */
528 ReleaseThunkLock( &lockCount );
533 SYSLEVEL_LeaveWin16Lock();
536 /***********************************************************************
539 * This is where all the magic of task-switching happens!
541 * 16-bit Windows performs non-preemptive (cooperative) multitasking.
542 * This means that each 16-bit task runs until it voluntarily yields
543 * control, at which point the scheduler gets active and selects the
546 * In Wine, all processes, even 16-bit ones, are scheduled preemptively
547 * by the standard scheduler of the underlying OS. As many 16-bit apps
548 * *rely* on the behaviour of the Windows scheduler, however, we have
549 * to simulate that behaviour.
551 * This is achieved as follows: every 16-bit task is at time (except
552 * during task creation and deletion) in one of two states: either it
553 * is the one currently running, then the global variable hCurrentTask
554 * contains its task handle, or it is not currently running, then it
555 * is blocked on a special scheduler event, a global handle to which
556 * is stored in the task struct.
558 * When the current task yields control, this routine gets called. Its
559 * purpose is to determine the next task to be active, signal the
560 * scheduler event of that task, and then put the current task to sleep
561 * waiting for *its* scheduler event to get signalled again.
563 * This routine can get called in a few other special situations as well:
565 * - On creation of a 16-bit task, the Unix process executing the task
566 * calls TASK_Reschedule once it has completed its initialization.
567 * At this point, the task needs to be blocked until its scheduler
568 * event is signalled the first time (this will be done by the parent
569 * process to get the task up and running).
571 * - When the task currently running terminates itself, this routine gets
572 * called and has to schedule another task, *without* blocking the
575 * - When a 32-bit thread posts an event for a 16-bit task, it might be
576 * the case that *no* 16-bit task is currently running. In this case
577 * the task that has now an event pending is to be scheduled.
580 void TASK_Reschedule(void)
582 TDB *pOldTask = NULL, *pNewTask = NULL;
583 HTASK16 hOldTask = 0, hNewTask = 0;
584 enum { MODE_YIELD, MODE_SLEEP, MODE_WAKEUP } mode;
587 SYSLEVEL_EnterWin16Lock();
589 /* Check what we need to do */
590 hOldTask = GetCurrentTask();
591 pOldTask = (TDB *)GlobalLock16( hOldTask );
592 TRACE_(task)( "entered with hCurrentTask %04x by hTask %04x (pid %ld)\n",
593 hCurrentTask, hOldTask, (long) getpid() );
595 if ( pOldTask && THREAD_IsWin16( NtCurrentTeb() ) )
597 /* We are called by an active (non-deleted) 16-bit task */
599 /* If we don't even have a current task, or else the current
600 task has yielded, we'll need to schedule a new task and
601 (possibly) put the calling task to sleep. Otherwise, we
602 only block the caller. */
604 if ( !hCurrentTask || hCurrentTask == hOldTask )
611 /* We are called by a deleted 16-bit task or a 32-bit thread */
613 /* The only situation where we need to do something is if we
614 now do not have a current task. Then, we'll need to wake up
615 some task that has events pending. */
617 if ( !hCurrentTask || hCurrentTask == hOldTask )
622 SYSLEVEL_LeaveWin16Lock();
627 /* Find a task to yield to: check for DirectedYield() */
628 if ( mode == MODE_YIELD && pOldTask && pOldTask->hYieldTo )
630 hNewTask = pOldTask->hYieldTo;
631 pNewTask = (TDB *)GlobalLock16( hNewTask );
632 if( !pNewTask || !pNewTask->nEvents) hNewTask = 0;
633 pOldTask->hYieldTo = 0;
636 /* Find a task to yield to: check for pending events */
637 if ( (mode == MODE_YIELD || mode == MODE_WAKEUP) && !hNewTask )
639 hNewTask = hFirstTask;
642 pNewTask = (TDB *)GlobalLock16( hNewTask );
644 TRACE_(task)( "\ttask = %04x, events = %i\n",
645 hNewTask, pNewTask->nEvents );
647 if (pNewTask->nEvents) break;
648 hNewTask = pNewTask->hNext;
650 if (hLockedTask && (hNewTask != hLockedTask)) hNewTask = 0;
653 /* If we are still the task with highest priority, just return ... */
654 if ( mode == MODE_YIELD && hNewTask == hCurrentTask )
656 TRACE_(task)("returning to the current task (%04x)\n", hCurrentTask );
657 SYSLEVEL_LeaveWin16Lock();
659 /* Allow Win32 threads to thunk down even while a Win16 task is
660 in a tight PeekMessage() or Yield() loop ... */
661 ReleaseThunkLock( &lockCount );
662 RestoreThunkLock( lockCount );
666 /* If no task to yield to found, suspend 16-bit scheduler ... */
667 if ( mode == MODE_YIELD && !hNewTask )
669 TRACE_(task)("No currently active task\n");
673 /* If we found a task to wake up, do it ... */
674 if ( (mode == MODE_YIELD || mode == MODE_WAKEUP) && hNewTask )
676 TRACE_(task)("Switching to task %04x (%.8s)\n",
677 hNewTask, pNewTask->module_name );
679 pNewTask->priority++;
680 TASK_UnlinkTask( hNewTask );
681 TASK_LinkTask( hNewTask );
682 pNewTask->priority--;
684 hCurrentTask = hNewTask;
685 SetEvent( pNewTask->hEvent );
687 /* This is set just in case some app reads it ... */
688 pNewTask->ss_sp = pNewTask->teb->cur_stack;
691 /* If we need to put the current task to sleep, do it ... */
692 if ( (mode == MODE_YIELD || mode == MODE_SLEEP) && hOldTask != hCurrentTask )
694 ResetEvent( pOldTask->hEvent );
696 ReleaseThunkLock( &lockCount );
697 SYSLEVEL_CheckNotLevel( 1 );
698 WaitForSingleObject( pOldTask->hEvent, INFINITE );
699 RestoreThunkLock( lockCount );
702 SYSLEVEL_LeaveWin16Lock();
705 /***********************************************************************
706 * InitTask (KERNEL.91)
708 * Called by the application startup code.
710 void WINAPI InitTask16( CONTEXT86 *context )
713 INSTANCEDATA *pinstance;
716 EAX_reg(context) = 0;
717 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return;
719 /* Note: we need to trust that BX/CX contain the stack/heap sizes,
720 as some apps, notably Visual Basic apps, *modify* the heap/stack
721 size of the instance data segment before calling InitTask() */
723 /* Initialize the INSTANCEDATA structure */
724 pinstance = (INSTANCEDATA *)PTR_SEG_OFF_TO_LIN(CURRENT_DS, 0);
725 pinstance->stackmin = OFFSETOF( pTask->teb->cur_stack );
726 pinstance->stackbottom = pinstance->stackmin; /* yup, that's right. Confused me too. */
727 pinstance->stacktop = ( pinstance->stackmin > BX_reg(context)?
728 pinstance->stackmin - BX_reg(context) : 0 ) + 150;
730 /* Initialize the local heap */
731 if ( CX_reg(context) )
732 LocalInit16( pTask->hInstance, 0, CX_reg(context) );
734 /* Initialize implicitly loaded DLLs */
735 NE_InitializeDLLs( pTask->hModule );
737 /* Registers on return are:
738 * ax 1 if OK, 0 on error
739 * cx stack limit in bytes
740 * dx cmdShow parameter
741 * si instance handle of the previous instance
742 * di instance handle of the new task
743 * es:bx pointer to command-line inside PSP
745 * 0 (=%bp) is pushed on the stack
747 ptr = STACK16_PUSH( pTask->teb, sizeof(WORD) );
748 *(WORD *)PTR_SEG_TO_LIN(ptr) = 0;
749 SP_reg(context) -= 2;
751 EAX_reg(context) = 1;
753 if (!pTask->pdb.cmdLine[0]) EBX_reg(context) = 0x80;
756 LPBYTE p = &pTask->pdb.cmdLine[1];
757 while ((*p == ' ') || (*p == '\t')) p++;
758 EBX_reg(context) = 0x80 + (p - pTask->pdb.cmdLine);
760 ECX_reg(context) = pinstance->stacktop;
761 EDX_reg(context) = pTask->nCmdShow;
762 ESI_reg(context) = (DWORD)pTask->hPrevInstance;
763 EDI_reg(context) = (DWORD)pTask->hInstance;
764 ES_reg (context) = (WORD)pTask->hPDB;
768 /***********************************************************************
769 * WaitEvent (KERNEL.30)
771 BOOL16 WINAPI WaitEvent16( HTASK16 hTask )
775 if (!hTask) hTask = GetCurrentTask();
776 pTask = (TDB *)GlobalLock16( hTask );
778 if ( !THREAD_IsWin16( NtCurrentTeb() ) )
780 FIXME_(task)("called for Win32 thread (%04x)!\n", NtCurrentTeb()->teb_sel);
784 if (pTask->nEvents > 0)
791 /* When we get back here, we have an event */
793 if (pTask->nEvents > 0) pTask->nEvents--;
798 /***********************************************************************
799 * PostEvent (KERNEL.31)
801 void WINAPI PostEvent16( HTASK16 hTask )
805 if (!hTask) hTask = GetCurrentTask();
806 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
808 if ( !THREAD_IsWin16( pTask->teb ) )
810 FIXME_(task)("called for Win32 thread (%04x)!\n", pTask->teb->teb_sel );
816 /* If we are a 32-bit task, we might need to wake up the 16-bit scheduler */
817 if ( !THREAD_IsWin16( NtCurrentTeb() ) )
822 /***********************************************************************
823 * SetPriority (KERNEL.32)
825 void WINAPI SetPriority16( HTASK16 hTask, INT16 delta )
830 if (!hTask) hTask = GetCurrentTask();
831 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
832 newpriority = pTask->priority + delta;
833 if (newpriority < -32) newpriority = -32;
834 else if (newpriority > 15) newpriority = 15;
836 pTask->priority = newpriority + 1;
837 TASK_UnlinkTask( hTask );
838 TASK_LinkTask( hTask );
843 /***********************************************************************
844 * LockCurrentTask (KERNEL.33)
846 HTASK16 WINAPI LockCurrentTask16( BOOL16 bLock )
848 if (bLock) hLockedTask = GetCurrentTask();
849 else hLockedTask = 0;
854 /***********************************************************************
855 * IsTaskLocked (KERNEL.122)
857 HTASK16 WINAPI IsTaskLocked16(void)
863 /***********************************************************************
864 * OldYield (KERNEL.117)
866 void WINAPI OldYield16(void)
868 TDB *pCurTask = (TDB *)GlobalLock16( GetCurrentTask() );
870 if ( !THREAD_IsWin16( NtCurrentTeb() ) )
872 FIXME_(task)("called for Win32 thread (%04x)!\n", NtCurrentTeb()->teb_sel);
876 if (pCurTask) pCurTask->nEvents++; /* Make sure we get back here */
878 if (pCurTask) pCurTask->nEvents--;
882 /***********************************************************************
883 * DirectedYield (KERNEL.150)
885 void WINAPI DirectedYield16( HTASK16 hTask )
887 TDB *pCurTask = (TDB *)GlobalLock16( GetCurrentTask() );
889 if ( !THREAD_IsWin16( NtCurrentTeb() ) )
891 FIXME_(task)("called for Win32 thread (%04x)!\n", NtCurrentTeb()->teb_sel);
895 TRACE_(task)("%04x: DirectedYield(%04x)\n", pCurTask->hSelf, hTask );
897 pCurTask->hYieldTo = hTask;
900 TRACE_(task)("%04x: back from DirectedYield(%04x)\n", pCurTask->hSelf, hTask );
903 /***********************************************************************
904 * Yield16 (KERNEL.29)
906 void WINAPI Yield16(void)
908 TDB *pCurTask = (TDB *)GlobalLock16( GetCurrentTask() );
910 if (pCurTask) pCurTask->hYieldTo = 0;
911 if (pCurTask && pCurTask->hQueue) Callout.UserYield16();
915 /***********************************************************************
916 * KERNEL_490 (KERNEL.490)
918 HTASK16 WINAPI KERNEL_490( HTASK16 someTask )
920 if ( !someTask ) return 0;
922 FIXME_(task)("(%04x): stub\n", someTask );
926 /***********************************************************************
927 * MakeProcInstance16 (KERNEL.51)
929 FARPROC16 WINAPI MakeProcInstance16( FARPROC16 func, HANDLE16 hInstance )
935 ERR_(task)("Ouch ! MakeProcInstance called with func == NULL !\n");
936 return (FARPROC16)0; /* Windows seems to do the same */
938 if (!hInstance) hInstance = CURRENT_DS;
939 thunkaddr = TASK_AllocThunk( GetCurrentTask() );
940 if (!thunkaddr) return (FARPROC16)0;
941 thunk = PTR_SEG_TO_LIN( thunkaddr );
942 lfunc = PTR_SEG_TO_LIN( func );
944 TRACE_(task)("(%08lx,%04x): got thunk %08lx\n",
945 (DWORD)func, hInstance, (DWORD)thunkaddr );
946 if (((lfunc[0]==0x8c) && (lfunc[1]==0xd8)) ||
947 ((lfunc[0]==0x1e) && (lfunc[1]==0x58))
949 FIXME_(task)("thunk would be useless for %p, overwriting with nop;nop;\n", func );
950 lfunc[0]=0x90; /* nop */
951 lfunc[1]=0x90; /* nop */
954 *thunk++ = 0xb8; /* movw instance, %ax */
955 *thunk++ = (BYTE)(hInstance & 0xff);
956 *thunk++ = (BYTE)(hInstance >> 8);
957 *thunk++ = 0xea; /* ljmp func */
958 *(DWORD *)thunk = (DWORD)func;
959 return (FARPROC16)thunkaddr;
963 /***********************************************************************
964 * FreeProcInstance16 (KERNEL.52)
966 void WINAPI FreeProcInstance16( FARPROC16 func )
968 TRACE_(task)("(%08lx)\n", (DWORD)func );
969 TASK_FreeThunk( GetCurrentTask(), (SEGPTR)func );
973 /**********************************************************************
974 * GetCodeHandle (KERNEL.93)
976 HANDLE16 WINAPI GetCodeHandle16( FARPROC16 proc )
979 BYTE *thunk = (BYTE *)PTR_SEG_TO_LIN( proc );
981 /* Return the code segment containing 'proc'. */
982 /* Not sure if this is really correct (shouldn't matter that much). */
984 /* Check if it is really a thunk */
985 if ((thunk[0] == 0xb8) && (thunk[3] == 0xea))
986 handle = GlobalHandle16( thunk[6] + (thunk[7] << 8) );
988 handle = GlobalHandle16( HIWORD(proc) );
993 /**********************************************************************
994 * GetCodeInfo (KERNEL.104)
996 VOID WINAPI GetCodeInfo16( FARPROC16 proc, SEGINFO *segInfo )
998 BYTE *thunk = (BYTE *)PTR_SEG_TO_LIN( proc );
999 NE_MODULE *pModule = NULL;
1000 SEGTABLEENTRY *pSeg = NULL;
1003 /* proc is either a thunk, or else a pair of module handle
1004 and segment number. In the first case, we also need to
1005 extract module and segment number. */
1007 if ((thunk[0] == 0xb8) && (thunk[3] == 0xea))
1009 WORD selector = thunk[6] + (thunk[7] << 8);
1010 pModule = NE_GetPtr( GlobalHandle16( selector ) );
1011 pSeg = pModule? NE_SEG_TABLE( pModule ) : NULL;
1014 for ( segNr = 0; segNr < pModule->seg_count; segNr++, pSeg++ )
1015 if ( GlobalHandleToSel16(pSeg->hSeg) == selector )
1018 if ( pModule && segNr >= pModule->seg_count )
1023 pModule = NE_GetPtr( HIWORD( proc ) );
1024 segNr = LOWORD( proc );
1026 if ( pModule && segNr < pModule->seg_count )
1027 pSeg = NE_SEG_TABLE( pModule ) + segNr;
1030 /* fill in segment information */
1032 segInfo->offSegment = pSeg? pSeg->filepos : 0;
1033 segInfo->cbSegment = pSeg? pSeg->size : 0;
1034 segInfo->flags = pSeg? pSeg->flags : 0;
1035 segInfo->cbAlloc = pSeg? pSeg->minsize : 0;
1036 segInfo->h = pSeg? pSeg->hSeg : 0;
1037 segInfo->alignShift = pModule? pModule->alignment : 0;
1041 /**********************************************************************
1042 * DefineHandleTable16 (KERNEL.94)
1044 BOOL16 WINAPI DefineHandleTable16( WORD wOffset )
1046 return TRUE; /* FIXME */
1050 /***********************************************************************
1051 * SetTaskQueue (KERNEL.34)
1053 HQUEUE16 WINAPI SetTaskQueue16( HTASK16 hTask, HQUEUE16 hQueue )
1058 if (!hTask) hTask = GetCurrentTask();
1059 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return 0;
1061 hPrev = pTask->hQueue;
1062 pTask->hQueue = hQueue;
1068 /***********************************************************************
1069 * GetTaskQueue (KERNEL.35)
1071 HQUEUE16 WINAPI GetTaskQueue16( HTASK16 hTask )
1075 if (!hTask) hTask = GetCurrentTask();
1076 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return 0;
1077 return pTask->hQueue;
1080 /***********************************************************************
1081 * SetThreadQueue (KERNEL.463)
1083 HQUEUE16 WINAPI SetThreadQueue16( DWORD thread, HQUEUE16 hQueue )
1085 TEB *teb = thread? THREAD_IdToTEB( thread ) : NtCurrentTeb();
1086 HQUEUE16 oldQueue = teb? teb->queue : 0;
1090 teb->queue = hQueue;
1092 if ( GetTaskQueue16( teb->process->task ) == oldQueue )
1093 SetTaskQueue16( teb->process->task, hQueue );
1099 /***********************************************************************
1100 * GetThreadQueue (KERNEL.464)
1102 HQUEUE16 WINAPI GetThreadQueue16( DWORD thread )
1106 teb = NtCurrentTeb();
1107 else if ( HIWORD(thread) )
1108 teb = THREAD_IdToTEB( thread );
1109 else if ( IsTask16( (HTASK16)thread ) )
1110 teb = ((TDB *)GlobalLock16( (HANDLE16)thread ))->teb;
1112 return (HQUEUE16)(teb? teb->queue : 0);
1115 /***********************************************************************
1116 * SetFastQueue (KERNEL.624)
1118 VOID WINAPI SetFastQueue16( DWORD thread, HANDLE hQueue )
1122 teb = NtCurrentTeb();
1123 else if ( HIWORD(thread) )
1124 teb = THREAD_IdToTEB( thread );
1125 else if ( IsTask16( (HTASK16)thread ) )
1126 teb = ((TDB *)GlobalLock16( (HANDLE16)thread ))->teb;
1128 if ( teb ) teb->queue = (HQUEUE16) hQueue;
1131 /***********************************************************************
1132 * GetFastQueue (KERNEL.625)
1134 HANDLE WINAPI GetFastQueue16( void )
1136 TEB *teb = NtCurrentTeb();
1140 Callout.InitThreadInput16( 0, THREAD_IsWin16(teb)? 4 : 5 );
1143 FIXME_(task)("(): should initialize thread-local queue, expect failure!\n" );
1145 return (HANDLE)teb->queue;
1148 /***********************************************************************
1149 * SwitchStackTo (KERNEL.108)
1151 void WINAPI SwitchStackTo16( WORD seg, WORD ptr, WORD top )
1154 STACK16FRAME *oldFrame, *newFrame;
1155 INSTANCEDATA *pData;
1158 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return;
1159 if (!(pData = (INSTANCEDATA *)GlobalLock16( seg ))) return;
1160 TRACE_(task)("old=%04x:%04x new=%04x:%04x\n",
1161 SELECTOROF( pTask->teb->cur_stack ),
1162 OFFSETOF( pTask->teb->cur_stack ), seg, ptr );
1164 /* Save the old stack */
1166 oldFrame = THREAD_STACK16( pTask->teb );
1167 /* pop frame + args and push bp */
1168 pData->old_ss_sp = pTask->teb->cur_stack + sizeof(STACK16FRAME)
1170 *(WORD *)PTR_SEG_TO_LIN(pData->old_ss_sp) = oldFrame->bp;
1171 pData->stacktop = top;
1172 pData->stackmin = ptr;
1173 pData->stackbottom = ptr;
1175 /* Switch to the new stack */
1177 /* Note: we need to take the 3 arguments into account; otherwise,
1178 * the stack will underflow upon return from this function.
1180 copySize = oldFrame->bp - OFFSETOF(pData->old_ss_sp);
1181 copySize += 3 * sizeof(WORD) + sizeof(STACK16FRAME);
1182 pTask->teb->cur_stack = PTR_SEG_OFF_TO_SEGPTR( seg, ptr - copySize );
1183 newFrame = THREAD_STACK16( pTask->teb );
1185 /* Copy the stack frame and the local variables to the new stack */
1187 memmove( newFrame, oldFrame, copySize );
1189 *(WORD *)PTR_SEG_OFF_TO_LIN( seg, ptr ) = 0; /* clear previous bp */
1193 /***********************************************************************
1194 * SwitchStackBack (KERNEL.109)
1196 void WINAPI SwitchStackBack16( CONTEXT86 *context )
1198 STACK16FRAME *oldFrame, *newFrame;
1199 INSTANCEDATA *pData;
1201 if (!(pData = (INSTANCEDATA *)GlobalLock16(SELECTOROF(NtCurrentTeb()->cur_stack))))
1203 if (!pData->old_ss_sp)
1205 WARN_(task)("No previous SwitchStackTo\n" );
1208 TRACE_(task)("restoring stack %04x:%04x\n",
1209 SELECTOROF(pData->old_ss_sp), OFFSETOF(pData->old_ss_sp) );
1211 oldFrame = CURRENT_STACK16;
1213 /* Pop bp from the previous stack */
1215 BP_reg(context) = *(WORD *)PTR_SEG_TO_LIN(pData->old_ss_sp);
1216 pData->old_ss_sp += sizeof(WORD);
1218 /* Switch back to the old stack */
1220 NtCurrentTeb()->cur_stack = pData->old_ss_sp - sizeof(STACK16FRAME);
1221 SS_reg(context) = SELECTOROF(pData->old_ss_sp);
1222 ESP_reg(context) = OFFSETOF(pData->old_ss_sp) - sizeof(DWORD); /*ret addr*/
1223 pData->old_ss_sp = 0;
1225 /* Build a stack frame for the return */
1227 newFrame = CURRENT_STACK16;
1228 newFrame->frame32 = oldFrame->frame32;
1229 if (TRACE_ON(relay))
1231 newFrame->entry_ip = oldFrame->entry_ip;
1232 newFrame->entry_cs = oldFrame->entry_cs;
1237 /***********************************************************************
1238 * GetTaskQueueDS16 (KERNEL.118)
1240 void WINAPI GetTaskQueueDS16(void)
1242 CURRENT_STACK16->ds = GlobalHandleToSel16( GetTaskQueue16(0) );
1246 /***********************************************************************
1247 * GetTaskQueueES16 (KERNEL.119)
1249 void WINAPI GetTaskQueueES16(void)
1251 CURRENT_STACK16->es = GlobalHandleToSel16( GetTaskQueue16(0) );
1255 /***********************************************************************
1256 * GetCurrentTask (KERNEL.36)
1258 HTASK16 WINAPI GetCurrentTask(void)
1260 return PROCESS_Current()->task;
1263 DWORD WINAPI WIN16_GetCurrentTask(void)
1265 /* This is the version used by relay code; the first task is */
1266 /* returned in the high word of the result */
1267 return MAKELONG( GetCurrentTask(), hFirstTask );
1271 /***********************************************************************
1272 * GetCurrentPDB (KERNEL.37)
1274 * UNDOC: returns PSP of KERNEL in high word
1276 DWORD WINAPI GetCurrentPDB16(void)
1280 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1281 return MAKELONG(pTask->hPDB, 0); /* FIXME */
1285 /***********************************************************************
1286 * GetCurPID16 (KERNEL.157)
1288 DWORD WINAPI GetCurPID16( DWORD unused )
1294 /***********************************************************************
1295 * GetInstanceData (KERNEL.54)
1297 INT16 WINAPI GetInstanceData16( HINSTANCE16 instance, WORD buffer, INT16 len )
1299 char *ptr = (char *)GlobalLock16( instance );
1300 if (!ptr || !len) return 0;
1301 if ((int)buffer + len >= 0x10000) len = 0x10000 - buffer;
1302 memcpy( (char *)GlobalLock16(CURRENT_DS) + buffer, ptr + buffer, len );
1307 /***********************************************************************
1308 * GetExeVersion (KERNEL.105)
1310 WORD WINAPI GetExeVersion16(void)
1314 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1315 return pTask->version;
1319 /***********************************************************************
1320 * SetErrorMode16 (KERNEL.107)
1322 UINT16 WINAPI SetErrorMode16( UINT16 mode )
1325 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1326 pTask->error_mode = mode;
1327 return SetErrorMode( mode );
1331 /***********************************************************************
1332 * GetDOSEnvironment (KERNEL.131)
1334 SEGPTR WINAPI GetDOSEnvironment16(void)
1338 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1339 return PTR_SEG_OFF_TO_SEGPTR( pTask->pdb.environment, 0 );
1343 /***********************************************************************
1344 * GetNumTasks (KERNEL.152)
1346 UINT16 WINAPI GetNumTasks16(void)
1352 /***********************************************************************
1353 * GetTaskDS (KERNEL.155)
1355 * Note: this function apparently returns a DWORD with LOWORD == HIWORD.
1356 * I don't think we need to bother with this.
1358 HINSTANCE16 WINAPI GetTaskDS16(void)
1362 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1363 return pTask->hInstance;
1366 /***********************************************************************
1367 * GetDummyModuleHandleDS (KERNEL.602)
1369 WORD WINAPI GetDummyModuleHandleDS16(void)
1374 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1375 if (!(pTask->flags & TDBF_WIN32)) return 0;
1376 selector = GlobalHandleToSel16( pTask->hModule );
1377 CURRENT_DS = selector;
1381 /***********************************************************************
1382 * IsTask (KERNEL.320)
1384 BOOL16 WINAPI IsTask16( HTASK16 hTask )
1388 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return FALSE;
1389 if (GlobalSize16( hTask ) < sizeof(TDB)) return FALSE;
1390 return (pTask->magic == TDB_MAGIC);
1394 /***********************************************************************
1395 * IsWinOldApTask16 (KERNEL.158)
1397 BOOL16 WINAPI IsWinOldApTask16( HTASK16 hTask )
1399 /* should return bit 0 of byte 0x48 in PSP */
1403 /***********************************************************************
1404 * SetTaskSignalProc (KERNEL.38)
1406 * Real 16-bit interface is provided by the THUNK_SetTaskSignalProc.
1408 FARPROC16 WINAPI SetTaskSignalProc( HTASK16 hTask, FARPROC16 proc )
1413 if (!hTask) hTask = GetCurrentTask();
1414 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return NULL;
1415 oldProc = (FARPROC16)pTask->userhandler;
1416 pTask->userhandler = (USERSIGNALPROC)proc;
1421 /***********************************************************************
1422 * SetSigHandler (KERNEL.140)
1424 WORD WINAPI SetSigHandler16( FARPROC16 newhandler, FARPROC16* oldhandler,
1425 UINT16 *oldmode, UINT16 newmode, UINT16 flag )
1427 FIXME_(task)("(%p,%p,%p,%d,%d), unimplemented.\n",
1428 newhandler,oldhandler,oldmode,newmode,flag );
1430 if (flag != 1) return 0;
1431 if (!newmode) newhandler = NULL; /* Default handler */
1436 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return 0;
1437 if (oldmode) *oldmode = pTask->signal_flags;
1438 pTask->signal_flags = newmode;
1439 if (oldhandler) *oldhandler = pTask->sighandler;
1440 pTask->sighandler = newhandler;
1446 /***********************************************************************
1447 * GlobalNotify (KERNEL.154)
1449 * Note that GlobalNotify does _not_ return the old NotifyProc
1450 * -- contrary to LocalNotify !!
1452 VOID WINAPI GlobalNotify16( FARPROC16 proc )
1456 if (!(pTask = (TDB *)GlobalLock16( GetCurrentTask() ))) return;
1457 pTask->discardhandler = proc;
1461 /***********************************************************************
1462 * GetExePtr (KERNEL.133)
1464 static inline HMODULE16 GetExePtrHelper( HANDLE16 handle, HTASK16 *hTask )
1469 /* Check for module handle */
1471 if (!(ptr = GlobalLock16( handle ))) return 0;
1472 if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return handle;
1474 /* Search for this handle inside all tasks */
1476 *hTask = hFirstTask;
1479 TDB *pTask = (TDB *)GlobalLock16( *hTask );
1480 if ((*hTask == handle) ||
1481 (pTask->hInstance == handle) ||
1482 (pTask->hQueue == handle) ||
1483 (pTask->hPDB == handle)) return pTask->hModule;
1484 *hTask = pTask->hNext;
1487 /* Check the owner for module handle */
1489 owner = FarGetOwner16( handle );
1490 if (!(ptr = GlobalLock16( owner ))) return 0;
1491 if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return owner;
1493 /* Search for the owner inside all tasks */
1495 *hTask = hFirstTask;
1498 TDB *pTask = (TDB *)GlobalLock16( *hTask );
1499 if ((*hTask == owner) ||
1500 (pTask->hInstance == owner) ||
1501 (pTask->hQueue == owner) ||
1502 (pTask->hPDB == owner)) return pTask->hModule;
1503 *hTask = pTask->hNext;
1509 HMODULE16 WINAPI WIN16_GetExePtr( HANDLE16 handle )
1512 HMODULE16 hModule = GetExePtrHelper( handle, &hTask );
1513 STACK16FRAME *frame = CURRENT_STACK16;
1514 frame->ecx = hModule;
1515 if (hTask) frame->es = hTask;
1519 HMODULE16 WINAPI GetExePtr( HANDLE16 handle )
1522 return GetExePtrHelper( handle, &hTask );
1526 /***********************************************************************
1527 * TaskFirst (TOOLHELP.63)
1529 BOOL16 WINAPI TaskFirst16( TASKENTRY *lpte )
1531 lpte->hNext = hFirstTask;
1532 return TaskNext16( lpte );
1536 /***********************************************************************
1537 * TaskNext (TOOLHELP.64)
1539 BOOL16 WINAPI TaskNext16( TASKENTRY *lpte )
1542 INSTANCEDATA *pInstData;
1544 TRACE_(toolhelp)("(%p): task=%04x\n", lpte, lpte->hNext );
1545 if (!lpte->hNext) return FALSE;
1546 pTask = (TDB *)GlobalLock16( lpte->hNext );
1547 if (!pTask || pTask->magic != TDB_MAGIC) return FALSE;
1548 pInstData = (INSTANCEDATA *)PTR_SEG_OFF_TO_LIN( pTask->hInstance, 0 );
1549 lpte->hTask = lpte->hNext;
1550 lpte->hTaskParent = pTask->hParent;
1551 lpte->hInst = pTask->hInstance;
1552 lpte->hModule = pTask->hModule;
1553 lpte->wSS = SELECTOROF( pTask->teb->cur_stack );
1554 lpte->wSP = OFFSETOF( pTask->teb->cur_stack );
1555 lpte->wStackTop = pInstData->stacktop;
1556 lpte->wStackMinimum = pInstData->stackmin;
1557 lpte->wStackBottom = pInstData->stackbottom;
1558 lpte->wcEvents = pTask->nEvents;
1559 lpte->hQueue = pTask->hQueue;
1560 strncpy( lpte->szModule, pTask->module_name, 8 );
1561 lpte->szModule[8] = '\0';
1562 lpte->wPSPOffset = 0x100; /*??*/
1563 lpte->hNext = pTask->hNext;
1568 /***********************************************************************
1569 * TaskFindHandle (TOOLHELP.65)
1571 BOOL16 WINAPI TaskFindHandle16( TASKENTRY *lpte, HTASK16 hTask )
1573 lpte->hNext = hTask;
1574 return TaskNext16( lpte );
1578 /***********************************************************************
1579 * GetAppCompatFlags16 (KERNEL.354)
1581 DWORD WINAPI GetAppCompatFlags16( HTASK16 hTask )
1583 return GetAppCompatFlags( hTask );
1587 /***********************************************************************
1588 * GetAppCompatFlags32 (USER32.206)
1590 DWORD WINAPI GetAppCompatFlags( HTASK hTask )
1594 if (!hTask) hTask = GetCurrentTask();
1595 if (!(pTask=(TDB *)GlobalLock16( (HTASK16)hTask ))) return 0;
1596 if (GlobalSize16(hTask) < sizeof(TDB)) return 0;
1597 return pTask->compat_flags;