ntdll: Use an NtWriteFile pointer instead of a static import.
[wine.git] / programs / winevdm / winevdm.c
blobca55d80c567858af4525ffb643af6a341f258775
1 /*
2 * Wine virtual DOS machine
4 * Copyright 2003 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 <stdio.h>
26 #include <stdlib.h>
28 #include "windef.h"
29 #include "winbase.h"
30 #include "wine/winbase16.h"
31 #include "winuser.h"
32 #include "wincon.h"
33 #include "wine/unicode.h"
34 #include "wine/debug.h"
36 WINE_DEFAULT_DEBUG_CHANNEL(winevdm);
38 extern void __wine_load_dos_exe( LPCSTR filename, LPCSTR cmdline );
41 /*** PIF file structures ***/
42 #include "pshpack1.h"
44 /* header of a PIF file */
45 typedef struct {
46 BYTE unk1[2]; /* 0x00 */
47 CHAR windowtitle[ 30 ]; /* 0x02 seems to be padded with blanks*/
48 WORD memmax; /* 0x20 */
49 WORD memmin; /* 0x22 */
50 CHAR program[63]; /* 0x24 seems to be zero terminated */
51 BYTE hdrflags1; /* 0x63 various flags:
52 * 02 286: text mode selected
53 * 10 close window at exit
55 BYTE startdrive; /* 0x64 */
56 char startdir[64]; /* 0x65 */
57 char optparams[64]; /* 0xa5 seems to be zero terminated */
58 BYTE videomode; /* 0xe5 */
59 BYTE unkn2; /* 0xe6 ?*/
60 BYTE irqlow; /* 0xe7 */
61 BYTE irqhigh; /* 0xe8 */
62 BYTE rows; /* 0xe9 */
63 BYTE cols; /* 0xea */
64 BYTE winY; /* 0xeb */
65 BYTE winX; /* 0xec */
66 WORD unkn3; /* 0xed 7??? */
67 CHAR unkn4[64]; /* 0xef */
68 CHAR unkn5[64]; /* 0x12f */
69 BYTE hdrflags2; /* 0x16f */
70 BYTE hdrflags3; /* 0x170 */
71 } pifhead_t;
73 /* record header: present on every record */
74 typedef struct {
75 CHAR recordname[16]; /* zero terminated */
76 WORD posofnextrecord; /* file offset, 0xffff if last */
77 WORD startofdata; /* file offset */
78 WORD sizeofdata; /* data is expected to follow directly */
79 } recordhead_t;
81 /* 386 -enhanced mode- record */
82 typedef struct {
83 WORD memmax; /* memory desired, overrides the pif header*/
84 WORD memmin; /* memory required, overrides the pif header*/
85 WORD prifg; /* foreground priority */
86 WORD pribg; /* background priority */
87 WORD emsmax; /* EMS memory limit */
88 WORD emsmin; /* EMS memory required */
89 WORD xmsmax; /* XMS memory limit */
90 WORD xmsmin; /* XMS memory required */
91 WORD optflags; /* option flags:
92 * 0008 full screen
93 * 0004 exclusive
94 * 0002 background
95 * 0001 close when active
97 WORD memflags; /* various memory flags*/
98 WORD videoflags; /* video flags:
99 * 0010 text
100 * 0020 med. res. graphics
101 * 0040 hi. res. graphics
103 WORD hotkey[9]; /* Hot key info */
104 CHAR optparams[64]; /* optional params, replaces those in the pif header */
105 } pif386rec_t;
107 #include "poppack.h"
109 /***********************************************************************
110 * find_dosbox
112 static char *find_dosbox(void)
114 const char *envpath = getenv( "PATH" );
115 struct stat st;
116 char *path, *p, *buffer, *dir;
118 if (!envpath) return NULL;
119 path = HeapAlloc( GetProcessHeap(), 0, strlen(envpath) );
120 buffer = HeapAlloc( GetProcessHeap(), 0, strlen(path) + sizeof("/dosbox") );
121 strcpy( path, envpath );
122 p = path;
123 while (*p)
125 while (*p == ':') p++;
126 if (!*p) break;
127 dir = p;
128 while (*p && *p != ':') p++;
129 *p++ = 0;
130 strcpy( buffer, dir );
131 strcat( buffer, "/dosbox" );
132 if (!stat( buffer, &st ))
134 HeapFree( GetProcessHeap(), 0, path );
135 return buffer;
138 HeapFree( GetProcessHeap(), 0, buffer );
139 HeapFree( GetProcessHeap(), 0, path );
140 return NULL;
144 /***********************************************************************
145 * start_dosbox
147 static void start_dosbox( const char *appname, const char *args )
149 static const WCHAR cfgW[] = {'c','f','g',0};
150 const char *config_dir = wine_get_config_dir();
151 WCHAR path[MAX_PATH], config[MAX_PATH];
152 HANDLE file;
153 char *p, *buffer;
154 int i;
155 int ret = 1;
156 DWORD written, drives = GetLogicalDrives();
157 char *dosbox = find_dosbox();
159 if (!dosbox) return;
160 if (!GetTempPathW( MAX_PATH, path )) return;
161 if (!GetTempFileNameW( path, cfgW, 0, config )) return;
162 if (!GetCurrentDirectoryW( MAX_PATH, path )) return;
163 file = CreateFileW( config, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0 );
164 if (file == INVALID_HANDLE_VALUE) return;
166 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof("[autoexec]") +
167 25 * (strlen(config_dir) + sizeof("mount c /dosdevices/c:")) +
168 4 * strlenW( path ) +
169 6 + strlen( appname ) + strlen( args ) + 20 );
170 p = buffer;
171 p += sprintf( p, "[autoexec]\n" );
172 for (i = 0; i < 25; i++)
173 if (drives & (1 << i))
174 p += sprintf( p, "mount %c %s/dosdevices/%c:\n", 'a' + i, config_dir, 'a' + i );
175 p += sprintf( p, "%c:\ncd ", path[0] );
176 p += WideCharToMultiByte( CP_UNIXCP, 0, path + 2, -1, p, 4 * strlenW(path), NULL, NULL ) - 1;
177 p += sprintf( p, "\n%s %s\n", appname, args );
178 p += sprintf( p, "exit\n" );
179 if (WriteFile( file, buffer, strlen(buffer), &written, NULL ) && written == strlen(buffer))
181 const char *args[4];
182 char *config_file = wine_get_unix_file_name( config );
183 args[0] = dosbox;
184 args[1] = "-conf";
185 args[2] = config_file;
186 args[3] = NULL;
187 ret = spawnvp( _P_WAIT, args[0], args );
189 CloseHandle( file );
190 DeleteFileW( config );
191 HeapFree( GetProcessHeap(), 0, buffer );
192 ExitProcess( ret );
196 /***********************************************************************
197 * start_dos_exe
199 static void start_dos_exe( LPCSTR filename, LPCSTR cmdline )
201 MEMORY_BASIC_INFORMATION mem_info;
202 const char *reason;
204 if (VirtualQuery( NULL, &mem_info, sizeof(mem_info) ) && mem_info.State != MEM_FREE)
206 __wine_load_dos_exe( filename, cmdline );
207 if (GetLastError() == ERROR_NOT_SUPPORTED)
208 reason = "because vm86 mode is not supported on this platform";
209 else
210 reason = wine_dbg_sprintf( "It failed with error code %u", GetLastError() );
212 else reason = "because the DOS memory range is unavailable";
214 start_dosbox( filename, cmdline );
216 WINE_MESSAGE( "winevdm: Cannot start DOS application %s\n", filename );
217 WINE_MESSAGE( " %s.\n", reason );
218 WINE_MESSAGE( " Try running this application with DOSBox.\n" );
219 ExitProcess(1);
222 /***********************************************************************
223 * read_pif_file
224 *pif386rec_tu
225 * Read a pif file and return the header and possibly the 286 (real mode)
226 * record or 386 (enhanced mode) record. Returns FALSE if the file is
227 * invalid otherwise TRUE.
229 static BOOL read_pif_file( HANDLE hFile, char *progname, char *title,
230 char *optparams, char *startdir, int *closeonexit, int *textmode)
232 DWORD nread;
233 LARGE_INTEGER filesize;
234 recordhead_t rhead;
235 BOOL found386rec = FALSE;
236 pif386rec_t pif386rec;
237 pifhead_t pifheader;
238 if( !GetFileSizeEx( hFile, &filesize) ||
239 filesize.QuadPart < (sizeof(pifhead_t) + sizeof(recordhead_t))) {
240 WINE_ERR("Invalid pif file: size error %d\n", (int)filesize.QuadPart);
241 return FALSE;
243 SetFilePointer( hFile, 0, NULL, FILE_BEGIN);
244 if( !ReadFile( hFile, &pifheader, sizeof(pifhead_t), &nread, NULL))
245 return FALSE;
246 WINE_TRACE("header: program %s title %s startdir %s params %s\n",
247 wine_dbgstr_a(pifheader.program),
248 wine_dbgstr_an(pifheader.windowtitle, sizeof(pifheader.windowtitle)),
249 wine_dbgstr_a(pifheader.startdir),
250 wine_dbgstr_a(pifheader.optparams));
251 WINE_TRACE("header: memory req'd %d desr'd %d drive %d videomode %d\n",
252 pifheader.memmin, pifheader.memmax, pifheader.startdrive,
253 pifheader.videomode);
254 WINE_TRACE("header: flags 0x%x 0x%x 0x%x\n",
255 pifheader.hdrflags1, pifheader.hdrflags2, pifheader.hdrflags3);
256 ReadFile( hFile, &rhead, sizeof(recordhead_t), &nread, NULL);
257 if( strncmp( rhead.recordname, "MICROSOFT PIFEX", 15)) {
258 WINE_ERR("Invalid pif file: magic string not found\n");
259 return FALSE;
261 /* now process the following records */
262 while( 1) {
263 WORD nextrecord = rhead.posofnextrecord;
264 if( (nextrecord & 0x8000) ||
265 filesize.QuadPart <( nextrecord + sizeof(recordhead_t))) break;
266 if( !SetFilePointer( hFile, nextrecord, NULL, FILE_BEGIN) ||
267 !ReadFile( hFile, &rhead, sizeof(recordhead_t), &nread, NULL))
268 return FALSE;
269 if( !rhead.recordname[0]) continue; /* deleted record */
270 WINE_TRACE("reading record %s size %d next 0x%x\n",
271 wine_dbgstr_a(rhead.recordname), rhead.sizeofdata,
272 rhead.posofnextrecord );
273 if( !strncmp( rhead.recordname, "WINDOWS 386", 11)) {
274 found386rec = TRUE;
275 ReadFile( hFile, &pif386rec, sizeof(pif386rec_t), &nread, NULL);
276 WINE_TRACE("386rec: memory req'd %d des'd %d EMS req'd %d des'd %d XMS req'd %d des'd %d\n",
277 pif386rec.memmin, pif386rec.memmax,
278 pif386rec.emsmin, pif386rec.emsmax,
279 pif386rec.xmsmin, pif386rec.xmsmax);
280 WINE_TRACE("386rec: option 0x%x memory 0x%x video 0x%x\n",
281 pif386rec.optflags, pif386rec.memflags,
282 pif386rec.videoflags);
283 WINE_TRACE("386rec: optional parameters %s\n",
284 wine_dbgstr_a(pif386rec.optparams));
287 /* prepare the return data */
288 strncpy( progname, pifheader.program, sizeof(pifheader.program));
289 memcpy( title, pifheader.windowtitle, sizeof(pifheader.windowtitle));
290 title[ sizeof(pifheader.windowtitle) ] = '\0';
291 if( found386rec)
292 strncpy( optparams, pif386rec.optparams, sizeof( pif386rec.optparams));
293 else
294 strncpy( optparams, pifheader.optparams, sizeof(pifheader.optparams));
295 strncpy( startdir, pifheader.startdir, sizeof(pifheader.startdir));
296 *closeonexit = pifheader.hdrflags1 & 0x10;
297 *textmode = found386rec ? pif386rec.videoflags & 0x0010
298 : pifheader.hdrflags1 & 0x0002;
299 return TRUE;
302 /***********************************************************************
303 * pif_cmd
305 * execute a pif file.
307 static VOID pif_cmd( char *filename, char *cmdline)
309 HANDLE hFile;
310 char progpath[MAX_PATH];
311 char buf[128];
312 char progname[64];
313 char title[31];
314 char optparams[64];
315 char startdir[64];
316 char *p;
317 int closeonexit;
318 int textmode;
319 if( (hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
320 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
322 WINE_ERR("open file %s failed\n", wine_dbgstr_a(filename));
323 return;
325 if( !read_pif_file( hFile, progname, title, optparams, startdir,
326 &closeonexit, &textmode)) {
327 WINE_ERR( "failed to read %s\n", wine_dbgstr_a(filename));
328 CloseHandle( hFile);
329 sprintf( buf, "%s\nInvalid file format. Check your pif file.",
330 filename);
331 MessageBoxA( NULL, buf, "16 bit DOS subsystem", MB_OK|MB_ICONWARNING);
332 SetLastError( ERROR_BAD_FORMAT);
333 return;
335 CloseHandle( hFile);
336 if( (p = strrchr( progname, '.')) && !strcasecmp( p, ".bat"))
337 WINE_FIXME(".bat programs in pif files are not supported.\n");
338 /* first change dir, so the search below can start from there */
339 if( startdir[0] && !SetCurrentDirectoryA( startdir)) {
340 WINE_ERR("Cannot change directory %s\n", wine_dbgstr_a( startdir));
341 sprintf( buf, "%s\nInvalid startup directory. Check your pif file.",
342 filename);
343 MessageBoxA( NULL, buf, "16 bit DOS subsystem", MB_OK|MB_ICONWARNING);
345 /* search for the program */
346 if( !SearchPathA( NULL, progname, NULL, MAX_PATH, progpath, NULL )) {
347 sprintf( buf, "%s\nInvalid program file name. Check your pif file.",
348 filename);
349 MessageBoxA( NULL, buf, "16 bit DOS subsystem", MB_OK|MB_ICONERROR);
350 SetLastError( ERROR_FILE_NOT_FOUND);
351 return;
353 if( textmode)
354 if( AllocConsole())
355 SetConsoleTitleA( title) ;
356 /* if no arguments on the commandline, use them from the pif file */
357 if( !cmdline[0] && optparams[0])
358 cmdline = optparams;
359 /* FIXME: do something with:
360 * - close on exit
361 * - graphic modes
362 * - hot key's
363 * - etc.
365 start_dos_exe( progpath, cmdline );
368 /***********************************************************************
369 * build_command_line
371 * Build the command line of a process from the argv array.
372 * Copied from ENV_BuildCommandLine.
374 static char *build_command_line( char **argv )
376 int len;
377 char *p, **arg, *cmd_line;
379 len = 0;
380 for (arg = argv; *arg; arg++)
382 int has_space,bcount;
383 char* a;
385 has_space=0;
386 bcount=0;
387 a=*arg;
388 if( !*a ) has_space=1;
389 while (*a!='\0') {
390 if (*a=='\\') {
391 bcount++;
392 } else {
393 if (*a==' ' || *a=='\t') {
394 has_space=1;
395 } else if (*a=='"') {
396 /* doubling of '\' preceding a '"',
397 * plus escaping of said '"'
399 len+=2*bcount+1;
401 bcount=0;
403 a++;
405 len+=(a-*arg)+1 /* for the separating space */;
406 if (has_space)
407 len+=2; /* for the quotes */
410 if (!(cmd_line = HeapAlloc( GetProcessHeap(), 0, len ? len + 1 : 2 )))
411 return NULL;
413 p = cmd_line;
414 *p++ = (len < 256) ? len : 255;
415 for (arg = argv; *arg; arg++)
417 int has_space,has_quote;
418 char* a;
420 /* Check for quotes and spaces in this argument */
421 has_space=has_quote=0;
422 a=*arg;
423 if( !*a ) has_space=1;
424 while (*a!='\0') {
425 if (*a==' ' || *a=='\t') {
426 has_space=1;
427 if (has_quote)
428 break;
429 } else if (*a=='"') {
430 has_quote=1;
431 if (has_space)
432 break;
434 a++;
437 /* Now transfer it to the command line */
438 if (has_space)
439 *p++='"';
440 if (has_quote) {
441 int bcount;
442 char* a;
444 bcount=0;
445 a=*arg;
446 while (*a!='\0') {
447 if (*a=='\\') {
448 *p++=*a;
449 bcount++;
450 } else {
451 if (*a=='"') {
452 int i;
454 /* Double all the '\\' preceding this '"', plus one */
455 for (i=0;i<=bcount;i++)
456 *p++='\\';
457 *p++='"';
458 } else {
459 *p++=*a;
461 bcount=0;
463 a++;
465 } else {
466 strcpy(p,*arg);
467 p+=strlen(*arg);
469 if (has_space)
470 *p++='"';
471 *p++=' ';
473 if (len) p--; /* remove last space */
474 *p = '\0';
475 return cmd_line;
479 /***********************************************************************
480 * usage
482 static void usage(void)
484 WINE_MESSAGE( "Usage: winevdm.exe [--app-name app.exe] command line\n\n" );
485 ExitProcess(1);
489 /***********************************************************************
490 * main
492 int main( int argc, char *argv[] )
494 DWORD count;
495 HINSTANCE16 instance;
496 LOADPARAMS16 params;
497 WORD showCmd[2];
498 char buffer[MAX_PATH];
499 STARTUPINFOA info;
500 char *cmdline, *appname, **first_arg;
501 char *p;
503 if (!argv[1]) usage();
505 if (!strcmp( argv[1], "--app-name" ))
507 if (!(appname = argv[2])) usage();
508 first_arg = argv + 3;
510 else
512 if (!SearchPathA( NULL, argv[1], ".exe", sizeof(buffer), buffer, NULL ))
514 WINE_MESSAGE( "winevdm: unable to exec '%s': file not found\n", argv[1] );
515 ExitProcess(1);
517 appname = buffer;
518 first_arg = argv + 1;
521 if (*first_arg) first_arg++; /* skip program name */
522 cmdline = build_command_line( first_arg );
524 if (WINE_TRACE_ON(winevdm))
526 int i;
527 WINE_TRACE( "GetCommandLine = '%s'\n", GetCommandLineA() );
528 WINE_TRACE( "appname = '%s'\n", appname );
529 WINE_TRACE( "cmdline = '%.*s'\n", cmdline[0], cmdline+1 );
530 for (i = 0; argv[i]; i++) WINE_TRACE( "argv[%d]: '%s'\n", i, argv[i] );
533 GetStartupInfoA( &info );
534 showCmd[0] = 2;
535 showCmd[1] = (info.dwFlags & STARTF_USESHOWWINDOW) ? info.wShowWindow : SW_SHOWNORMAL;
537 params.hEnvironment = 0;
538 params.cmdLine = MapLS( cmdline );
539 params.showCmd = MapLS( showCmd );
540 params.reserved = 0;
542 RestoreThunkLock(1); /* grab the Win16 lock */
544 /* some programs assume mmsystem is always present */
545 LoadLibrary16( "gdi.exe" );
546 LoadLibrary16( "user.exe" );
547 LoadLibrary16( "mmsystem.dll" );
549 if ((instance = LoadModule16( appname, &params )) < 32)
551 if (instance == 11)
553 /* first see if it is a .pif file */
554 if( ( p = strrchr( appname, '.' )) && !strcasecmp( p, ".pif"))
555 pif_cmd( appname, cmdline + 1);
556 else
558 /* try DOS format */
559 /* loader expects arguments to be regular C strings */
560 start_dos_exe( appname, cmdline + 1 );
562 /* if we get back here it failed */
563 instance = GetLastError();
566 WINE_MESSAGE( "winevdm: can't exec '%s': ", appname );
567 switch (instance)
569 case 2: WINE_MESSAGE("file not found\n" ); break;
570 case 11: WINE_MESSAGE("invalid program file\n" ); break;
571 default: WINE_MESSAGE("error=%d\n", instance ); break;
573 ExitProcess(instance);
576 /* wait forever; the process will be killed when the last task exits */
577 ReleaseThunkLock( &count );
578 Sleep( INFINITE );
579 return 0;