2 * WCMD - Wine-compatible command line interface.
4 * Copyright (C) 1999 - 2001 D A Pickles
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * - Cannot handle parameters in quotes
24 * - Lots of functionality missing from builtins
29 const char * const inbuilt[] = {"ATTRIB", "CALL", "CD", "CHDIR", "CLS", "COPY", "CTTY",
30 "DATE", "DEL", "DIR", "ECHO", "ERASE", "FOR", "GOTO",
31 "HELP", "IF", "LABEL", "MD", "MKDIR", "MOVE", "PATH", "PAUSE",
32 "PROMPT", "REM", "REN", "RENAME", "RD", "RMDIR", "SET", "SHIFT",
33 "TIME", "TITLE", "TYPE", "VERIFY", "VER", "VOL",
34 "ENDLOCAL", "SETLOCAL", "EXIT" };
38 int echo_mode = 1, verify_mode = 0;
39 const char nyi[] = "Not Yet Implemented\n\n";
40 const char newline[] = "\n";
41 const char version_string[] = "WCMD Version 0.17\n\n";
42 const char anykey[] = "Press Return key to continue: ";
43 char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
44 BATCH_CONTEXT *context = NULL;
45 static HANDLE old_stdin = INVALID_HANDLE_VALUE, old_stdout = INVALID_HANDLE_VALUE;
47 /*****************************************************************************
48 * Main entry point. This is a console application so we have a main() not a
52 int main (int argc, char *argv[])
58 int opt_c, opt_k, opt_q;
64 if (lstrcmpi(*argv,"/c")==0) {
68 } else if (lstrcmpi(*argv,"/q")==0) {
70 } else if (lstrcmpi(*argv,"/k")==0) {
74 } else if (lstrcmpi(*argv,"/t")==0 || lstrcmpi(*argv,"/x")==0 ||
75 lstrcmpi(*argv,"/y")==0) {
76 /* Ignored for compatibility with Windows */
92 /* Build the command to execute */
94 for (arg = argv; *arg; arg++)
102 if( !*a ) has_space=1;
107 if (*a==' ' || *a=='\t') {
109 } else if (*a=='"') {
110 /* doubling of '\' preceding a '"',
111 * plus escaping of said '"'
119 len+=(a-*arg)+1 /* for the separating space */;
121 len+=2; /* for the quotes */
124 cmd = HeapAlloc(GetProcessHeap(), 0, len);
129 for (arg = argv; *arg; arg++)
131 int has_space,has_quote;
134 /* Check for quotes and spaces in this argument */
135 has_space=has_quote=0;
137 if( !*a ) has_space=1;
139 if (*a==' ' || *a=='\t') {
143 } else if (*a=='"') {
151 /* Now transfer it to the command line */
168 /* Double all the '\\' preceding this '"', plus one */
169 for (i=0;i<=bcount;i++)
188 p--; /* remove last space */
193 /* If we do a "wcmd /c command", we don't want to allocate a new
194 * console since the command returns immediately. Rather, we use
195 * the currently allocated input and output handles. This allows
196 * us to pipe to and read from the command interpreter.
198 if (strchr(cmd,'|') != NULL)
201 WCMD_process_command(cmd);
202 HeapFree(GetProcessHeap(), 0, cmd);
206 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
207 ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
208 SetConsoleTitle("Wine Command Prompt");
211 WCMD_process_command(cmd);
212 HeapFree(GetProcessHeap(), 0, cmd);
216 * If there is an AUTOEXEC.BAT file, try to execute it.
219 GetFullPathName ("\\autoexec.bat", sizeof(string), string, NULL);
220 h = CreateFile (string, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
221 if (h != INVALID_HANDLE_VALUE) {
224 WCMD_batch_command (string);
229 * Loop forever getting commands and executing them.
235 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
237 string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
238 if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
239 if (lstrlen (string) != 0) {
240 if (strchr(string,'|') != NULL) {
244 WCMD_process_command (string);
252 /*****************************************************************************
253 * Process one command. If the command is EXIT this routine does not return.
254 * We will recurse through here executing batch files.
258 void WCMD_process_command (char *command)
262 DWORD count, creationDisposition;
265 SECURITY_ATTRIBUTES sa;
268 * Expand up environment variables.
270 len = ExpandEnvironmentStrings (command, NULL, 0);
271 cmd = HeapAlloc( GetProcessHeap(), 0, len );
272 status = ExpandEnvironmentStrings (command, cmd, len);
275 HeapFree( GetProcessHeap(), 0, cmd );
280 * Changing default drive has to be handled as a special case.
283 if ((cmd[1] == ':') && IsCharAlpha (cmd[0]) && (strlen(cmd) == 2)) {
284 status = SetCurrentDirectory (cmd);
285 if (!status) WCMD_print_error ();
286 HeapFree( GetProcessHeap(), 0, cmd );
290 /* Don't issue newline WCMD_output (newline); @JED*/
292 sa.nLength = sizeof(sa);
293 sa.lpSecurityDescriptor = NULL;
294 sa.bInheritHandle = TRUE;
296 * Redirect stdin and/or stdout if required.
299 if ((p = strchr(cmd,'<')) != NULL) {
300 h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
301 FILE_ATTRIBUTE_NORMAL, NULL);
302 if (h == INVALID_HANDLE_VALUE) {
304 HeapFree( GetProcessHeap(), 0, cmd );
307 old_stdin = GetStdHandle (STD_INPUT_HANDLE);
308 SetStdHandle (STD_INPUT_HANDLE, h);
310 if ((p = strchr(cmd,'>')) != NULL) {
313 creationDisposition = OPEN_ALWAYS;
317 creationDisposition = CREATE_ALWAYS;
319 h = CreateFile (WCMD_parameter (p, 0, NULL), GENERIC_WRITE, 0, &sa, creationDisposition,
320 FILE_ATTRIBUTE_NORMAL, NULL);
321 if (h == INVALID_HANDLE_VALUE) {
323 HeapFree( GetProcessHeap(), 0, cmd );
326 if (SetFilePointer (h, 0, NULL, FILE_END) ==
327 INVALID_SET_FILE_POINTER) {
330 old_stdout = GetStdHandle (STD_OUTPUT_HANDLE);
331 SetStdHandle (STD_OUTPUT_HANDLE, h);
333 if ((p = strchr(cmd,'<')) != NULL) *p = '\0';
336 * Strip leading whitespaces, and a '@' if supplied
338 whichcmd = WCMD_strtrim_leading_spaces(cmd);
339 if (whichcmd[0] == '@') whichcmd++;
342 * Check if the command entered is internal. If it is, pass the rest of the
343 * line down to the command. If not try to run a program.
347 while (IsCharAlphaNumeric(whichcmd[count])) {
350 for (i=0; i<=WCMD_EXIT; i++) {
351 if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
352 whichcmd, count, inbuilt[i], -1) == 2) break;
354 p = WCMD_strtrim_leading_spaces (&whichcmd[count]);
355 WCMD_parse (p, quals, param1, param2);
359 WCMD_setshow_attrib ();
362 WCMD_batch (param1, p, 1);
366 WCMD_setshow_default ();
369 WCMD_clear_screen ();
378 WCMD_setshow_date ();
388 WCMD_echo(&whichcmd[count]);
413 WCMD_setshow_path (p);
419 WCMD_setshow_prompt ();
438 WCMD_setshow_env (p);
444 WCMD_setshow_time ();
447 if (strlen(&whichcmd[count]) > 0)
448 WCMD_title(&whichcmd[count+1]);
465 WCMD_run_program (whichcmd);
467 HeapFree( GetProcessHeap(), 0, cmd );
468 if (old_stdin != INVALID_HANDLE_VALUE) {
469 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
470 SetStdHandle (STD_INPUT_HANDLE, old_stdin);
471 old_stdin = INVALID_HANDLE_VALUE;
473 if (old_stdout != INVALID_HANDLE_VALUE) {
474 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
475 SetStdHandle (STD_OUTPUT_HANDLE, old_stdout);
476 old_stdout = INVALID_HANDLE_VALUE;
480 static void init_msvcrt_io_block(STARTUPINFO* st)
483 /* fetch the parent MSVCRT info block if any, so that the child can use the
484 * same handles as its grand-father
486 st_p.cb = sizeof(STARTUPINFO);
487 GetStartupInfo(&st_p);
488 st->cbReserved2 = st_p.cbReserved2;
489 st->lpReserved2 = st_p.lpReserved2;
490 if (st_p.cbReserved2 && st_p.lpReserved2 &&
491 (old_stdin != INVALID_HANDLE_VALUE || old_stdout != INVALID_HANDLE_VALUE))
493 /* Override the entries for fd 0,1,2 if we happened
494 * to change those std handles (this depends on the way wcmd sets
495 * it's new input & output handles)
497 size_t sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
498 BYTE* ptr = HeapAlloc(GetProcessHeap(), 0, sz);
501 unsigned num = *(unsigned*)st_p.lpReserved2;
502 char* flags = (char*)(ptr + sizeof(unsigned));
503 HANDLE* handles = (HANDLE*)(flags + num * sizeof(char));
505 memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
506 st->cbReserved2 = sz;
507 st->lpReserved2 = ptr;
509 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
510 if (num <= 0 || (flags[0] & WX_OPEN))
512 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
515 if (num <= 1 || (flags[1] & WX_OPEN))
517 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
520 if (num <= 2 || (flags[2] & WX_OPEN))
522 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
530 /******************************************************************************
533 * Execute a command line as an external program. If no extension given then
534 * precedence is given to .BAT files. Must allow recursion.
536 * FIXME: Case sensitivity in suffixes!
539 void WCMD_run_program (char *command) {
542 PROCESS_INFORMATION pe;
548 char filetorun[MAX_PATH];
550 WCMD_parse (command, quals, param1, param2); /* Quick way to get the filename */
551 if (!(*param1) && !(*param2))
553 if (strpbrk (param1, "/\\:") == NULL) { /* No explicit path given */
554 char *ext = strrchr( param1, '.' );
555 if (!ext || !strcasecmp( ext, ".bat"))
557 if (SearchPath (NULL, param1, ".bat", sizeof(filetorun), filetorun, NULL)) {
558 WCMD_batch (filetorun, command, 0);
562 if (!ext || !strcasecmp( ext, ".cmd"))
564 if (SearchPath (NULL, param1, ".cmd", sizeof(filetorun), filetorun, NULL)) {
565 WCMD_batch (filetorun, command, 0);
570 else { /* Explicit path given */
571 char *ext = strrchr( param1, '.' );
572 if (ext && (!strcasecmp( ext, ".bat" ) || !strcasecmp( ext, ".cmd" )))
574 WCMD_batch (param1, command, 0);
578 if (ext && strpbrk( ext, "/\\:" )) ext = NULL;
581 strcpy (filetorun, param1);
582 strcat (filetorun, ".bat");
583 h = CreateFile (filetorun, GENERIC_READ, FILE_SHARE_READ,
584 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
585 if (h != INVALID_HANDLE_VALUE) {
587 WCMD_batch (param1, command, 0);
593 /* No batch file found, assume executable */
595 hinst = FindExecutable (param1, NULL, filetorun);
596 if ((int)hinst < 32) {
600 console = SHGetFileInfo (filetorun, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
601 ZeroMemory (&st, sizeof(STARTUPINFO));
602 st.cb = sizeof(STARTUPINFO);
603 init_msvcrt_io_block(&st);
605 status = CreateProcess (NULL, command, NULL, NULL, TRUE,
606 0, NULL, NULL, &st, &pe);
611 if (!console) errorlevel = 0;
614 if (!HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
615 GetExitCodeProcess (pe.hProcess, &errorlevel);
616 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
618 CloseHandle(pe.hProcess);
619 CloseHandle(pe.hThread);
622 /******************************************************************************
625 * Display the prompt on STDout
629 void WCMD_show_prompt (void) {
632 char out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
635 status = GetEnvironmentVariable ("PROMPT", prompt_string, sizeof(prompt_string));
636 if ((status == 0) || (status > sizeof(prompt_string))) {
637 lstrcpy (prompt_string, "$P$G");
649 switch (toupper(*p)) {
657 GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
670 status = GetCurrentDirectory (sizeof(curdir), curdir);
676 status = GetCurrentDirectory (sizeof(curdir), curdir);
686 GetTimeFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
690 lstrcat (q, version_string);
701 WCMD_output_asis (out_string);
704 /****************************************************************************
707 * Print the message for GetLastError
710 void WCMD_print_error (void) {
715 error_code = GetLastError ();
716 status = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
717 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
719 WCMD_output ("FIXME: Cannot display message for error %d, status %d\n",
720 error_code, GetLastError());
723 WCMD_output_asis (lpMsgBuf);
724 LocalFree ((HLOCAL)lpMsgBuf);
725 WCMD_output_asis (newline);
729 /*******************************************************************
730 * WCMD_parse - parse a command into parameters and qualifiers.
732 * On exit, all qualifiers are concatenated into q, the first string
733 * not beginning with "/" is in p1 and the
734 * second in p2. Any subsequent non-qualifier strings are lost.
735 * Parameters in quotes are handled.
738 void WCMD_parse (char *s, char *q, char *p1, char *p2) {
742 *q = *p1 = *p2 = '\0';
747 while ((*s != '\0') && (*s != ' ') && *s != '/') {
748 *q++ = toupper (*s++);
758 while ((*s != '\0') && (*s != '"')) {
759 if (p == 0) *p1++ = *s++;
760 else if (p == 1) *p2++ = *s++;
763 if (p == 0) *p1 = '\0';
764 if (p == 1) *p2 = '\0';
771 while ((*s != '\0') && (*s != ' ') && (*s != '\t')) {
772 if (p == 0) *p1++ = *s++;
773 else if (p == 1) *p2++ = *s++;
776 if (p == 0) *p1 = '\0';
777 if (p == 1) *p2 = '\0';
783 /*******************************************************************
784 * WCMD_output - send output to current standard output device.
788 void WCMD_output (const char *format, ...) {
795 ret = vsnprintf (string, sizeof( string), format, ap);
797 if( ret >= sizeof( string)) {
798 WCMD_output_asis("ERR: output truncated in WCMD_output\n" );
799 string[sizeof( string) -1] = '\0';
801 WCMD_output_asis(string);
805 static int line_count;
806 static int max_height;
807 static BOOL paged_mode;
809 void WCMD_enter_paged_mode(void)
811 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
813 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
814 max_height = consoleInfo.dwSize.Y;
818 line_count = 5; /* keep 5 lines from previous output */
821 void WCMD_leave_paged_mode(void)
826 /*******************************************************************
827 * WCMD_output_asis - send output to current standard output device.
828 * without formatting eg. when message contains '%'
831 void WCMD_output_asis (const char *message) {
838 if ((ptr = strchr(message, '\n')) != NULL) ptr++;
839 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message,
840 (ptr) ? ptr - message : lstrlen(message), &count, NULL);
842 if (++line_count >= max_height - 1) {
844 WCMD_output_asis (anykey);
845 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
848 } while ((message = ptr) != NULL);
850 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message, lstrlen(message), &count, NULL);
855 /***************************************************************************
856 * WCMD_strtrim_leading_spaces
858 * Remove leading spaces from a string. Return a pointer to the first
859 * non-space character. Does not modify the input string
862 char *WCMD_strtrim_leading_spaces (char *string) {
867 while (*ptr == ' ') ptr++;
871 /*************************************************************************
872 * WCMD_strtrim_trailing_spaces
874 * Remove trailing spaces from a string. This routine modifies the input
875 * string by placing a null after the last non-space character
878 void WCMD_strtrim_trailing_spaces (char *string) {
882 ptr = string + lstrlen (string) - 1;
883 while ((*ptr == ' ') && (ptr >= string)) {
889 /*************************************************************************
892 * Handle pipes within a command - the DOS way using temporary files.
895 void WCMD_pipe (char *command) {
898 char temp_path[MAX_PATH], temp_file[MAX_PATH], temp_file2[MAX_PATH], temp_cmd[1024];
900 GetTempPath (sizeof(temp_path), temp_path);
901 GetTempFileName (temp_path, "WCMD", 0, temp_file);
902 p = strchr(command, '|');
904 wsprintf (temp_cmd, "%s > %s", command, temp_file);
905 WCMD_process_command (temp_cmd);
907 while ((p = strchr(command, '|'))) {
909 GetTempFileName (temp_path, "WCMD", 0, temp_file2);
910 wsprintf (temp_cmd, "%s < %s > %s", command, temp_file, temp_file2);
911 WCMD_process_command (temp_cmd);
912 DeleteFile (temp_file);
913 lstrcpy (temp_file, temp_file2);
916 wsprintf (temp_cmd, "%s < %s", command, temp_file);
917 WCMD_process_command (temp_cmd);
918 DeleteFile (temp_file);