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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 * - Cannot handle parameters in quotes
24 * - Lots of functionality missing from builtins
30 const char * const inbuilt[] = {"ATTRIB", "CALL", "CD", "CHDIR", "CLS", "COPY", "CTTY",
31 "DATE", "DEL", "DIR", "ECHO", "ERASE", "FOR", "GOTO",
32 "HELP", "IF", "LABEL", "MD", "MKDIR", "MOVE", "PATH", "PAUSE",
33 "PROMPT", "REM", "REN", "RENAME", "RD", "RMDIR", "SET", "SHIFT",
34 "TIME", "TITLE", "TYPE", "VERIFY", "VER", "VOL",
35 "ENDLOCAL", "SETLOCAL", "EXIT" };
39 int echo_mode = 1, verify_mode = 0;
40 static int opt_c, opt_k, opt_s;
41 const char nyi[] = "Not Yet Implemented\n\n";
42 const char newline[] = "\n";
43 const char version_string[] = "WCMD Version " PACKAGE_VERSION "\n\n";
44 const char anykey[] = "Press Return key to continue: ";
45 char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
46 BATCH_CONTEXT *context = NULL;
47 static HANDLE old_stdin = INVALID_HANDLE_VALUE, old_stdout = INVALID_HANDLE_VALUE;
49 /*****************************************************************************
50 * Main entry point. This is a console application so we have a main() not a
54 int main (int argc, char *argv[])
62 opt_c=opt_k=opt_q=opt_s=0;
66 if ((*argv)[0]!='/' || (*argv)[1]=='\0') {
72 if (tolower(c)=='c') {
74 } else if (tolower(c)=='q') {
76 } else if (tolower(c)=='k') {
78 } else if (tolower(c)=='s') {
80 } else if (tolower(c)=='t' || tolower(c)=='x' || tolower(c)=='y') {
81 /* Ignored for compatibility with Windows */
86 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
89 if (opt_c || opt_k) /* break out of parsing immediately after c or k */
102 /* opt_s left unflagged if the command starts with and contains exactly
103 * one quoted string (exactly two quote characters). The quoted string
104 * must be an executable name that has whitespace and must not have the
105 * following characters: &<>()@^| */
107 /* Build the command to execute */
110 for (arg = argv; *arg; arg++)
112 int has_space,bcount;
118 if( !*a ) has_space=1;
123 if (*a==' ' || *a=='\t') {
125 } else if (*a=='"') {
126 /* doubling of '\' preceding a '"',
127 * plus escaping of said '"'
136 len+=(a-*arg)+1 /* for the separating space */;
139 len+=2; /* for the quotes */
147 /* check argv[0] for a space and invalid characters */
152 if (*p=='&' || *p=='<' || *p=='>' || *p=='(' || *p==')'
153 || *p=='@' || *p=='^' || *p=='|') {
163 cmd = HeapAlloc(GetProcessHeap(), 0, len);
168 for (arg = argv; *arg; arg++)
170 int has_space,has_quote;
173 /* Check for quotes and spaces in this argument */
174 has_space=has_quote=0;
176 if( !*a ) has_space=1;
178 if (*a==' ' || *a=='\t') {
182 } else if (*a=='"') {
190 /* Now transfer it to the command line */
207 /* Double all the '\\' preceding this '"', plus one */
208 for (i=0;i<=bcount;i++)
227 p--; /* remove last space */
230 /* strip first and last quote characters if opt_s; check for invalid
231 * executable is done later */
232 if (opt_s && *cmd=='\"')
233 WCMD_opt_s_strip_quotes(cmd);
237 /* If we do a "wcmd /c command", we don't want to allocate a new
238 * console since the command returns immediately. Rather, we use
239 * the currently allocated input and output handles. This allows
240 * us to pipe to and read from the command interpreter.
242 if (strchr(cmd,'|') != NULL)
245 WCMD_process_command(cmd);
246 HeapFree(GetProcessHeap(), 0, cmd);
250 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
251 ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
252 SetConsoleTitle("Wine Command Prompt");
255 WCMD_process_command(cmd);
256 HeapFree(GetProcessHeap(), 0, cmd);
260 * If there is an AUTOEXEC.BAT file, try to execute it.
263 GetFullPathName ("\\autoexec.bat", sizeof(string), string, NULL);
264 h = CreateFile (string, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
265 if (h != INVALID_HANDLE_VALUE) {
268 WCMD_batch_command (string);
273 * Loop forever getting commands and executing them.
279 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
281 string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
282 if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
283 if (lstrlen (string) != 0) {
284 if (strchr(string,'|') != NULL) {
288 WCMD_process_command (string);
296 /*****************************************************************************
297 * Process one command. If the command is EXIT this routine does not return.
298 * We will recurse through here executing batch files.
302 void WCMD_process_command (char *command)
306 DWORD count, creationDisposition;
309 SECURITY_ATTRIBUTES sa;
312 * Expand up environment variables.
314 len = ExpandEnvironmentStrings (command, NULL, 0);
315 cmd = HeapAlloc( GetProcessHeap(), 0, len );
316 status = ExpandEnvironmentStrings (command, cmd, len);
319 HeapFree( GetProcessHeap(), 0, cmd );
324 * Changing default drive has to be handled as a special case.
327 if ((cmd[1] == ':') && IsCharAlpha (cmd[0]) && (strlen(cmd) == 2)) {
328 status = SetCurrentDirectory (cmd);
329 if (!status) WCMD_print_error ();
330 HeapFree( GetProcessHeap(), 0, cmd );
334 /* Don't issue newline WCMD_output (newline); @JED*/
336 sa.nLength = sizeof(sa);
337 sa.lpSecurityDescriptor = NULL;
338 sa.bInheritHandle = TRUE;
340 * Redirect stdin and/or stdout if required.
343 if ((p = strchr(cmd,'<')) != NULL) {
344 h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
345 FILE_ATTRIBUTE_NORMAL, NULL);
346 if (h == INVALID_HANDLE_VALUE) {
348 HeapFree( GetProcessHeap(), 0, cmd );
351 old_stdin = GetStdHandle (STD_INPUT_HANDLE);
352 SetStdHandle (STD_INPUT_HANDLE, h);
354 if ((p = strchr(cmd,'>')) != NULL) {
357 creationDisposition = OPEN_ALWAYS;
361 creationDisposition = CREATE_ALWAYS;
363 h = CreateFile (WCMD_parameter (p, 0, NULL), GENERIC_WRITE, 0, &sa, creationDisposition,
364 FILE_ATTRIBUTE_NORMAL, NULL);
365 if (h == INVALID_HANDLE_VALUE) {
367 HeapFree( GetProcessHeap(), 0, cmd );
370 if (SetFilePointer (h, 0, NULL, FILE_END) ==
371 INVALID_SET_FILE_POINTER) {
374 old_stdout = GetStdHandle (STD_OUTPUT_HANDLE);
375 SetStdHandle (STD_OUTPUT_HANDLE, h);
377 if ((p = strchr(cmd,'<')) != NULL) *p = '\0';
380 * Strip leading whitespaces, and a '@' if supplied
382 whichcmd = WCMD_strtrim_leading_spaces(cmd);
383 if (whichcmd[0] == '@') whichcmd++;
386 * Check if the command entered is internal. If it is, pass the rest of the
387 * line down to the command. If not try to run a program.
391 while (IsCharAlphaNumeric(whichcmd[count])) {
394 for (i=0; i<=WCMD_EXIT; i++) {
395 if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
396 whichcmd, count, inbuilt[i], -1) == 2) break;
398 p = WCMD_strtrim_leading_spaces (&whichcmd[count]);
399 WCMD_parse (p, quals, param1, param2);
403 WCMD_setshow_attrib ();
406 WCMD_run_program (p, 1);
410 WCMD_setshow_default ();
413 WCMD_clear_screen ();
422 WCMD_setshow_date ();
432 WCMD_echo(&whichcmd[count]);
457 WCMD_setshow_path (p);
463 WCMD_setshow_prompt ();
482 WCMD_setshow_env (p);
488 WCMD_setshow_time ();
491 if (strlen(&whichcmd[count]) > 0)
492 WCMD_title(&whichcmd[count+1]);
509 WCMD_run_program (whichcmd, 0);
511 HeapFree( GetProcessHeap(), 0, cmd );
512 if (old_stdin != INVALID_HANDLE_VALUE) {
513 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
514 SetStdHandle (STD_INPUT_HANDLE, old_stdin);
515 old_stdin = INVALID_HANDLE_VALUE;
517 if (old_stdout != INVALID_HANDLE_VALUE) {
518 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
519 SetStdHandle (STD_OUTPUT_HANDLE, old_stdout);
520 old_stdout = INVALID_HANDLE_VALUE;
524 static void init_msvcrt_io_block(STARTUPINFO* st)
527 /* fetch the parent MSVCRT info block if any, so that the child can use the
528 * same handles as its grand-father
530 st_p.cb = sizeof(STARTUPINFO);
531 GetStartupInfo(&st_p);
532 st->cbReserved2 = st_p.cbReserved2;
533 st->lpReserved2 = st_p.lpReserved2;
534 if (st_p.cbReserved2 && st_p.lpReserved2 &&
535 (old_stdin != INVALID_HANDLE_VALUE || old_stdout != INVALID_HANDLE_VALUE))
537 /* Override the entries for fd 0,1,2 if we happened
538 * to change those std handles (this depends on the way wcmd sets
539 * it's new input & output handles)
541 size_t sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
542 BYTE* ptr = HeapAlloc(GetProcessHeap(), 0, sz);
545 unsigned num = *(unsigned*)st_p.lpReserved2;
546 char* flags = (char*)(ptr + sizeof(unsigned));
547 HANDLE* handles = (HANDLE*)(flags + num * sizeof(char));
549 memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
550 st->cbReserved2 = sz;
551 st->lpReserved2 = ptr;
553 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
554 if (num <= 0 || (flags[0] & WX_OPEN))
556 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
559 if (num <= 1 || (flags[1] & WX_OPEN))
561 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
564 if (num <= 2 || (flags[2] & WX_OPEN))
566 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
574 /******************************************************************************
577 * Execute a command line as an external program. If no extension given then
578 * precedence is given to .BAT files. Must allow recursion.
580 * called is 1 if the program was invoked with a CALL command - removed
581 * from command -. It is only used for batch programs.
583 * FIXME: Case sensitivity in suffixes!
586 void WCMD_run_program (char *command, int called) {
589 PROCESS_INFORMATION pe;
595 char filetorun[MAX_PATH];
597 WCMD_parse (command, quals, param1, param2); /* Quick way to get the filename */
598 if (!(*param1) && !(*param2))
600 if (strpbrk (param1, "/\\:") == NULL) { /* No explicit path given */
601 char *ext = strrchr( param1, '.' );
602 if (!ext || !strcasecmp( ext, ".bat"))
604 if (SearchPath (NULL, param1, ".bat", sizeof(filetorun), filetorun, NULL)) {
605 WCMD_batch (filetorun, command, called);
609 if (!ext || !strcasecmp( ext, ".cmd"))
611 if (SearchPath (NULL, param1, ".cmd", sizeof(filetorun), filetorun, NULL)) {
612 WCMD_batch (filetorun, command, called);
617 else { /* Explicit path given */
618 char *ext = strrchr( param1, '.' );
619 if (ext && (!strcasecmp( ext, ".bat" ) || !strcasecmp( ext, ".cmd" )))
621 WCMD_batch (param1, command, called);
625 if (ext && strpbrk( ext, "/\\:" )) ext = NULL;
628 strcpy (filetorun, param1);
629 strcat (filetorun, ".bat");
630 h = CreateFile (filetorun, GENERIC_READ, FILE_SHARE_READ,
631 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
632 if (h != INVALID_HANDLE_VALUE) {
634 WCMD_batch (param1, command, called);
640 /* No batch file found, assume executable */
642 hinst = FindExecutable (param1, NULL, filetorun);
643 if ((INT_PTR)hinst < 32)
646 console = SHGetFileInfo (filetorun, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
648 ZeroMemory (&st, sizeof(STARTUPINFO));
649 st.cb = sizeof(STARTUPINFO);
650 init_msvcrt_io_block(&st);
652 status = CreateProcess (NULL, command, NULL, NULL, TRUE,
653 0, NULL, NULL, &st, &pe);
654 if ((opt_c || opt_k) && !opt_s && !status
655 && GetLastError()==ERROR_FILE_NOT_FOUND && command[0]=='\"') {
656 /* strip first and last quote characters and try again */
657 WCMD_opt_s_strip_quotes(command);
659 WCMD_run_program(command, called);
666 if (!console) errorlevel = 0;
669 if (!HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
670 GetExitCodeProcess (pe.hProcess, &errorlevel);
671 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
673 CloseHandle(pe.hProcess);
674 CloseHandle(pe.hThread);
677 /******************************************************************************
680 * Display the prompt on STDout
684 void WCMD_show_prompt (void) {
687 char out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
690 status = GetEnvironmentVariable ("PROMPT", prompt_string, sizeof(prompt_string));
691 if ((status == 0) || (status > sizeof(prompt_string))) {
692 lstrcpy (prompt_string, "$P$G");
704 switch (toupper(*p)) {
712 GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
725 status = GetCurrentDirectory (sizeof(curdir), curdir);
731 status = GetCurrentDirectory (sizeof(curdir), curdir);
741 GetTimeFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
745 lstrcat (q, version_string);
756 WCMD_output_asis (out_string);
759 /****************************************************************************
762 * Print the message for GetLastError
765 void WCMD_print_error (void) {
770 error_code = GetLastError ();
771 status = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
772 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
774 WCMD_output ("FIXME: Cannot display message for error %d, status %d\n",
775 error_code, GetLastError());
778 WCMD_output_asis (lpMsgBuf);
779 LocalFree ((HLOCAL)lpMsgBuf);
780 WCMD_output_asis (newline);
784 /*******************************************************************
785 * WCMD_parse - parse a command into parameters and qualifiers.
787 * On exit, all qualifiers are concatenated into q, the first string
788 * not beginning with "/" is in p1 and the
789 * second in p2. Any subsequent non-qualifier strings are lost.
790 * Parameters in quotes are handled.
793 void WCMD_parse (char *s, char *q, char *p1, char *p2) {
797 *q = *p1 = *p2 = '\0';
802 while ((*s != '\0') && (*s != ' ') && *s != '/') {
803 *q++ = toupper (*s++);
813 while ((*s != '\0') && (*s != '"')) {
814 if (p == 0) *p1++ = *s++;
815 else if (p == 1) *p2++ = *s++;
818 if (p == 0) *p1 = '\0';
819 if (p == 1) *p2 = '\0';
826 while ((*s != '\0') && (*s != ' ') && (*s != '\t')) {
827 if (p == 0) *p1++ = *s++;
828 else if (p == 1) *p2++ = *s++;
831 if (p == 0) *p1 = '\0';
832 if (p == 1) *p2 = '\0';
838 /*******************************************************************
839 * WCMD_output - send output to current standard output device.
843 void WCMD_output (const char *format, ...) {
850 ret = vsnprintf (string, sizeof( string), format, ap);
852 if( ret >= sizeof( string)) {
853 WCMD_output_asis("ERR: output truncated in WCMD_output\n" );
854 string[sizeof( string) -1] = '\0';
856 WCMD_output_asis(string);
860 static int line_count;
861 static int max_height;
862 static BOOL paged_mode;
864 void WCMD_enter_paged_mode(void)
866 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
868 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
869 max_height = consoleInfo.dwSize.Y;
873 line_count = 5; /* keep 5 lines from previous output */
876 void WCMD_leave_paged_mode(void)
881 /*******************************************************************
882 * WCMD_output_asis - send output to current standard output device.
883 * without formatting eg. when message contains '%'
886 void WCMD_output_asis (const char *message) {
893 if ((ptr = strchr(message, '\n')) != NULL) ptr++;
894 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message,
895 (ptr) ? ptr - message : lstrlen(message), &count, NULL);
897 if (++line_count >= max_height - 1) {
899 WCMD_output_asis (anykey);
900 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
903 } while ((message = ptr) != NULL);
905 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message, lstrlen(message), &count, NULL);
910 /***************************************************************************
911 * WCMD_strtrim_leading_spaces
913 * Remove leading spaces from a string. Return a pointer to the first
914 * non-space character. Does not modify the input string
917 char *WCMD_strtrim_leading_spaces (char *string) {
922 while (*ptr == ' ') ptr++;
926 /*************************************************************************
927 * WCMD_strtrim_trailing_spaces
929 * Remove trailing spaces from a string. This routine modifies the input
930 * string by placing a null after the last non-space character
933 void WCMD_strtrim_trailing_spaces (char *string) {
937 ptr = string + lstrlen (string) - 1;
938 while ((*ptr == ' ') && (ptr >= string)) {
944 /*************************************************************************
945 * WCMD_opt_s_strip_quotes
947 * Remove first and last quote characters, preserving all other text
950 void WCMD_opt_s_strip_quotes(char *cmd) {
951 char *src = cmd + 1, *dest = cmd, *lastq = NULL;
952 while((*dest=*src) != '\0') {
959 while ((*dest++=*lastq++) != 0)
964 /*************************************************************************
967 * Handle pipes within a command - the DOS way using temporary files.
970 void WCMD_pipe (char *command) {
973 char temp_path[MAX_PATH], temp_file[MAX_PATH], temp_file2[MAX_PATH], temp_cmd[1024];
975 GetTempPath (sizeof(temp_path), temp_path);
976 GetTempFileName (temp_path, "WCMD", 0, temp_file);
977 p = strchr(command, '|');
979 wsprintf (temp_cmd, "%s > %s", command, temp_file);
980 WCMD_process_command (temp_cmd);
982 while ((p = strchr(command, '|'))) {
984 GetTempFileName (temp_path, "WCMD", 0, temp_file2);
985 wsprintf (temp_cmd, "%s < %s > %s", command, temp_file, temp_file2);
986 WCMD_process_command (temp_cmd);
987 DeleteFile (temp_file);
988 lstrcpy (temp_file, temp_file2);
991 wsprintf (temp_cmd, "%s < %s", command, temp_file);
992 WCMD_process_command (temp_cmd);
993 DeleteFile (temp_file);