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 const char nyi[] = "Not Yet Implemented\n\n";
41 const char newline[] = "\n";
42 const char version_string[] = "WCMD Version " PACKAGE_VERSION "\n\n";
43 const char anykey[] = "Press Return key to continue: ";
44 char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
45 BATCH_CONTEXT *context = NULL;
46 static HANDLE old_stdin = INVALID_HANDLE_VALUE, old_stdout = INVALID_HANDLE_VALUE;
48 /*****************************************************************************
49 * Main entry point. This is a console application so we have a main() not a
53 int main (int argc, char *argv[])
59 int opt_c, opt_k, opt_q;
65 if ((*argv)[0]!='/' || (*argv)[1]=='\0') {
71 if (tolower(c)=='c') {
73 } else if (tolower(c)=='q') {
75 } else if (tolower(c)=='k') {
77 } else if (tolower(c)=='t' || tolower(c)=='x' || tolower(c)=='y') {
78 /* Ignored for compatibility with Windows */
83 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
86 if (opt_c || opt_k) /* break out of parsing immediately after c or k */
99 /* Build the command to execute */
101 for (arg = argv; *arg; arg++)
103 int has_space,bcount;
109 if( !*a ) has_space=1;
114 if (*a==' ' || *a=='\t') {
116 } else if (*a=='"') {
117 /* doubling of '\' preceding a '"',
118 * plus escaping of said '"'
126 len+=(a-*arg)+1 /* for the separating space */;
128 len+=2; /* for the quotes */
131 cmd = HeapAlloc(GetProcessHeap(), 0, len);
136 for (arg = argv; *arg; arg++)
138 int has_space,has_quote;
141 /* Check for quotes and spaces in this argument */
142 has_space=has_quote=0;
144 if( !*a ) has_space=1;
146 if (*a==' ' || *a=='\t') {
150 } else if (*a=='"') {
158 /* Now transfer it to the command line */
175 /* Double all the '\\' preceding this '"', plus one */
176 for (i=0;i<=bcount;i++)
195 p--; /* remove last space */
200 /* If we do a "wcmd /c command", we don't want to allocate a new
201 * console since the command returns immediately. Rather, we use
202 * the currently allocated input and output handles. This allows
203 * us to pipe to and read from the command interpreter.
205 if (strchr(cmd,'|') != NULL)
208 WCMD_process_command(cmd);
209 HeapFree(GetProcessHeap(), 0, cmd);
213 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
214 ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
215 SetConsoleTitle("Wine Command Prompt");
218 WCMD_process_command(cmd);
219 HeapFree(GetProcessHeap(), 0, cmd);
223 * If there is an AUTOEXEC.BAT file, try to execute it.
226 GetFullPathName ("\\autoexec.bat", sizeof(string), string, NULL);
227 h = CreateFile (string, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
228 if (h != INVALID_HANDLE_VALUE) {
231 WCMD_batch_command (string);
236 * Loop forever getting commands and executing them.
242 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
244 string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
245 if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
246 if (lstrlen (string) != 0) {
247 if (strchr(string,'|') != NULL) {
251 WCMD_process_command (string);
259 /*****************************************************************************
260 * Process one command. If the command is EXIT this routine does not return.
261 * We will recurse through here executing batch files.
265 void WCMD_process_command (char *command)
269 DWORD count, creationDisposition;
272 SECURITY_ATTRIBUTES sa;
275 * Expand up environment variables.
277 len = ExpandEnvironmentStrings (command, NULL, 0);
278 cmd = HeapAlloc( GetProcessHeap(), 0, len );
279 status = ExpandEnvironmentStrings (command, cmd, len);
282 HeapFree( GetProcessHeap(), 0, cmd );
287 * Changing default drive has to be handled as a special case.
290 if ((cmd[1] == ':') && IsCharAlpha (cmd[0]) && (strlen(cmd) == 2)) {
291 status = SetCurrentDirectory (cmd);
292 if (!status) WCMD_print_error ();
293 HeapFree( GetProcessHeap(), 0, cmd );
297 /* Don't issue newline WCMD_output (newline); @JED*/
299 sa.nLength = sizeof(sa);
300 sa.lpSecurityDescriptor = NULL;
301 sa.bInheritHandle = TRUE;
303 * Redirect stdin and/or stdout if required.
306 if ((p = strchr(cmd,'<')) != NULL) {
307 h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
308 FILE_ATTRIBUTE_NORMAL, NULL);
309 if (h == INVALID_HANDLE_VALUE) {
311 HeapFree( GetProcessHeap(), 0, cmd );
314 old_stdin = GetStdHandle (STD_INPUT_HANDLE);
315 SetStdHandle (STD_INPUT_HANDLE, h);
317 if ((p = strchr(cmd,'>')) != NULL) {
320 creationDisposition = OPEN_ALWAYS;
324 creationDisposition = CREATE_ALWAYS;
326 h = CreateFile (WCMD_parameter (p, 0, NULL), GENERIC_WRITE, 0, &sa, creationDisposition,
327 FILE_ATTRIBUTE_NORMAL, NULL);
328 if (h == INVALID_HANDLE_VALUE) {
330 HeapFree( GetProcessHeap(), 0, cmd );
333 if (SetFilePointer (h, 0, NULL, FILE_END) ==
334 INVALID_SET_FILE_POINTER) {
337 old_stdout = GetStdHandle (STD_OUTPUT_HANDLE);
338 SetStdHandle (STD_OUTPUT_HANDLE, h);
340 if ((p = strchr(cmd,'<')) != NULL) *p = '\0';
343 * Strip leading whitespaces, and a '@' if supplied
345 whichcmd = WCMD_strtrim_leading_spaces(cmd);
346 if (whichcmd[0] == '@') whichcmd++;
349 * Check if the command entered is internal. If it is, pass the rest of the
350 * line down to the command. If not try to run a program.
354 while (IsCharAlphaNumeric(whichcmd[count])) {
357 for (i=0; i<=WCMD_EXIT; i++) {
358 if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
359 whichcmd, count, inbuilt[i], -1) == 2) break;
361 p = WCMD_strtrim_leading_spaces (&whichcmd[count]);
362 WCMD_parse (p, quals, param1, param2);
366 WCMD_setshow_attrib ();
369 WCMD_run_program (p, 1);
373 WCMD_setshow_default ();
376 WCMD_clear_screen ();
385 WCMD_setshow_date ();
395 WCMD_echo(&whichcmd[count]);
420 WCMD_setshow_path (p);
426 WCMD_setshow_prompt ();
445 WCMD_setshow_env (p);
451 WCMD_setshow_time ();
454 if (strlen(&whichcmd[count]) > 0)
455 WCMD_title(&whichcmd[count+1]);
472 WCMD_run_program (whichcmd, 0);
474 HeapFree( GetProcessHeap(), 0, cmd );
475 if (old_stdin != INVALID_HANDLE_VALUE) {
476 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
477 SetStdHandle (STD_INPUT_HANDLE, old_stdin);
478 old_stdin = INVALID_HANDLE_VALUE;
480 if (old_stdout != INVALID_HANDLE_VALUE) {
481 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
482 SetStdHandle (STD_OUTPUT_HANDLE, old_stdout);
483 old_stdout = INVALID_HANDLE_VALUE;
487 static void init_msvcrt_io_block(STARTUPINFO* st)
490 /* fetch the parent MSVCRT info block if any, so that the child can use the
491 * same handles as its grand-father
493 st_p.cb = sizeof(STARTUPINFO);
494 GetStartupInfo(&st_p);
495 st->cbReserved2 = st_p.cbReserved2;
496 st->lpReserved2 = st_p.lpReserved2;
497 if (st_p.cbReserved2 && st_p.lpReserved2 &&
498 (old_stdin != INVALID_HANDLE_VALUE || old_stdout != INVALID_HANDLE_VALUE))
500 /* Override the entries for fd 0,1,2 if we happened
501 * to change those std handles (this depends on the way wcmd sets
502 * it's new input & output handles)
504 size_t sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
505 BYTE* ptr = HeapAlloc(GetProcessHeap(), 0, sz);
508 unsigned num = *(unsigned*)st_p.lpReserved2;
509 char* flags = (char*)(ptr + sizeof(unsigned));
510 HANDLE* handles = (HANDLE*)(flags + num * sizeof(char));
512 memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
513 st->cbReserved2 = sz;
514 st->lpReserved2 = ptr;
516 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
517 if (num <= 0 || (flags[0] & WX_OPEN))
519 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
522 if (num <= 1 || (flags[1] & WX_OPEN))
524 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
527 if (num <= 2 || (flags[2] & WX_OPEN))
529 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
537 /******************************************************************************
540 * Execute a command line as an external program. If no extension given then
541 * precedence is given to .BAT files. Must allow recursion.
543 * called is 1 if the program was invoked with a CALL command - removed
544 * from command -. It is only used for batch programs.
546 * FIXME: Case sensitivity in suffixes!
549 void WCMD_run_program (char *command, int called) {
552 PROCESS_INFORMATION pe;
558 char filetorun[MAX_PATH];
560 WCMD_parse (command, quals, param1, param2); /* Quick way to get the filename */
561 if (!(*param1) && !(*param2))
563 if (strpbrk (param1, "/\\:") == NULL) { /* No explicit path given */
564 char *ext = strrchr( param1, '.' );
565 if (!ext || !strcasecmp( ext, ".bat"))
567 if (SearchPath (NULL, param1, ".bat", sizeof(filetorun), filetorun, NULL)) {
568 WCMD_batch (filetorun, command, called);
572 if (!ext || !strcasecmp( ext, ".cmd"))
574 if (SearchPath (NULL, param1, ".cmd", sizeof(filetorun), filetorun, NULL)) {
575 WCMD_batch (filetorun, command, called);
580 else { /* Explicit path given */
581 char *ext = strrchr( param1, '.' );
582 if (ext && (!strcasecmp( ext, ".bat" ) || !strcasecmp( ext, ".cmd" )))
584 WCMD_batch (param1, command, called);
588 if (ext && strpbrk( ext, "/\\:" )) ext = NULL;
591 strcpy (filetorun, param1);
592 strcat (filetorun, ".bat");
593 h = CreateFile (filetorun, GENERIC_READ, FILE_SHARE_READ,
594 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
595 if (h != INVALID_HANDLE_VALUE) {
597 WCMD_batch (param1, command, called);
603 /* No batch file found, assume executable */
605 hinst = FindExecutable (param1, NULL, filetorun);
606 if ((INT_PTR)hinst < 32)
609 console = SHGetFileInfo (filetorun, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
611 ZeroMemory (&st, sizeof(STARTUPINFO));
612 st.cb = sizeof(STARTUPINFO);
613 init_msvcrt_io_block(&st);
615 status = CreateProcess (NULL, command, NULL, NULL, TRUE,
616 0, NULL, NULL, &st, &pe);
621 if (!console) errorlevel = 0;
624 if (!HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
625 GetExitCodeProcess (pe.hProcess, &errorlevel);
626 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
628 CloseHandle(pe.hProcess);
629 CloseHandle(pe.hThread);
632 /******************************************************************************
635 * Display the prompt on STDout
639 void WCMD_show_prompt (void) {
642 char out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
645 status = GetEnvironmentVariable ("PROMPT", prompt_string, sizeof(prompt_string));
646 if ((status == 0) || (status > sizeof(prompt_string))) {
647 lstrcpy (prompt_string, "$P$G");
659 switch (toupper(*p)) {
667 GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
680 status = GetCurrentDirectory (sizeof(curdir), curdir);
686 status = GetCurrentDirectory (sizeof(curdir), curdir);
696 GetTimeFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
700 lstrcat (q, version_string);
711 WCMD_output_asis (out_string);
714 /****************************************************************************
717 * Print the message for GetLastError
720 void WCMD_print_error (void) {
725 error_code = GetLastError ();
726 status = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
727 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
729 WCMD_output ("FIXME: Cannot display message for error %d, status %d\n",
730 error_code, GetLastError());
733 WCMD_output_asis (lpMsgBuf);
734 LocalFree ((HLOCAL)lpMsgBuf);
735 WCMD_output_asis (newline);
739 /*******************************************************************
740 * WCMD_parse - parse a command into parameters and qualifiers.
742 * On exit, all qualifiers are concatenated into q, the first string
743 * not beginning with "/" is in p1 and the
744 * second in p2. Any subsequent non-qualifier strings are lost.
745 * Parameters in quotes are handled.
748 void WCMD_parse (char *s, char *q, char *p1, char *p2) {
752 *q = *p1 = *p2 = '\0';
757 while ((*s != '\0') && (*s != ' ') && *s != '/') {
758 *q++ = toupper (*s++);
768 while ((*s != '\0') && (*s != '"')) {
769 if (p == 0) *p1++ = *s++;
770 else if (p == 1) *p2++ = *s++;
773 if (p == 0) *p1 = '\0';
774 if (p == 1) *p2 = '\0';
781 while ((*s != '\0') && (*s != ' ') && (*s != '\t')) {
782 if (p == 0) *p1++ = *s++;
783 else if (p == 1) *p2++ = *s++;
786 if (p == 0) *p1 = '\0';
787 if (p == 1) *p2 = '\0';
793 /*******************************************************************
794 * WCMD_output - send output to current standard output device.
798 void WCMD_output (const char *format, ...) {
805 ret = vsnprintf (string, sizeof( string), format, ap);
807 if( ret >= sizeof( string)) {
808 WCMD_output_asis("ERR: output truncated in WCMD_output\n" );
809 string[sizeof( string) -1] = '\0';
811 WCMD_output_asis(string);
815 static int line_count;
816 static int max_height;
817 static BOOL paged_mode;
819 void WCMD_enter_paged_mode(void)
821 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
823 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
824 max_height = consoleInfo.dwSize.Y;
828 line_count = 5; /* keep 5 lines from previous output */
831 void WCMD_leave_paged_mode(void)
836 /*******************************************************************
837 * WCMD_output_asis - send output to current standard output device.
838 * without formatting eg. when message contains '%'
841 void WCMD_output_asis (const char *message) {
848 if ((ptr = strchr(message, '\n')) != NULL) ptr++;
849 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message,
850 (ptr) ? ptr - message : lstrlen(message), &count, NULL);
852 if (++line_count >= max_height - 1) {
854 WCMD_output_asis (anykey);
855 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
858 } while ((message = ptr) != NULL);
860 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message, lstrlen(message), &count, NULL);
865 /***************************************************************************
866 * WCMD_strtrim_leading_spaces
868 * Remove leading spaces from a string. Return a pointer to the first
869 * non-space character. Does not modify the input string
872 char *WCMD_strtrim_leading_spaces (char *string) {
877 while (*ptr == ' ') ptr++;
881 /*************************************************************************
882 * WCMD_strtrim_trailing_spaces
884 * Remove trailing spaces from a string. This routine modifies the input
885 * string by placing a null after the last non-space character
888 void WCMD_strtrim_trailing_spaces (char *string) {
892 ptr = string + lstrlen (string) - 1;
893 while ((*ptr == ' ') && (ptr >= string)) {
899 /*************************************************************************
902 * Handle pipes within a command - the DOS way using temporary files.
905 void WCMD_pipe (char *command) {
908 char temp_path[MAX_PATH], temp_file[MAX_PATH], temp_file2[MAX_PATH], temp_cmd[1024];
910 GetTempPath (sizeof(temp_path), temp_path);
911 GetTempFileName (temp_path, "WCMD", 0, temp_file);
912 p = strchr(command, '|');
914 wsprintf (temp_cmd, "%s > %s", command, temp_file);
915 WCMD_process_command (temp_cmd);
917 while ((p = strchr(command, '|'))) {
919 GetTempFileName (temp_path, "WCMD", 0, temp_file2);
920 wsprintf (temp_cmd, "%s < %s > %s", command, temp_file, temp_file2);
921 WCMD_process_command (temp_cmd);
922 DeleteFile (temp_file);
923 lstrcpy (temp_file, temp_file2);
926 wsprintf (temp_cmd, "%s < %s", command, temp_file);
927 WCMD_process_command (temp_cmd);
928 DeleteFile (temp_file);