/
cmd.c
2428 lines (2138 loc) · 67.1 KB
/
cmd.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* CMD.C - command-line interface.
*
*
* History:
*
* 17 Jun 1994 (Tim Norman)
* started.
*
* 08 Aug 1995 (Matt Rains)
* I have cleaned up the source code. changes now bring this source
* into guidelines for recommended programming practice.
*
* A added the the standard FreeDOS GNU licence test to the
* initialize() function.
*
* Started to replace puts() with printf(). this will help
* standardize output. please follow my lead.
*
* I have added some constants to help making changes easier.
*
* 15 Dec 1995 (Tim Norman)
* major rewrite of the code to make it more efficient and add
* redirection support (finally!)
*
* 06 Jan 1996 (Tim Norman)
* finished adding redirection support! Changed to use our own
* exec code (MUCH thanks to Svante Frey!!)
*
* 29 Jan 1996 (Tim Norman)
* added support for CHDIR, RMDIR, MKDIR, and ERASE, as per
* suggestion of Steffan Kaiser
*
* changed "file not found" error message to "bad command or
* filename" thanks to Dustin Norman for noticing that confusing
* message!
*
* changed the format to call internal commands (again) so that if
* they want to split their commands, they can do it themselves
* (none of the internal functions so far need that much power, anyway)
*
* 27 Aug 1996 (Tim Norman)
* added in support for Oliver Mueller's ALIAS command
*
* 14 Jun 1997 (Steffan Kaiser)
* added ctrl-break handling and error level
*
* 16 Jun 1998 (Rob Lake)
* Runs command.com if /P is specified in command line. Command.com
* also stays permanent. If /C is in the command line, starts the
* program next in the line.
*
* 21 Jun 1998 (Rob Lake)
* Fixed up /C so that arguments for the program
*
* 08-Jul-1998 (John P. Price)
* Now sets COMSPEC environment variable
* misc clean up and optimization
* added date and time commands
* changed to using spawnl instead of exec. exec does not copy the
* environment to the child process!
*
* 14 Jul 1998 (Hans B Pufal)
* Reorganised source to be more efficient and to more closely
* follow MS-DOS conventions. (eg %..% environment variable
* replacement works form command line as well as batch file.
*
* New organisation also properly support nested batch files.
*
* New command table structure is half way towards providing a
* system in which COMMAND will find out what internal commands
* are loaded
*
* 24 Jul 1998 (Hans B Pufal) [HBP_003]
* Fixed return value when called with /C option
*
* 27 Jul 1998 John P. Price
* added config.h include
*
* 28 Jul 1998 John P. Price
* added showcmds function to show commands and options available
*
* 07-Aug-1998 (John P Price <linux-guru@gcfl.net>)
* Fixed carriage return output to better match MSDOS with echo
* on or off. (marked with "JPP 19980708")
*
* 07-Dec-1998 (Eric Kohl)
* First ReactOS release.
* Extended length of commandline buffers to 512.
*
* 13-Dec-1998 (Eric Kohl)
* Added COMSPEC environment variable.
* Added "/t" support (color) on cmd command line.
*
* 07-Jan-1999 (Eric Kohl)
* Added help text ("cmd /?").
*
* 25-Jan-1999 (Eric Kohl)
* Unicode and redirection safe!
* Fixed redirections and piping.
* Piping is based on temporary files, but basic support
* for anonymous pipes already exists.
*
* 27-Jan-1999 (Eric Kohl)
* Replaced spawnl() by CreateProcess().
*
* 22-Oct-1999 (Eric Kohl)
* Added break handler.
*
* 15-Dec-1999 (Eric Kohl)
* Fixed current directory
*
* 28-Dec-1999 (Eric Kohl)
* Restore window title after program/batch execution
*
* 03-Feb-2001 (Eric Kohl)
* Workaround because argc[0] is NULL under ReactOS
*
* 23-Feb-2001 (Carl Nettelblad <cnettel@hem.passagen.se>)
* %envvar% replacement conflicted with for.
*
* 30-Apr-2004 (Filip Navara <xnavara@volny.cz>)
* Make MakeSureDirectoryPathExistsEx unicode safe.
*
* 28-Mai-2004
* Removed MakeSureDirectoryPathExistsEx.
* Use the current directory if GetTempPath fails.
*
* 12-Jul-2004 (Jens Collin <jens.collin@lakhei.com>)
* Added ShellExecute call when all else fails to be able to "launch" any file.
*
* 02-Apr-2005 (Magnus Olsen <magnus@greatlord.com>)
* Remove all hardcode string to En.rc
*
* 06-May-2005 (Klemens Friedl <frik85@gmail.com>)
* Add 'help' command (list all commands plus description)
*
* 06-jul-2005 (Magnus Olsen <magnus@greatlord.com>)
* translate '%errorlevel%' to the internal value.
* Add proper memory alloc ProcessInput, the error
* handling for memory handling need to be improve
*/
#include "precomp.h"
#include <reactos/buildno.h>
#include <reactos/version.h>
typedef NTSTATUS (WINAPI *NtQueryInformationProcessProc)(HANDLE, PROCESSINFOCLASS,
PVOID, ULONG, PULONG);
typedef NTSTATUS (WINAPI *NtReadVirtualMemoryProc)(HANDLE, PVOID, PVOID, SIZE_T, PSIZE_T);
BOOL bExit = FALSE; /* Indicates EXIT was typed */
BOOL bCanExit = TRUE; /* Indicates if this shell is exitable */
BOOL bCtrlBreak = FALSE; /* Ctrl-Break or Ctrl-C hit */
BOOL bIgnoreEcho = FALSE; /* Set this to TRUE to prevent a newline, when executing a command */
static BOOL fSingleCommand = 0; /* When we are executing something passed on the command line after /C or /K */
static BOOL bAlwaysStrip = FALSE;
INT nErrorLevel = 0; /* Errorlevel of last launched external program */
CRITICAL_SECTION ChildProcessRunningLock;
BOOL bDisableBatchEcho = FALSE;
BOOL bEnableExtensions = TRUE;
BOOL bDelayedExpansion = FALSE;
DWORD dwChildProcessId = 0;
LPTSTR lpOriginalEnvironment;
HANDLE CMD_ModuleHandle;
BOOL bTitleSet = FALSE; /* Indicates whether the console title has been changed and needs to be restored later */
TCHAR szCurTitle[MAX_PATH];
static NtQueryInformationProcessProc NtQueryInformationProcessPtr = NULL;
static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr = NULL;
/*
* Default output file stream translation mode is UTF8, but CMD switches
* allow to change it to either UTF16 (/U) or ANSI (/A).
*/
CON_STREAM_MODE OutputStreamMode = UTF8Text; // AnsiText;
#ifdef INCLUDE_CMD_COLOR
WORD wDefColor = 0; /* Default color */
#endif
/*
* convert
*
* insert commas into a number
*/
INT
ConvertULargeInteger(ULONGLONG num, LPTSTR des, UINT len, BOOL bPutSeparator)
{
TCHAR temp[39]; /* maximum length with nNumberGroups == 1 */
UINT n, iTarget;
if (len <= 1)
return 0;
n = 0;
iTarget = nNumberGroups;
if (!nNumberGroups)
bPutSeparator = FALSE;
do
{
if (iTarget == n && bPutSeparator)
{
iTarget += nNumberGroups + 1;
temp[38 - n++] = cThousandSeparator;
}
temp[38 - n++] = (TCHAR)(num % 10) + _T('0');
num /= 10;
} while (num > 0);
if (n > len-1)
n = len-1;
memcpy(des, temp + 39 - n, n * sizeof(TCHAR));
des[n] = _T('\0');
return n;
}
/*
* Is a process a console process?
*/
static BOOL IsConsoleProcess(HANDLE Process)
{
NTSTATUS Status;
PROCESS_BASIC_INFORMATION Info;
PEB ProcessPeb;
SIZE_T BytesRead;
if (NULL == NtQueryInformationProcessPtr || NULL == NtReadVirtualMemoryPtr)
{
return TRUE;
}
Status = NtQueryInformationProcessPtr (
Process, ProcessBasicInformation,
&Info, sizeof(PROCESS_BASIC_INFORMATION), NULL);
if (! NT_SUCCESS(Status))
{
WARN ("NtQueryInformationProcess failed with status %08x\n", Status);
return TRUE;
}
Status = NtReadVirtualMemoryPtr (
Process, Info.PebBaseAddress, &ProcessPeb,
sizeof(PEB), &BytesRead);
if (! NT_SUCCESS(Status) || sizeof(PEB) != BytesRead)
{
WARN ("Couldn't read virt mem status %08x bytes read %Iu\n", Status, BytesRead);
return TRUE;
}
return IMAGE_SUBSYSTEM_WINDOWS_CUI == ProcessPeb.ImageSubsystem;
}
#ifdef _UNICODE
#define SHELLEXECUTETEXT "ShellExecuteExW"
#else
#define SHELLEXECUTETEXT "ShellExecuteExA"
#endif
typedef BOOL (WINAPI *MYEX)(LPSHELLEXECUTEINFO lpExecInfo);
HANDLE RunFile(DWORD flags, LPTSTR filename, LPTSTR params,
LPTSTR directory, INT show)
{
SHELLEXECUTEINFO sei;
HMODULE hShell32;
MYEX hShExt;
BOOL ret;
TRACE ("RunFile(%s)\n", debugstr_aw(filename));
hShell32 = LoadLibrary(_T("SHELL32.DLL"));
if (!hShell32)
{
WARN ("RunFile: couldn't load SHELL32.DLL!\n");
return NULL;
}
hShExt = (MYEX)(FARPROC)GetProcAddress(hShell32, SHELLEXECUTETEXT);
if (!hShExt)
{
WARN ("RunFile: couldn't find ShellExecuteExA/W in SHELL32.DLL!\n");
FreeLibrary(hShell32);
return NULL;
}
TRACE ("RunFile: ShellExecuteExA/W is at %x\n", hShExt);
memset(&sei, 0, sizeof sei);
sei.cbSize = sizeof sei;
sei.fMask = flags;
sei.lpFile = filename;
sei.lpParameters = params;
sei.lpDirectory = directory;
sei.nShow = show;
ret = hShExt(&sei);
TRACE ("RunFile: ShellExecuteExA/W returned 0x%p\n", ret);
FreeLibrary(hShell32);
return ret ? sei.hProcess : NULL;
}
static VOID
SetConTitle(LPCTSTR pszTitle)
{
TCHAR szNewTitle[MAX_PATH];
if (!pszTitle)
return;
/* Don't do anything if we run inside a batch file, or we are just running a single command */
if (bc || (fSingleCommand == 1))
return;
/* Save the original console title and build a new one */
GetConsoleTitle(szCurTitle, ARRAYSIZE(szCurTitle));
StringCchPrintf(szNewTitle, ARRAYSIZE(szNewTitle),
_T("%s - %s"), szCurTitle, pszTitle);
bTitleSet = TRUE;
ConSetTitle(szNewTitle);
}
static VOID
ResetConTitle(VOID)
{
/* Restore the original console title */
if (!bc && bTitleSet)
{
ConSetTitle(szCurTitle);
bTitleSet = FALSE;
}
}
/*
* This command (in First) was not found in the command table
*
* Full - output buffer to hold whole command line
* First - first word on command line
* Rest - rest of command line
*/
static INT
Execute(LPTSTR Full, LPTSTR First, LPTSTR Rest, PARSED_COMMAND *Cmd)
{
TCHAR *first, *rest, *dot;
DWORD dwExitCode = 0;
TCHAR *FirstEnd;
TCHAR szFullName[MAX_PATH];
TCHAR szFullCmdLine[CMDLINE_LENGTH];
TRACE ("Execute: \'%s\' \'%s\'\n", debugstr_aw(First), debugstr_aw(Rest));
/* Though it was already parsed once, we have a different set of rules
for parsing before we pass to CreateProcess */
if (First[0] == _T('/') || (First[0] && First[1] == _T(':')))
{
/* Use the entire first word as the program name (no change) */
FirstEnd = First + _tcslen(First);
}
else
{
/* If present in the first word, spaces and ,;=/ end the program
* name and become the beginning of its parameters. */
BOOL bInside = FALSE;
for (FirstEnd = First; *FirstEnd; FirstEnd++)
{
if (!bInside && (_istspace(*FirstEnd) || _tcschr(_T(",;=/"), *FirstEnd)))
break;
bInside ^= *FirstEnd == _T('"');
}
}
/* Copy the new first/rest into the buffer */
rest = &Full[FirstEnd - First + 1];
_tcscpy(rest, FirstEnd);
_tcscat(rest, Rest);
first = Full;
*FirstEnd = _T('\0');
_tcscpy(first, First);
/* check for a drive change */
if ((_istalpha (first[0])) && (!_tcscmp (first + 1, _T(":"))))
{
BOOL working = TRUE;
if (!SetCurrentDirectory(first))
{
/* Guess they changed disc or something, handle that gracefully and get to root */
TCHAR str[4];
str[0]=first[0];
str[1]=_T(':');
str[2]=_T('\\');
str[3]=0;
working = SetCurrentDirectory(str);
}
if (!working) ConErrResPuts (STRING_FREE_ERROR1);
return !working;
}
/* get the PATH environment variable and parse it */
/* search the PATH environment variable for the binary */
StripQuotes(First);
if (!SearchForExecutable(First, szFullName))
{
error_bad_command(first);
return 1;
}
/* Set the new console title */
FirstEnd = first + (FirstEnd - First); /* Point to the separating NULL in the full built string */
*FirstEnd = _T(' ');
SetConTitle(Full);
/* check if this is a .BAT or .CMD file */
dot = _tcsrchr (szFullName, _T('.'));
if (dot && (!_tcsicmp (dot, _T(".bat")) || !_tcsicmp (dot, _T(".cmd"))))
{
while (*rest == _T(' '))
rest++;
*FirstEnd = _T('\0');
TRACE ("[BATCH: %s %s]\n", debugstr_aw(szFullName), debugstr_aw(rest));
dwExitCode = Batch(szFullName, first, rest, Cmd);
}
else
{
/* exec the program */
PROCESS_INFORMATION prci;
STARTUPINFO stui;
/* build command line for CreateProcess(): FullName + " " + rest */
BOOL quoted = !!_tcschr(First, _T(' '));
_tcscpy(szFullCmdLine, quoted ? _T("\"") : _T(""));
_tcsncat(szFullCmdLine, First, CMDLINE_LENGTH - _tcslen(szFullCmdLine) - 1);
_tcsncat(szFullCmdLine, quoted ? _T("\"") : _T(""), CMDLINE_LENGTH - _tcslen(szFullCmdLine) - 1);
if (*rest)
{
_tcsncat(szFullCmdLine, _T(" "), CMDLINE_LENGTH - _tcslen(szFullCmdLine) - 1);
_tcsncat(szFullCmdLine, rest, CMDLINE_LENGTH - _tcslen(szFullCmdLine) - 1);
}
TRACE ("[EXEC: %s]\n", debugstr_aw(szFullCmdLine));
/* fill startup info */
memset(&stui, 0, sizeof(stui));
stui.cb = sizeof(stui);
stui.lpTitle = Full;
stui.dwFlags = STARTF_USESHOWWINDOW;
stui.wShowWindow = SW_SHOWDEFAULT;
/* Set the console to standard mode */
SetConsoleMode(ConStreamGetOSHandle(StdIn),
ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
if (CreateProcess(szFullName,
szFullCmdLine,
NULL,
NULL,
TRUE,
0,
NULL,
NULL,
&stui,
&prci))
{
CloseHandle(prci.hThread);
}
else
{
// See if we can run this with ShellExecute() ie myfile.xls
prci.hProcess = RunFile(SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NO_CONSOLE,
szFullName,
rest,
NULL,
SW_SHOWNORMAL);
}
*FirstEnd = _T('\0');
if (prci.hProcess != NULL)
{
if (bc != NULL || fSingleCommand != 0 || IsConsoleProcess(prci.hProcess))
{
/* when processing a batch file or starting console processes: execute synchronously */
EnterCriticalSection(&ChildProcessRunningLock);
dwChildProcessId = prci.dwProcessId;
WaitForSingleObject(prci.hProcess, INFINITE);
LeaveCriticalSection(&ChildProcessRunningLock);
GetExitCodeProcess(prci.hProcess, &dwExitCode);
nErrorLevel = (INT)dwExitCode;
}
CloseHandle(prci.hProcess);
}
else
{
TRACE ("[ShellExecute failed!: %s]\n", debugstr_aw(Full));
error_bad_command(first);
dwExitCode = 1;
}
/* Restore the default console mode */
SetConsoleMode(ConStreamGetOSHandle(StdIn),
ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
SetConsoleMode(ConStreamGetOSHandle(StdOut),
ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
}
/* Update the local code page cache */
{
UINT uNewInputCodePage = GetConsoleCP();
UINT uNewOutputCodePage = GetConsoleOutputCP();
if ((InputCodePage != uNewInputCodePage) ||
(OutputCodePage != uNewOutputCodePage))
{
InputCodePage = uNewInputCodePage;
OutputCodePage = uNewOutputCodePage;
/* Reset the current thread UI language */
if (IsConsoleHandle(ConStreamGetOSHandle(StdOut)) ||
IsConsoleHandle(ConStreamGetOSHandle(StdErr)))
{
ConSetThreadUILanguage(0);
}
/* Update the streams cached code page */
ConStdStreamsSetCacheCodePage(InputCodePage, OutputCodePage);
/* Update the locale as well */
InitLocale();
}
}
/* Restore the original console title */
ResetConTitle();
return dwExitCode;
}
/*
* Look through the internal commands and determine whether or not this
* command is one of them. If it is, call the command. If not, call
* execute to run it as an external program.
*
* first - first word on command line
* rest - rest of command line
*/
INT
DoCommand(LPTSTR first, LPTSTR rest, PARSED_COMMAND *Cmd)
{
TCHAR *com;
TCHAR *cp;
LPTSTR param; /* Pointer to command's parameters */
INT cl;
LPCOMMAND cmdptr;
BOOL nointernal = FALSE;
INT ret;
TRACE ("DoCommand: (\'%s\' \'%s\')\n", debugstr_aw(first), debugstr_aw(rest));
/* Full command line */
com = cmd_alloc((_tcslen(first) + _tcslen(rest) + 2) * sizeof(TCHAR));
if (com == NULL)
{
error_out_of_memory();
return 1;
}
/* If present in the first word, these characters end the name of an
* internal command and become the beginning of its parameters. */
cp = first + _tcscspn(first, _T("\t +,/;=[]"));
for (cl = 0; cl < (cp - first); cl++)
{
/* These characters do it too, but if one of them is present,
* then we check to see if the word is a file name and skip
* checking for internal commands if so.
* This allows running programs with names like "echo.exe" */
if (_tcschr(_T(".:\\"), first[cl]))
{
TCHAR tmp = *cp;
*cp = _T('\0');
nointernal = IsExistingFile(first);
*cp = tmp;
break;
}
}
/* Scan internal command table */
for (cmdptr = cmds; !nointernal && cmdptr->name; cmdptr++)
{
if (!_tcsnicmp(first, cmdptr->name, cl) && cmdptr->name[cl] == _T('\0'))
{
_tcscpy(com, first);
_tcscat(com, rest);
param = &com[cl];
/* Skip over whitespace to rest of line, exclude 'echo' command */
if (_tcsicmp(cmdptr->name, _T("echo")) != 0)
{
while (_istspace(*param))
param++;
}
/* Set the new console title */
SetConTitle(com);
ret = cmdptr->func(param);
/* Restore the original console title */
ResetConTitle();
cmd_free(com);
return ret;
}
}
ret = Execute(com, first, rest, Cmd);
cmd_free(com);
return ret;
}
/*
* process the command line and execute the appropriate functions
* full input/output redirection and piping are supported
*/
INT ParseCommandLine(LPTSTR cmd)
{
INT Ret = 0;
PARSED_COMMAND *Cmd;
Cmd = ParseCommand(cmd);
if (!Cmd)
{
/* Return an adequate error code */
return (!bParseError ? 0 : 1);
}
Ret = ExecuteCommand(Cmd);
FreeCommand(Cmd);
return Ret;
}
/* Execute a command without waiting for it to finish. If it's an internal
* command or batch file, we must create a new cmd.exe process to handle it.
* TODO: For now, this just always creates a cmd.exe process.
* This works, but is inefficient for running external programs,
* which could just be run directly. */
static HANDLE
ExecuteAsync(PARSED_COMMAND *Cmd)
{
TCHAR CmdPath[MAX_PATH];
TCHAR CmdParams[CMDLINE_LENGTH], *ParamsEnd;
STARTUPINFO stui;
PROCESS_INFORMATION prci;
/* Get the path to cmd.exe */
GetModuleFileName(NULL, CmdPath, ARRAYSIZE(CmdPath));
/* Build the parameter string to pass to cmd.exe */
ParamsEnd = _stpcpy(CmdParams, _T("/S/D/C\""));
ParamsEnd = UnparseCommand(Cmd, ParamsEnd, &CmdParams[CMDLINE_LENGTH - 2]);
if (!ParamsEnd)
{
error_out_of_memory();
return NULL;
}
_tcscpy(ParamsEnd, _T("\""));
memset(&stui, 0, sizeof stui);
stui.cb = sizeof(STARTUPINFO);
if (!CreateProcess(CmdPath, CmdParams, NULL, NULL, TRUE, 0,
NULL, NULL, &stui, &prci))
{
ErrorMessage(GetLastError(), NULL);
return NULL;
}
CloseHandle(prci.hThread);
return prci.hProcess;
}
static INT
ExecutePipeline(PARSED_COMMAND *Cmd)
{
#ifdef FEATURE_REDIRECTION
HANDLE hInput = NULL;
HANDLE hOldConIn = GetStdHandle(STD_INPUT_HANDLE);
HANDLE hOldConOut = GetStdHandle(STD_OUTPUT_HANDLE);
HANDLE hProcess[MAXIMUM_WAIT_OBJECTS];
INT nProcesses = 0;
DWORD dwExitCode;
/* Do all but the last pipe command */
do
{
HANDLE hPipeRead, hPipeWrite;
if (nProcesses > (MAXIMUM_WAIT_OBJECTS - 2))
{
error_too_many_parameters(_T("|"));
goto failed;
}
/* Create the pipe that this process will write into.
* Make the handles non-inheritable initially, because this
* process shouldn't inherit the reading handle. */
if (!CreatePipe(&hPipeRead, &hPipeWrite, NULL, 0))
{
error_no_pipe();
goto failed;
}
/* The writing side of the pipe is STDOUT for this process */
SetHandleInformation(hPipeWrite, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
SetStdHandle(STD_OUTPUT_HANDLE, hPipeWrite);
/* Execute it (error check is done later for easier cleanup) */
hProcess[nProcesses] = ExecuteAsync(Cmd->Subcommands);
CloseHandle(hPipeWrite);
if (hInput)
CloseHandle(hInput);
/* The reading side of the pipe will be STDIN for the next process */
SetHandleInformation(hPipeRead, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
SetStdHandle(STD_INPUT_HANDLE, hPipeRead);
hInput = hPipeRead;
if (!hProcess[nProcesses])
goto failed;
nProcesses++;
Cmd = Cmd->Subcommands->Next;
} while (Cmd->Type == C_PIPE);
/* The last process uses the original STDOUT */
SetStdHandle(STD_OUTPUT_HANDLE, hOldConOut);
hProcess[nProcesses] = ExecuteAsync(Cmd);
if (!hProcess[nProcesses])
goto failed;
nProcesses++;
CloseHandle(hInput);
SetStdHandle(STD_INPUT_HANDLE, hOldConIn);
/* Wait for all processes to complete */
EnterCriticalSection(&ChildProcessRunningLock);
WaitForMultipleObjects(nProcesses, hProcess, TRUE, INFINITE);
LeaveCriticalSection(&ChildProcessRunningLock);
/* Use the exit code of the last process in the pipeline */
GetExitCodeProcess(hProcess[nProcesses - 1], &dwExitCode);
nErrorLevel = (INT)dwExitCode;
while (--nProcesses >= 0)
CloseHandle(hProcess[nProcesses]);
return nErrorLevel;
failed:
if (hInput)
CloseHandle(hInput);
while (--nProcesses >= 0)
{
TerminateProcess(hProcess[nProcesses], 0);
CloseHandle(hProcess[nProcesses]);
}
SetStdHandle(STD_INPUT_HANDLE, hOldConIn);
SetStdHandle(STD_OUTPUT_HANDLE, hOldConOut);
#endif
return nErrorLevel;
}
INT
ExecuteCommand(
IN PARSED_COMMAND *Cmd)
{
#define SeenGoto() \
(bc && bc->current == NULL)
PARSED_COMMAND *Sub;
LPTSTR First, Rest;
INT Ret = 0;
/* If we don't have any command, or if this is REM, ignore it */
if (!Cmd || (Cmd->Type == C_REM))
return 0;
/*
* Do not execute any command if we are about to exit CMD, or about to
* change batch execution context, e.g. in case of a CALL / GOTO / EXIT.
*/
if (bExit || SeenGoto())
return 0;
if (!PerformRedirection(Cmd->Redirections))
return 1;
switch (Cmd->Type)
{
case C_COMMAND:
Ret = 1;
First = DoDelayedExpansion(Cmd->Command.First);
if (First)
{
Rest = DoDelayedExpansion(Cmd->Command.Rest);
if (Rest)
{
Ret = DoCommand(First, Rest, Cmd);
cmd_free(Rest);
}
cmd_free(First);
}
/* Fall through */
case C_REM:
break;
case C_QUIET:
case C_BLOCK:
case C_MULTI:
for (Sub = Cmd->Subcommands; Sub && !SeenGoto(); Sub = Sub->Next)
Ret = ExecuteCommand(Sub);
break;
case C_OR:
Sub = Cmd->Subcommands;
Ret = ExecuteCommand(Sub);
if ((Ret != 0) && !SeenGoto())
{
nErrorLevel = Ret;
Ret = ExecuteCommand(Sub->Next);
}
break;
case C_AND:
Sub = Cmd->Subcommands;
Ret = ExecuteCommand(Sub);
if ((Ret == 0) && !SeenGoto())
Ret = ExecuteCommand(Sub->Next);
break;
case C_PIPE:
Ret = ExecutePipeline(Cmd);
break;
case C_FOR:
Ret = ExecuteFor(Cmd);
break;
case C_IF:
Ret = ExecuteIf(Cmd);
break;
}
UndoRedirection(Cmd->Redirections, NULL);
return Ret;
#undef SeenGoto
}
INT
ExecuteCommandWithEcho(
IN PARSED_COMMAND *Cmd)
{
/* Echo the reconstructed command line */
if (bEcho && !bDisableBatchEcho && Cmd && (Cmd->Type != C_QUIET))
{
if (!bIgnoreEcho)
ConOutChar(_T('\n'));
PrintPrompt();
EchoCommand(Cmd);
ConOutChar(_T('\n'));
}
/* Run the command */
return ExecuteCommand(Cmd);
}
LPTSTR
GetEnvVar(LPCTSTR varName)
{
static LPTSTR ret = NULL;
UINT size;
cmd_free(ret);
ret = NULL;
size = GetEnvironmentVariable(varName, NULL, 0);
if (size > 0)
{
ret = cmd_alloc(size * sizeof(TCHAR));
if (ret != NULL)
GetEnvironmentVariable(varName, ret, size + 1);
}
return ret;
}
LPCTSTR
GetEnvVarOrSpecial(LPCTSTR varName)
{
static TCHAR ret[MAX_PATH];
LPTSTR var = GetEnvVar(varName);
if (var)
return var;
/* The environment variable doesn't exist, look for
* a "special" one only if extensions are enabled. */
if (!bEnableExtensions)
return NULL;
/* %CD% */
if (_tcsicmp(varName, _T("CD")) == 0)
{
GetCurrentDirectory(ARRAYSIZE(ret), ret);
return ret;
}
/* %DATE% */
else if (_tcsicmp(varName, _T("DATE")) == 0)
{
return GetDateString();
}
/* %TIME% */
else if (_tcsicmp(varName, _T("TIME")) == 0)
{
return GetTimeString();
}
/* %RANDOM% */
else if (_tcsicmp(varName, _T("RANDOM")) == 0)
{
/* Get random number */
_itot(rand(), ret, 10);
return ret;
}
/* %CMDCMDLINE% */
else if (_tcsicmp(varName, _T("CMDCMDLINE")) == 0)
{
return GetCommandLine();
}
/* %CMDEXTVERSION% */
else if (_tcsicmp(varName, _T("CMDEXTVERSION")) == 0)
{
/* Set Command Extensions version number to CMDEXTVERSION */
_itot(CMDEXTVERSION, ret, 10);
return ret;
}
/* %ERRORLEVEL% */
else if (_tcsicmp(varName, _T("ERRORLEVEL")) == 0)
{
_itot(nErrorLevel, ret, 10);
return ret;
}
#if (NTDDI_VERSION >= NTDDI_WIN7)
/* Available in Win7+, even if the underlying API is available in Win2003+ */
/* %HIGHESTNUMANODENUMBER% */
else if (_tcsicmp(varName, _T("HIGHESTNUMANODENUMBER")) == 0)
{
ULONG NumaNodeNumber = 0;
GetNumaHighestNodeNumber(&NumaNodeNumber);
_itot(NumaNodeNumber, ret, 10);
return ret;
}
#endif
return NULL;
}
/* Handle the %~var syntax */
static PCTSTR
GetEnhancedVar(
IN OUT PCTSTR* pFormat,
IN BOOL (*GetVar)(TCHAR, PCTSTR*, BOOL*))
{
static const TCHAR ModifierTable[] = _T("dpnxfsatz");
enum {
M_DRIVE = 1, /* D: drive letter */
M_PATH = 2, /* P: path */
M_NAME = 4, /* N: filename */
M_EXT = 8, /* X: extension */
M_FULL = 16, /* F: full path (drive+path+name+ext) */
M_SHORT = 32, /* S: full path (drive+path+name+ext), use short names */
M_ATTR = 64, /* A: attributes */
M_TIME = 128, /* T: modification time */
M_SIZE = 256, /* Z: file size */
} Modifiers = 0;
PCTSTR Format, FormatEnd;
PCTSTR PathVarName = NULL;
PCTSTR Variable;
PCTSTR VarEnd;
BOOL VariableIsParam0;
TCHAR FullPath[MAX_PATH];
TCHAR FixedPath[MAX_PATH];
PTCHAR Filename, Extension;
HANDLE hFind;