kernel32/lcformat: Avoid back jumps on failure.
[wine/multimedia.git] / dlls / kernel32 / task.c
blob1bcf21180b9ea582044762f9b28f4b87150f5f6b
1 /*
2 * Task functions
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <stdarg.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <assert.h>
28 #ifdef HAVE_UNISTD_H
29 # include <unistd.h>
30 #endif
32 #include "windef.h"
33 #include "winbase.h"
34 #include "wingdi.h"
35 #include "winnt.h"
36 #include "wownt32.h"
37 #include "winuser.h"
39 #include "wine/winbase16.h"
40 #include "winternl.h"
41 #include "kernel_private.h"
42 #include "kernel16_private.h"
44 #include "wine/debug.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(task);
48 #include "pshpack1.h"
50 struct thunk
52 BYTE movw;
53 HANDLE16 instance;
54 BYTE ljmp;
55 FARPROC16 func;
58 /* Segment containing MakeProcInstance() thunks */
59 typedef struct
61 WORD next; /* Selector of next segment */
62 WORD magic; /* Thunks signature */
63 WORD unused;
64 WORD free; /* Head of the free list */
65 struct thunk thunks[1];
66 } THUNKS;
68 #include "poppack.h"
70 #define THUNK_MAGIC ('P' | ('T' << 8))
72 /* Min. number of thunks allocated when creating a new segment */
73 #define MIN_THUNKS 32
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, main_task;
87 /***********************************************************************
88 * TASK_InstallTHHook
90 void TASK_InstallTHHook( THHOOK *pNewThhook )
92 THHOOK *pOldThhook = pThhook;
94 pThhook = pNewThhook? pNewThhook : &DefaultThhook;
96 *pThhook = *pOldThhook;
99 /***********************************************************************
100 * TASK_GetPtr
102 static TDB *TASK_GetPtr( HTASK16 hTask )
104 return GlobalLock16( hTask );
108 /***********************************************************************
109 * TASK_GetCurrent
111 TDB *TASK_GetCurrent(void)
113 return TASK_GetPtr( GetCurrentTask() );
117 /***********************************************************************
118 * TASK_LinkTask
120 static void TASK_LinkTask( HTASK16 hTask )
122 HTASK16 *prevTask;
123 TDB *pTask;
125 if (!(pTask = TASK_GetPtr( hTask ))) return;
126 prevTask = &hFirstTask;
127 while (*prevTask)
129 TDB *prevTaskPtr = TASK_GetPtr( *prevTask );
130 if (prevTaskPtr->priority >= pTask->priority) break;
131 prevTask = &prevTaskPtr->hNext;
133 pTask->hNext = *prevTask;
134 *prevTask = hTask;
135 nTaskCount++;
139 /***********************************************************************
140 * TASK_UnlinkTask
142 static void TASK_UnlinkTask( HTASK16 hTask )
144 HTASK16 *prevTask;
145 TDB *pTask;
147 prevTask = &hFirstTask;
148 while (*prevTask && (*prevTask != hTask))
150 pTask = TASK_GetPtr( *prevTask );
151 prevTask = &pTask->hNext;
153 if (*prevTask)
155 pTask = TASK_GetPtr( *prevTask );
156 *prevTask = pTask->hNext;
157 pTask->hNext = 0;
158 nTaskCount--;
163 /***********************************************************************
164 * TASK_CreateThunks
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 )
171 int i;
172 THUNKS *pThunk;
174 pThunk = (THUNKS *)((BYTE *)GlobalLock16( handle ) + offset);
175 pThunk->next = 0;
176 pThunk->magic = THUNK_MAGIC;
177 pThunk->free = FIELD_OFFSET( THUNKS, thunks );
178 for (i = 0; i < count-1; i++)
179 *(WORD *)&pThunk->thunks[i] = FIELD_OFFSET( THUNKS, thunks[i+1] );
180 *(WORD *)&pThunk->thunks[i] = 0; /* Last thunk */
184 /***********************************************************************
185 * TASK_AllocThunk
187 * Allocate a thunk for MakeProcInstance().
189 static SEGPTR TASK_AllocThunk(void)
191 TDB *pTask;
192 THUNKS *pThunk;
193 WORD sel, base;
195 if (!(pTask = TASK_GetCurrent())) return 0;
196 sel = pTask->hCSAlias;
197 pThunk = (THUNKS *)pTask->thunks;
198 base = (char *)pThunk - (char *)pTask;
199 while (!pThunk->free)
201 sel = pThunk->next;
202 if (!sel) /* Allocate a new segment */
204 sel = GLOBAL_Alloc( GMEM_FIXED, sizeof(THUNKS) + (MIN_THUNKS-1)*8,
205 pTask->hPDB, WINE_LDT_FLAGS_CODE );
206 if (!sel) return 0;
207 TASK_CreateThunks( sel, 0, MIN_THUNKS );
208 pThunk->next = sel;
210 pThunk = GlobalLock16( sel );
211 base = 0;
213 base += pThunk->free;
214 pThunk->free = *(WORD *)((BYTE *)pThunk + pThunk->free);
215 return MAKESEGPTR( sel, base );
219 /***********************************************************************
220 * TASK_FreeThunk
222 * Free a MakeProcInstance() thunk.
224 static BOOL TASK_FreeThunk( SEGPTR thunk )
226 TDB *pTask;
227 THUNKS *pThunk;
228 WORD sel, base;
230 if (!(pTask = TASK_GetCurrent())) return 0;
231 sel = pTask->hCSAlias;
232 pThunk = (THUNKS *)pTask->thunks;
233 base = (char *)pThunk - (char *)pTask;
234 while (sel && (sel != HIWORD(thunk)))
236 sel = pThunk->next;
237 pThunk = GlobalLock16( sel );
238 base = 0;
240 if (!sel) return FALSE;
241 *(WORD *)((BYTE *)pThunk + LOWORD(thunk) - base) = pThunk->free;
242 pThunk->free = LOWORD(thunk) - base;
243 return TRUE;
247 /***********************************************************************
248 * TASK_Create
250 * NOTE: This routine might be called by a Win32 thread. Thus, we need
251 * to be careful to protect global data structures. We do this
252 * by entering the Win16Lock while linking the task into the
253 * global task list.
255 static TDB *TASK_Create( NE_MODULE *pModule, UINT16 cmdShow, LPCSTR cmdline, BYTE len )
257 HTASK16 hTask;
258 TDB *pTask;
259 FARPROC16 proc;
260 char curdir[MAX_PATH];
261 HMODULE16 hModule = pModule ? pModule->self : 0;
263 /* Allocate the task structure */
265 hTask = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, sizeof(TDB) );
266 if (!hTask) return NULL;
267 pTask = TASK_GetPtr( hTask );
268 FarSetOwner16( hTask, hModule );
270 /* Fill the task structure */
272 pTask->hSelf = hTask;
274 pTask->version = pModule ? pModule->ne_expver : 0x0400;
275 pTask->hModule = hModule;
276 pTask->hParent = GetCurrentTask();
277 pTask->magic = TDB_MAGIC;
278 pTask->nCmdShow = cmdShow;
280 GetCurrentDirectoryA( sizeof(curdir), curdir );
281 GetShortPathNameA( curdir, curdir, sizeof(curdir) );
282 pTask->curdrive = (curdir[0] - 'A') | 0x80;
283 lstrcpynA( pTask->curdir, curdir + 2, sizeof(pTask->curdir) );
285 /* Create the thunks block */
287 TASK_CreateThunks( hTask, (char *)pTask->thunks - (char *)pTask, 7 );
289 /* Copy the module name */
291 if (hModule)
293 char name[sizeof(pTask->module_name)+1];
294 size_t len;
295 GetModuleName16( hModule, name, sizeof(name) );
296 len = strlen(name) + 1;
297 memcpy(pTask->module_name, name, min(len,sizeof(pTask->module_name)));
298 pTask->compat_flags = GetProfileIntA( "Compatibility", name, 0 );
301 /* Allocate a selector for the PDB */
303 pTask->hPDB = GLOBAL_CreateBlock( GMEM_FIXED, &pTask->pdb, sizeof(PDB16),
304 hModule, WINE_LDT_FLAGS_DATA );
306 /* Fill the PDB */
308 pTask->pdb.int20 = 0x20cd;
309 pTask->pdb.dispatcher[0] = 0x9a; /* ljmp */
310 proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DOS3Call" );
311 memcpy( &pTask->pdb.dispatcher[1], &proc, sizeof(proc) );
312 pTask->pdb.savedint22 = 0;
313 pTask->pdb.savedint23 = 0;
314 pTask->pdb.savedint24 = 0;
315 pTask->pdb.fileHandlesPtr =
316 MAKESEGPTR( GlobalHandleToSel16(pTask->hPDB), FIELD_OFFSET( PDB16, fileHandles ));
317 pTask->pdb.hFileHandles = 0;
318 memset( pTask->pdb.fileHandles, 0xff, sizeof(pTask->pdb.fileHandles) );
319 /* FIXME: should we make a copy of the environment? */
320 pTask->pdb.environment = SELECTOROF(GetDOSEnvironment16());
321 pTask->pdb.nbFiles = 20;
323 /* Fill the command line */
325 if (!cmdline)
327 cmdline = GetCommandLineA();
328 /* remove the first word (program name) */
329 if (*cmdline == '"')
330 if (!(cmdline = strchr( cmdline+1, '"' ))) cmdline = GetCommandLineA();
331 while (*cmdline && (*cmdline != ' ') && (*cmdline != '\t')) cmdline++;
332 while ((*cmdline == ' ') || (*cmdline == '\t')) cmdline++;
333 len = strlen(cmdline);
335 if (len >= sizeof(pTask->pdb.cmdLine)) len = sizeof(pTask->pdb.cmdLine)-1;
336 pTask->pdb.cmdLine[0] = len;
337 memcpy( pTask->pdb.cmdLine + 1, cmdline, len );
338 /* pTask->pdb.cmdLine[len+1] = 0; */
340 TRACE("cmdline='%.*s' task=%04x\n", len, cmdline, hTask );
342 /* Allocate a code segment alias for the TDB */
344 pTask->hCSAlias = GLOBAL_CreateBlock( GMEM_FIXED, pTask, sizeof(TDB),
345 pTask->hPDB, WINE_LDT_FLAGS_CODE );
347 /* Default DTA overwrites command line */
349 pTask->dta = MAKESEGPTR( pTask->hPDB, FIELD_OFFSET( PDB16, cmdLine ));
351 /* Create scheduler event for 16-bit tasks */
353 if ( !(pTask->flags & TDBF_WIN32) )
354 NtCreateEvent( &pTask->hEvent, EVENT_ALL_ACCESS, NULL, TRUE, FALSE );
356 if (!initial_task) initial_task = hTask;
358 return pTask;
362 /***********************************************************************
363 * TASK_DeleteTask
365 static void TASK_DeleteTask( HTASK16 hTask )
367 TDB *pTask;
368 HGLOBAL16 hPDB;
370 if (!(pTask = TASK_GetPtr( hTask ))) return;
371 hPDB = pTask->hPDB;
373 pTask->magic = 0xdead; /* invalidate signature */
375 /* Free the selector aliases */
377 GLOBAL_FreeBlock( pTask->hCSAlias );
378 GLOBAL_FreeBlock( pTask->hPDB );
380 /* Free the task module */
382 FreeModule16( pTask->hModule );
384 /* Free the task structure itself */
386 GlobalFree16( hTask );
388 /* Free all memory used by this task (including the 32-bit stack, */
389 /* the environment block and the thunk segments). */
391 GlobalFreeAll16( hPDB );
395 /***********************************************************************
396 * TASK_CreateMainTask
398 * Create a task for the main (32-bit) process.
400 void TASK_CreateMainTask(void)
402 TDB *pTask;
403 STARTUPINFOA startup_info;
404 UINT cmdShow = 1; /* SW_SHOWNORMAL but we don't want to include winuser.h here */
406 GetStartupInfoA( &startup_info );
407 if (startup_info.dwFlags & STARTF_USESHOWWINDOW) cmdShow = startup_info.wShowWindow;
408 pTask = TASK_Create( NULL, cmdShow, NULL, 0 );
409 if (!pTask)
411 ERR("could not create task for main process\n");
412 ExitProcess(1);
415 pTask->flags |= TDBF_WIN32;
416 pTask->hInstance = 0;
417 pTask->hPrevInstance = 0;
418 pTask->teb = NtCurrentTeb();
420 /* Add the task to the linked list */
421 /* (no need to get the win16 lock, we are the only thread at this point) */
422 TASK_LinkTask( pTask->hSelf );
423 main_task = pTask->hSelf;
427 struct create_data
429 TDB *task;
430 WIN16_SUBSYSTEM_TIB *tib;
433 /* allocate the win16 TIB for a new 16-bit task */
434 static WIN16_SUBSYSTEM_TIB *allocate_win16_tib( TDB *pTask )
436 WCHAR path[MAX_PATH];
437 WIN16_SUBSYSTEM_TIB *tib;
438 UNICODE_STRING *curdir;
439 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
441 if (!(tib = HeapAlloc( GetProcessHeap(), 0, sizeof(*tib) ))) return NULL;
442 MultiByteToWideChar( CP_ACP, 0, NE_MODULE_NAME(pModule), -1, path, MAX_PATH );
443 GetLongPathNameW( path, path, MAX_PATH );
444 if (RtlCreateUnicodeString( &tib->exe_str, path )) tib->exe_name = &tib->exe_str;
445 else tib->exe_name = NULL;
447 RtlAcquirePebLock();
448 if (NtCurrentTeb()->Tib.SubSystemTib)
449 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
450 else
451 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
452 tib->curdir.DosPath.MaximumLength = sizeof(tib->curdir_buffer);
453 tib->curdir.DosPath.Length = min( curdir->Length, tib->curdir.DosPath.MaximumLength-sizeof(WCHAR) );
454 tib->curdir.DosPath.Buffer = tib->curdir_buffer;
455 tib->curdir.Handle = 0;
456 memcpy( tib->curdir_buffer, curdir->Buffer, tib->curdir.DosPath.Length );
457 tib->curdir_buffer[tib->curdir.DosPath.Length/sizeof(WCHAR)] = 0;
458 RtlReleasePebLock();
459 return tib;
462 static inline void free_win16_tib( WIN16_SUBSYSTEM_TIB *tib )
464 if (tib->exe_name) RtlFreeUnicodeString( tib->exe_name );
465 HeapFree( GetProcessHeap(), 0, tib );
468 /* startup routine for a new 16-bit thread */
469 static DWORD CALLBACK task_start( LPVOID p )
471 struct create_data *data = p;
472 TDB *pTask = data->task;
473 DWORD ret;
475 kernel_get_thread_data()->htask16 = pTask->hSelf;
476 NtCurrentTeb()->Tib.SubSystemTib = data->tib;
477 HeapFree( GetProcessHeap(), 0, data );
479 _EnterWin16Lock();
480 TASK_LinkTask( pTask->hSelf );
481 pTask->teb = NtCurrentTeb();
482 ret = NE_StartTask();
483 _LeaveWin16Lock();
484 return ret;
488 /***********************************************************************
489 * TASK_SpawnTask
491 * Spawn a new 16-bit task.
493 HTASK16 TASK_SpawnTask( NE_MODULE *pModule, WORD cmdShow,
494 LPCSTR cmdline, BYTE len, HANDLE *hThread )
496 struct create_data *data = NULL;
497 WIN16_SUBSYSTEM_TIB *tib;
498 TDB *pTask;
500 if (!(pTask = TASK_Create( pModule, cmdShow, cmdline, len ))) return 0;
501 if (!(tib = allocate_win16_tib( pTask ))) goto failed;
502 if (!(data = HeapAlloc( GetProcessHeap(), 0, sizeof(*data)))) goto failed;
503 data->task = pTask;
504 data->tib = tib;
505 if (!(*hThread = CreateThread( NULL, 0, task_start, data, 0, NULL ))) goto failed;
506 return pTask->hSelf;
508 failed:
509 if (tib) free_win16_tib( tib );
510 HeapFree( GetProcessHeap(), 0, data );
511 TASK_DeleteTask( pTask->hSelf );
512 return 0;
516 /***********************************************************************
517 * TASK_GetTaskFromThread
519 HTASK16 TASK_GetTaskFromThread( DWORD thread )
521 TDB *p = TASK_GetPtr( hFirstTask );
522 while (p)
524 if (p->teb->ClientId.UniqueThread == (HANDLE)thread) return p->hSelf;
525 p = TASK_GetPtr( p->hNext );
527 return 0;
531 /***********************************************************************
532 * TASK_CallTaskSignalProc
534 static void TASK_CallTaskSignalProc( UINT16 uCode, HANDLE16 hTaskOrModule )
536 WORD args[5];
537 TDB *pTask = TASK_GetCurrent();
539 if ( !pTask || !pTask->userhandler ) return;
541 args[4] = hTaskOrModule;
542 args[3] = uCode;
543 args[2] = 0;
544 args[1] = pTask->hInstance;
545 args[0] = pTask->hQueue;
546 WOWCallback16Ex( (DWORD)pTask->userhandler, WCB16_PASCAL, sizeof(args), args, NULL );
550 /***********************************************************************
551 * TASK_ExitTask
553 void TASK_ExitTask(void)
555 WIN16_SUBSYSTEM_TIB *tib;
556 TDB *pTask;
557 DWORD lockCount;
559 /* Enter the Win16Lock to protect global data structures */
560 _EnterWin16Lock();
562 pTask = TASK_GetCurrent();
563 if ( !pTask )
565 _LeaveWin16Lock();
566 return;
569 TRACE("Killing task %04x\n", pTask->hSelf );
571 /* Perform USER cleanup */
573 TASK_CallTaskSignalProc( USIG16_TERMINATION, pTask->hSelf );
575 /* Remove the task from the list to be sure we never switch back to it */
576 TASK_UnlinkTask( pTask->hSelf );
578 if (!nTaskCount || (nTaskCount == 1 && hFirstTask == initial_task))
580 TRACE("this is the last task, exiting\n" );
581 ExitKernel16();
584 pTask->nEvents = 0;
586 if ( hLockedTask == pTask->hSelf )
587 hLockedTask = 0;
589 TASK_DeleteTask( pTask->hSelf );
591 if ((tib = NtCurrentTeb()->Tib.SubSystemTib))
593 free_win16_tib( tib );
594 NtCurrentTeb()->Tib.SubSystemTib = NULL;
597 /* ... and completely release the Win16Lock, just in case. */
598 ReleaseThunkLock( &lockCount );
602 /***********************************************************************
603 * ExitKernel (KERNEL.2)
605 * Clean-up everything and exit the Wine process.
607 void WINAPI ExitKernel16(void)
609 WriteOutProfiles16();
610 TerminateProcess( GetCurrentProcess(), 0 );
614 /***********************************************************************
615 * InitTask (KERNEL.91)
617 * Called by the application startup code.
619 void WINAPI InitTask16( CONTEXT86 *context )
621 TDB *pTask;
622 INSTANCEDATA *pinstance;
623 SEGPTR ptr;
625 context->Eax = 0;
626 if (!(pTask = TASK_GetCurrent())) return;
628 /* Note: we need to trust that BX/CX contain the stack/heap sizes,
629 as some apps, notably Visual Basic apps, *modify* the heap/stack
630 size of the instance data segment before calling InitTask() */
632 /* Initialize the INSTANCEDATA structure */
633 pinstance = MapSL( MAKESEGPTR(CURRENT_DS, 0) );
634 pinstance->stackmin = OFFSETOF(NtCurrentTeb()->WOW32Reserved) + sizeof( STACK16FRAME );
635 pinstance->stackbottom = pinstance->stackmin; /* yup, that's right. Confused me too. */
636 pinstance->stacktop = ( pinstance->stackmin > LOWORD(context->Ebx) ?
637 pinstance->stackmin - LOWORD(context->Ebx) : 0 ) + 150;
639 /* Initialize the local heap */
640 if (LOWORD(context->Ecx))
641 LocalInit16( GlobalHandleToSel16(pTask->hInstance), 0, LOWORD(context->Ecx) );
643 /* Initialize implicitly loaded DLLs */
644 NE_InitializeDLLs( pTask->hModule );
645 NE_DllProcessAttach( pTask->hModule );
647 /* Registers on return are:
648 * ax 1 if OK, 0 on error
649 * cx stack limit in bytes
650 * dx cmdShow parameter
651 * si instance handle of the previous instance
652 * di instance handle of the new task
653 * es:bx pointer to command line inside PSP
655 * 0 (=%bp) is pushed on the stack
657 ptr = stack16_push( sizeof(WORD) );
658 *(WORD *)MapSL(ptr) = 0;
659 context->Esp -= 2;
661 context->Eax = 1;
663 if (!pTask->pdb.cmdLine[0]) context->Ebx = 0x80;
664 else
666 LPBYTE p = &pTask->pdb.cmdLine[1];
667 while ((*p == ' ') || (*p == '\t')) p++;
668 context->Ebx = 0x80 + (p - pTask->pdb.cmdLine);
670 context->Ecx = pinstance->stacktop;
671 context->Edx = pTask->nCmdShow;
672 context->Esi = (DWORD)pTask->hPrevInstance;
673 context->Edi = (DWORD)pTask->hInstance;
674 context->SegEs = (WORD)pTask->hPDB;
678 /***********************************************************************
679 * WaitEvent (KERNEL.30)
681 BOOL16 WINAPI WaitEvent16( HTASK16 hTask )
683 TDB *pTask;
685 if (!hTask) hTask = GetCurrentTask();
686 pTask = TASK_GetPtr( hTask );
688 if (pTask->flags & TDBF_WIN32)
690 FIXME("called for Win32 thread (%04x)!\n", GetCurrentThreadId());
691 return TRUE;
694 if (pTask->nEvents > 0)
696 pTask->nEvents--;
697 return FALSE;
700 if (pTask->teb == NtCurrentTeb())
702 DWORD lockCount;
704 NtResetEvent( pTask->hEvent, NULL );
705 ReleaseThunkLock( &lockCount );
706 SYSLEVEL_CheckNotLevel( 1 );
707 WaitForSingleObject( pTask->hEvent, INFINITE );
708 RestoreThunkLock( lockCount );
709 if (pTask->nEvents > 0) pTask->nEvents--;
711 else FIXME("for other task %04x cur=%04x\n",pTask->hSelf,GetCurrentTask());
713 return TRUE;
717 /***********************************************************************
718 * PostEvent (KERNEL.31)
720 void WINAPI PostEvent16( HTASK16 hTask )
722 TDB *pTask;
724 if (!hTask) hTask = GetCurrentTask();
725 if (!(pTask = TASK_GetPtr( hTask ))) return;
727 if (pTask->flags & TDBF_WIN32)
729 FIXME("called for Win32 thread (%04x)!\n", (DWORD)pTask->teb->ClientId.UniqueThread );
730 return;
733 pTask->nEvents++;
735 if (pTask->nEvents == 1) NtSetEvent( pTask->hEvent, NULL );
739 /***********************************************************************
740 * SetPriority (KERNEL.32)
742 void WINAPI SetPriority16( HTASK16 hTask, INT16 delta )
744 TDB *pTask;
745 INT16 newpriority;
747 if (!hTask) hTask = GetCurrentTask();
748 if (!(pTask = TASK_GetPtr( hTask ))) return;
749 newpriority = pTask->priority + delta;
750 if (newpriority < -32) newpriority = -32;
751 else if (newpriority > 15) newpriority = 15;
753 pTask->priority = newpriority + 1;
754 TASK_UnlinkTask( pTask->hSelf );
755 TASK_LinkTask( pTask->hSelf );
756 pTask->priority--;
760 /***********************************************************************
761 * LockCurrentTask (KERNEL.33)
763 HTASK16 WINAPI LockCurrentTask16( BOOL16 bLock )
765 if (bLock) hLockedTask = GetCurrentTask();
766 else hLockedTask = 0;
767 return hLockedTask;
771 /***********************************************************************
772 * IsTaskLocked (KERNEL.122)
774 HTASK16 WINAPI IsTaskLocked16(void)
776 return hLockedTask;
780 /***********************************************************************
781 * OldYield (KERNEL.117)
783 void WINAPI OldYield16(void)
785 DWORD count;
787 ReleaseThunkLock(&count);
788 RestoreThunkLock(count);
791 /***********************************************************************
792 * WIN32_OldYield (KERNEL.447)
794 void WINAPI WIN32_OldYield16(void)
796 DWORD count;
798 ReleaseThunkLock(&count);
799 RestoreThunkLock(count);
802 /***********************************************************************
803 * DirectedYield (KERNEL.150)
805 void WINAPI DirectedYield16( HTASK16 hTask )
807 OldYield16();
810 /***********************************************************************
811 * Yield (KERNEL.29)
813 void WINAPI Yield16(void)
815 TDB *pCurTask = TASK_GetCurrent();
817 if (pCurTask && pCurTask->hQueue)
819 HMODULE mod = GetModuleHandleA( "user32.dll" );
820 if (mod)
822 BOOL (WINAPI *pPeekMessageW)( MSG *msg, HWND hwnd, UINT first, UINT last, UINT flags );
823 pPeekMessageW = (void *)GetProcAddress( mod, "PeekMessageW" );
824 if (pPeekMessageW)
826 MSG msg;
827 pPeekMessageW( &msg, 0, 0, 0, PM_REMOVE | PM_QS_SENDMESSAGE );
828 return;
832 OldYield16();
835 /***********************************************************************
836 * KERNEL_490 (KERNEL.490)
838 HTASK16 WINAPI KERNEL_490( HTASK16 someTask )
840 if ( !someTask ) return 0;
842 FIXME("(%04x): stub\n", someTask );
843 return 0;
846 /***********************************************************************
847 * MakeProcInstance (KERNEL.51)
849 FARPROC16 WINAPI MakeProcInstance16( FARPROC16 func, HANDLE16 hInstance )
851 struct thunk *thunk;
852 BYTE *lfunc;
853 SEGPTR thunkaddr;
854 WORD hInstanceSelector;
856 hInstanceSelector = GlobalHandleToSel16(hInstance);
858 TRACE("(%p, %04x);\n", func, hInstance);
860 if (!HIWORD(func)) {
861 /* Win95 actually protects via SEH, but this is better for debugging */
862 WARN("Ouch ! Called with invalid func %p !\n", func);
863 return NULL;
866 if ( (GlobalHandleToSel16(CURRENT_DS) != hInstanceSelector)
867 && (hInstance != 0)
868 && (hInstance != 0xffff) )
870 /* calling MPI with a foreign DSEG is invalid ! */
871 WARN("Problem with hInstance? Got %04x, using %04x instead\n",
872 hInstance,CURRENT_DS);
875 /* Always use the DSEG that MPI was entered with.
876 * We used to set hInstance to GetTaskDS16(), but this should be wrong
877 * as CURRENT_DS provides the DSEG value we need.
878 * ("calling" DS, *not* "task" DS !) */
879 hInstanceSelector = CURRENT_DS;
880 hInstance = GlobalHandle16(hInstanceSelector);
882 /* no thunking for DLLs */
883 if (NE_GetPtr(FarGetOwner16(hInstance))->ne_flags & NE_FFLAGS_LIBMODULE)
884 return func;
886 thunkaddr = TASK_AllocThunk();
887 if (!thunkaddr) return NULL;
888 thunk = MapSL( thunkaddr );
889 lfunc = MapSL( (SEGPTR)func );
891 TRACE("(%p,%04x): got thunk %08x\n", func, hInstance, thunkaddr );
892 if (((lfunc[0]==0x8c) && (lfunc[1]==0xd8)) || /* movw %ds, %ax */
893 ((lfunc[0]==0x1e) && (lfunc[1]==0x58)) /* pushw %ds, popw %ax */
895 WARN("This was the (in)famous \"thunk useless\" warning. We thought we have to overwrite with nop;nop;, but this isn't true.\n");
898 thunk->movw = 0xb8; /* movw instance, %ax */
899 thunk->instance = hInstanceSelector;
900 thunk->ljmp = 0xea; /* ljmp func */
901 thunk->func = func;
902 return (FARPROC16)thunkaddr;
903 /* CX reg indicates if thunkaddr != NULL, implement if needed */
907 /***********************************************************************
908 * FreeProcInstance (KERNEL.52)
910 void WINAPI FreeProcInstance16( FARPROC16 func )
912 TRACE("(%p)\n", func );
913 TASK_FreeThunk( (SEGPTR)func );
916 /**********************************************************************
917 * TASK_GetCodeSegment
919 * Helper function for GetCodeHandle/GetCodeInfo: Retrieve the module
920 * and logical segment number of a given code segment.
922 * 'proc' either *is* already a pair of module handle and segment number,
923 * in which case there's nothing to do. Otherwise, it is a pointer to
924 * a function, and we need to retrieve the code segment. If the pointer
925 * happens to point to a thunk, we'll retrieve info about the code segment
926 * where the function pointed to by the thunk resides, not the thunk itself.
928 * FIXME: if 'proc' is a SNOOP16 return stub, we should retrieve info about
929 * the function the snoop code will return to ...
932 static BOOL TASK_GetCodeSegment( FARPROC16 proc, NE_MODULE **ppModule,
933 SEGTABLEENTRY **ppSeg, int *pSegNr )
935 NE_MODULE *pModule = NULL;
936 SEGTABLEENTRY *pSeg = NULL;
937 int segNr=0;
939 /* Try pair of module handle / segment number */
940 pModule = GlobalLock16( HIWORD( proc ) );
941 if ( pModule && pModule->ne_magic == IMAGE_OS2_SIGNATURE )
943 segNr = LOWORD( proc );
944 if ( segNr && segNr <= pModule->ne_cseg )
945 pSeg = NE_SEG_TABLE( pModule ) + segNr-1;
948 /* Try thunk or function */
949 else
951 BYTE *thunk = MapSL( (SEGPTR)proc );
952 WORD selector;
954 if ((thunk[0] == 0xb8) && (thunk[3] == 0xea))
955 selector = thunk[6] + (thunk[7] << 8);
956 else
957 selector = HIWORD( proc );
959 pModule = NE_GetPtr( GlobalHandle16( selector ) );
960 pSeg = pModule? NE_SEG_TABLE( pModule ) : NULL;
962 if ( pModule )
963 for ( segNr = 1; segNr <= pModule->ne_cseg; segNr++, pSeg++ )
964 if ( GlobalHandleToSel16(pSeg->hSeg) == selector )
965 break;
967 if ( pModule && segNr > pModule->ne_cseg )
968 pSeg = NULL;
971 /* Abort if segment not found */
973 if ( !pModule || !pSeg )
974 return FALSE;
976 /* Return segment data */
978 if ( ppModule ) *ppModule = pModule;
979 if ( ppSeg ) *ppSeg = pSeg;
980 if ( pSegNr ) *pSegNr = segNr;
982 return TRUE;
985 /**********************************************************************
986 * GetCodeHandle (KERNEL.93)
988 HANDLE16 WINAPI GetCodeHandle16( FARPROC16 proc )
990 SEGTABLEENTRY *pSeg;
992 if ( !TASK_GetCodeSegment( proc, NULL, &pSeg, NULL ) )
993 return 0;
995 return pSeg->hSeg;
998 /**********************************************************************
999 * GetCodeInfo (KERNEL.104)
1001 BOOL16 WINAPI GetCodeInfo16( FARPROC16 proc, SEGINFO *segInfo )
1003 NE_MODULE *pModule;
1004 SEGTABLEENTRY *pSeg;
1005 int segNr;
1007 if ( !TASK_GetCodeSegment( proc, &pModule, &pSeg, &segNr ) )
1008 return FALSE;
1010 /* Fill in segment information */
1012 segInfo->offSegment = pSeg->filepos;
1013 segInfo->cbSegment = pSeg->size;
1014 segInfo->flags = pSeg->flags;
1015 segInfo->cbAlloc = pSeg->minsize;
1016 segInfo->h = pSeg->hSeg;
1017 segInfo->alignShift = pModule->ne_align;
1019 if ( segNr == pModule->ne_autodata )
1020 segInfo->cbAlloc += pModule->ne_heap + pModule->ne_stack;
1022 /* Return module handle in %es */
1024 CURRENT_STACK16->es = GlobalHandleToSel16( pModule->self );
1026 return TRUE;
1030 /**********************************************************************
1031 * DefineHandleTable (KERNEL.94)
1033 BOOL16 WINAPI DefineHandleTable16( WORD wOffset )
1035 FIXME("(%04x): stub ?\n", wOffset);
1036 return TRUE;
1040 /***********************************************************************
1041 * SetTaskQueue (KERNEL.34)
1043 HQUEUE16 WINAPI SetTaskQueue16( HTASK16 hTask, HQUEUE16 hQueue )
1045 FIXME( "stub, should not get called\n" );
1046 return 0xbeef;
1050 /***********************************************************************
1051 * GetTaskQueue (KERNEL.35)
1053 HQUEUE16 WINAPI GetTaskQueue16( HTASK16 hTask )
1055 FIXME( "stub, should not get called\n" );
1056 return 0xbeef;
1059 /***********************************************************************
1060 * SetThreadQueue (KERNEL.463)
1062 HQUEUE16 WINAPI SetThreadQueue16( DWORD thread, HQUEUE16 hQueue )
1064 FIXME( "stub, should not get called\n" );
1065 return 0xbeef;
1068 /***********************************************************************
1069 * GetThreadQueue (KERNEL.464)
1071 HQUEUE16 WINAPI GetThreadQueue16( DWORD thread )
1073 FIXME( "stub, should not get called\n" );
1074 return 0xbeef;
1077 /***********************************************************************
1078 * SetFastQueue (KERNEL.624)
1080 VOID WINAPI SetFastQueue16( DWORD thread, HQUEUE16 hQueue )
1082 FIXME( "stub, should not get called\n" );
1085 /***********************************************************************
1086 * GetFastQueue (KERNEL.625)
1088 HQUEUE16 WINAPI GetFastQueue16( void )
1090 FIXME( "stub, should not get called\n" );
1091 return 0xbeef;
1094 /***********************************************************************
1095 * SwitchStackTo (KERNEL.108)
1097 void WINAPI SwitchStackTo16( WORD seg, WORD ptr, WORD top )
1099 STACK16FRAME *oldFrame, *newFrame;
1100 INSTANCEDATA *pData;
1101 UINT16 copySize;
1103 if (!(pData = GlobalLock16( seg ))) return;
1104 TRACE("old=%04x:%04x new=%04x:%04x\n",
1105 SELECTOROF( NtCurrentTeb()->WOW32Reserved ),
1106 OFFSETOF( NtCurrentTeb()->WOW32Reserved ), seg, ptr );
1108 /* Save the old stack */
1110 oldFrame = CURRENT_STACK16;
1111 /* pop frame + args and push bp */
1112 pData->old_ss_sp = (SEGPTR)NtCurrentTeb()->WOW32Reserved + sizeof(STACK16FRAME)
1113 + 2 * sizeof(WORD);
1114 *(WORD *)MapSL(pData->old_ss_sp) = oldFrame->bp;
1115 pData->stacktop = top;
1116 pData->stackmin = ptr;
1117 pData->stackbottom = ptr;
1119 /* Switch to the new stack */
1121 /* Note: we need to take the 3 arguments into account; otherwise,
1122 * the stack will underflow upon return from this function.
1124 copySize = oldFrame->bp - OFFSETOF(pData->old_ss_sp);
1125 copySize += 3 * sizeof(WORD) + sizeof(STACK16FRAME);
1126 NtCurrentTeb()->WOW32Reserved = (void *)MAKESEGPTR( seg, ptr - copySize );
1127 newFrame = CURRENT_STACK16;
1129 /* Copy the stack frame and the local variables to the new stack */
1131 memmove( newFrame, oldFrame, copySize );
1132 newFrame->bp = ptr;
1133 *(WORD *)MapSL( MAKESEGPTR( seg, ptr ) ) = 0; /* clear previous bp */
1137 /***********************************************************************
1138 * SwitchStackBack (KERNEL.109)
1140 void WINAPI SwitchStackBack16( CONTEXT86 *context )
1142 STACK16FRAME *oldFrame, *newFrame;
1143 INSTANCEDATA *pData;
1145 if (!(pData = GlobalLock16(SELECTOROF(NtCurrentTeb()->WOW32Reserved))))
1146 return;
1147 if (!pData->old_ss_sp)
1149 WARN("No previous SwitchStackTo\n" );
1150 return;
1152 TRACE("restoring stack %04x:%04x\n",
1153 SELECTOROF(pData->old_ss_sp), OFFSETOF(pData->old_ss_sp) );
1155 oldFrame = CURRENT_STACK16;
1157 /* Pop bp from the previous stack */
1159 context->Ebp = (context->Ebp & ~0xffff) | *(WORD *)MapSL(pData->old_ss_sp);
1160 pData->old_ss_sp += sizeof(WORD);
1162 /* Switch back to the old stack */
1164 NtCurrentTeb()->WOW32Reserved = (void *)(pData->old_ss_sp - sizeof(STACK16FRAME));
1165 context->SegSs = SELECTOROF(pData->old_ss_sp);
1166 context->Esp = OFFSETOF(pData->old_ss_sp) - sizeof(DWORD); /*ret addr*/
1167 pData->old_ss_sp = 0;
1169 /* Build a stack frame for the return */
1171 newFrame = CURRENT_STACK16;
1172 newFrame->frame32 = oldFrame->frame32;
1173 newFrame->module_cs = oldFrame->module_cs;
1174 newFrame->callfrom_ip = oldFrame->callfrom_ip;
1175 newFrame->entry_ip = oldFrame->entry_ip;
1179 /***********************************************************************
1180 * GetTaskQueueDS (KERNEL.118)
1182 void WINAPI GetTaskQueueDS16(void)
1184 CURRENT_STACK16->ds = GlobalHandleToSel16( GetTaskQueue16(0) );
1188 /***********************************************************************
1189 * GetTaskQueueES (KERNEL.119)
1191 void WINAPI GetTaskQueueES16(void)
1193 CURRENT_STACK16->es = GlobalHandleToSel16( GetTaskQueue16(0) );
1197 /***********************************************************************
1198 * GetCurrentTask (KERNEL32.@)
1200 HTASK16 WINAPI GetCurrentTask(void)
1202 HTASK16 ret = kernel_get_thread_data()->htask16;
1203 if (!ret) ret = main_task;
1204 return ret;
1207 /***********************************************************************
1208 * GetCurrentTask (KERNEL.36)
1210 DWORD WINAPI WIN16_GetCurrentTask(void)
1212 /* This is the version used by relay code; the first task is */
1213 /* returned in the high word of the result */
1214 return MAKELONG( GetCurrentTask(), hFirstTask );
1218 /***********************************************************************
1219 * GetCurrentPDB (KERNEL.37)
1221 * UNDOC: returns PSP of KERNEL in high word
1223 DWORD WINAPI GetCurrentPDB16(void)
1225 TDB *pTask;
1227 if (!(pTask = TASK_GetCurrent())) return 0;
1228 return MAKELONG(pTask->hPDB, 0); /* FIXME */
1232 /***********************************************************************
1233 * GetCurPID (KERNEL.157)
1235 DWORD WINAPI GetCurPID16( DWORD unused )
1237 return 0;
1241 /***********************************************************************
1242 * GetInstanceData (KERNEL.54)
1244 INT16 WINAPI GetInstanceData16( HINSTANCE16 instance, WORD buffer, INT16 len )
1246 char *ptr = GlobalLock16( instance );
1247 if (!ptr || !len) return 0;
1248 if ((int)buffer + len >= 0x10000) len = 0x10000 - buffer;
1249 memcpy( (char *)GlobalLock16(CURRENT_DS) + buffer, ptr + buffer, len );
1250 return len;
1254 /***********************************************************************
1255 * GetExeVersion (KERNEL.105)
1257 WORD WINAPI GetExeVersion16(void)
1259 TDB *pTask;
1261 if (!(pTask = TASK_GetCurrent())) return 0;
1262 return pTask->version;
1266 /***********************************************************************
1267 * SetErrorMode (KERNEL.107)
1269 UINT16 WINAPI SetErrorMode16( UINT16 mode )
1271 TDB *pTask;
1272 if (!(pTask = TASK_GetCurrent())) return 0;
1273 pTask->error_mode = mode;
1274 return SetErrorMode( mode );
1278 /***********************************************************************
1279 * GetNumTasks (KERNEL.152)
1281 UINT16 WINAPI GetNumTasks16(void)
1283 return nTaskCount;
1287 /***********************************************************************
1288 * GetTaskDS (KERNEL.155)
1290 * Note: this function apparently returns a DWORD with LOWORD == HIWORD.
1291 * I don't think we need to bother with this.
1293 HINSTANCE16 WINAPI GetTaskDS16(void)
1295 TDB *pTask;
1297 if (!(pTask = TASK_GetCurrent())) return 0;
1298 return GlobalHandleToSel16(pTask->hInstance);
1301 /***********************************************************************
1302 * GetDummyModuleHandleDS (KERNEL.602)
1304 WORD WINAPI GetDummyModuleHandleDS16(void)
1306 TDB *pTask;
1307 WORD selector;
1309 if (!(pTask = TASK_GetCurrent())) return 0;
1310 if (!(pTask->flags & TDBF_WIN32)) return 0;
1311 selector = GlobalHandleToSel16( pTask->hModule );
1312 CURRENT_DS = selector;
1313 return selector;
1316 /***********************************************************************
1317 * IsTask (KERNEL.320)
1319 BOOL16 WINAPI IsTask16( HTASK16 hTask )
1321 TDB *pTask;
1323 if (!(pTask = TASK_GetPtr( hTask ))) return FALSE;
1324 if (GlobalSize16( hTask ) < sizeof(TDB)) return FALSE;
1325 return (pTask->magic == TDB_MAGIC);
1329 /***********************************************************************
1330 * IsWinOldApTask (KERNEL.158)
1332 BOOL16 WINAPI IsWinOldApTask16( HTASK16 hTask )
1334 /* should return bit 0 of byte 0x48 in PSP */
1335 return FALSE;
1338 /***********************************************************************
1339 * SetTaskSignalProc (KERNEL.38)
1341 FARPROC16 WINAPI SetTaskSignalProc( HTASK16 hTask, FARPROC16 proc )
1343 TDB *pTask;
1344 FARPROC16 oldProc;
1346 if (!hTask) hTask = GetCurrentTask();
1347 if (!(pTask = TASK_GetPtr( hTask ))) return NULL;
1348 oldProc = pTask->userhandler;
1349 pTask->userhandler = proc;
1350 return oldProc;
1353 /***********************************************************************
1354 * SetSigHandler (KERNEL.140)
1356 WORD WINAPI SetSigHandler16( FARPROC16 newhandler, FARPROC16* oldhandler,
1357 UINT16 *oldmode, UINT16 newmode, UINT16 flag )
1359 FIXME("(%p,%p,%p,%d,%d), unimplemented.\n",
1360 newhandler,oldhandler,oldmode,newmode,flag );
1362 if (flag != 1) return 0;
1363 if (!newmode) newhandler = NULL; /* Default handler */
1364 if (newmode != 4)
1366 TDB *pTask;
1368 if (!(pTask = TASK_GetCurrent())) return 0;
1369 if (oldmode) *oldmode = pTask->signal_flags;
1370 pTask->signal_flags = newmode;
1371 if (oldhandler) *oldhandler = pTask->sighandler;
1372 pTask->sighandler = newhandler;
1374 return 0;
1378 /***********************************************************************
1379 * GlobalNotify (KERNEL.154)
1381 * Note that GlobalNotify does _not_ return the old NotifyProc
1382 * -- contrary to LocalNotify !!
1384 VOID WINAPI GlobalNotify16( FARPROC16 proc )
1386 TDB *pTask;
1388 if (!(pTask = TASK_GetCurrent())) return;
1389 pTask->discardhandler = proc;
1393 /***********************************************************************
1394 * GetExePtrHelper
1396 static inline HMODULE16 GetExePtrHelper( HANDLE16 handle, HTASK16 *hTask )
1398 char *ptr;
1399 HANDLE16 owner;
1401 /* Check for module handle */
1403 if (!(ptr = GlobalLock16( handle ))) return 0;
1404 if (((NE_MODULE *)ptr)->ne_magic == IMAGE_OS2_SIGNATURE) return handle;
1406 /* Search for this handle inside all tasks */
1408 *hTask = hFirstTask;
1409 while (*hTask)
1411 TDB *pTask = TASK_GetPtr( *hTask );
1412 if ((*hTask == handle) ||
1413 (pTask->hInstance == handle) ||
1414 (pTask->hQueue == handle) ||
1415 (pTask->hPDB == handle)) return pTask->hModule;
1416 *hTask = pTask->hNext;
1419 /* Check the owner for module handle */
1421 owner = FarGetOwner16( handle );
1422 if (!(ptr = GlobalLock16( owner ))) return 0;
1423 if (((NE_MODULE *)ptr)->ne_magic == IMAGE_OS2_SIGNATURE) return owner;
1425 /* Search for the owner inside all tasks */
1427 *hTask = hFirstTask;
1428 while (*hTask)
1430 TDB *pTask = TASK_GetPtr( *hTask );
1431 if ((*hTask == owner) ||
1432 (pTask->hInstance == owner) ||
1433 (pTask->hQueue == owner) ||
1434 (pTask->hPDB == owner)) return pTask->hModule;
1435 *hTask = pTask->hNext;
1438 return 0;
1441 /***********************************************************************
1442 * GetExePtr (KERNEL.133)
1444 HMODULE16 WINAPI WIN16_GetExePtr( HANDLE16 handle )
1446 HTASK16 hTask = 0;
1447 HMODULE16 hModule = GetExePtrHelper( handle, &hTask );
1448 STACK16FRAME *frame = CURRENT_STACK16;
1449 frame->ecx = hModule;
1450 if (hTask) frame->es = hTask;
1451 return hModule;
1455 /***********************************************************************
1456 * K228 (KERNEL.228)
1458 HMODULE16 WINAPI GetExePtr( HANDLE16 handle )
1460 HTASK16 hTask = 0;
1461 return GetExePtrHelper( handle, &hTask );
1465 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND hWnd, LPCSTR text, LPCSTR title, UINT type);
1467 /**************************************************************************
1468 * FatalAppExit (KERNEL.137)
1470 void WINAPI FatalAppExit16( UINT16 action, LPCSTR str )
1472 TDB *pTask = TASK_GetCurrent();
1474 if (!pTask || !(pTask->error_mode & SEM_NOGPFAULTERRORBOX))
1476 HMODULE mod = GetModuleHandleA( "user32.dll" );
1477 if (mod)
1479 MessageBoxA_funcptr pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
1480 if (pMessageBoxA)
1482 pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
1483 goto done;
1486 ERR( "%s\n", debugstr_a(str) );
1488 done:
1489 ExitThread(0xff);
1493 /***********************************************************************
1494 * GetAppCompatFlags (KERNEL.354)
1496 DWORD WINAPI GetAppCompatFlags16( HTASK16 hTask )
1498 TDB *pTask;
1500 if (!hTask) hTask = GetCurrentTask();
1501 if (!(pTask=TASK_GetPtr( hTask ))) return 0;
1502 if (GlobalSize16(hTask) < sizeof(TDB)) return 0;
1503 return pTask->compat_flags;
1507 /***********************************************************************
1508 * GetDOSEnvironment (KERNEL.131)
1510 * Note: the environment is allocated once, it doesn't track changes
1511 * made using the Win32 API. This shouldn't matter.
1513 * Format of a 16-bit environment block:
1514 * ASCIIZ string 1 (xx=yy format)
1515 * ...
1516 * ASCIIZ string n
1517 * BYTE 0
1518 * WORD 1
1519 * ASCIIZ program name (e.g. C:\WINDOWS\SYSTEM\KRNL386.EXE)
1521 SEGPTR WINAPI GetDOSEnvironment16(void)
1523 static const char ENV_program_name[] = "C:\\WINDOWS\\SYSTEM\\KRNL386.EXE";
1524 static HGLOBAL16 handle; /* handle to the 16 bit environment */
1526 if (!handle)
1528 DWORD size;
1529 LPSTR p, env;
1531 p = env = GetEnvironmentStringsA();
1532 while (*p) p += strlen(p) + 1;
1533 p++; /* skip last null */
1534 size = (p - env) + sizeof(WORD) + sizeof(ENV_program_name);
1535 handle = GlobalAlloc16( GMEM_FIXED, size );
1536 if (handle)
1538 WORD one = 1;
1539 LPSTR env16 = GlobalLock16( handle );
1540 memcpy( env16, env, p - env );
1541 memcpy( env16 + (p - env), &one, sizeof(one));
1542 memcpy( env16 + (p - env) + sizeof(WORD), ENV_program_name, sizeof(ENV_program_name));
1543 GlobalUnlock16( handle );
1545 FreeEnvironmentStringsA( env );
1547 return WOWGlobalLock16( handle );