Release 980628
[wine/gsoc-2012-control.git] / loader / task.c
blob5483f0f5f2bebc8f8bde29a450386e0c79df8dd6
1 /*
2 * Task functions
4 * Copyright 1995 Alexandre Julliard
5 */
7 #include <stdlib.h>
8 #include <string.h>
10 #include "windows.h"
11 #include "user.h"
12 #include "callback.h"
13 #include "drive.h"
14 #include "file.h"
15 #include "global.h"
16 #include "instance.h"
17 #include "message.h"
18 #include "miscemu.h"
19 #include "module.h"
20 #include "neexe.h"
21 #include "peexe.h"
22 #include "pe_image.h"
23 #include "process.h"
24 #include "queue.h"
25 #include "selectors.h"
26 #include "stackframe.h"
27 #include "task.h"
28 #include "thread.h"
29 #include "toolhelp.h"
30 #include "winnt.h"
31 #include "winsock.h"
32 #include "thread.h"
33 #include "debug.h"
34 #include "dde_proc.h"
36 /* Min. number of thunks allocated when creating a new segment */
37 #define MIN_THUNKS 32
39 /* Pointer to function to switch to a larger stack */
40 int (*IF1632_CallLargeStack)( int (*func)(), void *arg ) = NULL;
42 static HTASK16 hFirstTask = 0;
43 static HTASK16 hCurrentTask = 0;
44 static HTASK16 hTaskToKill = 0;
45 static HTASK16 hLockedTask = 0;
46 static UINT16 nTaskCount = 0;
48 static void TASK_YieldToSystem(TDB*);
51 /***********************************************************************
52 * TASK_GetNextTask
54 HTASK16 TASK_GetNextTask( HTASK16 hTask )
56 TDB* pTask = (TDB*)GlobalLock16(hTask);
58 if (pTask->hNext) return pTask->hNext;
59 return (hFirstTask != hTask) ? hFirstTask : 0;
63 /***********************************************************************
64 * TASK_LinkTask
66 static void TASK_LinkTask( HTASK16 hTask )
68 HTASK16 *prevTask;
69 TDB *pTask;
71 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
72 prevTask = &hFirstTask;
73 while (*prevTask)
75 TDB *prevTaskPtr = (TDB *)GlobalLock16( *prevTask );
76 if (prevTaskPtr->priority >= pTask->priority) break;
77 prevTask = &prevTaskPtr->hNext;
79 pTask->hNext = *prevTask;
80 *prevTask = hTask;
81 nTaskCount++;
85 /***********************************************************************
86 * TASK_UnlinkTask
88 static void TASK_UnlinkTask( HTASK16 hTask )
90 HTASK16 *prevTask;
91 TDB *pTask;
93 prevTask = &hFirstTask;
94 while (*prevTask && (*prevTask != hTask))
96 pTask = (TDB *)GlobalLock16( *prevTask );
97 prevTask = &pTask->hNext;
99 if (*prevTask)
101 pTask = (TDB *)GlobalLock16( *prevTask );
102 *prevTask = pTask->hNext;
103 pTask->hNext = 0;
104 nTaskCount--;
109 /***********************************************************************
110 * TASK_CreateThunks
112 * Create a thunk free-list in segment 'handle', starting from offset 'offset'
113 * and containing 'count' entries.
115 static void TASK_CreateThunks( HGLOBAL16 handle, WORD offset, WORD count )
117 int i;
118 WORD free;
119 THUNKS *pThunk;
121 pThunk = (THUNKS *)((BYTE *)GlobalLock16( handle ) + offset);
122 pThunk->next = 0;
123 pThunk->magic = THUNK_MAGIC;
124 pThunk->free = (int)&pThunk->thunks - (int)pThunk;
125 free = pThunk->free;
126 for (i = 0; i < count-1; i++)
128 free += 8; /* Offset of next thunk */
129 pThunk->thunks[4*i] = free;
131 pThunk->thunks[4*i] = 0; /* Last thunk */
135 /***********************************************************************
136 * TASK_AllocThunk
138 * Allocate a thunk for MakeProcInstance().
140 static SEGPTR TASK_AllocThunk( HTASK16 hTask )
142 TDB *pTask;
143 THUNKS *pThunk;
144 WORD sel, base;
146 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return 0;
147 sel = pTask->hCSAlias;
148 pThunk = &pTask->thunks;
149 base = (int)pThunk - (int)pTask;
150 while (!pThunk->free)
152 sel = pThunk->next;
153 if (!sel) /* Allocate a new segment */
155 sel = GLOBAL_Alloc( GMEM_FIXED, sizeof(THUNKS) + (MIN_THUNKS-1)*8,
156 pTask->hPDB, TRUE, FALSE, FALSE );
157 if (!sel) return (SEGPTR)0;
158 TASK_CreateThunks( sel, 0, MIN_THUNKS );
159 pThunk->next = sel;
161 pThunk = (THUNKS *)GlobalLock16( sel );
162 base = 0;
164 base += pThunk->free;
165 pThunk->free = *(WORD *)((BYTE *)pThunk + pThunk->free);
166 return PTR_SEG_OFF_TO_SEGPTR( sel, base );
170 /***********************************************************************
171 * TASK_FreeThunk
173 * Free a MakeProcInstance() thunk.
175 static BOOL32 TASK_FreeThunk( HTASK16 hTask, SEGPTR thunk )
177 TDB *pTask;
178 THUNKS *pThunk;
179 WORD sel, base;
181 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return 0;
182 sel = pTask->hCSAlias;
183 pThunk = &pTask->thunks;
184 base = (int)pThunk - (int)pTask;
185 while (sel && (sel != HIWORD(thunk)))
187 sel = pThunk->next;
188 pThunk = (THUNKS *)GlobalLock16( sel );
189 base = 0;
191 if (!sel) return FALSE;
192 *(WORD *)((BYTE *)pThunk + LOWORD(thunk) - base) = pThunk->free;
193 pThunk->free = LOWORD(thunk) - base;
194 return TRUE;
198 /***********************************************************************
199 * TASK_CallToStart
201 * 32-bit entry point for a new task. This function is responsible for
202 * setting up the registers and jumping to the 16-bit entry point.
204 static void TASK_CallToStart(void)
206 int exit_code = 1;
207 TDB *pTask = (TDB *)GlobalLock16( hCurrentTask );
208 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
209 SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
211 SET_CUR_THREAD( pTask->thdb );
212 /* Terminate the stack frame */
213 THREAD_STACK16(pTask->thdb)->frame32 = NULL;
214 if (pModule->flags & NE_FFLAGS_WIN32)
216 /* FIXME: all this is an ugly hack */
218 FARPROC32 entry = (FARPROC32)RVA_PTR( PROCESS_Current()->exe_modref->module, OptionalHeader.AddressOfEntryPoint );
220 pTask->userhandler = (USERSIGNALPROC)&USER_SignalProc;
221 if (pModule->heap_size)
222 LocalInit( pTask->hInstance, 0, pModule->heap_size );
224 InitApp( pTask->hModule );
225 PE_InitializeDLLs( PROCESS_Current(), DLL_PROCESS_ATTACH, (LPVOID)-1 );
226 TRACE(relay, "(entryproc=%p)\n", entry );
227 exit_code = entry();
228 TASK_KillCurrentTask( exit_code );
230 else
232 /* Registers at initialization must be:
233 * ax zero
234 * bx stack size in bytes
235 * cx heap size in bytes
236 * si previous app instance
237 * di current app instance
238 * bp zero
239 * es selector to the PSP
240 * ds dgroup of the application
241 * ss stack selector
242 * sp top of the stack
244 CONTEXT context;
246 memset( &context, 0, sizeof(context) );
247 CS_reg(&context) = pSegTable[pModule->cs - 1].selector;
248 DS_reg(&context) = pSegTable[pModule->dgroup - 1].selector;
249 ES_reg(&context) = pTask->hPDB;
250 EIP_reg(&context) = pModule->ip;
251 EBX_reg(&context) = pModule->stack_size;
252 ECX_reg(&context) = pModule->heap_size;
253 EDI_reg(&context) = context.SegDs;
255 TRACE(task, "Starting main program: cs:ip=%04lx:%04x ds=%04lx ss:sp=%04x:%04x\n",
256 CS_reg(&context), IP_reg(&context), DS_reg(&context),
257 SELECTOROF(pTask->thdb->cur_stack),
258 OFFSETOF(pTask->thdb->cur_stack) );
260 Callbacks->CallRegisterShortProc( &context, 0 );
261 /* This should never return */
262 ERR( task, "Main program returned! (should never happen)\n" );
263 TASK_KillCurrentTask( 1 );
268 /***********************************************************************
269 * TASK_Create
271 HTASK16 TASK_Create( THDB *thdb, NE_MODULE *pModule, HINSTANCE16 hInstance,
272 HINSTANCE16 hPrevInstance, UINT16 cmdShow)
274 HTASK16 hTask;
275 TDB *pTask;
276 LPSTR cmd_line;
277 WORD sp;
278 char *stack32Top;
279 char name[10];
280 STACK16FRAME *frame16;
281 STACK32FRAME *frame32;
282 PDB32 *pdb32 = thdb->process;
283 SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
285 /* Allocate the task structure */
287 hTask = GLOBAL_Alloc( GMEM_FIXED | GMEM_ZEROINIT, sizeof(TDB),
288 pModule->self, FALSE, FALSE, FALSE );
289 if (!hTask) return 0;
290 pTask = (TDB *)GlobalLock16( hTask );
292 /* Fill the task structure */
294 pTask->nEvents = 1; /* So the task can be started */
295 pTask->hSelf = hTask;
296 pTask->flags = 0;
298 if (pModule->flags & NE_FFLAGS_WIN32)
299 pTask->flags |= TDBF_WIN32;
301 pTask->version = pModule->expected_version;
302 pTask->hInstance = hInstance;
303 pTask->hPrevInstance = hPrevInstance;
304 pTask->hModule = pModule->self;
305 pTask->hParent = hCurrentTask;
306 pTask->magic = TDB_MAGIC;
307 pTask->nCmdShow = cmdShow;
308 pTask->thdb = thdb;
309 pTask->curdrive = DRIVE_GetCurrentDrive() | 0x80;
310 strcpy( pTask->curdir, "\\" );
311 lstrcpyn32A( pTask->curdir + 1, DRIVE_GetDosCwd( DRIVE_GetCurrentDrive() ),
312 sizeof(pTask->curdir) - 1 );
314 /* Create the thunks block */
316 TASK_CreateThunks( hTask, (int)&pTask->thunks - (int)pTask, 7 );
318 /* Copy the module name */
320 GetModuleName( pModule->self, name, sizeof(name) );
321 strncpy( pTask->module_name, name, sizeof(pTask->module_name) );
323 /* Allocate a selector for the PDB */
325 pTask->hPDB = GLOBAL_CreateBlock( GMEM_FIXED, &pTask->pdb, sizeof(PDB),
326 pModule->self, FALSE, FALSE, FALSE, NULL );
328 /* Fill the PDB */
330 pTask->pdb.int20 = 0x20cd;
331 pTask->pdb.dispatcher[0] = 0x9a; /* ljmp */
332 PUT_DWORD(&pTask->pdb.dispatcher[1], (DWORD)NE_GetEntryPoint(
333 GetModuleHandle16("KERNEL"), 102 )); /* KERNEL.102 is DOS3Call() */
334 pTask->pdb.savedint22 = INT_GetHandler( 0x22 );
335 pTask->pdb.savedint23 = INT_GetHandler( 0x23 );
336 pTask->pdb.savedint24 = INT_GetHandler( 0x24 );
337 pTask->pdb.fileHandlesPtr =
338 PTR_SEG_OFF_TO_SEGPTR( GlobalHandleToSel(pTask->hPDB),
339 (int)&((PDB *)0)->fileHandles );
340 pTask->pdb.hFileHandles = 0;
341 memset( pTask->pdb.fileHandles, 0xff, sizeof(pTask->pdb.fileHandles) );
342 pTask->pdb.environment = pdb32->env_db->env_sel;
343 pTask->pdb.nbFiles = 20;
345 /* Fill the command line */
347 cmd_line = pdb32->env_db->cmd_line;
348 while (*cmd_line && (*cmd_line != ' ') && (*cmd_line != '\t')) cmd_line++;
349 while ((*cmd_line == ' ') || (*cmd_line == '\t')) cmd_line++;
350 lstrcpyn32A( pTask->pdb.cmdLine+1, cmd_line, sizeof(pTask->pdb.cmdLine)-1);
351 pTask->pdb.cmdLine[0] = strlen( pTask->pdb.cmdLine + 1 );
353 /* Get the compatibility flags */
355 pTask->compat_flags = GetProfileInt32A( "Compatibility", name, 0 );
357 /* Allocate a code segment alias for the TDB */
359 pTask->hCSAlias = GLOBAL_CreateBlock( GMEM_FIXED, (void *)pTask,
360 sizeof(TDB), pTask->hPDB, TRUE,
361 FALSE, FALSE, NULL );
363 /* Set the owner of the environment block */
365 FarSetOwner( pTask->pdb.environment, pTask->hPDB );
367 /* Default DTA overwrites command-line */
369 pTask->dta = PTR_SEG_OFF_TO_SEGPTR( pTask->hPDB,
370 (int)&pTask->pdb.cmdLine - (int)&pTask->pdb );
372 /* Create the 16-bit stack frame */
374 if (!(sp = pModule->sp))
375 sp = pSegTable[pModule->ss-1].minsize + pModule->stack_size;
376 sp &= ~1;
377 pTask->thdb->cur_stack = PTR_SEG_OFF_TO_SEGPTR( pTask->hInstance, sp );
378 pTask->thdb->cur_stack -= sizeof(STACK16FRAME) + sizeof(STACK32FRAME *);
379 frame16 = (STACK16FRAME *)PTR_SEG_TO_LIN( pTask->thdb->cur_stack );
380 frame16->ebp = sp + (int)&((STACK16FRAME *)0)->bp;
381 frame16->bp = LOWORD(frame16->ebp);
382 frame16->ds = frame16->es = pTask->hInstance;
383 frame16->entry_point = 0;
384 frame16->entry_cs = 0;
385 /* The remaining fields will be initialized in TASK_Reschedule */
387 /* Create the 32-bit stack frame */
389 stack32Top = (char*)pTask->thdb->teb.stack_top;
390 frame16->frame32 = frame32 = (STACK32FRAME *)stack32Top - 1;
391 frame32->frame16 = pTask->thdb->cur_stack + sizeof(STACK16FRAME);
392 frame32->edi = 0;
393 frame32->esi = 0;
394 frame32->edx = 0;
395 frame32->ecx = 0;
396 frame32->ebx = 0;
397 frame32->retaddr = (DWORD)TASK_CallToStart;
398 /* The remaining fields will be initialized in TASK_Reschedule */
400 if (!THREAD_Current()->cur_stack)
401 THREAD_Current()->cur_stack = pTask->thdb->cur_stack;
403 /* Add the task to the linked list */
405 TASK_LinkTask( hTask );
407 TRACE(task, "module='%s' cmdline='%s' task=%04x\n",
408 name, cmd_line, hTask );
410 return hTask;
414 /***********************************************************************
415 * TASK_DeleteTask
417 static void TASK_DeleteTask( HTASK16 hTask )
419 TDB *pTask;
420 HGLOBAL16 hPDB;
422 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
423 hPDB = pTask->hPDB;
425 pTask->magic = 0xdead; /* invalidate signature */
427 /* Delete the Win32 part of the task */
429 K32OBJ_DecCount( &pTask->thdb->process->header );
430 K32OBJ_DecCount( &pTask->thdb->header );
432 /* Free the task module */
434 FreeModule16( pTask->hModule );
436 /* Free the selector aliases */
438 GLOBAL_FreeBlock( pTask->hCSAlias );
439 GLOBAL_FreeBlock( pTask->hPDB );
441 /* Free the task structure itself */
443 GlobalFree16( hTask );
445 /* Free all memory used by this task (including the 32-bit stack, */
446 /* the environment block and the thunk segments). */
448 GlobalFreeAll( hPDB );
452 /***********************************************************************
453 * TASK_KillCurrentTask
455 * Kill the currently running task. As it's not possible to kill the
456 * current task like this, it is simply marked for destruction, and will
457 * be killed when either TASK_Reschedule or this function is called again
458 * in the context of another task.
460 void TASK_KillCurrentTask( INT16 exitCode )
462 TDB* pTask = (TDB*) GlobalLock16( hCurrentTask );
463 if (!pTask) USER_ExitWindows(); /* No current task yet */
465 TRACE(task, "Killing task %04x\n", hCurrentTask );
467 /* Delete active sockets */
469 if( pTask->pwsi )
470 WINSOCK_DeleteTaskWSI( pTask, pTask->pwsi );
472 /* Perform USER cleanup */
474 if (pTask->userhandler)
475 pTask->userhandler( hCurrentTask, USIG_TERMINATION, 0,
476 pTask->hInstance, pTask->hQueue );
478 if (hTaskToKill && (hTaskToKill != hCurrentTask))
480 /* If another task is already marked for destruction, */
481 /* we can kill it now, as we are in another context. */
482 TASK_DeleteTask( hTaskToKill );
485 if (nTaskCount <= 1)
487 TRACE(task, "this is the last task, exiting\n" );
488 USER_ExitWindows();
491 /* Remove the task from the list to be sure we never switch back to it */
492 TASK_UnlinkTask( hCurrentTask );
493 if( nTaskCount )
495 TDB* p = (TDB *)GlobalLock16( hFirstTask );
496 while( p )
498 if( p->hYieldTo == hCurrentTask ) p->hYieldTo = 0;
499 p = (TDB *)GlobalLock16( p->hNext );
503 hTaskToKill = hCurrentTask;
504 hLockedTask = 0;
506 pTask->nEvents = 0;
507 TASK_YieldToSystem(pTask);
509 /* We should never return from this Yield() */
511 ERR(task,"Return of the living dead %04x!!!\n", hCurrentTask);
512 exit(1);
515 /***********************************************************************
516 * TASK_Reschedule
518 * This is where all the magic of task-switching happens!
520 * Note: This function should only be called via the TASK_YieldToSystem()
521 * wrapper, to make sure that all the context is saved correctly.
523 * It must not call functions that may yield control.
525 void TASK_Reschedule(void)
527 TDB *pOldTask = NULL, *pNewTask;
528 HTASK16 hTask = 0;
529 STACK16FRAME *newframe16;
531 #ifdef CONFIG_IPC
532 dde_reschedule();
533 #endif
534 /* First check if there's a task to kill */
536 if (hTaskToKill && (hTaskToKill != hCurrentTask))
538 TASK_DeleteTask( hTaskToKill );
539 hTaskToKill = 0;
542 /* Find a task to yield to */
544 pOldTask = (TDB *)GlobalLock16( hCurrentTask );
545 if (pOldTask && pOldTask->hYieldTo)
547 /* check for DirectedYield() */
549 hTask = pOldTask->hYieldTo;
550 pNewTask = (TDB *)GlobalLock16( hTask );
551 if( !pNewTask || !pNewTask->nEvents) hTask = 0;
552 pOldTask->hYieldTo = 0;
555 /* extract hardware events only! */
557 if (!hTask) EVENT_WaitNetEvent( FALSE, TRUE );
559 while (!hTask)
561 /* Find a task that has an event pending */
563 hTask = hFirstTask;
564 while (hTask)
566 pNewTask = (TDB *)GlobalLock16( hTask );
568 TRACE(task, "\ttask = %04x, events = %i\n", hTask, pNewTask->nEvents);
570 if (pNewTask->nEvents) break;
571 hTask = pNewTask->hNext;
573 if (hLockedTask && (hTask != hLockedTask)) hTask = 0;
574 if (hTask) break;
576 /* No task found, wait for some events to come in */
578 EVENT_WaitNetEvent( TRUE, TRUE );
581 if (hTask == hCurrentTask)
583 TRACE(task, "returning to the current task(%04x)\n", hTask );
584 return; /* Nothing to do */
586 pNewTask = (TDB *)GlobalLock16( hTask );
587 TRACE(task, "Switching to task %04x (%.8s)\n",
588 hTask, pNewTask->module_name );
590 /* Make the task the last in the linked list (round-robin scheduling) */
592 pNewTask->priority++;
593 TASK_UnlinkTask( hTask );
594 TASK_LinkTask( hTask );
595 pNewTask->priority--;
597 /* Finish initializing the new task stack if necessary */
599 newframe16 = THREAD_STACK16( pNewTask->thdb );
600 if (!newframe16->entry_cs)
602 STACK16FRAME *oldframe16 = CURRENT_STACK16;
603 STACK32FRAME *oldframe32 = oldframe16->frame32;
604 STACK32FRAME *newframe32 = newframe16->frame32;
605 newframe16->entry_ip = oldframe16->entry_ip;
606 newframe16->entry_cs = oldframe16->entry_cs;
607 newframe16->ip = oldframe16->ip;
608 newframe16->cs = oldframe16->cs;
609 newframe32->ebp = oldframe32->ebp;
610 newframe32->restore_addr = oldframe32->restore_addr;
611 newframe32->codeselector = oldframe32->codeselector;
614 /* Switch to the new stack */
616 hCurrentTask = hTask;
617 SET_CUR_THREAD( pNewTask->thdb );
618 pNewTask->ss_sp = pNewTask->thdb->cur_stack;
622 /***********************************************************************
623 * TASK_YieldToSystem
625 * Scheduler interface, this way we ensure that all "unsafe" events are
626 * processed outside the scheduler.
628 void TASK_YieldToSystem(TDB* pTask)
630 MESSAGEQUEUE* pQ;
632 Callbacks->CallTaskRescheduleProc();
634 if( pTask )
636 pQ = (MESSAGEQUEUE*)GlobalLock16(pTask->hQueue);
637 if( pQ && pQ->flags & QUEUE_FLAG_XEVENT &&
638 !(pQ->wakeBits & (QS_SENDMESSAGE | QS_SMRESULT)) )
640 pQ->flags &= ~QUEUE_FLAG_XEVENT;
641 EVENT_WaitNetEvent( FALSE, FALSE );
647 /***********************************************************************
648 * InitTask (KERNEL.91)
650 * Called by the application startup code.
652 void WINAPI InitTask( CONTEXT *context )
654 TDB *pTask;
655 NE_MODULE *pModule;
656 SEGTABLEENTRY *pSegTable;
657 INSTANCEDATA *pinstance;
658 LONG stacklow, stackhi;
660 if (context) EAX_reg(context) = 0;
661 if (!(pTask = (TDB *)GlobalLock16( hCurrentTask ))) return;
662 if (!(pModule = NE_GetPtr( pTask->hModule ))) return;
664 /* This is a hack to install task USER signal handler before
665 * implicitly loaded DLLs are initialized (see windows/user.c) */
667 pTask->userhandler = (USERSIGNALPROC)&USER_SignalProc;
669 /* Initialize implicitly loaded DLLs */
670 NE_InitializeDLLs( pTask->hModule );
672 if (context)
674 /* Registers on return are:
675 * ax 1 if OK, 0 on error
676 * cx stack limit in bytes
677 * dx cmdShow parameter
678 * si instance handle of the previous instance
679 * di instance handle of the new task
680 * es:bx pointer to command-line inside PSP
682 EAX_reg(context) = 1;
684 if (!pTask->pdb.cmdLine[0]) EBX_reg(context) = 0x80;
685 else
687 LPBYTE p = &pTask->pdb.cmdLine[1];
688 while ((*p == ' ') || (*p == '\t')) p++;
689 EBX_reg(context) = 0x80 + (p - pTask->pdb.cmdLine);
691 ECX_reg(context) = pModule->stack_size;
692 EDX_reg(context) = pTask->nCmdShow;
693 ESI_reg(context) = (DWORD)pTask->hPrevInstance;
694 EDI_reg(context) = (DWORD)pTask->hInstance;
695 ES_reg (context) = (WORD)pTask->hPDB;
698 /* Initialize the local heap */
699 if ( pModule->heap_size )
701 LocalInit( pTask->hInstance, 0, pModule->heap_size );
704 /* Initialize the INSTANCEDATA structure */
705 pSegTable = NE_SEG_TABLE( pModule );
706 stacklow = pSegTable[pModule->ss - 1].minsize;
707 stackhi = stacklow + pModule->stack_size;
708 if (stackhi > 0xffff) stackhi = 0xffff;
709 pinstance = (INSTANCEDATA *)PTR_SEG_OFF_TO_LIN(CURRENT_DS, 0);
710 pinstance->stackbottom = stackhi; /* yup, that's right. Confused me too. */
711 pinstance->stacktop = stacklow;
712 pinstance->stackmin = OFFSETOF( pTask->thdb->cur_stack );
716 /***********************************************************************
717 * WaitEvent (KERNEL.30)
719 BOOL16 WINAPI WaitEvent( HTASK16 hTask )
721 TDB *pTask;
723 if (!hTask) hTask = hCurrentTask;
724 pTask = (TDB *)GlobalLock16( hTask );
725 if (pTask->nEvents > 0)
727 pTask->nEvents--;
728 return FALSE;
730 TASK_YieldToSystem(pTask);
732 /* When we get back here, we have an event */
734 if (pTask->nEvents > 0) pTask->nEvents--;
735 return TRUE;
739 /***********************************************************************
740 * PostEvent (KERNEL.31)
742 void WINAPI PostEvent( HTASK16 hTask )
744 TDB *pTask;
746 if (!hTask) hTask = hCurrentTask;
747 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
748 pTask->nEvents++;
752 /***********************************************************************
753 * SetPriority (KERNEL.32)
755 void WINAPI SetPriority( HTASK16 hTask, INT16 delta )
757 TDB *pTask;
758 INT16 newpriority;
760 if (!hTask) hTask = hCurrentTask;
761 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return;
762 newpriority = pTask->priority + delta;
763 if (newpriority < -32) newpriority = -32;
764 else if (newpriority > 15) newpriority = 15;
766 pTask->priority = newpriority + 1;
767 TASK_UnlinkTask( hTask );
768 TASK_LinkTask( hTask );
769 pTask->priority--;
773 /***********************************************************************
774 * LockCurrentTask (KERNEL.33)
776 HTASK16 WINAPI LockCurrentTask( BOOL16 bLock )
778 if (bLock) hLockedTask = hCurrentTask;
779 else hLockedTask = 0;
780 return hLockedTask;
784 /***********************************************************************
785 * IsTaskLocked (KERNEL.122)
787 HTASK16 WINAPI IsTaskLocked(void)
789 return hLockedTask;
793 /***********************************************************************
794 * OldYield (KERNEL.117)
796 void WINAPI OldYield(void)
798 TDB *pCurTask;
800 pCurTask = (TDB *)GlobalLock16( hCurrentTask );
801 if (pCurTask) pCurTask->nEvents++; /* Make sure we get back here */
802 TASK_YieldToSystem(pCurTask);
803 if (pCurTask) pCurTask->nEvents--;
807 /***********************************************************************
808 * DirectedYield (KERNEL.150)
810 void WINAPI DirectedYield( HTASK16 hTask )
812 TDB *pCurTask = (TDB *)GlobalLock16( hCurrentTask );
813 pCurTask->hYieldTo = hTask;
814 OldYield();
818 /***********************************************************************
819 * UserYield (USER.332)
821 void WINAPI UserYield(void)
823 TDB *pCurTask = (TDB *)GlobalLock16( hCurrentTask );
824 MESSAGEQUEUE *queue = (MESSAGEQUEUE *)GlobalLock16( pCurTask->hQueue );
825 /* Handle sent messages */
826 while (queue && (queue->wakeBits & QS_SENDMESSAGE))
827 QUEUE_ReceiveMessage( queue );
829 OldYield();
831 queue = (MESSAGEQUEUE *)GlobalLock16( pCurTask->hQueue );
832 while (queue && (queue->wakeBits & QS_SENDMESSAGE))
833 QUEUE_ReceiveMessage( queue );
837 /***********************************************************************
838 * Yield16 (KERNEL.29)
840 void WINAPI Yield16(void)
842 TDB *pCurTask = (TDB *)GlobalLock16( hCurrentTask );
843 if (pCurTask) pCurTask->hYieldTo = 0;
844 if (pCurTask && pCurTask->hQueue) UserYield();
845 else OldYield();
849 /***********************************************************************
850 * MakeProcInstance16 (KERNEL.51)
852 FARPROC16 WINAPI MakeProcInstance16( FARPROC16 func, HANDLE16 hInstance )
854 BYTE *thunk,*lfunc;
855 SEGPTR thunkaddr;
857 if (!hInstance) hInstance = CURRENT_DS;
858 thunkaddr = TASK_AllocThunk( hCurrentTask );
859 if (!thunkaddr) return (FARPROC16)0;
860 thunk = PTR_SEG_TO_LIN( thunkaddr );
861 lfunc = PTR_SEG_TO_LIN( func );
863 TRACE(task, "(%08lx,%04x): got thunk %08lx\n",
864 (DWORD)func, hInstance, (DWORD)thunkaddr );
865 if (((lfunc[0]==0x8c) && (lfunc[1]==0xd8)) ||
866 ((lfunc[0]==0x1e) && (lfunc[1]==0x58))
868 FIXME(task,"thunk would be useless for %p, overwriting with nop;nop;\n", func );
869 lfunc[0]=0x90; /* nop */
870 lfunc[1]=0x90; /* nop */
873 *thunk++ = 0xb8; /* movw instance, %ax */
874 *thunk++ = (BYTE)(hInstance & 0xff);
875 *thunk++ = (BYTE)(hInstance >> 8);
876 *thunk++ = 0xea; /* ljmp func */
877 *(DWORD *)thunk = (DWORD)func;
878 return (FARPROC16)thunkaddr;
882 /***********************************************************************
883 * FreeProcInstance16 (KERNEL.52)
885 void WINAPI FreeProcInstance16( FARPROC16 func )
887 TRACE(task, "(%08lx)\n", (DWORD)func );
888 TASK_FreeThunk( hCurrentTask, (SEGPTR)func );
892 /**********************************************************************
893 * GetCodeHandle (KERNEL.93)
895 HANDLE16 WINAPI GetCodeHandle( FARPROC16 proc )
897 HANDLE16 handle;
898 BYTE *thunk = (BYTE *)PTR_SEG_TO_LIN( proc );
900 /* Return the code segment containing 'proc'. */
901 /* Not sure if this is really correct (shouldn't matter that much). */
903 /* Check if it is really a thunk */
904 if ((thunk[0] == 0xb8) && (thunk[3] == 0xea))
905 handle = GlobalHandle16( thunk[6] + (thunk[7] << 8) );
906 else
907 handle = GlobalHandle16( HIWORD(proc) );
909 return handle;
913 /**********************************************************************
914 * DefineHandleTable16 (KERNEL.94)
916 BOOL16 WINAPI DefineHandleTable16( WORD wOffset )
918 return TRUE; /* FIXME */
922 /***********************************************************************
923 * SetTaskQueue (KERNEL.34)
925 HQUEUE16 WINAPI SetTaskQueue( HTASK16 hTask, HQUEUE16 hQueue )
927 HQUEUE16 hPrev;
928 TDB *pTask;
930 if (!hTask) hTask = hCurrentTask;
931 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return 0;
933 hPrev = pTask->hQueue;
934 pTask->hQueue = hQueue;
936 TIMER_SwitchQueue( hPrev, hQueue );
938 return hPrev;
942 /***********************************************************************
943 * GetTaskQueue (KERNEL.35)
945 HQUEUE16 WINAPI GetTaskQueue( HTASK16 hTask )
947 TDB *pTask;
949 if (!hTask) hTask = hCurrentTask;
950 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return 0;
951 return pTask->hQueue;
955 /***********************************************************************
956 * SwitchStackTo (KERNEL.108)
958 void WINAPI SwitchStackTo( WORD seg, WORD ptr, WORD top )
960 TDB *pTask;
961 STACK16FRAME *oldFrame, *newFrame;
962 INSTANCEDATA *pData;
963 UINT16 copySize;
965 if (!(pTask = (TDB *)GlobalLock16( hCurrentTask ))) return;
966 if (!(pData = (INSTANCEDATA *)GlobalLock16( seg ))) return;
967 TRACE(task, "old=%04x:%04x new=%04x:%04x\n",
968 SELECTOROF( pTask->thdb->cur_stack ),
969 OFFSETOF( pTask->thdb->cur_stack ), seg, ptr );
971 /* Save the old stack */
973 oldFrame = THREAD_STACK16( pTask->thdb );
974 /* pop frame + args and push bp */
975 pData->old_ss_sp = pTask->thdb->cur_stack - sizeof(STACK16FRAME)
976 - 2 * sizeof(WORD);
977 *(WORD *)PTR_SEG_TO_LIN(pData->old_ss_sp) = oldFrame->bp;
978 pData->stacktop = top;
979 pData->stackmin = ptr;
980 pData->stackbottom = ptr;
982 /* Switch to the new stack */
984 /* Note: we need to take the 3 arguments into account; otherwise,
985 * the stack will underflow upon return from this function.
987 copySize = oldFrame->bp - OFFSETOF(pData->old_ss_sp);
988 copySize += 3 * sizeof(WORD) + sizeof(STACK16FRAME);
989 pTask->thdb->cur_stack = PTR_SEG_OFF_TO_SEGPTR( seg, ptr - copySize );
990 newFrame = THREAD_STACK16( pTask->thdb );
992 /* Copy the stack frame and the local variables to the new stack */
994 memmove( newFrame, oldFrame, copySize );
995 newFrame->bp = ptr;
996 *(WORD *)PTR_SEG_OFF_TO_LIN( seg, ptr ) = 0; /* clear previous bp */
1000 /***********************************************************************
1001 * SwitchStackBack (KERNEL.109)
1003 void WINAPI SwitchStackBack( CONTEXT *context )
1005 TDB *pTask;
1006 STACK16FRAME *oldFrame, *newFrame;
1007 INSTANCEDATA *pData;
1009 if (!(pTask = (TDB *)GlobalLock16( hCurrentTask ))) return;
1010 if (!(pData = (INSTANCEDATA *)GlobalLock16(SELECTOROF(pTask->thdb->cur_stack))))
1011 return;
1012 if (!pData->old_ss_sp)
1014 WARN( task, "No previous SwitchStackTo\n" );
1015 return;
1017 TRACE(task, "restoring stack %04x:%04x\n",
1018 SELECTOROF(pData->old_ss_sp), OFFSETOF(pData->old_ss_sp) );
1020 oldFrame = THREAD_STACK16( pTask->thdb );
1022 /* Pop bp from the previous stack */
1024 BP_reg(context) = *(WORD *)PTR_SEG_TO_LIN(pData->old_ss_sp);
1025 pData->old_ss_sp += sizeof(WORD);
1027 /* Switch back to the old stack */
1029 pTask->thdb->cur_stack = pData->old_ss_sp - sizeof(STACK16FRAME);
1030 SS_reg(context) = SELECTOROF(pData->old_ss_sp);
1031 ESP_reg(context) = OFFSETOF(pData->old_ss_sp) - sizeof(DWORD); /*ret addr*/
1032 pData->old_ss_sp = 0;
1034 /* Build a stack frame for the return */
1036 newFrame = THREAD_STACK16( pTask->thdb );
1037 newFrame->frame32 = oldFrame->frame32;
1038 if (TRACE_ON(relay))
1040 newFrame->entry_ip = oldFrame->entry_ip;
1041 newFrame->entry_cs = oldFrame->entry_cs;
1046 /***********************************************************************
1047 * GetTaskQueueDS (KERNEL.118)
1049 void WINAPI GetTaskQueueDS( CONTEXT *context )
1051 DS_reg(context) = GlobalHandleToSel( GetTaskQueue(0) );
1055 /***********************************************************************
1056 * GetTaskQueueES (KERNEL.119)
1058 void WINAPI GetTaskQueueES( CONTEXT *context )
1060 ES_reg(context) = GlobalHandleToSel( GetTaskQueue(0) );
1064 /***********************************************************************
1065 * GetCurrentTask (KERNEL.36)
1067 HTASK16 WINAPI GetCurrentTask(void)
1069 return hCurrentTask;
1072 DWORD WINAPI WIN16_GetCurrentTask(void)
1074 /* This is the version used by relay code; the first task is */
1075 /* returned in the high word of the result */
1076 return MAKELONG( hCurrentTask, hFirstTask );
1080 /***********************************************************************
1081 * GetCurrentPDB (KERNEL.37)
1083 HANDLE16 WINAPI GetCurrentPDB(void)
1085 TDB *pTask;
1087 if (!(pTask = (TDB *)GlobalLock16( hCurrentTask ))) return 0;
1088 return pTask->hPDB;
1092 /***********************************************************************
1093 * GetInstanceData (KERNEL.54)
1095 INT16 WINAPI GetInstanceData( HINSTANCE16 instance, WORD buffer, INT16 len )
1097 char *ptr = (char *)GlobalLock16( instance );
1098 if (!ptr || !len) return 0;
1099 if ((int)buffer + len >= 0x10000) len = 0x10000 - buffer;
1100 memcpy( (char *)GlobalLock16(CURRENT_DS) + buffer, ptr + buffer, len );
1101 return len;
1105 /***********************************************************************
1106 * GetExeVersion (KERNEL.105)
1108 WORD WINAPI GetExeVersion(void)
1110 TDB *pTask;
1112 if (!(pTask = (TDB *)GlobalLock16( hCurrentTask ))) return 0;
1113 return pTask->version;
1117 /***********************************************************************
1118 * SetErrorMode16 (KERNEL.107)
1120 UINT16 WINAPI SetErrorMode16( UINT16 mode )
1122 TDB *pTask;
1123 UINT16 oldMode;
1125 if (!(pTask = (TDB *)GlobalLock16( hCurrentTask ))) return 0;
1126 oldMode = pTask->error_mode;
1127 pTask->error_mode = mode;
1128 pTask->thdb->process->error_mode = mode;
1129 return oldMode;
1133 /***********************************************************************
1134 * SetErrorMode32 (KERNEL32.486)
1136 UINT32 WINAPI SetErrorMode32( UINT32 mode )
1138 return SetErrorMode16( (UINT16)mode );
1142 /***********************************************************************
1143 * GetDOSEnvironment (KERNEL.131)
1145 SEGPTR WINAPI GetDOSEnvironment(void)
1147 TDB *pTask;
1149 if (!(pTask = (TDB *)GlobalLock16( hCurrentTask ))) return 0;
1150 return PTR_SEG_OFF_TO_SEGPTR( pTask->pdb.environment, 0 );
1154 /***********************************************************************
1155 * GetNumTasks (KERNEL.152)
1157 UINT16 WINAPI GetNumTasks(void)
1159 return nTaskCount;
1163 /***********************************************************************
1164 * GetTaskDS (KERNEL.155)
1166 * Note: this function apparently returns a DWORD with LOWORD == HIWORD.
1167 * I don't think we need to bother with this.
1169 HINSTANCE16 WINAPI GetTaskDS(void)
1171 TDB *pTask;
1173 if (!(pTask = (TDB *)GlobalLock16( hCurrentTask ))) return 0;
1174 return pTask->hInstance;
1178 /***********************************************************************
1179 * IsTask (KERNEL.320)
1181 BOOL16 WINAPI IsTask( HTASK16 hTask )
1183 TDB *pTask;
1185 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return FALSE;
1186 if (GlobalSize16( hTask ) < sizeof(TDB)) return FALSE;
1187 return (pTask->magic == TDB_MAGIC);
1191 /***********************************************************************
1192 * SetTaskSignalProc (KERNEL.38)
1194 * Real 16-bit interface is provided by the THUNK_SetTaskSignalProc.
1196 FARPROC16 WINAPI SetTaskSignalProc( HTASK16 hTask, FARPROC16 proc )
1198 TDB *pTask;
1199 FARPROC16 oldProc;
1201 if (!hTask) hTask = hCurrentTask;
1202 if (!(pTask = (TDB *)GlobalLock16( hTask ))) return NULL;
1203 oldProc = (FARPROC16)pTask->userhandler;
1204 pTask->userhandler = (USERSIGNALPROC)proc;
1205 return oldProc;
1209 /***********************************************************************
1210 * SetSigHandler (KERNEL.140)
1212 WORD WINAPI SetSigHandler( FARPROC16 newhandler, FARPROC16* oldhandler,
1213 UINT16 *oldmode, UINT16 newmode, UINT16 flag )
1215 FIXME(task,"(%p,%p,%p,%d,%d), unimplemented.\n",
1216 newhandler,oldhandler,oldmode,newmode,flag );
1218 if (flag != 1) return 0;
1219 if (!newmode) newhandler = NULL; /* Default handler */
1220 if (newmode != 4)
1222 TDB *pTask;
1224 if (!(pTask = (TDB *)GlobalLock16( hCurrentTask ))) return 0;
1225 if (oldmode) *oldmode = pTask->signal_flags;
1226 pTask->signal_flags = newmode;
1227 if (oldhandler) *oldhandler = pTask->sighandler;
1228 pTask->sighandler = newhandler;
1230 return 0;
1234 /***********************************************************************
1235 * GlobalNotify (KERNEL.154)
1237 VOID WINAPI GlobalNotify( FARPROC16 proc )
1239 TDB *pTask;
1241 if (!(pTask = (TDB *)GlobalLock16( hCurrentTask ))) return;
1242 pTask->discardhandler = proc;
1246 /***********************************************************************
1247 * GetExePtr (KERNEL.133)
1249 static HMODULE16 GetExePtrHelper( HANDLE16 handle, HTASK16 *hTask )
1251 char *ptr;
1252 HANDLE16 owner;
1254 /* Check for module handle */
1256 if (!(ptr = GlobalLock16( handle ))) return 0;
1257 if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return handle;
1259 /* Search for this handle inside all tasks */
1261 *hTask = hFirstTask;
1262 while (*hTask)
1264 TDB *pTask = (TDB *)GlobalLock16( *hTask );
1265 if ((*hTask == handle) ||
1266 (pTask->hInstance == handle) ||
1267 (pTask->hQueue == handle) ||
1268 (pTask->hPDB == handle)) return pTask->hModule;
1269 *hTask = pTask->hNext;
1272 /* Check the owner for module handle */
1274 owner = FarGetOwner( handle );
1275 if (!(ptr = GlobalLock16( owner ))) return 0;
1276 if (((NE_MODULE *)ptr)->magic == IMAGE_OS2_SIGNATURE) return owner;
1278 /* Search for the owner inside all tasks */
1280 *hTask = hFirstTask;
1281 while (*hTask)
1283 TDB *pTask = (TDB *)GlobalLock16( *hTask );
1284 if ((*hTask == owner) ||
1285 (pTask->hInstance == owner) ||
1286 (pTask->hQueue == owner) ||
1287 (pTask->hPDB == owner)) return pTask->hModule;
1288 *hTask = pTask->hNext;
1291 return 0;
1294 HMODULE16 WINAPI GetExePtr( HANDLE16 handle )
1296 HTASK16 dummy;
1297 return GetExePtrHelper( handle, &dummy );
1300 void WINAPI WIN16_GetExePtr( CONTEXT *context )
1302 WORD *stack = PTR_SEG_OFF_TO_LIN(SS_reg(context), SP_reg(context));
1303 HANDLE16 handle = (HANDLE16)stack[2];
1304 HTASK16 hTask = 0;
1305 HMODULE16 hModule;
1307 hModule = GetExePtrHelper( handle, &hTask );
1309 AX_reg(context) = CX_reg(context) = hModule;
1310 if (hTask) ES_reg(context) = hTask;
1313 /***********************************************************************
1314 * TaskFirst (TOOLHELP.63)
1316 BOOL16 WINAPI TaskFirst( TASKENTRY *lpte )
1318 lpte->hNext = hFirstTask;
1319 return TaskNext( lpte );
1323 /***********************************************************************
1324 * TaskNext (TOOLHELP.64)
1326 BOOL16 WINAPI TaskNext( TASKENTRY *lpte )
1328 TDB *pTask;
1329 INSTANCEDATA *pInstData;
1331 TRACE(toolhelp, "(%p): task=%04x\n", lpte, lpte->hNext );
1332 if (!lpte->hNext) return FALSE;
1333 pTask = (TDB *)GlobalLock16( lpte->hNext );
1334 if (!pTask || pTask->magic != TDB_MAGIC) return FALSE;
1335 pInstData = (INSTANCEDATA *)PTR_SEG_OFF_TO_LIN( pTask->hInstance, 0 );
1336 lpte->hTask = lpte->hNext;
1337 lpte->hTaskParent = pTask->hParent;
1338 lpte->hInst = pTask->hInstance;
1339 lpte->hModule = pTask->hModule;
1340 lpte->wSS = SELECTOROF( pTask->thdb->cur_stack );
1341 lpte->wSP = OFFSETOF( pTask->thdb->cur_stack );
1342 lpte->wStackTop = pInstData->stacktop;
1343 lpte->wStackMinimum = pInstData->stackmin;
1344 lpte->wStackBottom = pInstData->stackbottom;
1345 lpte->wcEvents = pTask->nEvents;
1346 lpte->hQueue = pTask->hQueue;
1347 strncpy( lpte->szModule, pTask->module_name, 8 );
1348 lpte->szModule[8] = '\0';
1349 lpte->wPSPOffset = 0x100; /*??*/
1350 lpte->hNext = pTask->hNext;
1351 return TRUE;
1355 /***********************************************************************
1356 * TaskFindHandle (TOOLHELP.65)
1358 BOOL16 WINAPI TaskFindHandle( TASKENTRY *lpte, HTASK16 hTask )
1360 lpte->hNext = hTask;
1361 return TaskNext( lpte );
1365 /***********************************************************************
1366 * GetAppCompatFlags16 (KERNEL.354)
1368 DWORD WINAPI GetAppCompatFlags16( HTASK16 hTask )
1370 return GetAppCompatFlags32( hTask );
1374 /***********************************************************************
1375 * GetAppCompatFlags32 (USER32.206)
1377 DWORD WINAPI GetAppCompatFlags32( HTASK32 hTask )
1379 TDB *pTask;
1381 if (!hTask) hTask = GetCurrentTask();
1382 if (!(pTask=(TDB *)GlobalLock16( (HTASK16)hTask ))) return 0;
1383 if (GlobalSize16(hTask) < sizeof(TDB)) return 0;
1384 return pTask->compat_flags;