winmm: Use wide-char string literals.
[wine.git] / programs / winevdm / winevdm.c
blobe550232c9af92874d10d1642dcb77e31763219eb
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 #define DOSBOX "dosbox"
40 /*** PIF file structures ***/
41 #include "pshpack1.h"
43 /* header of a PIF file */
44 typedef struct {
45 BYTE unk1[2]; /* 0x00 */
46 CHAR windowtitle[ 30 ]; /* 0x02 seems to be padded with blanks*/
47 WORD memmax; /* 0x20 */
48 WORD memmin; /* 0x22 */
49 CHAR program[63]; /* 0x24 seems to be zero terminated */
50 BYTE hdrflags1; /* 0x63 various flags:
51 * 02 286: text mode selected
52 * 10 close window at exit
54 BYTE startdrive; /* 0x64 */
55 char startdir[64]; /* 0x65 */
56 char optparams[64]; /* 0xa5 seems to be zero terminated */
57 BYTE videomode; /* 0xe5 */
58 BYTE unkn2; /* 0xe6 ?*/
59 BYTE irqlow; /* 0xe7 */
60 BYTE irqhigh; /* 0xe8 */
61 BYTE rows; /* 0xe9 */
62 BYTE cols; /* 0xea */
63 BYTE winY; /* 0xeb */
64 BYTE winX; /* 0xec */
65 WORD unkn3; /* 0xed 7??? */
66 CHAR unkn4[64]; /* 0xef */
67 CHAR unkn5[64]; /* 0x12f */
68 BYTE hdrflags2; /* 0x16f */
69 BYTE hdrflags3; /* 0x170 */
70 } pifhead_t;
72 /* record header: present on every record */
73 typedef struct {
74 CHAR recordname[16]; /* zero terminated */
75 WORD posofnextrecord; /* file offset, 0xffff if last */
76 WORD startofdata; /* file offset */
77 WORD sizeofdata; /* data is expected to follow directly */
78 } recordhead_t;
80 /* 386 -enhanced mode- record */
81 typedef struct {
82 WORD memmax; /* memory desired, overrides the pif header*/
83 WORD memmin; /* memory required, overrides the pif header*/
84 WORD prifg; /* foreground priority */
85 WORD pribg; /* background priority */
86 WORD emsmax; /* EMS memory limit */
87 WORD emsmin; /* EMS memory required */
88 WORD xmsmax; /* XMS memory limit */
89 WORD xmsmin; /* XMS memory required */
90 WORD optflags; /* option flags:
91 * 0008 full screen
92 * 0004 exclusive
93 * 0002 background
94 * 0001 close when active
96 WORD memflags; /* various memory flags*/
97 WORD videoflags; /* video flags:
98 * 0010 text
99 * 0020 med. res. graphics
100 * 0040 hi. res. graphics
102 WORD hotkey[9]; /* Hot key info */
103 CHAR optparams[64]; /* optional params, replaces those in the pif header */
104 } pif386rec_t;
106 #include "poppack.h"
108 /***********************************************************************
109 * find_dosbox
111 static char *find_dosbox(void)
113 const char *envpath = getenv( "PATH" );
114 struct stat st;
115 char *path, *p, *buffer, *dir;
116 size_t envpath_len;
118 if (!envpath) return NULL;
120 envpath_len = strlen( envpath );
121 path = HeapAlloc( GetProcessHeap(), 0, envpath_len + 1 );
122 buffer = HeapAlloc( GetProcessHeap(), 0, envpath_len + strlen(DOSBOX) + 2 );
123 strcpy( path, envpath );
125 p = path;
126 while (*p)
128 while (*p == ':') p++;
129 if (!*p) break;
130 dir = p;
131 while (*p && *p != ':') p++;
132 if (*p == ':') *p++ = 0;
133 strcpy( buffer, dir );
134 strcat( buffer, "/" DOSBOX );
135 if (!stat( buffer, &st ))
137 HeapFree( GetProcessHeap(), 0, path );
138 return buffer;
141 HeapFree( GetProcessHeap(), 0, buffer );
142 HeapFree( GetProcessHeap(), 0, path );
143 return NULL;
147 /***********************************************************************
148 * start_dosbox
150 static void start_dosbox( const char *appname, const char *args )
152 static const WCHAR cfgW[] = {'c','f','g',0};
153 const char *home = getenv( "HOME" );
154 const char *prefix = getenv( "WINEPREFIX" );
155 WCHAR path[MAX_PATH], config[MAX_PATH];
156 HANDLE file;
157 char *p, *buffer, app[MAX_PATH];
158 int i, len;
159 int ret = 1;
160 DWORD written, drives = GetLogicalDrives();
161 char *dosbox = find_dosbox();
163 if (!dosbox) return;
164 if (!GetTempPathW( MAX_PATH, path )) return;
165 if (!GetTempFileNameW( path, cfgW, 0, config )) return;
166 if (!GetCurrentDirectoryW( MAX_PATH, path )) return;
167 if (!GetShortPathNameA( appname, app, MAX_PATH )) return;
168 GetShortPathNameW( path, path, MAX_PATH );
169 file = CreateFileW( config, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0 );
170 if (file == INVALID_HANDLE_VALUE) return;
172 len = prefix ? strlen(prefix) : strlen(home) + strlen("/.wine");
173 buffer = HeapAlloc( GetProcessHeap(), 0, sizeof("[autoexec]") +
174 sizeof("mount -z c") + sizeof("config -securemode") +
175 25 * (len + sizeof("mount c /dosdevices/c:")) +
176 4 * strlenW( path ) +
177 6 + strlen( app ) + strlen( args ) + 20 );
178 p = buffer;
179 p += sprintf( p, "[autoexec]\n" );
180 for (i = 25; i >= 0; i--)
181 if (!(drives & (1 << i)))
183 p += sprintf( p, "mount -z %c\n", 'a' + i );
184 break;
186 for (i = 0; i <= 25; i++)
188 if (!(drives & (1 << i))) continue;
189 if (prefix)
190 p += sprintf( p, "mount %c %s/dosdevices/%c:\n", 'a' + i, prefix, 'a' + i );
191 else
192 p += sprintf( p, "mount %c %s/.wine/dosdevices/%c:\n", 'a' + i, home, 'a' + i );
194 p += sprintf( p, "%c:\ncd ", path[0] );
195 p += WideCharToMultiByte( CP_UNIXCP, 0, path + 2, -1, p, 4 * strlenW(path), NULL, NULL ) - 1;
196 p += sprintf( p, "\nconfig -securemode\n" );
197 p += sprintf( p, "%s %s\n", app, args );
198 p += sprintf( p, "exit\n" );
199 if (WriteFile( file, buffer, strlen(buffer), &written, NULL ) && written == strlen(buffer))
201 const char *args[5];
202 char *config_file = wine_get_unix_file_name( config );
203 args[0] = dosbox;
204 args[1] = "-userconf";
205 args[2] = "-conf";
206 args[3] = config_file;
207 args[4] = NULL;
208 ret = _spawnvp( _P_WAIT, args[0], args );
210 CloseHandle( file );
211 DeleteFileW( config );
212 HeapFree( GetProcessHeap(), 0, buffer );
213 ExitProcess( ret );
217 /***********************************************************************
218 * start_dos_exe
220 static void start_dos_exe( LPCSTR filename, LPCSTR cmdline )
222 start_dosbox( filename, cmdline );
223 WINE_MESSAGE( "winevdm: %s is a DOS application, you need to install DOSBox.\n", filename );
224 ExitProcess(1);
227 /***********************************************************************
228 * read_pif_file
229 *pif386rec_tu
230 * Read a pif file and return the header and possibly the 286 (real mode)
231 * record or 386 (enhanced mode) record. Returns FALSE if the file is
232 * invalid otherwise TRUE.
234 static BOOL read_pif_file( HANDLE hFile, char *progname, char *title,
235 char *optparams, char *startdir, int *closeonexit, int *textmode)
237 DWORD nread;
238 LARGE_INTEGER filesize;
239 recordhead_t rhead;
240 BOOL found386rec = FALSE;
241 pif386rec_t pif386rec;
242 pifhead_t pifheader;
243 if( !GetFileSizeEx( hFile, &filesize) ||
244 filesize.QuadPart < (sizeof(pifhead_t) + sizeof(recordhead_t))) {
245 WINE_ERR("Invalid pif file: size error %d\n", (int)filesize.QuadPart);
246 return FALSE;
248 SetFilePointer( hFile, 0, NULL, FILE_BEGIN);
249 if( !ReadFile( hFile, &pifheader, sizeof(pifhead_t), &nread, NULL))
250 return FALSE;
251 WINE_TRACE("header: program %s title %s startdir %s params %s\n",
252 wine_dbgstr_a(pifheader.program),
253 wine_dbgstr_an(pifheader.windowtitle, sizeof(pifheader.windowtitle)),
254 wine_dbgstr_a(pifheader.startdir),
255 wine_dbgstr_a(pifheader.optparams));
256 WINE_TRACE("header: memory req'd %d desr'd %d drive %d videomode %d\n",
257 pifheader.memmin, pifheader.memmax, pifheader.startdrive,
258 pifheader.videomode);
259 WINE_TRACE("header: flags 0x%x 0x%x 0x%x\n",
260 pifheader.hdrflags1, pifheader.hdrflags2, pifheader.hdrflags3);
261 ReadFile( hFile, &rhead, sizeof(recordhead_t), &nread, NULL);
262 if( strncmp( rhead.recordname, "MICROSOFT PIFEX", 15)) {
263 WINE_ERR("Invalid pif file: magic string not found\n");
264 return FALSE;
266 /* now process the following records */
267 while( 1) {
268 WORD nextrecord = rhead.posofnextrecord;
269 if( (nextrecord & 0x8000) ||
270 filesize.QuadPart <( nextrecord + sizeof(recordhead_t))) break;
271 if( !SetFilePointer( hFile, nextrecord, NULL, FILE_BEGIN) ||
272 !ReadFile( hFile, &rhead, sizeof(recordhead_t), &nread, NULL))
273 return FALSE;
274 if( !rhead.recordname[0]) continue; /* deleted record */
275 WINE_TRACE("reading record %s size %d next 0x%x\n",
276 wine_dbgstr_a(rhead.recordname), rhead.sizeofdata,
277 rhead.posofnextrecord );
278 if( !strncmp( rhead.recordname, "WINDOWS 386", 11)) {
279 found386rec = TRUE;
280 ReadFile( hFile, &pif386rec, sizeof(pif386rec_t), &nread, NULL);
281 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",
282 pif386rec.memmin, pif386rec.memmax,
283 pif386rec.emsmin, pif386rec.emsmax,
284 pif386rec.xmsmin, pif386rec.xmsmax);
285 WINE_TRACE("386rec: option 0x%x memory 0x%x video 0x%x\n",
286 pif386rec.optflags, pif386rec.memflags,
287 pif386rec.videoflags);
288 WINE_TRACE("386rec: optional parameters %s\n",
289 wine_dbgstr_a(pif386rec.optparams));
292 /* prepare the return data */
293 lstrcpynA( progname, pifheader.program, sizeof(pifheader.program)+1);
294 lstrcpynA( title, pifheader.windowtitle, sizeof(pifheader.windowtitle)+1);
295 if( found386rec)
296 lstrcpynA( optparams, pif386rec.optparams, sizeof( pif386rec.optparams)+1);
297 else
298 lstrcpynA( optparams, pifheader.optparams, sizeof(pifheader.optparams)+1);
299 lstrcpynA( startdir, pifheader.startdir, sizeof(pifheader.startdir)+1);
300 *closeonexit = pifheader.hdrflags1 & 0x10;
301 *textmode = found386rec ? pif386rec.videoflags & 0x0010
302 : pifheader.hdrflags1 & 0x0002;
303 return TRUE;
306 /***********************************************************************
307 * pif_cmd
309 * execute a pif file.
311 static VOID pif_cmd( char *filename, char *cmdline)
313 HANDLE hFile;
314 char progpath[MAX_PATH];
315 char buf[308];
316 char progname[64];
317 char title[31];
318 char optparams[65];
319 char startdir[65];
320 char *p;
321 int closeonexit;
322 int textmode;
323 if( (hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
324 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
326 WINE_ERR("open file %s failed\n", wine_dbgstr_a(filename));
327 return;
329 if( !read_pif_file( hFile, progname, title, optparams, startdir,
330 &closeonexit, &textmode)) {
331 WINE_ERR( "failed to read %s\n", wine_dbgstr_a(filename));
332 CloseHandle( hFile);
333 sprintf( buf, "%s\nInvalid file format. Check your pif file.",
334 filename);
335 MessageBoxA( NULL, buf, "16 bit DOS subsystem", MB_OK|MB_ICONWARNING);
336 SetLastError( ERROR_BAD_FORMAT);
337 return;
339 CloseHandle( hFile);
340 if( (p = strrchr( progname, '.')) && !strcasecmp( p, ".bat"))
341 WINE_FIXME(".bat programs in pif files are not supported.\n");
342 /* first change dir, so the search below can start from there */
343 if( startdir[0] && !SetCurrentDirectoryA( startdir)) {
344 WINE_ERR("Cannot change directory %s\n", wine_dbgstr_a( startdir));
345 sprintf( buf, "%s\nInvalid startup directory. Check your pif file.",
346 filename);
347 MessageBoxA( NULL, buf, "16 bit DOS subsystem", MB_OK|MB_ICONWARNING);
349 /* search for the program */
350 if( !SearchPathA( NULL, progname, NULL, MAX_PATH, progpath, NULL )) {
351 sprintf( buf, "%s\nInvalid program file name. Check your pif file.",
352 filename);
353 MessageBoxA( NULL, buf, "16 bit DOS subsystem", MB_OK|MB_ICONERROR);
354 SetLastError( ERROR_FILE_NOT_FOUND);
355 return;
357 if( textmode)
358 if( AllocConsole())
359 SetConsoleTitleA( title) ;
360 /* if no arguments on the commandline, use them from the pif file */
361 if( !cmdline[0] && optparams[0])
362 cmdline = optparams;
363 /* FIXME: do something with:
364 * - close on exit
365 * - graphic modes
366 * - hot key's
367 * - etc.
369 start_dos_exe( progpath, cmdline );
372 /***********************************************************************
373 * build_command_line
375 * Build the command line of a process from the argv array.
376 * Copied from ENV_BuildCommandLine.
378 static char *build_command_line( char **argv )
380 int len;
381 char *p, **arg, *cmd_line;
383 len = 0;
384 for (arg = argv; *arg; arg++)
386 BOOL has_space;
387 int bcount;
388 char* a;
390 has_space=FALSE;
391 bcount=0;
392 a=*arg;
393 if( !*a ) has_space=TRUE;
394 while (*a!='\0') {
395 if (*a=='\\') {
396 bcount++;
397 } else {
398 if (*a==' ' || *a=='\t') {
399 has_space=TRUE;
400 } else if (*a=='"') {
401 /* doubling of '\' preceding a '"',
402 * plus escaping of said '"'
404 len+=2*bcount+1;
406 bcount=0;
408 a++;
410 len+=(a-*arg)+1 /* for the separating space */;
411 if (has_space)
412 len+=2; /* for the quotes */
415 if (!(cmd_line = HeapAlloc( GetProcessHeap(), 0, len ? len + 1 : 2 )))
416 return NULL;
418 p = cmd_line;
419 *p++ = (len < 256) ? len : 255;
420 for (arg = argv; *arg; arg++)
422 BOOL has_space,has_quote;
423 char* a;
425 /* Check for quotes and spaces in this argument */
426 has_space=has_quote=FALSE;
427 a=*arg;
428 if( !*a ) has_space=TRUE;
429 while (*a!='\0') {
430 if (*a==' ' || *a=='\t') {
431 has_space=TRUE;
432 if (has_quote)
433 break;
434 } else if (*a=='"') {
435 has_quote=TRUE;
436 if (has_space)
437 break;
439 a++;
442 /* Now transfer it to the command line */
443 if (has_space)
444 *p++='"';
445 if (has_quote) {
446 int bcount;
448 bcount=0;
449 a=*arg;
450 while (*a!='\0') {
451 if (*a=='\\') {
452 *p++=*a;
453 bcount++;
454 } else {
455 if (*a=='"') {
456 int i;
458 /* Double all the '\\' preceding this '"', plus one */
459 for (i=0;i<=bcount;i++)
460 *p++='\\';
461 *p++='"';
462 } else {
463 *p++=*a;
465 bcount=0;
467 a++;
469 } else {
470 strcpy(p,*arg);
471 p+=strlen(*arg);
473 if (has_space)
474 *p++='"';
475 *p++=' ';
477 if (len) p--; /* remove last space */
478 *p = '\0';
479 return cmd_line;
483 /***********************************************************************
484 * usage
486 static void usage(void)
488 WINE_MESSAGE( "Usage: winevdm.exe [--app-name app.exe] command line\n\n" );
489 ExitProcess(1);
493 /***********************************************************************
494 * main
496 int __cdecl main( int argc, char *argv[] )
498 DWORD count;
499 HINSTANCE16 instance;
500 LOADPARAMS16 params;
501 WORD showCmd[2];
502 char buffer[MAX_PATH];
503 STARTUPINFOA info;
504 char *cmdline, *appname, **first_arg;
505 char *p;
507 if (!argv[1]) usage();
509 if (!strcmp( argv[1], "--app-name" ))
511 if (!(appname = argv[2])) usage();
512 first_arg = argv + 3;
514 else
516 if (!SearchPathA( NULL, argv[1], ".exe", sizeof(buffer), buffer, NULL ))
518 WINE_MESSAGE( "winevdm: unable to exec '%s': file not found\n", argv[1] );
519 ExitProcess(1);
521 appname = buffer;
522 first_arg = argv + 1;
525 if (*first_arg) first_arg++; /* skip program name */
526 cmdline = build_command_line( first_arg );
528 if (WINE_TRACE_ON(winevdm))
530 int i;
531 WINE_TRACE( "GetCommandLine = '%s'\n", GetCommandLineA() );
532 WINE_TRACE( "appname = '%s'\n", appname );
533 WINE_TRACE( "cmdline = '%.*s'\n", cmdline[0], cmdline+1 );
534 for (i = 0; argv[i]; i++) WINE_TRACE( "argv[%d]: '%s'\n", i, argv[i] );
537 GetStartupInfoA( &info );
538 showCmd[0] = 2;
539 showCmd[1] = (info.dwFlags & STARTF_USESHOWWINDOW) ? info.wShowWindow : SW_SHOWNORMAL;
541 params.hEnvironment = 0;
542 params.cmdLine = MapLS( cmdline );
543 params.showCmd = MapLS( showCmd );
544 params.reserved = 0;
546 RestoreThunkLock(1); /* grab the Win16 lock */
548 /* some programs assume mmsystem is always present */
549 LoadLibrary16( "gdi.exe" );
550 LoadLibrary16( "user.exe" );
551 LoadLibrary16( "mmsystem.dll" );
553 if ((instance = LoadModule16( appname, &params )) < 32)
555 if (instance == 11)
557 /* first see if it is a .pif file */
558 if( ( p = strrchr( appname, '.' )) && !strcasecmp( p, ".pif"))
559 pif_cmd( appname, cmdline + 1);
560 else
562 /* try DOS format */
563 /* loader expects arguments to be regular C strings */
564 start_dos_exe( appname, cmdline + 1 );
566 /* if we get back here it failed */
567 instance = GetLastError();
570 WINE_MESSAGE( "winevdm: can't exec '%s': ", appname );
571 switch (instance)
573 case 2: WINE_MESSAGE("file not found\n" ); break;
574 case 11: WINE_MESSAGE("invalid program file\n" ); break;
575 default: WINE_MESSAGE("error=%d\n", instance ); break;
577 ExitProcess(instance);
580 /* wait forever; the process will be killed when the last task exits */
581 ReleaseThunkLock( &count );
582 Sleep( INFINITE );
583 return 0;