Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4373 lines
137 KiB

  1. /*++
  2. Copyright (c) 1988-1999 Microsoft Corporation
  3. Module Name:
  4. cbatch.c
  5. Abstract:
  6. Batch file processing
  7. --*/
  8. #include "cmd.h"
  9. struct batdata *CurrentBatchFile = NULL;
  10. int EchoFlag = E_ON; /* E_ON = commands are to be echoed */
  11. int EchoSave; /* M016 - Save echo status here */
  12. extern int Necho;
  13. BOOLEAN GotoFlag = FALSE; /* TRUE = eGoto() found a label */
  14. TCHAR *Fvars = NULL;
  15. TCHAR **Fsubs = NULL;
  16. TCHAR *save_Fvars = NULL; /* @@ */
  17. TCHAR **save_Fsubs = NULL; /* @@ */
  18. int FvarsSaved = FALSE; /* @@ */
  19. extern UINT CurrentCP;
  20. extern ULONG DCount; /* M031 */
  21. extern unsigned DosErr; /* M033 */
  22. extern unsigned flgwd; /* M040 */
  23. /* M011 - Removed RemStr, BatSpecStr, NewBatName and OldBatName from
  24. * external declarations below.
  25. */
  26. extern TCHAR CurDrvDir[];
  27. extern TCHAR Fmt02[], Fmt11[], Fmt12[], Fmt13[], Fmt15[], Fmt17[], Fmt18[]; /* M024 */
  28. extern TCHAR Fmt20[]; /* M017/M024 */
  29. extern TCHAR Fmt00[]; /* @@4 */
  30. extern TCHAR TmpBuf[]; /* M030 - Used for GOTO search */
  31. extern CHAR AnsiBuf[];
  32. extern TCHAR GotoStr[];
  33. extern TCHAR GotoEofStr[];
  34. extern TCHAR ForStr[];
  35. extern TCHAR ForLoopStr[];
  36. extern TCHAR ForDirTooStr[];
  37. extern TCHAR ForParseStr[];
  38. extern TCHAR ForRecurseStr[];
  39. extern int LastRetCode;
  40. extern TCHAR chCompletionCtrl;
  41. extern TCHAR chPathCompletionCtrl;
  42. extern unsigned global_dfvalue; /* @@4 */
  43. extern TCHAR LexBuffer[]; /* @@4 */
  44. extern TCHAR SwitChar; /* M020 - Reference global switch byte */
  45. extern BOOL CtrlCSeen;
  46. void CheckCtrlC();
  47. extern jmp_buf MainEnv;
  48. #define BIG_BAT_NEST 200
  49. #define MAX_STACK_USE_PERCENT 90
  50. BOOLEAN flChkStack;
  51. int CntBatNest;
  52. PVOID FixedPtrOnStack;
  53. typedef struct {
  54. PVOID Base;
  55. PVOID GuardPage;
  56. PVOID Bottom;
  57. PVOID ApprxSP;
  58. } STACK_USE;
  59. STACK_USE GlStackUsage;
  60. #define DEFAULT_DELIMS TEXT( " \t" )
  61. // to handle OS/2 vs DOS errorlevel setting rules in a script files.
  62. int glBatType = NO_TYPE;
  63. /*** ChkStack - check the stack usage
  64. *
  65. * Args:
  66. * pFixed - fixed pointer on stack
  67. * pStackUse - struct stack info to return to caller
  68. *
  69. * Returns:
  70. * FAILURE - if stack info is not good
  71. * SUCCESS - otherwise
  72. *
  73. * Notes:
  74. * See the comments below about Stack Pointer
  75. *
  76. *
  77. */
  78. int ChkStack (PVOID pFixed, STACK_USE *pStackUse )
  79. {
  80. MEMORY_BASIC_INFORMATION Mbi;
  81. PVOID BasePtr;
  82. PCHAR WalkPtr;
  83. int cnt;
  84. PVOID ThreadStackBase,
  85. ThreadStackLimit;
  86. CHAR VarOnStack; // keep this automatic var. here !
  87. // 950119 the best (right) way to find the Current Stack Pointer is
  88. // to write assembly code for all platforms.
  89. // I implemented the most portable code. It should work OK with current NT
  90. // memory models. If NT memory models change then a lot of code will have to
  91. // be re-written anyway. Several NT projects rely on same assumption.
  92. // I also have consistency test for all pointers.
  93. pStackUse->ApprxSP = (VOID *) &VarOnStack; // address of automatic variable
  94. // should be close to current SP
  95. // suggested by MarkL 950119
  96. ThreadStackBase = (PVOID) (NtCurrentTeb()->NtTib.StackBase );
  97. ThreadStackLimit = (PVOID) (NtCurrentTeb()->NtTib.StackLimit );
  98. if ( (pStackUse->ApprxSP >= ThreadStackBase) ||
  99. (pStackUse->ApprxSP <= ThreadStackLimit ) )
  100. return(FAILURE);
  101. if ( (pFixed >= ThreadStackBase) ||
  102. (pFixed <= ThreadStackLimit ) )
  103. return(FAILURE);
  104. // 1. Pass fixed on-the-stack pointer to find out the base address.
  105. if ( (VirtualQuery (pFixed, &Mbi, sizeof(Mbi) ) ) != sizeof (Mbi) )
  106. return(FAILURE);
  107. BasePtr = Mbi.AllocationBase;
  108. // 2. walk all the Virtual Memory Regions with same Allocation Base Address.
  109. cnt = 0;
  110. for (WalkPtr = (CHAR *)BasePtr; Mbi.AllocationBase == BasePtr; WalkPtr += Mbi.RegionSize) {
  111. if ( (VirtualQuery ( (PVOID) WalkPtr, &Mbi, sizeof(Mbi) ) ) != sizeof (Mbi) )
  112. return(FAILURE);
  113. if (cnt == 0) {
  114. if (Mbi.BaseAddress != Mbi.AllocationBase)
  115. return(FAILURE);
  116. }
  117. if (Mbi.Protect & PAGE_GUARD)
  118. pStackUse->GuardPage = Mbi.BaseAddress;
  119. if (Mbi.AllocationBase == BasePtr)
  120. pStackUse->Bottom = (PVOID) ( ( (CHAR *) Mbi.BaseAddress) + Mbi.RegionSize);
  121. cnt++;
  122. if (cnt >= 1000) // normally there are 3 regions : committed, guard, reserved.
  123. return(FAILURE);
  124. }
  125. pStackUse->Base = BasePtr;
  126. if ( pStackUse->Bottom != ThreadStackBase)
  127. return(FAILURE);
  128. if ( ( pStackUse->Base != GlStackUsage.Base) ||
  129. ( pStackUse->Bottom != GlStackUsage.Bottom ) ||
  130. ( pStackUse->Bottom <= pStackUse->Base ) )
  131. return(FAILURE);
  132. return(SUCCESS);
  133. }
  134. /*** BatAbort - terminate the batch processing unconditionally.
  135. *
  136. * Notes:
  137. * Similar to CtrlCAbort()
  138. *
  139. *
  140. */
  141. void BatAbort ()
  142. {
  143. struct batdata *bdat;
  144. //
  145. // End local environments ( Otherwise we can end up with garbage
  146. // in the main environment if any batch file used the setlocal
  147. // command ).
  148. //
  149. if (CurrentBatchFile) {
  150. bdat = CurrentBatchFile;
  151. while ( bdat ) {
  152. EndAllLocals( bdat );
  153. bdat = bdat->backptr;
  154. }
  155. }
  156. SigCleanUp();
  157. CntBatNest = 0;
  158. longjmp(MainEnv, 1);
  159. }
  160. //
  161. // Used to set and reset ctlcseen flag
  162. //
  163. VOID SetCtrlC();
  164. VOID ResetCtrlC( );
  165. /*** BatProc - does the set up before and the cleanup after batch processing
  166. *
  167. * Purpose:
  168. * Set up for the execution of a batch job. If this job is being
  169. * chained, (will come here only if part of compound statement),
  170. * use the existing batch data structure thereby ending execution
  171. * of the existing batch job (though still keeping its stack and data
  172. * usage). If this is the first job or this job is being called,
  173. * allocate a new batch data structure. In either case, use SetBat
  174. * to fill the structure and prepare the job, then call BatLoop to
  175. * at least begin the execution. When this returns at completion,
  176. * check the env and dircpy fields of the data structure to see if
  177. * the current directory and environment need to be reset. Finally,
  178. * turn on the echoflag if no more batch jobs are on the stack.
  179. *
  180. * There are 3 ways to execute a batch job. They are:
  181. * 1. Exactly as DOS 3.x. This is the default method and
  182. * occurs whenever a batch file is simply executed at the
  183. * command line or chained by another batch file. In the
  184. * former case, it is the first job and will go through
  185. * BatProc, else it will be detected in BatLoop and will
  186. * will simply replace its parent.
  187. * 2. Nested via the CALL statement. This is new functionality
  188. * and provides the means of executing the child batch
  189. * file and returning to the parent.
  190. * 3. Invocation of an external batch processor via ExtCom()
  191. * which then executes the batch file. This is accomplished
  192. * by the first line of the batch file being of the form:
  193. *
  194. * ExtProc <batch processor name> [add'l args]
  195. *
  196. * int BatProc(struct cmdnode *n, TCHAR *fname, int typflag)
  197. *
  198. * Args:
  199. * n - parse tree node containing the batch job command
  200. * fname - the name of the batch file (MUST BE MAX_PATH LONG!)
  201. * typflg - 0 = Normal batch file execution
  202. * 1 = Result of CALL statement
  203. *
  204. * Returns:
  205. * FAILURE if the batch processor cannot execute the batch job.
  206. * Otherwise, the retcode of the last command in which was executed.
  207. *
  208. */
  209. int BatProc(n, fname, typflg)
  210. struct cmdnode *n;
  211. TCHAR *fname;
  212. int typflg; /* M011 - "how called" flag */
  213. {
  214. struct batdata *bdat; /* Ptr to new batch data struct */
  215. int batretcode; /* Retcode - last batch command */
  216. int istoplevel;
  217. SIZE_T StackUsedPerCent;
  218. STACK_USE StackUsage;
  219. #ifdef USE_STACKAVAIL // unfortunately not available
  220. if ( stackavail() < MINSTACKNEED ) { /* If not enough stack @@4 */
  221. /* space, stop processing */
  222. PutStdErr(MSG_TRAPC,ONEARG,Fmt00); /* @@4 */
  223. return(FAILURE);
  224. }
  225. #endif
  226. DEBUG((BPGRP,BPLVL,"BP: fname = %ws argptr = %ws", fname, n->argptr));
  227. /* M016 - If this is the first batch file executed, the interactive echo
  228. * status is saved for later restoration.
  229. */
  230. if (!CurrentBatchFile) {
  231. EchoSave = EchoFlag;
  232. istoplevel = 1;
  233. CntBatNest = 0;
  234. } else
  235. istoplevel = 0;
  236. // to check stack only if we are looping too much,
  237. // to avoid unnecessary overhead
  238. if (flChkStack && ( CntBatNest > BIG_BAT_NEST ) ) {
  239. if ( ChkStack (FixedPtrOnStack, &StackUsage) == FAILURE ) {
  240. flChkStack = 0;
  241. } else {
  242. GlStackUsage.GuardPage = StackUsage.GuardPage;
  243. GlStackUsage.ApprxSP = StackUsage.ApprxSP;
  244. StackUsedPerCent = ( ( (UINT_PTR)StackUsage.Bottom - (UINT_PTR)StackUsage.ApprxSP) * 100 ) /
  245. ( (UINT_PTR)StackUsage.Bottom - (UINT_PTR)StackUsage.Base );
  246. if ( StackUsedPerCent >= MAX_STACK_USE_PERCENT ) {
  247. PutStdErr(MSG_ERROR_BATCH_RECURSION,
  248. TWOARGS,
  249. CntBatNest,
  250. StackUsedPerCent );
  251. // if ^C was reported by "^C thread" then handle it here, before calling BatAbort().
  252. CheckCtrlC();
  253. BatAbort();
  254. }
  255. }
  256. }
  257. if (typflg)
  258. CntBatNest++;
  259. /* M011 - Altered to conditionally build a new data structure based on the
  260. * values of typflg and CurrentBatchFile. Provided the first structure has
  261. * been built, chained files no longer cause a new structure, while
  262. * CALLed files do. Also, backpointer and CurrentBatchFile are set here
  263. * rather than in BatLoop() as before. Finally, note that the
  264. * file position indicator bdat->filepos must be reset to zero now
  265. * when a new file is exec'd. Otherwise a chained file using the old
  266. * structure would start off where the last one ended.
  267. */
  268. if (typflg || !CurrentBatchFile) {
  269. DEBUG((BPGRP,BPLVL,"BP: Making new structure"));
  270. bdat = (struct batdata *) mkstr(sizeof(struct batdata));
  271. if ( ! bdat )
  272. return( FAILURE );
  273. bdat->backptr = CurrentBatchFile;
  274. } else {
  275. DEBUG((BPGRP,BPLVL,"BP: Using old structure"));
  276. bdat = CurrentBatchFile;
  277. }
  278. CurrentBatchFile = bdat; /* Takes care of both cases */
  279. /* M011 ends */
  280. bdat->stackmin = DCount; /* M031 - Fix datacount */
  281. mystrcpy(TmpBuf,fname); /* Put where expected */
  282. if (SetBat(n, fname)) /* M031 - All work done */
  283. return(FAILURE); /* ...in SetBat now */
  284. #ifndef WIN95_CMD
  285. // Following two CmdBatNotification calls are being made to
  286. // let NTVDM know that the binary is coming from a .bat/.cmd
  287. // file. Without this all those DOS .bat programs are broken which
  288. // first run a TSR and then run a real DOS app. There are a lot
  289. // of such cases, Ventura Publisher, Civilization and many more
  290. // games which first run a TSR. If .bat/.cmd does'nt have any
  291. // DOS binary these calls dont have any effect.
  292. if (istoplevel) {
  293. // to determine the type of the script file: CMD or BAT
  294. // to decide how to handle the errorlevel
  295. glBatType = BAT_TYPE; // default
  296. if (fname && (mystrlen(fname) >= 5) ) {
  297. PTCHAR tmp;
  298. tmp = fname + mystrlen(fname) - 1;
  299. if ( ( (*tmp == TEXT ('D')) || (*tmp == TEXT ('d')) ) &&
  300. ( (*(tmp-1) == TEXT ('M')) || (*(tmp-1) == TEXT ('m')) ) &&
  301. ( (*(tmp-2) == TEXT ('C')) || (*(tmp-2) == TEXT ('c')) ) &&
  302. ( *(tmp-3) == DOT ) ) {
  303. glBatType = CMD_TYPE;
  304. }
  305. }
  306. CmdBatNotification (CMD_BAT_OPERATION_STARTING);
  307. }
  308. #endif // WIN95_CMD
  309. batretcode = BatLoop(bdat,n); /* M039 */
  310. if (istoplevel) {
  311. #ifndef WIN95_CMD
  312. CmdBatNotification (CMD_BAT_OPERATION_TERMINATING);
  313. #endif // WIN95_CMD
  314. CntBatNest = 0;
  315. glBatType = NO_TYPE;
  316. }
  317. DEBUG((BPGRP, BPLVL, "BP: Returned from BatLoop"));
  318. DEBUG((BPGRP, BPLVL, "BP: bdat = %lx CurrentBatchFile = %lx",bdat,CurrentBatchFile));
  319. /* M011 - Now that setlocal and endlocal control the saving and restoring
  320. * of environments and current directories, it is necessary to
  321. * check each batch data structure before popping it off the stack
  322. * to see if its file issued a SETLOCAL command. EndAllLocals() tests
  323. * the env and dircpy fields, doing nothing if no localization
  324. * needs to be reset. No tests need be done before calling it.
  325. */
  326. if (CurrentBatchFile == bdat) {
  327. DEBUG((BPGRP, BPLVL, "BP: bdat=CurrentBatchFile, calling EndAllLocals"));
  328. EndAllLocals(bdat);
  329. CurrentBatchFile = bdat->backptr;
  330. if (CntBatNest > 0)
  331. CntBatNest--;
  332. }
  333. if (CurrentBatchFile == NULL) {
  334. EchoFlag = EchoSave; /* M016 - Restore echo status */
  335. CntBatNest = 0;
  336. }
  337. DEBUG((BPGRP, BPLVL, "BP: Exiting, CurrentBatchFile = %lx", CurrentBatchFile));
  338. return(batretcode);
  339. }
  340. /*** BatLoop - controls the execution of batch files
  341. *
  342. * Purpose:
  343. * Loop through the statements in a batch file. Do the substitution.
  344. * If this is the first statement and it is a REM command, call eRem()
  345. * directly to check for possible external batch processor invocation.
  346. * Otherwise, call Dispatch() to execute it and continue.
  347. *
  348. * BatLoop(struct batdata *bdat, struct cmdnode *c) (M031)
  349. *
  350. * Args:
  351. * bdat - Contains info needed to execute the current batch job
  352. * c - The node for this batch file (M031)
  353. *
  354. * Returns:
  355. * The retcode of the last command in the batch file.
  356. *
  357. * Notes:
  358. * Execution should end if the target label of a Goto command is not
  359. * found, a signal is received or an unrecoverable error occurs. It
  360. * will be indicated by the current batch data structure being
  361. * popped off the batch jobs stack and is detected by comparing
  362. * CurrentBatchFile and bdat. If they aren't equal, something happened so
  363. * return.
  364. *
  365. * GotoFlag is reset everytime through the loop to make sure that
  366. * execution resumes after a goto statement is executed.
  367. *
  368. */
  369. BatLoop(bdat,c)
  370. struct batdata *bdat;
  371. struct cmdnode *c;
  372. {
  373. struct node *n; /* Ptr to next statement */
  374. BOOL fSilentNext;
  375. int firstline = TRUE; /* TRUE = first valid line */
  376. CRTHANDLE fh; /* Batch job file handle */
  377. int batretcode = SUCCESS; /* Last Retcode (M008 init) */
  378. fSilentNext = FALSE;
  379. for (; CurrentBatchFile == bdat; ) {
  380. CheckCtrlC();
  381. GotoFlag = FALSE;
  382. //
  383. // If extensions are enabled, this is the first line in the
  384. // file and it begins with a COLON, then we got here via
  385. // CALL :label, so turn this into a GOTO :label command
  386. // as BatProc/SetBat have already done the work of pushing
  387. // our state and parsing the arguments.
  388. //
  389. if (fEnableExtensions && firstline && *c->cmdline == COLON) {
  390. struct cmdnode *c1;
  391. c1 = (struct cmdnode *)mknode();
  392. if (c1 == NULL) {
  393. PutStdErr(MSG_NO_MEMORY, NOARGS );
  394. return( FAILURE );
  395. }
  396. c1->type = CMDTYP;
  397. c1->cmdline = mkstr((mystrlen(GotoStr)+1)*sizeof(TCHAR));
  398. if (c1->cmdline == NULL) {
  399. PutStdErr(MSG_NO_MEMORY, NOARGS );
  400. return FAILURE;
  401. }
  402. mystrcpy(c1->cmdline, GotoStr);
  403. c1->argptr = mkstr((mystrlen(c->cmdline)+1)*sizeof(TCHAR));
  404. if (c1->argptr == NULL) {
  405. PutStdErr(MSG_NO_MEMORY, NOARGS );
  406. return FAILURE;
  407. }
  408. mystrcpy(c1->argptr, c->cmdline);
  409. *(c1->argptr) = SPACE;
  410. //
  411. // Set a flag so eGoTo does not try to abort a FOR loop
  412. // because of one of these new CALL forms.
  413. //
  414. c1->flag = CMDNODE_FLAG_GOTO;
  415. //
  416. // Then again, maybe not. I have to think about this some
  417. // more.
  418. //
  419. c1->flag = 0;
  420. n = (struct node *)c1;
  421. //
  422. // Since we generated this GOTO statement, dont let the user
  423. // know
  424. //
  425. fSilentNext = TRUE;
  426. } else {
  427. //
  428. // Open and position the batch file to where next statement
  429. //
  430. if ((fh = OpenPosBat(bdat)) == BADHANDLE)
  431. return( FAILURE); /* Ret if error */
  432. DEBUG((BPGRP, BPLVL, "BLOOP: fh = %d", (ULONG)fh));
  433. n = Parser(READFILE, (INT_PTR)fh, bdat->stacksize); /* Parse */
  434. bdat->filepos = _tell(fh); // next statement
  435. Cclose(fh);
  436. if ((n == NULL) || (n == (struct node *) EOS)) {
  437. continue;
  438. }
  439. DEBUG((BPGRP, BPLVL, "BLOOP: node = %x", n));
  440. DEBUG((BPGRP, BPLVL, "BLOOP: fpos = %lx", bdat->filepos));
  441. /* If syntax error, it is impossible to continue so abort. Note that
  442. * the Abort() function doesn't return.
  443. */
  444. if ( ( n == (struct node *)PARSERROR) || /* If error...*/
  445. /* @@4 */ ( global_dfvalue == MSG_SYNERR_GENL ) )
  446. /* @@4 */
  447. {
  448. PSError();
  449. if ((EchoFlag == E_ON) && !Necho) {
  450. DEBUG((BPGRP, BPLVL, "BLOOP: Displaying Statement."));
  451. PrintPrompt();
  452. PutStdOut(MSG_LITERAL_TEXT,ONEARG,&LexBuffer[1]);
  453. }
  454. Abort(); /* ...quit */
  455. }
  456. if (n == (struct node *) EOF) /* If EOF... */
  457. return(batretcode); /* ...return also */
  458. }
  459. DEBUG((BPGRP, BPLVL, "BLOOP: type = %d", n->type));
  460. /* M008 - By the addition of the second conditional term (&& n), any
  461. * leading NULL lines in the batch file will be skipped without
  462. * penalty.
  463. */
  464. if (firstline && n) /* Kill firstline... */
  465. firstline = FALSE; /* ...when passed */
  466. /* M008 - Don't prompt, display or dispatch if statement is label for Goto
  467. * M009 - Altered second conditional below to test for REMTYP. Was a test
  468. * for CMDTYP and a strcmpi with the RemStr string.
  469. */
  470. if (n->type == CMDTYP &&
  471. *(((struct cmdnode *) n)->cmdline) == COLON)
  472. continue;
  473. /* M019 - Added extra conditional to test for leading SILent node
  474. */
  475. if (fSilentNext)
  476. fSilentNext = FALSE;
  477. else
  478. if (EchoFlag == E_ON && n->type != SILTYP && !Necho) {
  479. DEBUG((BPGRP, BPLVL, "BLOOP: Displaying Statement."));
  480. PrintPrompt();
  481. DisplayStatement(n, DSP_SIL); /* M019 */
  482. cmd_printf(CrLf); /* M026 */
  483. }
  484. if ( n->type == SILTYP ) { /* @@ take care of */
  485. n = n->lhs; /* @@ recursive batch files */
  486. } /* endif */
  487. /* M031 - Chained batch files no longer go through dispatch. They become
  488. * simply an extention of the current one by adding their redirection
  489. * and replacing the current batch data information with their own.
  490. */
  491. if ( n == NULL ) {
  492. batretcode = SUCCESS;
  493. } else if (n->type == CMDTYP &&
  494. FindCmd(CMDHIGH, ((struct cmdnode *)n)->cmdline, TmpBuf) == -1 &&
  495. /* M035 */ !mystrchr(((struct cmdnode *)n)->cmdline, STAR) &&
  496. /* M035 */ !mystrchr(((struct cmdnode *)n)->cmdline, QMARK) &&
  497. SearchForExecutable((struct cmdnode *)n, TmpBuf) == SFE_ISBAT) {
  498. DEBUG((BPGRP, BPLVL, "BLOOP: Chaining to %ws", bdat->filespec));
  499. if ((n->rio && AddRedir(c,(struct cmdnode *)n)) ||
  500. SetBat((struct cmdnode *)n, bdat->filespec)) {
  501. return(FAILURE);
  502. }
  503. firstline = TRUE;
  504. batretcode = SUCCESS;
  505. } else {
  506. DEBUG((BPGRP, BPLVL, "BLOOP: Calling Dispatch()..."));
  507. DEBUG((BPGRP, BPLVL, "BLOOP: ...node type = %d",n->type));
  508. batretcode = Dispatch(RIO_BATLOOP, n);
  509. {
  510. extern CPINFO CurrentCPInfo;
  511. ResetConsoleMode();
  512. //
  513. // Get current CodePage Info. We need this to decide whether
  514. // or not to use half-width characters.
  515. //
  516. GetCPInfo((CurrentCP=GetConsoleOutputCP()), &CurrentCPInfo);
  517. //
  518. // Maybe console output code page was changed by CHCP or MODE,
  519. // so need to reset LanguageID to correspond to code page.
  520. //
  521. #if !defined( WIN95_CMD )
  522. CmdSetThreadUILanguage(0);
  523. #endif
  524. }
  525. }
  526. }
  527. DEBUG((BPGRP, BPLVL, "BLOOP: At end, returning %d", batretcode));
  528. DEBUG((BPGRP, BPLVL, "BLOOP: At end, CurrentBatchFile = %lx", CurrentBatchFile));
  529. DEBUG((BPGRP, BPLVL, "BLOOP: At end, bdat = %lx", bdat));
  530. return(batretcode);
  531. }
  532. /*** SetBat - Replaces current batch data with new. (M031)
  533. *
  534. * Purpose:
  535. * Causes a chained batch file's information to replace its parent's
  536. * in the current batch data structure.
  537. *
  538. * SetBat(struct cmdnode *n, TCHAR *fp)
  539. *
  540. * Args:
  541. * n - pointer to the node for the chained batch file target.
  542. * fp - pointer to filename found for batch file.
  543. * NOTE: In addition, the batch filename will be in TmpBuf at entry.
  544. *
  545. * Returns:
  546. * FAILURE if memory could not be allocated
  547. * SUCCESS otherwise
  548. *
  549. * Notes:
  550. * - WARNING - No allocation of memory must occur above the call to
  551. * FreeStack(). When this call occurs, all allocated heap space
  552. * is freed back to the empty batch data structure and its filespec
  553. * string. Any allocated memory would also be freed.
  554. * - The string used for "->filespec" is that malloc'd by ECWork or
  555. * eCall during the search for the batch file. In the case of
  556. * calls from BatLoop, the existing "->filespec" string is used
  557. * by copying the new batch file name into it. THIS STRING MUST
  558. * NOT BE RESIZED!
  559. *
  560. */
  561. int
  562. SetBat(struct cmdnode *n, PTCHAR fp)
  563. {
  564. int i; // Index counters
  565. int j;
  566. TCHAR *s; // Temp pointer
  567. SAFER_CODE_PROPERTIES CodeProps = {sizeof(SAFER_CODE_PROPERTIES), SAFER_CRITERIA_IMAGEPATH, 0};
  568. SAFER_LEVEL_HANDLE Level = NULL;
  569. DEBUG((BPGRP,BPLVL,"SETBAT: Entered"));
  570. CurrentBatchFile->hRestrictedToken = NULL; // Restricted token for batchfile
  571. //
  572. // We delay load these routines in order to allow CMD to work on downlevel versions
  573. //
  574. ReportDelayLoadErrors = FALSE;
  575. try {
  576. //
  577. // Now get the restricted token to be used for this batch file. The batch file
  578. // may appear in TmpBuf (for normal batch execution or calls) or, in the case of
  579. // CALL :LABEL
  580. // the name appears in CurrentBatchFile->backptr->filespec
  581. //
  582. CodeProps.ImagePath = (WCHAR *) TmpBuf;
  583. if (fEnableExtensions && *n->cmdline == COLON) {
  584. CodeProps.ImagePath = (WCHAR *)CurrentBatchFile->backptr->filespec;
  585. }
  586. //
  587. // Identify the level at which the code should be run.
  588. //
  589. if (SaferIdentifyLevel(1, &CodeProps, &Level, NULL)) {
  590. //
  591. // Compute the token from the level.
  592. //
  593. // Temp until Safer gets fixed
  594. // BOOL FailAlways = _tcsstr( TmpBuf, TEXT( "disallowed" )) != NULL;
  595. if (
  596. // !FailAlways &&
  597. SaferComputeTokenFromLevel(Level, NULL, &CurrentBatchFile->hRestrictedToken, SAFER_TOKEN_NULL_IF_EQUAL, NULL)) {
  598. //
  599. // All is well. We have successfuly computed a restricted token for
  600. // the batch file. Close the handle to authorization level.
  601. //
  602. SaferCloseLevel(Level);
  603. //
  604. // Impersonate if a restricted token was returned by authorization.
  605. // The revert happens in EndAllLocals.
  606. //
  607. if (CurrentBatchFile->hRestrictedToken != NULL) {
  608. if (!ImpersonateLoggedOnUser(CurrentBatchFile->hRestrictedToken)) {
  609. //
  610. // We failed to impersonate. Close the token handle and
  611. // return failure.
  612. //
  613. CloseHandle(CurrentBatchFile->hRestrictedToken);
  614. CurrentBatchFile->hRestrictedToken = NULL;
  615. return(FAILURE);
  616. }
  617. }
  618. } else {
  619. DWORD dwLastError = GetLastError();
  620. // if (FailAlways) dwLastError = ERROR_ACCESS_DISABLED_BY_POLICY;
  621. if (dwLastError == ERROR_ACCESS_DISABLED_BY_POLICY) {
  622. SaferRecordEventLogEntry(
  623. Level,
  624. (WCHAR *) fp,
  625. NULL);
  626. PutStdErr(ERROR_ACCESS_DISABLED_BY_POLICY, NOARGS );
  627. }
  628. //
  629. // We failed to compute the restricted token from the authorization level.
  630. // We will not run the batchfile.
  631. //
  632. CurrentBatchFile->hRestrictedToken = NULL;
  633. SaferCloseLevel(Level);
  634. return(FAILURE);
  635. }
  636. } else {
  637. //
  638. // In case of errors, return failure.
  639. //
  640. return(FAILURE);
  641. }
  642. } except (LastRetCode = GetExceptionCode( ), EXCEPTION_EXECUTE_HANDLER) {
  643. if (LastRetCode != VcppException(ERROR_SEVERITY_ERROR, ERROR_PROC_NOT_FOUND)) {
  644. ReportDelayLoadErrors = TRUE;
  645. return FAILURE;
  646. }
  647. }
  648. ReportDelayLoadErrors = TRUE;
  649. CurrentBatchFile->filepos = 0; // Zero position pointer
  650. CurrentBatchFile->filespec = fp; // Insure correct str
  651. //
  652. // If extensions are enabled and the command line begins with
  653. // a COLON then we got here via CALL :label, so update our
  654. // CurrentBatchFile file spec with our parents file spec, since we are
  655. // in the same file.
  656. //
  657. if (fEnableExtensions && *n->cmdline == COLON) {
  658. struct batdata *bdat;
  659. bdat = CurrentBatchFile->backptr;
  660. mystrcpy(CurrentBatchFile->filespec, bdat->filespec);
  661. CurrentBatchFile->filepos = bdat->filepos;
  662. } else {
  663. //
  664. // Otherwise old behavior is going to a new file. Get its full name
  665. //
  666. if (FullPath(CurrentBatchFile->filespec, TmpBuf,MAX_PATH)) /* If bad name, */
  667. return(FAILURE); /* ...return failure */
  668. }
  669. mystrcpy(TmpBuf, n->cmdline); /* Preserve cmdline and */
  670. *(s = TmpBuf+mystrlen(TmpBuf)+1) = NULLC; /* ...argstr in case this */
  671. if (n->argptr)
  672. mystrcpy(s, n->argptr); /* ...is a chain and node */
  673. FreeStack(CurrentBatchFile->stackmin); /* ...gets lost here */
  674. DEBUG((BPGRP,BPLVL,"SETBAT: fspec = `%ws'",CurrentBatchFile->filespec));
  675. DEBUG((BPGRP,BPLVL,"SETBAT: orgargs = `%ws'",s));
  676. DEBUG((BPGRP,BPLVL,"SETBAT: Making arg0 string"));
  677. CurrentBatchFile->alens[0] = mystrlen(TmpBuf);
  678. CurrentBatchFile->aptrs[0] = mkstr( (CurrentBatchFile->alens[0]+1) * sizeof( TCHAR ) );
  679. if (CurrentBatchFile->aptrs[0] == NULL) {
  680. PutStdErr(MSG_NO_MEMORY, NOARGS );
  681. return(FAILURE);
  682. }
  683. mystrcpy(CurrentBatchFile->aptrs[0], TmpBuf);
  684. CurrentBatchFile->orgaptr0 = CurrentBatchFile->aptrs[0];
  685. DEBUG((BPGRP, BPLVL, "SETBAT: arg 0 = %ws", CurrentBatchFile->aptrs[0]));
  686. DEBUG((BPGRP, BPLVL, "SETBAT: len 0 = %d", CurrentBatchFile->alens[0]));
  687. DEBUG((BPGRP, BPLVL, "SETBAT: Zeroing remaining arg elements"));
  688. for (i = 1; i < 10; i++) { /* Zero any previous */
  689. CurrentBatchFile->aptrs[i] = 0; /* ...arg pointers and */
  690. CurrentBatchFile->alens[i] = 0; /* ...length values */
  691. }
  692. if (*s) {
  693. DEBUG((BPGRP,BPLVL,"SETBAT: Making orgargs string"));
  694. CurrentBatchFile->orgargs = mkstr( (mystrlen( s ) + 1) * sizeof( TCHAR ) );
  695. if (CurrentBatchFile->orgargs == NULL) {
  696. PutStdErr(MSG_NO_MEMORY, NOARGS );
  697. return(FAILURE);
  698. }
  699. //
  700. // Strip leading spaces from orgargs
  701. //
  702. s += _tcsspn( s, TEXT( " \t" ));
  703. mystrcpy( CurrentBatchFile->orgargs, s );
  704. //
  705. // Strip trailing spaces from orgargs
  706. //
  707. s = CurrentBatchFile->orgargs + mystrlen( CurrentBatchFile->orgargs );
  708. while (s != CurrentBatchFile->orgargs) {
  709. if (s[-1] != TEXT( ' ' ) && s[-1] != TEXT( '\t' )) {
  710. break;
  711. }
  712. s--;
  713. }
  714. *s = TEXT( '\0' );
  715. if (!fEnableExtensions) {
  716. //
  717. // /Q on batch script invocation only supported when extensions disabled
  718. //
  719. s = CurrentBatchFile->orgargs;
  720. while (s = mystrchr(s, SwitChar)) {
  721. if (_totupper(*(++s)) == QUIETCH) {
  722. EchoFlag = E_OFF;
  723. mystrcpy(s-1,s+1);
  724. DEBUG((BPGRP,BPLVL,"SETBAT: Found Q switch, orgargs now = %ws",CurrentBatchFile->orgargs));
  725. break;
  726. }
  727. }
  728. }
  729. DEBUG((BPGRP,BPLVL,"SETBAT: Tokenizing orgargs string"));
  730. s = TokStr(CurrentBatchFile->orgargs, NULL, TS_NOFLAGS);
  731. for (i = 1; *s && i < 10; s += j+1, i++) {
  732. CurrentBatchFile->aptrs[i] = s;
  733. CurrentBatchFile->alens[i] = j = mystrlen(s);
  734. DEBUG((BPGRP, BPLVL, "SETBAT: arg %d = %ws", i, CurrentBatchFile->aptrs[i]));
  735. DEBUG((BPGRP, BPLVL, "SETBAT: len %d = %d", i, CurrentBatchFile->alens[i]));
  736. }
  737. CurrentBatchFile->args = s;
  738. } else {
  739. DEBUG((BPGRP, BPLVL, "SETBAT: No args found, ptrs = 0"));
  740. CurrentBatchFile->orgargs = CurrentBatchFile->args = NULL;
  741. }
  742. CurrentBatchFile->stacksize = DCount; /* Protect from parser */
  743. DEBUG((BPGRP, BPLVL, "SETBAT: Stack set: Min = %d, size = %d",CurrentBatchFile->stackmin,CurrentBatchFile->stacksize));
  744. return(SUCCESS);
  745. }
  746. /*** DisplayStatement - controls the displaying of batch file statements
  747. *
  748. * Purpose:
  749. * Walk a parse tree to display the statement contained in it.
  750. * If n is null, the node contains a label, or the node is SILTYP
  751. * and flg is DSP_SIL, do nothing.
  752. *
  753. * void DisplayStatement(struct node *n, int flg)
  754. *
  755. * Args:
  756. * n - pointer to root of the parse tree
  757. * flg - flag indicates "silent" or "verbose" mode
  758. *
  759. */
  760. void DisplayStatement(n, flg)
  761. struct node *n;
  762. int flg; /* M019 - New flag argument */
  763. {
  764. TCHAR *eqstr = TEXT("");
  765. void DisplayOperator(),
  766. DisplayRedirection(); /* M008 - Made void */
  767. /* M019 - Added extra conditionals to determine whether or not to display
  768. * any part of the tree that following a SILent node. This is done
  769. * based on a new flag argument which indicates SILENT or VERBOSE
  770. * mode (DSP_SIL or DSP_VER).
  771. * NOTE: When this routine is combined with pipes to xfer statements
  772. * to a child Command.com via STDOUT, it will have to be changed in
  773. * order to discriminate between the two purposes for which it is
  774. * called. Flag definitions already exist in CMD.H for this purpose
  775. * (DSP_SCN & DSP_PIP).
  776. */
  777. if (!n ||
  778. (n->type == SILTYP && flg == DSP_SIL) ||
  779. ((((struct cmdnode *) n)->cmdline) &&
  780. *(((struct cmdnode *) n)->cmdline) == COLON))
  781. return;
  782. switch (n->type) {
  783. case LFTYP:
  784. DisplayOperator(n, CrLf);
  785. break;
  786. case CSTYP:
  787. DisplayOperator(n, CSSTR);
  788. break;
  789. case ORTYP:
  790. DisplayOperator(n, ORSTR);
  791. break;
  792. case ANDTYP:
  793. DisplayOperator(n, ANDSTR);
  794. break;
  795. case PIPTYP:
  796. DisplayOperator(n, PIPSTR);
  797. break;
  798. case SILTYP:
  799. CmdPutString( SILSTR );
  800. DisplayStatement(n->lhs, DSP_VER);
  801. DisplayRedirection(n);
  802. break;
  803. case PARTYP:
  804. DEBUG((BPGRP, BPLVL, "DST: Doing parens"));
  805. CmdPutString( LEFTPSTR );
  806. if (n->lhs->type == LFTYP)
  807. cmd_printf( CrLf );
  808. DisplayStatement(n->lhs, DSP_SIL); /* M019 */
  809. if (n->lhs->type == LFTYP)
  810. cmd_printf( CrLf );
  811. cmd_printf(Fmt11, RPSTR); /* M013 */
  812. DisplayRedirection(n);
  813. break;
  814. case FORTYP:
  815. DEBUG((BPGRP, BPLVL, "DST: Displaying FOR."));
  816. //
  817. // If extensions are enabled, handle displaying the new
  818. // optional switches on the FOR statement.
  819. //
  820. if (fEnableExtensions) {
  821. cmd_printf(TEXT("%.3s"), ((struct fornode *) n)->cmdline);
  822. if (((struct fornode *)n)->flag & FOR_LOOP)
  823. cmd_printf(TEXT(" %s"), ForLoopStr);
  824. else
  825. if (((struct fornode *)n)->flag & FOR_MATCH_DIRONLY)
  826. cmd_printf(TEXT(" %S"), ForDirTooStr);
  827. else
  828. if (((struct fornode *)n)->flag & FOR_MATCH_PARSE) {
  829. cmd_printf(TEXT(" %s"), ForParseStr);
  830. if (((struct fornode *)n)->parseOpts)
  831. cmd_printf(TEXT(" %s"), ((struct fornode *)n)->parseOpts);
  832. } else
  833. if (((struct fornode *)n)->flag & FOR_MATCH_RECURSE) {
  834. cmd_printf(TEXT(" %s"), ForRecurseStr);
  835. if (((struct fornode *)n)->recurseDir)
  836. cmd_printf(TEXT(" %s"), ((struct fornode *)n)->recurseDir );
  837. }
  838. cmd_printf(TEXT(" %s "), ((struct fornode *) n)->cmdline+_tcslen(ForStr)+1);
  839. } else
  840. cmd_printf(Fmt11, ((struct fornode *) n)->cmdline);
  841. cmd_printf(Fmt13, ((struct fornode *) n)->arglist, ((struct fornode *) n)->cmdline+DOPOS);
  842. /* M019 */DisplayStatement(((struct fornode *) n)->body, DSP_VER);
  843. break;
  844. case IFTYP:
  845. DEBUG((BPGRP, BPLVL, "DST: Displaying IF."));
  846. cmd_printf(Fmt11, ((struct ifnode *) n)->cmdline); /* M013 */
  847. //
  848. // If extensions are enabled, handle displaying the new
  849. // optional /I switch on the IF statement.
  850. //
  851. if (fEnableExtensions) {
  852. if (((struct ifnode *)n)->cond->type != NOTTYP) {
  853. if (((struct ifnode *)n)->cond->flag == CMDNODE_FLAG_IF_IGNCASE)
  854. cmd_printf(TEXT("/I "));
  855. } else
  856. if (((struct cmdnode *)(((struct ifnode *)n)->cond->argptr))->flag == CMDNODE_FLAG_IF_IGNCASE)
  857. cmd_printf(TEXT("/I "));
  858. }
  859. /* M019 */DisplayStatement((struct node *)(((struct ifnode *) n)->cond), DSP_SIL);
  860. /* M019 */DisplayStatement(((struct ifnode *) n)->ifbody, DSP_SIL);
  861. if (((struct ifnode *) n)->elsebody) {
  862. cmd_printf(Fmt02, ((struct ifnode *) n)->elseline); /* M013 */
  863. /* M019 */DisplayStatement(((struct ifnode *) n)->elsebody, DSP_SIL);
  864. }
  865. break;
  866. case NOTTYP:
  867. DEBUG((BPGRP, BPLVL, "DST: Displaying NOT."));
  868. /* M002 - Removed '\n' from printf statement below.
  869. */
  870. cmd_printf(Fmt11, ((struct cmdnode *) n)->cmdline); /* M013 */
  871. /* M002 ends */
  872. /* M019 */DisplayStatement((struct node *)(((struct cmdnode *) n)->argptr), DSP_SIL);
  873. break;
  874. case STRTYP:
  875. case CMPTYP:
  876. eqstr = TEXT("== ");
  877. //
  878. // If extensions are enabled, handle displaying the
  879. // new forms of comparison operators.
  880. //
  881. if (fEnableExtensions) {
  882. if (((struct cmdnode *) n)->cmdarg == CMDNODE_ARG_IF_EQU)
  883. eqstr = TEXT("EQU ");
  884. else
  885. if (((struct cmdnode *) n)->cmdarg == CMDNODE_ARG_IF_NEQ)
  886. eqstr = TEXT("NEQ ");
  887. else
  888. if (((struct cmdnode *) n)->cmdarg == CMDNODE_ARG_IF_LSS)
  889. eqstr = TEXT("LSS ");
  890. else
  891. if (((struct cmdnode *) n)->cmdarg == CMDNODE_ARG_IF_LEQ)
  892. eqstr = TEXT("LEQ ");
  893. else
  894. if (((struct cmdnode *) n)->cmdarg == CMDNODE_ARG_IF_GTR)
  895. eqstr = TEXT("GTR ");
  896. else
  897. if (((struct cmdnode *) n)->cmdarg == CMDNODE_ARG_IF_GEQ)
  898. eqstr = TEXT("GEQ ");
  899. }
  900. cmd_printf(Fmt12, ((struct cmdnode *) n)->cmdline, eqstr, ((struct cmdnode *) n)->argptr); /* M013 */
  901. break;
  902. case ERRTYP:
  903. case EXSTYP:
  904. case CMDVERTYP:
  905. case DEFTYP:
  906. cmd_printf(Fmt15, ((struct cmdnode *) n)->cmdline, ((struct cmdnode *) n)->argptr); /* M013 */
  907. break;
  908. case REMTYP: /* M009 - Rem now seperate type */
  909. case CMDTYP:
  910. DEBUG((BPGRP, BPLVL, "DST: Displaying command."));
  911. CmdPutString( ((struct cmdnode *) n)->cmdline );
  912. if (((struct cmdnode *) n)->argptr)
  913. cmd_printf(Fmt11, ((struct cmdnode *) n)->argptr); /* M013 */
  914. DisplayRedirection(n);
  915. }
  916. }
  917. /*** DisplayOperator - controls displaying statments containing operators
  918. *
  919. * Purpose:
  920. * Diplay an operator and recurse on its left and right hand sides.
  921. *
  922. * void DisplayOperator(struct node *n, TCHAR *opstr)
  923. *
  924. * Args:
  925. * n - node of operator to be displayed
  926. * opstr - the operator to print
  927. *
  928. */
  929. void DisplayOperator(n, opstr)
  930. struct node *n;
  931. TCHAR *opstr;
  932. {
  933. void DisplayStatement(); /* M008 - made void */
  934. DEBUG((BPGRP, BPLVL, "DOP"));
  935. DisplayStatement(n->lhs, DSP_SIL); /* M019 */
  936. if (n->rhs) {
  937. cmd_printf(Fmt02, opstr);
  938. DisplayStatement(n->rhs, DSP_SIL); /* M019 */
  939. }
  940. }
  941. /*** DisplayRedirection - displays statements' I/O redirection
  942. *
  943. * Purpose:
  944. * Display the type and file names of any redirection associated with
  945. * this node.
  946. *
  947. * void DisplayRedirection(struct node *n)
  948. *
  949. * Args:
  950. * n - the node to check for redirection
  951. *
  952. * Notes:
  953. * M017 - This function has been extensively modified to conform
  954. * to new data structures for redirection.
  955. * M018 - Modified for redirection of handles other than 0 for input.
  956. */
  957. void DisplayRedirection(n)
  958. struct node *n;
  959. {
  960. struct relem *tmp;
  961. DEBUG((BPGRP, BPLVL, "DRD"));
  962. tmp = n->rio;
  963. while (tmp) {
  964. cmd_printf(Fmt18, TEXT('0')+tmp->rdhndl, tmp->rdop);
  965. if (tmp->flag)
  966. cmd_printf(Fmt20);
  967. cmd_printf(Fmt11, tmp->fname);
  968. tmp = tmp->nxt;
  969. }
  970. }
  971. /*** OpenPosBat - open a batch file and position its file pointer
  972. *
  973. * Purpose:
  974. * Open a batch file and position the file pointer to the location at
  975. * which the next statement is to be read.
  976. *
  977. * int OpenPosBat(struct batdata *bdat)
  978. *
  979. * Args:
  980. * bdat - pointer to current batch job structure
  981. *
  982. * Returns:
  983. * The handle of the file if everything is successful. Otherwise,
  984. * FAILURE.
  985. *
  986. * Notes:
  987. * M033 - Now reports sharing violation errors if appropriate.
  988. *
  989. */
  990. CRTHANDLE OpenPosBat(bdat)
  991. struct batdata *bdat;
  992. {
  993. CRTHANDLE fh; /* Batch file handle */
  994. int DriveIsFixed();
  995. DEBUG((BPGRP, BPLVL, "OPB: fspec = %ws", bdat->filespec));
  996. while ((fh = Copen(bdat->filespec, O_RDONLY|O_BINARY)) == BADHANDLE) {
  997. if (DosErr != ERROR_FILE_NOT_FOUND) { /* M037 */
  998. PrtErr(ERROR_OPEN_FAILED); /* M037 */
  999. return(fh);
  1000. } else if ( DriveIsFixed( bdat->filespec ) ) { /* @@4 */
  1001. PutStdErr( MSG_CMD_BATCH_FILE_MISSING, NOARGS); /* @@4 */
  1002. return(fh); /* @@4 */
  1003. } else {
  1004. PutStdErr(MSG_INSRT_DISK_BAT, NOARGS);
  1005. if (0x3 == _getch()) {
  1006. SetCtrlC();
  1007. return(fh);
  1008. }
  1009. }
  1010. }
  1011. SetFilePointer(CRTTONT(fh), bdat->filepos, NULL, FILE_BEGIN);
  1012. return(fh);
  1013. }
  1014. /*** eEcho - execute an Echo command
  1015. *
  1016. * Purpose:
  1017. * To either print a message, change the echo status, or display the
  1018. * echo status.
  1019. *
  1020. * int eEcho(struct cmdnode *n)
  1021. *
  1022. * Args:
  1023. * n - the parse tree node containing the echo command
  1024. *
  1025. * Returns:
  1026. * SUCCESS always.
  1027. *
  1028. */
  1029. int eEcho(
  1030. struct cmdnode *n
  1031. )
  1032. {
  1033. int oocret;
  1034. int rc;
  1035. DEBUG((BPGRP, OTLVL, "eECHO: Entered."));
  1036. switch (oocret = OnOffCheck(n->argptr, OOC_NOERROR)) {
  1037. case OOC_EMPTY:
  1038. rc = PutStdOut(((EchoFlag == E_ON) ? MSG_ECHO_ON : MSG_ECHO_OFF), NOARGS);
  1039. if (rc != 0) {
  1040. if (FileIsPipe(STDOUT)) {
  1041. PutStdErr( MSG_CMD_INVAL_PIPE, NOARGS );
  1042. } else if ( !FileIsDevice( STDOUT ) ) {
  1043. PutStdErr( rc, NOARGS );
  1044. } else if (!(flgwd & 2)) {
  1045. PutStdErr( ERROR_WRITE_FAULT, NOARGS );
  1046. }
  1047. }
  1048. break;
  1049. case OOC_OTHER:
  1050. cmd_printf(Fmt17, n->argptr+1);
  1051. break;
  1052. default:
  1053. EchoFlag = oocret;
  1054. }
  1055. return(SUCCESS);
  1056. }
  1057. /*** eFor - controls the execution of a For loop
  1058. *
  1059. * Purpose:
  1060. * Loop through the elements in a FOR loop arg list. Expand those that
  1061. * contain wildcards.
  1062. *
  1063. * int eFor(struct fornode *n)
  1064. *
  1065. * Args:
  1066. * n - the FOR loop parse tree node
  1067. *
  1068. * Returns:
  1069. * The retcode of the last command executed in the FOR body.
  1070. *
  1071. * Notes:
  1072. * *** IMPORTANT ***
  1073. * Each iteration through the FOR loop being executed causes more memory
  1074. * to be allocated. This can cause Command to run out of memory. To
  1075. * keep this from happening, we use DCount to locate the end of the data
  1076. * stack after the first iteration through the FOR loop. At the end of
  1077. * each successive iteration through the loop, memory is freed that was
  1078. * allocated during that iteration of the loop. The first iterations'
  1079. * memory is NOT freed because there is data allocated there that must
  1080. * be kept for successive iterations; namely, the save structure in the
  1081. * for loop node.
  1082. *
  1083. */
  1084. void FvarRestore()
  1085. {
  1086. if ( FvarsSaved ) { /* @@ */
  1087. FvarsSaved = FALSE; /* @@ */
  1088. Fvars = save_Fvars; /* @@ */
  1089. Fsubs = save_Fsubs; /* @@ */
  1090. } /* @@ */
  1091. }
  1092. FRecurseWork(
  1093. TCHAR *path,
  1094. TCHAR *filepart,
  1095. struct fornode *pForNode,
  1096. PCPYINFO fsinfo,
  1097. int i,
  1098. TCHAR *argtoks
  1099. );
  1100. FParseWork(
  1101. struct fornode *pForNode,
  1102. int i,
  1103. BOOL bFirstLoop
  1104. );
  1105. FLoopWork(
  1106. struct fornode *pForNode,
  1107. PCPYINFO fsinfo,
  1108. int i,
  1109. TCHAR *argtoks,
  1110. BOOL bFirstLoop
  1111. );
  1112. int eFor(struct fornode *pForNode)
  1113. {
  1114. TCHAR *argtoks; /* Tokenized argument list */
  1115. int i = 0; /* Temp */
  1116. int datacount; /* Elts on data stack not to free */
  1117. int forretcode = SUCCESS;
  1118. /*509*/int argtoklen;
  1119. BOOL bFirstLoop;
  1120. PCPYINFO fsinfo; /* Used for expanded fspec */
  1121. FvarsSaved = FALSE; /* @@ */
  1122. bFirstLoop = TRUE;
  1123. fsinfo = (PCPYINFO) mkstr(sizeof(CPYINFO));
  1124. if (!fsinfo) {
  1125. PutStdErr(MSG_NO_MEMORY, NOARGS );
  1126. return(FAILURE);
  1127. }
  1128. if (Fvars) {
  1129. Fvars = (TCHAR*)resize(Fvars,((i = mystrlen(Fvars))+2)*sizeof(TCHAR));
  1130. Fsubs = (TCHAR **)resize(Fsubs,(i+1)*(sizeof(TCHAR *)) );
  1131. } else {
  1132. Fvars = (TCHAR*)mkstr(2*sizeof(TCHAR)); /* If no str, make one */
  1133. Fsubs = (TCHAR **)mkstr(sizeof(TCHAR *)); /* ...also a table */
  1134. }
  1135. if (Fvars == NULL || Fsubs == NULL) {
  1136. PutStdErr(MSG_NO_MEMORY, NOARGS );
  1137. return FAILURE;
  1138. }
  1139. Fvars[i] = (TCHAR)(pForNode->forvar); /* Add new var to str */
  1140. Fvars[i+1] = NULLC;
  1141. //
  1142. // Check for the new forms of the FOR loop. None of these flags
  1143. // will be set if extensions are not enabled
  1144. //
  1145. if (pForNode->flag & FOR_LOOP) {
  1146. TCHAR ForLoopBuffer[32];
  1147. int ForLoopValue, ForLoopStep, ForLoopLimit;
  1148. //
  1149. // Handle the loop for of the FOR statement, where the set
  1150. // is described by a starting number and step value (+ or -)
  1151. // and an end number
  1152. //
  1153. // FOR /L %i in (start,step,end) do
  1154. //
  1155. argtoks = TokStr(pForNode->arglist, NULL, TS_NOFLAGS);
  1156. ForLoopValue = _tcstol( argtoks, NULL, 0 );
  1157. argtoklen = mystrlen( argtoks );
  1158. argtoks += argtoklen+1;
  1159. ForLoopStep = _tcstol( argtoks, NULL, 0 );
  1160. argtoklen = mystrlen( argtoks );
  1161. argtoks += argtoklen+1;
  1162. ForLoopLimit = _tcstol( argtoks, NULL, 0 );
  1163. //
  1164. // We have the three numbers, now run the body of the FOR
  1165. // loop with each value described
  1166. //
  1167. datacount = 0;
  1168. while (TRUE) {
  1169. //
  1170. // If step is negative, go until loop value is less
  1171. // than limit. Otherwise go until it is greater than
  1172. // limit.
  1173. //
  1174. if (ForLoopStep < 0) {
  1175. if (ForLoopValue < ForLoopLimit)
  1176. break;
  1177. } else {
  1178. if (ForLoopValue > ForLoopLimit)
  1179. break;
  1180. }
  1181. FvarRestore();
  1182. DEBUG((BPGRP, FOLVL, "FOR: element %d = `%ws'",i ,argtoks));
  1183. CheckCtrlC();
  1184. //
  1185. // Convert the loop value to text and set the value of the loop
  1186. // variable
  1187. //
  1188. _sntprintf(ForLoopBuffer, 32, TEXT("%d"), ForLoopValue);
  1189. Fsubs[i] = ForLoopBuffer;
  1190. //
  1191. // Run the body of the FOR Loop
  1192. //
  1193. forretcode = FWork(pForNode->body,bFirstLoop);
  1194. datacount = ForFree(datacount);
  1195. bFirstLoop = FALSE;
  1196. //
  1197. // Step to next value
  1198. //
  1199. ForLoopValue += ForLoopStep;
  1200. }
  1201. } else
  1202. if (pForNode->flag & FOR_MATCH_PARSE) {
  1203. //
  1204. // Handle the new parse form of the FOR loop
  1205. //
  1206. // FOR /F "parameters" %i in (filelist) do ...
  1207. // FOR /F "parameters" %i in (`command to execute`) do ...
  1208. // FOR /F "parameters" %i in ('literal string') do ...
  1209. //
  1210. forretcode = FParseWork(pForNode,
  1211. i,
  1212. TRUE
  1213. );
  1214. } else
  1215. if (pForNode->flag & FOR_MATCH_RECURSE) {
  1216. TCHAR pathbuf[MAX_PATH];
  1217. TCHAR *filepart;
  1218. TCHAR *p;
  1219. DWORD Length;
  1220. //
  1221. // Handle the new recurse form of the FOR loop
  1222. //
  1223. // FOR /R directory %i in (filespecs) do ...
  1224. //
  1225. // Where directory is an optional directory path of where to start
  1226. // walking the directory tree. Default is the current directory.
  1227. // filespecs is one or more file name specifications, wildcards
  1228. // allowed.
  1229. //
  1230. //
  1231. // Get the full path of the directory to start walking, defaulting
  1232. // to the current directory.
  1233. //
  1234. p = StripQuotes( pForNode->recurseDir ? pForNode->recurseDir : TEXT(".\\"));
  1235. Length = GetFullPathName( p, MAX_PATH, pathbuf, &filepart );
  1236. if (Length == 0 || Length >= MAX_PATH ) {
  1237. PutStdErr( MSG_FULL_PATH_TOO_LONG, ONEARG, p );
  1238. forretcode = FAILURE;
  1239. } else {
  1240. if (filepart == NULL) {
  1241. filepart = lastc(pathbuf);
  1242. if (*filepart != BSLASH) {
  1243. *++filepart = BSLASH;
  1244. }
  1245. *++filepart = NULLC;
  1246. } else {
  1247. //
  1248. // A directory is present. Append a path sep
  1249. //
  1250. mystrcat( pathbuf, TEXT( "\\" ));
  1251. filepart = lastc( pathbuf ) + 1;
  1252. }
  1253. //
  1254. // Tokenize the list of file specifications
  1255. //
  1256. argtoks = TokStr(pForNode->arglist, NULL, TS_NOFLAGS);
  1257. //
  1258. // Do the work
  1259. //
  1260. forretcode = FRecurseWork(pathbuf, filepart, pForNode, fsinfo, i, argtoks);
  1261. }
  1262. } else {
  1263. //
  1264. // If none of the new flags specified, then old style FOR statement
  1265. // Tokenize the elements of the set and loop over them
  1266. //
  1267. argtoks = TokStr(pForNode->arglist, NULL, TS_NOFLAGS);
  1268. DEBUG((BPGRP, FOLVL, "FOR: initial argtok = `%ws'", argtoks));
  1269. forretcode = FLoopWork(pForNode, fsinfo, i, argtoks, TRUE);
  1270. DEBUG((BPGRP, FOLVL, "FOR: Exiting."));
  1271. }
  1272. //
  1273. // All done, deallocate the FOR variable
  1274. //
  1275. if (i) {
  1276. if (Fvars || (*Fvars)) {
  1277. *(Fvars+mystrlen(Fvars)-1) = NULLC;
  1278. }
  1279. Fsubs[i] = NULL;
  1280. } else {
  1281. Fvars = NULL;
  1282. Fsubs = NULL;
  1283. }
  1284. return(forretcode);
  1285. }
  1286. /*** FRecurseWork - controls the execution of a For loop with the /R option
  1287. *
  1288. * Purpose:
  1289. * Execute a FOR loop statement for recursive walk of a directory tree
  1290. *
  1291. * FRecurseWork(TCHAR *path, TCHAR *filepart,
  1292. * struct fornode *pForNode, PCPYINFOfsinfo,
  1293. * int i, TCHAR *argtoks)
  1294. *
  1295. * Args:
  1296. * path - full path of directory to start recursing down
  1297. * filepart - tail portion of full path where file name portion is
  1298. * pForNode - pointer to the FOR parse tree node
  1299. * fsinfo - work buffer for expanding file specification wildcards
  1300. * i - FOR variable index in Fvars and Fsubs arrays
  1301. * argtoks - the tokenized data set to loop over. This set is presumed
  1302. * to be file names with possible wild cards. This set is
  1303. * evaluated for each directory seen by the recusive walk of the
  1304. * the directory tree. So FOR /R "." %i in (*.c *.h) do echo %i
  1305. * would echo all the .c and .h files in a directory tree
  1306. *
  1307. * Returns:
  1308. * The retcode of the last statement executed in the for body or FORERROR.
  1309. *
  1310. */
  1311. FRecurseWork(
  1312. TCHAR *path,
  1313. TCHAR *filepart,
  1314. struct fornode *pForNode,
  1315. PCPYINFO fsinfo,
  1316. int i,
  1317. TCHAR *argtoks
  1318. )
  1319. {
  1320. WIN32_FIND_DATA buf; /* Buffer for find first/next */
  1321. HANDLE hnFirst; /* handle from ffirst() */
  1322. int forretcode = FORERROR;
  1323. int npfxlen, ntoks;
  1324. TCHAR *s1;
  1325. TCHAR *s2;
  1326. TCHAR *tmpargtoks;
  1327. //
  1328. // Calculate the length of the path and find the end of the
  1329. // tokenized data set and the number of tokens in the set.
  1330. //
  1331. npfxlen = _tcslen(path);
  1332. ntoks = 0;
  1333. s1 = argtoks;
  1334. while (*s1) {
  1335. ntoks += 1;
  1336. while (*s1++) {
  1337. NOTHING;
  1338. }
  1339. }
  1340. //
  1341. // Now allocate space for a copy of the tokenized data set with room to prefix
  1342. // each element of the set with the path string. Construct the copy of the set
  1343. //
  1344. tmpargtoks = mkstr( ntoks * ((npfxlen + ((int)(s1 - argtoks) + 1)) * sizeof(TCHAR)) );
  1345. if (tmpargtoks == NULL) {
  1346. PutStdErr(MSG_NO_MEMORY, NOARGS );
  1347. return FAILURE;
  1348. }
  1349. s1 = argtoks;
  1350. s2 = tmpargtoks;
  1351. while (*s1) {
  1352. _tcsncpy(s2, path, npfxlen);
  1353. _tcscpy(s2+npfxlen, s1);
  1354. s2 += npfxlen;
  1355. while (*s1++)
  1356. s2 += 1;
  1357. s2 += 1;
  1358. }
  1359. *s2++ = NULLC;
  1360. //
  1361. // Now run the body of the FOR loop with the new data set, then free it.
  1362. //
  1363. forretcode = FLoopWork(pForNode, fsinfo, i, tmpargtoks, TRUE);
  1364. //
  1365. // Now find any subdirectories in path and recurse on them
  1366. //
  1367. filepart[0] = STAR;
  1368. filepart[1] = NULLC;
  1369. hnFirst = FindFirstFile( path, &buf );
  1370. filepart[0] = NULLC;
  1371. if (hnFirst != INVALID_HANDLE_VALUE) {
  1372. do {
  1373. _tcscpy(filepart, buf.cFileName);
  1374. if (buf.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
  1375. _tcscmp(buf.cFileName, TEXT(".")) &&
  1376. _tcscmp(buf.cFileName, TEXT(".."))) {
  1377. s1 = lastc(filepart);
  1378. *++s1 = BSLASH;
  1379. *++s1 = NULLC;
  1380. forretcode = FRecurseWork(path, s1, pForNode, fsinfo, i, argtoks);
  1381. }
  1382. } while (FindNextFile( hnFirst, &buf ));
  1383. FindClose(hnFirst);
  1384. }
  1385. return(forretcode);
  1386. }
  1387. /*** FParseWork - controls the execution of a For loop with the /F option
  1388. *
  1389. * Purpose:
  1390. * Execute a FOR loop statement for parsing the contents of a file
  1391. *
  1392. * FParseWork(struct fornode *pForNode, PCPYINFOfsinfo,
  1393. * int i, TCHAR *argtoks, BOOL bFirstLoop)
  1394. *
  1395. * Args:
  1396. * pForNode - pointer to the FOR parse tree node
  1397. * i - FOR variable index in Fvars and Fsubs arrays
  1398. * bFirstLoop - TRUE if first time through loop
  1399. *
  1400. * Returns:
  1401. * The retcode of the last statement executed in the for body or FORERROR.
  1402. *
  1403. */
  1404. FParseWork(
  1405. struct fornode *pForNode,
  1406. int i,
  1407. BOOL bFirstLoop
  1408. )
  1409. {
  1410. HANDLE hFile; /* handle from ffirst() */
  1411. DWORD dwFileSize, dwBytesRead;
  1412. int datacount; /* Elts on data stack not to free */
  1413. int argtoklen;
  1414. int forretcode = FORERROR;
  1415. TCHAR *argtoks;
  1416. TCHAR *s1;
  1417. TCHAR *s2;
  1418. TCHAR *sToken;
  1419. TCHAR *sEnd;
  1420. TCHAR *tmpargtoks = NULL;
  1421. TCHAR eol=TEXT(';');
  1422. TCHAR quoteChar;
  1423. TCHAR *delims;
  1424. TCHAR chCmdLine, chLiteralString;
  1425. int nVars;
  1426. int nSkip;
  1427. int nSkipSave;
  1428. int nTok, nTokEnd, nTokBits, nTokStar;
  1429. DWORD nTokenMask;
  1430. BOOL bNewSemantics;
  1431. //
  1432. // First see if we have any parse options present. Possible parse options are:
  1433. //
  1434. // eol=c // c is the end of line comment character
  1435. // delims=cccc // cccc specifies one or more delimeter characters
  1436. // skip=n // n specifies how many lines at the begin of each file
  1437. // // to skip (defaults to zero).
  1438. // tokens=m,n-o // m is a token number to pass to the body of the FOR loop
  1439. // // n-o is a range of token numbers to pass. (defaults
  1440. // // to tokens=1
  1441. // usebackq // If present, allows new back quotes for command line,
  1442. // // single quote for literal strings, which frees up double
  1443. // // quotes for quoting file names
  1444. //
  1445. //
  1446. delims = (TCHAR *) gmkstr( (_tcslen( DEFAULT_DELIMS ) + 1) * sizeof( TCHAR ) );
  1447. mystrcpy( delims, DEFAULT_DELIMS );
  1448. nSkip = 0;
  1449. nVars = 1;
  1450. nTokenMask = 1;
  1451. nTokStar = 0;
  1452. bNewSemantics = FALSE;
  1453. if (pForNode->parseOpts) {
  1454. s1 = pForNode->parseOpts;
  1455. if (*s1 == QUOTE || *s1 == TEXT('\'')) {
  1456. quoteChar = *s1++;
  1457. } else {
  1458. quoteChar = NULLC;
  1459. }
  1460. nTokBits = 1;
  1461. while (s1 && *s1) {
  1462. while (*s1 && *s1 <= SPACE)
  1463. s1 += 1;
  1464. if (*s1 == quoteChar)
  1465. break;
  1466. if (!_tcsnicmp(s1, TEXT("usebackq"), 8)) {
  1467. bNewSemantics = TRUE;
  1468. s1 += 8;
  1469. } else
  1470. if (!_tcsnicmp(s1, TEXT("useback"), 7)) {
  1471. bNewSemantics = TRUE;
  1472. s1 += 7;
  1473. } else
  1474. if (!_tcsnicmp(s1, TEXT("eol="), 4)) {
  1475. eol=s1[4];
  1476. s1 += 5;
  1477. } else
  1478. if (!_tcsnicmp(s1, TEXT("delims="), 7)) {
  1479. s1 += 7;
  1480. s2 = s1;
  1481. //
  1482. // Advance to the next space or end of string
  1483. //
  1484. while (*s1 && *s1 != quoteChar) {
  1485. if (*s1 == SPACE && s1[1] != quoteChar)
  1486. break;
  1487. else
  1488. s1 += 1;
  1489. }
  1490. //
  1491. // New delimiter characters
  1492. //
  1493. FreeStr( delims );
  1494. delims = (TCHAR *) gmkstr( ((int)(s1 - s2) + 1) * sizeof( TCHAR ));
  1495. _tcsncpy(delims, s2, (UINT)(s1-s2));
  1496. delims[s1-s2] = NULLC;
  1497. if (*s1)
  1498. s1 += 1;
  1499. } else
  1500. if (!_tcsnicmp(s1, TEXT("skip="), 5)) {
  1501. s1 += 5;
  1502. nSkip = _tcstol(s1, &s1, 0);
  1503. if (nSkip <= 0)
  1504. goto badtokens;
  1505. } else
  1506. if (!_tcsnicmp(s1, TEXT("tokens="), 7)) {
  1507. s1 += 7;
  1508. nTokenMask = 0;
  1509. nTokBits = 0;
  1510. while (*s1 && *s1 != quoteChar) {
  1511. if (*s1 == STAR) {
  1512. s1 += 1;
  1513. nTokBits += 1;
  1514. nTokStar = nTokBits;
  1515. break;
  1516. }
  1517. nTok = _tcstol(s1, &s1, 0);
  1518. if (nTok <= 0)
  1519. goto badtokens;
  1520. if (*s1 == MINUS) {
  1521. nTokEnd = _tcstol(s1+1, &s1, 0);
  1522. if (nTokEnd <= 0)
  1523. goto badtokens;
  1524. } else
  1525. nTokEnd = nTok;
  1526. if (nTok > 0 && nTokEnd < 32)
  1527. while (nTok <= nTokEnd) {
  1528. nTokBits += 1;
  1529. nTokenMask |= 1 << (nTok - 1);
  1530. nTok += 1;
  1531. }
  1532. if (*s1 == COMMA)
  1533. s1 += 1;
  1534. else
  1535. if (*s1 != STAR)
  1536. break;
  1537. }
  1538. if (nTokBits > nVars)
  1539. nVars = nTokBits;
  1540. } else {
  1541. badtokens:
  1542. PutStdErr(MSG_SYNERR_GENL,ONEARG,s1);
  1543. return(FAILURE);
  1544. }
  1545. }
  1546. //
  1547. // If user specified more than one token then we need to allocate
  1548. // additional FOR variable names to pass them to the body of the
  1549. // FOR loop. The variables names are the next nVars-1 letters after
  1550. // the one the user specified in the FOR statement. So if they specified
  1551. // %i as the variable name and requested 3 tokens, then %j and %k would
  1552. // be allocated here.
  1553. //
  1554. if (nVars > 1) {
  1555. Fvars = (TCHAR*)resize(Fvars,(i+nVars)*sizeof(TCHAR) );
  1556. Fsubs = (TCHAR **)resize(Fsubs,(i+nVars)*sizeof(TCHAR *) );
  1557. if (Fvars == NULL || Fsubs == NULL) {
  1558. PutStdErr(MSG_NO_MEMORY, NOARGS );
  1559. Abort( );
  1560. }
  1561. for (nTok=1; nTok<nVars; nTok++) {
  1562. Fvars[i+nTok] = (TCHAR)(pForNode->forvar+nTok);
  1563. Fsubs[i+nTok] = NULL;
  1564. }
  1565. Fvars[i+nTok] = NULLC;
  1566. }
  1567. }
  1568. //
  1569. // Parse string between parenthesis. Only parse it if present and
  1570. // not either the Command Line or Literal String mode
  1571. //
  1572. argtoks = pForNode->arglist;
  1573. if (bNewSemantics) {
  1574. chCmdLine = TEXT('`');
  1575. chLiteralString = TEXT('\'');
  1576. } else {
  1577. chCmdLine = TEXT('\'');
  1578. chLiteralString = QUOTE;
  1579. }
  1580. if (!argtoks || (*argtoks != chCmdLine && *argtoks != chLiteralString))
  1581. //
  1582. // If not the command line form, then tokenize the set of file names
  1583. //
  1584. argtoks = TokStr(argtoks, NULL, TS_NOFLAGS);
  1585. // Now loop over the set of files, opening and parsing each one.
  1586. //
  1587. nSkipSave = nSkip;
  1588. for (datacount = 0; *argtoks && !GotoFlag; argtoks += argtoklen+1) {
  1589. FvarRestore();
  1590. CheckCtrlC();
  1591. s1 = sEnd = NULL;
  1592. tmpargtoks = NULL;
  1593. nSkip = nSkipSave;
  1594. argtoklen = mystrlen( argtoks );
  1595. if (*argtoks == chCmdLine && argtoklen > 1 && argtoks[argtoklen-1] == chCmdLine) {
  1596. FILE *pChildOutput;
  1597. char *spBegin;
  1598. size_t cbUsed, cbTotal;
  1599. //
  1600. // If the file name is a quoted string, with single quotes, then it is a command
  1601. // line to execute. So strip off the quotes. Note that the for() loop expects
  1602. // there to be a double NUL at the end. However, we DON'T have such a thing here
  1603. // since we never called TokStr. We fake this by putting in a NUL to terminate
  1604. // the command line and then lie about the length
  1605. //
  1606. argtoks += 1;
  1607. argtoklen -= 2;
  1608. argtoks[argtoklen] = NULLC;
  1609. //
  1610. // Execute the command line, getting a handle to its standard output
  1611. // stream.
  1612. //
  1613. pChildOutput = _tpopen( argtoks, TEXT( "rb" ));
  1614. if (pChildOutput == NULL) {
  1615. PutStdErr(MSG_DIR_BAD_COMMAND_OR_FILE, ONEARG, argtoks);
  1616. return(GetLastError());
  1617. }
  1618. //
  1619. // Now read the standard output stream, collecting it into allocated
  1620. // memory so we can parse it when the command finishes. Read until
  1621. // we hit EOF or an error on the child output handle.
  1622. //
  1623. cbUsed = cbTotal = 0;
  1624. spBegin = NULL;
  1625. while (!feof(pChildOutput) && !ferror(pChildOutput)) {
  1626. if ((cbTotal-cbUsed) < 512) {
  1627. cbTotal += 256;
  1628. if (spBegin)
  1629. spBegin = resize(spBegin, cbTotal);
  1630. else
  1631. spBegin = mkstr(cbTotal);
  1632. if (spBegin == NULL) {
  1633. PutStdErr(MSG_NO_MEMORY, ONEARG, argtoks);
  1634. _pclose(pChildOutput);
  1635. return(ERROR_NOT_ENOUGH_MEMORY);
  1636. }
  1637. }
  1638. spBegin[cbUsed] = TEXT( '\0' );
  1639. if (!fgets(spBegin+cbUsed, (int)(cbTotal-cbUsed), pChildOutput))
  1640. break;
  1641. cbUsed = strlen(spBegin);
  1642. }
  1643. //
  1644. // All done. Close the child output handle, which will actually wait
  1645. // for the child process to terminate.
  1646. //
  1647. _pclose(pChildOutput);
  1648. //
  1649. // Reallocate memory to what we actually need for the UNICODE representation
  1650. //
  1651. spBegin = resize(spBegin, (cbUsed+2) * sizeof(TCHAR));
  1652. if (Fvars == NULL || Fsubs == NULL) {
  1653. PutStdErr(MSG_NO_MEMORY, ONEARG, argtoks);
  1654. return(ERROR_NOT_ENOUGH_MEMORY);
  1655. }
  1656. //
  1657. // Move the ANSI data to the second half of the buffer so we can convert it
  1658. // to UNICODE
  1659. //
  1660. memmove(spBegin+cbUsed, spBegin, cbUsed);
  1661. tmpargtoks = (TCHAR *)spBegin;
  1662. dwFileSize = dwBytesRead = cbUsed;
  1663. //
  1664. // No go treat the in memory buffer we have created as if it were a
  1665. // file read in from disk.
  1666. //
  1667. goto gotfileinmemory;
  1668. } else if (*argtoks == chLiteralString
  1669. && argtoklen > 1
  1670. && argtoks[argtoklen-1] == chLiteralString) {
  1671. //
  1672. // If the file name is a literal string then it is an immediate
  1673. // string to be parsed. Fake things up for the parsing logic
  1674. // and fall through to it.
  1675. //
  1676. argtoks[argtoklen - 1] = NLN;
  1677. argtoks += 1;
  1678. argtoklen -= 2;
  1679. s1 = argtoks;
  1680. sEnd = s1 + argtoklen + 1;
  1681. } else {
  1682. if (*argtoks == QUOTE) {
  1683. argtoks += 1;
  1684. argtoklen -= 1;
  1685. s1 = lastc(argtoks);
  1686. if (*s1 == QUOTE) {
  1687. do {
  1688. *s1-- = NULLC;
  1689. }
  1690. while (s1 >= argtoks && *s1 == SPACE);
  1691. }
  1692. }
  1693. //
  1694. // We have an actual file name to try to open and read. So do it
  1695. //
  1696. hFile = CreateFile( argtoks,
  1697. GENERIC_READ,
  1698. FILE_SHARE_READ | FILE_SHARE_DELETE,
  1699. NULL,
  1700. OPEN_EXISTING,
  1701. 0,
  1702. NULL
  1703. );
  1704. if (hFile == INVALID_HANDLE_VALUE) {
  1705. PutStdErr(MSG_CMD_FILE_NOT_FOUND, ONEARG, argtoks);
  1706. return GetLastError();
  1707. } else {
  1708. BOOL b;
  1709. dwFileSize = SetFilePointer(hFile, 0, NULL, FILE_END);
  1710. SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
  1711. tmpargtoks = mkstr((dwFileSize+2) * sizeof( TCHAR ));
  1712. if (tmpargtoks == NULL) {
  1713. PutStdErr(MSG_NO_MEMORY, ONEARG, argtoks);
  1714. CloseHandle( hFile );
  1715. return(ERROR_NOT_ENOUGH_MEMORY);
  1716. }
  1717. dwBytesRead = 0xFFFFFFFF;
  1718. b = ReadFile( hFile,
  1719. #ifdef UNICODE
  1720. (LPSTR)tmpargtoks+dwFileSize,
  1721. #else
  1722. tmpargtoks,
  1723. #endif
  1724. dwFileSize,
  1725. &dwBytesRead,
  1726. NULL
  1727. );
  1728. CloseHandle(hFile);
  1729. if (!b) {
  1730. dwBytesRead = 0;
  1731. }
  1732. gotfileinmemory:
  1733. if (dwBytesRead == dwFileSize) {
  1734. //
  1735. // Successfully opened and read the data. Convert it to UNICODE
  1736. // and setup the variables for the parsing loop
  1737. //
  1738. #ifdef UNICODE
  1739. #ifdef FE_SB
  1740. dwFileSize =
  1741. #endif
  1742. MultiByteToWideChar(CurrentCP,
  1743. MB_PRECOMPOSED,
  1744. (LPSTR)tmpargtoks+dwFileSize,
  1745. dwFileSize,
  1746. tmpargtoks,
  1747. dwFileSize);
  1748. #endif
  1749. s1 = tmpargtoks;
  1750. sEnd = s1 + dwFileSize;
  1751. if (sEnd == s1 || sEnd[-1] != NLN)
  1752. *sEnd++ = NLN;
  1753. *sEnd = NULLC;
  1754. }
  1755. }
  1756. }
  1757. //
  1758. // This is the parsing loop
  1759. //
  1760. // s1 points to next character.
  1761. // sEnd points just after the last valid character to parse
  1762. //
  1763. // Loop isolates next line in input buffer, parse that line,
  1764. // Passes any tokens from the line to body of the FOR loop and
  1765. // then loops.
  1766. //
  1767. while (s1 < sEnd && !GotoFlag) {
  1768. CheckCtrlC();
  1769. //
  1770. // Not past the end of the buffer. Find the next
  1771. // newline
  1772. //
  1773. s1 = _tcschr(s2=s1, NLN);
  1774. //
  1775. // If no newline, then done parsing
  1776. //
  1777. if (s1 == NULL)
  1778. break;
  1779. //
  1780. // If CRLF, nuke the CR and the LF
  1781. //
  1782. if (s1 > s2 && s1[-1] == CR)
  1783. s1[-1] = NULLC;
  1784. *s1++ = NULLC;
  1785. //
  1786. // Done skipping input lines?
  1787. //
  1788. if (!nSkip) {
  1789. //
  1790. // Yes, parse this line
  1791. //
  1792. for (nTok=1; nTok<nVars; nTok++) {
  1793. Fsubs[i+nTok] = NULL;
  1794. }
  1795. nTok = 0;
  1796. nTokBits = 0;
  1797. //
  1798. // Null is the end of line marker now
  1799. //
  1800. while (*s2) {
  1801. //
  1802. // Skip any leading delimeters
  1803. //
  1804. while (*s2 && _tcschr(delims, *s2) != NULL)
  1805. s2++;
  1806. //
  1807. // If first character is eol comment character than
  1808. // skip this line
  1809. //
  1810. if (nTok == 0 && *s2==eol)
  1811. break;
  1812. //
  1813. // Remember start of token
  1814. //
  1815. sToken = s2;
  1816. if (nTokStar != 0 && (nTokBits+1) == nTokStar) {
  1817. Fsubs[i+nTokBits] = sToken;
  1818. nTokBits += 1;
  1819. break;
  1820. }
  1821. //
  1822. // Find the end of the token
  1823. //
  1824. while (*s2 && !_tcschr(delims, *s2))
  1825. s2 += 1;
  1826. //
  1827. // If we got a token, and it is not more than we can
  1828. // handle, then see if they want this token. If so,
  1829. // set the value of the appropriate FOR variable
  1830. //
  1831. if (sToken != s2 && nTok < 32) {
  1832. if ((nTokenMask & (1 << nTok++)) != 0) {
  1833. Fsubs[i+nTokBits] = sToken;
  1834. nTokBits += 1;
  1835. }
  1836. }
  1837. //
  1838. // If we're not at the end of the string, terminate this
  1839. // token and advance
  1840. //
  1841. if (*s2 != NULLC) {
  1842. *s2++ = NULLC;
  1843. }
  1844. }
  1845. //
  1846. // If we set any FOR variables, then run the body of the FOR loop
  1847. //
  1848. if (nTokBits) {
  1849. forretcode = FWork(pForNode->body,bFirstLoop);
  1850. datacount = ForFree(datacount);
  1851. bFirstLoop = FALSE;
  1852. }
  1853. } else
  1854. nSkip -= 1;
  1855. }
  1856. //
  1857. // If we allocated memory for the output of the command line, free it up
  1858. //
  1859. if (tmpargtoks != NULL) {
  1860. FreeStr( tmpargtoks );
  1861. tmpargtoks = NULL;
  1862. }
  1863. }
  1864. //
  1865. // If we used any additonal FOR variables, clear them here as we are done with them,
  1866. //
  1867. if (nVars > 1 && Fvars && (*Fvars)) {
  1868. Fvars[i+1] = NULLC;
  1869. Fsubs[i+1] = NULL;
  1870. }
  1871. return(forretcode);
  1872. }
  1873. /*** FLoopWork - controls the execution of a For loop
  1874. *
  1875. * Purpose:
  1876. * Execute a FOR loop statement for a given set
  1877. *
  1878. * FLoopWork(struct fornode *pForNode, PCPYINFOfsinfo, int i, TCHAR *argtoks, BOOL bFirstLoop
  1879. *
  1880. * Args:
  1881. * pForNode - pointer to the FOR parse tree node
  1882. * fsinfo - work buffer for expanding file specification wildcards
  1883. * i - FOR variable index in Fvars and Fsubs arrays
  1884. * argtoks - the tokenized data set to loop over
  1885. * bFirstLoop - TRUE if first time through loop
  1886. *
  1887. * Returns:
  1888. * The retcode of the last statement executed in the for body or FORERROR.
  1889. *
  1890. */
  1891. FLoopWork(
  1892. struct fornode *pForNode,
  1893. PCPYINFO fsinfo,
  1894. int i,
  1895. TCHAR *argtoks,
  1896. BOOL bFirstLoop
  1897. )
  1898. {
  1899. TCHAR *forexpname; /* Used to hold expanded fspec */
  1900. WIN32_FIND_DATA buf; /* Buffer for find first/next */
  1901. HANDLE hnFirst; /* handle from ffirst() */
  1902. int datacount; /* Elts on data stack not to free */
  1903. int forretcode = SUCCESS;
  1904. int catspot; /* Add fnames to forexpname here */
  1905. int argtoklen;
  1906. DWORD forexpnamelen;
  1907. DWORD dwMatchAttributes;
  1908. //
  1909. // Loop, processing each string in the argtoks set
  1910. //
  1911. for (datacount = 0; *argtoks && !GotoFlag; argtoks += argtoklen+1) {
  1912. FvarRestore();
  1913. DEBUG((BPGRP, FOLVL, "FOR: element %d = `%ws'",i ,argtoks));
  1914. CheckCtrlC();
  1915. //
  1916. // Save the length of next string in set so we can skip over it
  1917. //
  1918. argtoklen = mystrlen( argtoks );
  1919. if (!(mystrchr(argtoks, STAR) || mystrchr(argtoks, QMARK))) {
  1920. //
  1921. // String contains no wildcard characters, so set the value of
  1922. // the FOR variable to the string and evaluate the body of the
  1923. // FOR loop
  1924. //
  1925. Fsubs[i] = argtoks;
  1926. forretcode = FWork(pForNode->body,bFirstLoop);
  1927. datacount = ForFree(datacount);
  1928. bFirstLoop = FALSE;
  1929. } else { /* Else, expand wildcards */
  1930. forexpnamelen = 0;
  1931. forexpname = NULL;
  1932. //
  1933. // String contains file specification wildcard characters.
  1934. // Expand the reference into one or more file or directory names,
  1935. // processing each name as a string
  1936. //
  1937. dwMatchAttributes = (pForNode->flag & FOR_MATCH_DIRONLY) ? A_AEVH : A_AEDVH;
  1938. mystrcpy( argtoks, StripQuotes( argtoks ) );
  1939. if (ffirst(argtoks, dwMatchAttributes, &buf, &hnFirst)) {
  1940. //
  1941. // Found at least one file. Parse it as a file name.
  1942. //
  1943. fsinfo->fspec = argtoks;
  1944. ScanFSpec(fsinfo);
  1945. //
  1946. // Remember where the file name portion is so we can append each
  1947. // matching file name to create a full path.
  1948. //
  1949. catspot = (fsinfo->pathend) ? (int)(fsinfo->pathend-fsinfo->fspec+1) : 0;
  1950. if (forexpnamelen < mystrlen(fsinfo->fspec)) {
  1951. forexpnamelen = mystrlen(fsinfo->fspec)+1;
  1952. if (forexpname == NULL)
  1953. forexpname = mkstr(forexpnamelen*sizeof(TCHAR));
  1954. else
  1955. forexpname = resize(forexpname, forexpnamelen*sizeof(TCHAR));
  1956. }
  1957. if (forexpname == NULL) {
  1958. PutStdErr( MSG_NO_MEMORY, NOARGS );
  1959. Abort( );
  1960. }
  1961. mystrcpy(forexpname, fsinfo->fspec);
  1962. do {
  1963. FvarRestore(); /* @@ */
  1964. //
  1965. // Copy current file name into full path buffer
  1966. //
  1967. if (forexpnamelen < (forexpnamelen+mystrlen(buf.cFileName))) {
  1968. forexpnamelen += mystrlen(buf.cFileName);
  1969. if (forexpname == NULL)
  1970. forexpname = mkstr(forexpnamelen*sizeof(TCHAR));
  1971. else
  1972. forexpname = resize(forexpname, forexpnamelen*sizeof(TCHAR));
  1973. if (forexpname == NULL) {
  1974. PutStdErr( MSG_NO_MEMORY, NOARGS );
  1975. Abort( );
  1976. }
  1977. }
  1978. mystrcpy(&forexpname[catspot], buf.cFileName);
  1979. //
  1980. // See if user wants files or directories and what we have
  1981. // and evaluate the body of the FOR loop if we have what the
  1982. // user wants. Ignore the bogus . and .. directory names
  1983. // returned by file systems.
  1984. //
  1985. if (!(pForNode->flag & FOR_MATCH_DIRONLY) ||
  1986. (buf.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
  1987. _tcscmp(buf.cFileName, TEXT(".")) &&
  1988. _tcscmp(buf.cFileName, TEXT("..")))) {
  1989. DEBUG((BPGRP, FOLVL, "FOR: forexpname = `%ws'", forexpname));
  1990. //
  1991. // User wants this file or directory name, so set
  1992. // the value of the FOR variable and evaluate the
  1993. // body of the FOR loop.
  1994. //
  1995. Fsubs[i] = forexpname;
  1996. forretcode = FWork(pForNode->body,bFirstLoop);
  1997. bFirstLoop = FALSE;
  1998. }
  1999. //
  2000. // Check for CtrlC and then get next matching file name
  2001. //
  2002. CheckCtrlC();
  2003. } while (fnext(&buf, dwMatchAttributes, hnFirst) && !GotoFlag);
  2004. datacount = ForFree(datacount);
  2005. //
  2006. // No more matching files, close the find handle
  2007. // Even though we've completed an iteration, we may NOT be the first
  2008. // pass through the loop since nothing may have been enumerated
  2009. //
  2010. findclose(hnFirst); /* @@4-@@M1 */
  2011. }
  2012. }
  2013. }
  2014. return(forretcode);
  2015. }
  2016. /*** FWork - controls the execution of 1 iteration of a For loop
  2017. *
  2018. * Purpose:
  2019. * Execute a FOR loop statement.
  2020. *
  2021. * FWork(struct node *n, TCHAR var, TCHAR *varval)
  2022. *
  2023. * Args:
  2024. * n - pointer to the body of the FOR loop
  2025. * bFirstLoop - TRUE if first time through loop
  2026. *
  2027. * Returns:
  2028. * The retcode of the last statement executed in the for body or FORERROR.
  2029. *
  2030. */
  2031. FWork(n,bFirstLoop)
  2032. struct node *n;
  2033. BOOL bFirstLoop;
  2034. {
  2035. int forretcode; /* Dispatch Retcode or FORERROR */
  2036. void DisplayStatement(); /* M008 - made void */
  2037. DEBUG((BPGRP, FOLVL, "FW: Entered; Substituting variable"));
  2038. if (SubFor(n,bFirstLoop)) {
  2039. return(FORERROR);
  2040. } else {
  2041. DEBUG((BPGRP, FOLVL, "FW: EchoFlag = %d", EchoFlag));
  2042. if (EchoFlag == E_ON && n->type != SILTYP && !Necho) {
  2043. PrintPrompt();
  2044. DisplayStatement(n, DSP_SIL); /* M019 */
  2045. cmd_printf(CrLf); /* M026 */
  2046. }
  2047. forretcode = Dispatch(RIO_OTHER,n); /* M000 */
  2048. }
  2049. DEBUG((BPGRP, FOLVL, "FW: Returning %d", forretcode));
  2050. return(forretcode);
  2051. }
  2052. /*** SubFor - controls FOR variable substitutions
  2053. *
  2054. * Purpose:
  2055. * To walk a parse tree and make FOR variable substitutions on
  2056. * individual nodes. SFWork() is called to do individual string
  2057. * substitutions.
  2058. *
  2059. * int SubFor(struct node *n)
  2060. *
  2061. * Args:
  2062. * n - pointer to the statement subtree in which the substitutions are
  2063. * to be made
  2064. * bFirstLoop - TRUE if first time through loop
  2065. *
  2066. * Returns:
  2067. * SUCCESS if all goes well.
  2068. * FAILURE if an oversized command is found.
  2069. *
  2070. * Note:
  2071. * The variables to be substituted for are contained in Fvars and
  2072. * Fsubs is an array of string pointers to corresponding replacement
  2073. * strings. For I/O redirection, the list contained in the node
  2074. * must also be walked and its filespec strings examined.
  2075. *
  2076. */
  2077. int SubFor(n,bFirstLoop)
  2078. struct node *n;
  2079. BOOL bFirstLoop;
  2080. {
  2081. int j; /* Temps used to make substitutions... */
  2082. struct relem *io; /* M017 - Pointer to redir list */
  2083. DEBUG((BPGRP, FOLVL, "SUBFOR: Entered."));
  2084. if (!n) {
  2085. DEBUG((BPGRP, FOLVL, "SUBFOR: Found NULL node."));
  2086. return(0);
  2087. }
  2088. switch (n->type) {
  2089. case LFTYP:
  2090. case CSTYP:
  2091. case ORTYP:
  2092. case ANDTYP:
  2093. case PIPTYP:
  2094. case PARTYP:
  2095. case SILTYP: /* M019 - New type */
  2096. DEBUG((BPGRP, FOLVL, "SUBFOR: Found operator."));
  2097. if (SubFor(n->lhs,bFirstLoop) ||
  2098. SubFor(n->rhs,bFirstLoop))
  2099. return(FAILURE);
  2100. for (j=0, io=n->rio; j < 10 && io; j++, io=io->nxt) {
  2101. // can't pass freed io->fname
  2102. DEBUG((BPGRP, FOLVL, "SUBFOR: s = %lx", &io->fname));
  2103. if (SFWork(n, &io->fname, j,bFirstLoop))
  2104. return(FAILURE);
  2105. DEBUG((BPGRP, FOLVL, "SUBFOR: *s = `%ws' &*s = %lx", io->fname, &io->fname));
  2106. }
  2107. return(SUCCESS);
  2108. /* M017 ends */
  2109. case FORTYP:
  2110. DEBUG((BPGRP, FOLVL, "SUBFOR: Found FOR."));
  2111. if (SFWork(n, &((struct fornode *) n)->arglist, 0,bFirstLoop))
  2112. return(FAILURE);
  2113. return(SubFor(((struct fornode *)n)->body,bFirstLoop));
  2114. case IFTYP:
  2115. DEBUG((BPGRP, FOLVL, "SUBFOR: Found IF."));
  2116. if (SubFor((struct node *)((struct ifnode *) n)->cond,bFirstLoop) ||
  2117. SubFor((struct node *)((struct ifnode *) n)->ifbody,bFirstLoop))
  2118. return(FAILURE);
  2119. return(SubFor(((struct ifnode *)n)->elsebody,bFirstLoop));
  2120. case NOTTYP:
  2121. DEBUG((BPGRP, FOLVL, "SUBFOR: Found NOT."));
  2122. return(SubFor((struct node *)((struct cmdnode *)n)->argptr,bFirstLoop));
  2123. case REMTYP: /* M009 - Rem now separate type */
  2124. case CMDTYP:
  2125. case CMDVERTYP:
  2126. case ERRTYP:
  2127. case DEFTYP:
  2128. case EXSTYP:
  2129. case STRTYP:
  2130. case CMPTYP:
  2131. DEBUG((BPGRP, FOLVL, "SUBFOR: Found command."));
  2132. if (SFWork(n, &((struct cmdnode *)n)->cmdline, 0,bFirstLoop) ||
  2133. SFWork(n, &((struct cmdnode *)n)->argptr, 1,bFirstLoop))
  2134. return(FAILURE);
  2135. for (j=2, io=n->rio; j < 12 && io; j++, io=io->nxt) {
  2136. // can't pass freed io->fname
  2137. DEBUG((BPGRP, FOLVL, "SUBFOR: s = %lx ", &io->fname) );
  2138. if (SFWork(n, &io->fname, j,bFirstLoop))
  2139. return(FAILURE);
  2140. DEBUG((BPGRP, FOLVL, "SUBFOR: *s = `%ws' &*s = %lx", io->fname, &io->fname));
  2141. }
  2142. /* M017 ends */
  2143. return(SUCCESS);
  2144. }
  2145. // If we get here we have an invalid node type. All case entries should
  2146. // return themselfs.
  2147. DEBUG((BPGRP, FOLVL, "SUBFOR: Invalid Node type"));
  2148. return(0);
  2149. }
  2150. /*** SFWork - does batch file variable substitutions
  2151. *
  2152. * Purpose:
  2153. * Make FOR variable substitutions in a single string. If a FOR loop
  2154. * substitution is being made, a pointer to the original string is
  2155. * saved so that it can be used for subsequent iterations.
  2156. *
  2157. * SFWork(struct node *n, TCHAR **src, int index)
  2158. *
  2159. * Args:
  2160. * n - parse tree node containing the string being substituted
  2161. * src - the string being examined
  2162. * index - index in save structure
  2163. * bFirstLoop - TRUE if first time through loop
  2164. *
  2165. * Returns:
  2166. * SUCCESS if substitutions could be made.
  2167. * FAILURE if the new string is too long.
  2168. *
  2169. * Notes:
  2170. *
  2171. */
  2172. SFWork(n, src, index, bFirstLoop)
  2173. struct node *n;
  2174. TCHAR **src;
  2175. int index;
  2176. BOOL bFirstLoop;
  2177. {
  2178. TCHAR *dest; /* Destination string pointer */
  2179. TCHAR *srcstr, /* Source string pointer */
  2180. *srcpy, /* Copy of srcstr */
  2181. *t, /* Temp pointer */
  2182. c; /* Current character being copied */
  2183. int dlen; /* Length of dest string */
  2184. int sslen, /* Length of substr */
  2185. i; /* Work variable */
  2186. DEBUG((BPGRP, FOLVL, "SFW: Entered."));
  2187. if (*src == NULL) {
  2188. DEBUG((BPGRP, FOLVL, "SFW: Passed null ptr, returning now."));
  2189. return(SUCCESS);
  2190. }
  2191. /* If this string has been previously substituted, get the original string.
  2192. * Else, "*src" is the original.
  2193. */
  2194. if (n->save.saveptrs[index]) {
  2195. srcpy = n->save.saveptrs[index];
  2196. DEBUG((BPGRP, FOLVL, "SFW: Src is saved string `%ws'",srcpy));
  2197. } else {
  2198. if (!bFirstLoop) {
  2199. // arg got created. get rid of it.
  2200. *src = NULL;
  2201. return(SUCCESS);
  2202. }
  2203. srcpy = *src;
  2204. DEBUG((BPGRP, FOLVL, "SFW: Src is passed string `%ws'",srcpy));
  2205. }
  2206. srcstr = srcpy;
  2207. if (!(dest = mkstr((MAXTOKLEN+1)*sizeof(TCHAR))))
  2208. return(FAILURE);
  2209. DEBUG((BPGRP, FOLVL, "SFW: dest = %lx", dest));
  2210. for (dlen = 0; (c = *srcstr++) && dlen <= MAXTOKLEN; ) {
  2211. //
  2212. // See if we have a percent character indicating a variable
  2213. // reference. If not, continue scanning.
  2214. //
  2215. if ( (c != PERCENT) || ( !(*srcstr)) || *srcstr == PERCENT) { /* @@4 */
  2216. DEBUG((BPGRP, FOLVL, " SFW: No PERCENT adding `%c'", c));
  2217. *dest++ = c;
  2218. dlen++;
  2219. continue;
  2220. }
  2221. //
  2222. // Found a percent character which might represent a for loop
  2223. // variable reference.
  2224. //
  2225. // If extensions are enabled then use the new substitution routine
  2226. // that supports path manipulation, etc. If it succeeds, accept
  2227. // its substitution.
  2228. //
  2229. if (fEnableExtensions && (t = MSCmdVar(NULL, srcstr, &sslen, Fvars, Fsubs))) {
  2230. srcstr += sslen;
  2231. sslen = mystrlen(t); /* Calc length */
  2232. if (dlen+sslen > MAXTOKLEN) /* Too long? */
  2233. return(FAILURE); /* ...yes, quit */
  2234. mystrcpy(dest, t);
  2235. dlen += sslen;
  2236. dest += sslen;
  2237. continue;
  2238. }
  2239. //
  2240. // Either extensions are disabled or new code could not
  2241. // resolve the variable references, so let the old code
  2242. // do it.
  2243. //
  2244. c = *srcstr++;
  2245. DEBUG((BPGRP, FOLVL, " SFW: Got PERCENT next is `%c'", c));
  2246. DEBUG((BPGRP, FOLVL, " SFW: Fvars are `%ws' @ %lx", Fvars, Fvars));
  2247. if (t = mystrrchr(Fvars,c)) { /* @@4 */ /* If c is var */
  2248. i = (int)(t - Fvars); /* ...make index */
  2249. DEBUG((BPGRP, FOLVL, " SFW: Found @ %lx", t));
  2250. DEBUG((BPGRP, FOLVL, " SFW: Index is %d", i));
  2251. DEBUG((BPGRP, FOLVL, " SFW: Substitute is `%ws'", Fsubs[i]));
  2252. sslen = mystrlen(Fsubs[i]); /* Calc length */
  2253. if (dlen+sslen > MAXTOKLEN) /* Too long? */
  2254. return(FAILURE); /* ...yes, quit */
  2255. DEBUG((BPGRP, FOLVL, " SFW: Copying to dest."));
  2256. mystrcpy(dest, Fsubs[i]);
  2257. dlen += sslen;
  2258. dest += sslen;
  2259. DEBUG((BPGRP, FOLVL, "SFW: Forsub, dest = `%ws'", dest-dlen));
  2260. } else {
  2261. DEBUG((BPGRP, FOLVL, " SFW: Not a var adding PERCENT and `%c'",c));
  2262. *dest++ = PERCENT;
  2263. *dest++ = c;
  2264. dlen += 2;
  2265. }
  2266. }
  2267. DEBUG((BPGRP, FOLVL, "SFW: Done, dlen = %d dest = `%ws'", dlen, dest-dlen));
  2268. if (dlen > MAXTOKLEN) {
  2269. DEBUG((BPGRP, FOLVL, "SFW: Error, too long."));
  2270. return(FAILURE);
  2271. }
  2272. DEBUG((BPGRP, FOLVL, "SFW: Saving FOR string."));
  2273. if (bFirstLoop) {
  2274. n->save.saveptrs[index] = srcpy;
  2275. }
  2276. if (!(*src = (TCHAR*)resize(dest-dlen, (dlen+1)*sizeof(TCHAR*)))) /* Free unused spc */
  2277. return(FAILURE);
  2278. DEBUG((BPGRP, FOLVL, "SFW: After resize *src = `%ws'", *src));
  2279. return(SUCCESS);
  2280. }
  2281. /*** ForFree - controls memory freeing during For loop execution
  2282. *
  2283. * Purpose:
  2284. * To free up space used during the execution of a for loop body as
  2285. * explained in the note in the comments for eFor(). If datacount
  2286. * is 0, this is the first time ForFree() has been called so DCount
  2287. * is used to get the number of elements on the data stack that must
  2288. * stay there for the corect execution of the loop. If datacount is
  2289. * not 0, it is the number discussed above. In this case, this number
  2290. * is passed to FreeStack().
  2291. *
  2292. * int ForFree(int datacount)
  2293. *
  2294. * Args:
  2295. * datacount - see above
  2296. *
  2297. * Returns:
  2298. * Datacount
  2299. *
  2300. */
  2301. int ForFree(datacount)
  2302. int datacount;
  2303. {
  2304. if (datacount)
  2305. FreeStack(datacount);
  2306. else
  2307. datacount = DCount;
  2308. return(datacount);
  2309. }
  2310. /*** eGoto - executes a Goto statement
  2311. *
  2312. * Purpose:
  2313. * Find the label associated with the goto command and set the file
  2314. * position field in the current batch job structure to the position
  2315. * right after the label. After the label is found, set the GotoFlag.
  2316. * This tells function eFor() to stop executing a for loop and it
  2317. * tells Dispatch() that no more commands are to be executed until
  2318. * the flag is reset. This way, if the goto command is buried inside
  2319. * of any kind of compound statement, Command will be able to work its
  2320. * way out of the statement and reset I/O redirection before continuing
  2321. * with the statement after the label which was found.
  2322. *
  2323. * If the label isn't found, an error message is printed and the
  2324. * current batch job is terminated by popping its structure of the
  2325. * stack.
  2326. *
  2327. * If no batch job is in progress, this command is a nop.
  2328. *
  2329. * int eGoto(struct cmdnode *n)
  2330. *
  2331. * Args:
  2332. * n - parse tree node containing the goto command
  2333. *
  2334. * Returns:
  2335. * SUCCESS if the label is found.
  2336. * FAILURE otherwise.
  2337. *
  2338. * Notes:
  2339. * M030 - This function has been completely rewritten for speed-up
  2340. * of GOTO label searches. Now uses complete 257 byte temporary
  2341. * buffer.
  2342. * M031 - Function altered to speed up GOTO's. Optimized for
  2343. * forward searches and buffer increased to 512 bytes.
  2344. *
  2345. */
  2346. //
  2347. // BUFFERLENGTH is the amount we read from the batch file each
  2348. // time we fill the internal buffer
  2349. //
  2350. #define BUFFERLENGTH 512
  2351. int eGoto(n)
  2352. struct cmdnode *n;
  2353. {
  2354. struct batdata *bdat;
  2355. unsigned cnt; /* Count of bytes read from file */
  2356. TCHAR s[128], /* Ptr to search label */
  2357. t[128], /* Ptr to found label */
  2358. *p1, /* Place keeper ptr 1 */
  2359. *p2, /* Place keeper ptr 2 */
  2360. *p3; /* Place keeper ptr 3 */
  2361. CRTHANDLE fh; /* Batch file handle */
  2362. int frstpass = TRUE, /* First time through indicator */
  2363. gotoretcode = SUCCESS; /* Just what it says */
  2364. long Backup, /* Rewind count for seek */
  2365. savepos; /* Save location for file pos */
  2366. DWORD filesize;
  2367. DEBUG((BPGRP, OTLVL, "GOTO: CurrentBatchFile = %lx", CurrentBatchFile));
  2368. if (!(bdat = CurrentBatchFile))
  2369. return(FAILURE);
  2370. //
  2371. // If no target of goto is present, then treat it like a label-not-found
  2372. //
  2373. if ( n->argptr == NULL) {
  2374. EndAllLocals(bdat);
  2375. CurrentBatchFile = bdat->backptr;
  2376. PutStdErr(MSG_NO_BAT_LABEL, NOARGS);
  2377. DEBUG((BPGRP, OTLVL, "GOTO: No label to goto, returning FAILURE, CurrentBatchFile = %lx", CurrentBatchFile));
  2378. return FAILURE;
  2379. }
  2380. ParseLabel( n->argptr, s, sizeof( s ) / sizeof( s[0] ), TRUE ); /* TRUE indicates source label */
  2381. savepos = bdat->filepos;
  2382. if ((fh = OpenPosBat( bdat )) == BADHANDLE)
  2383. return(FAILURE); /* Err if can't open */
  2384. DEBUG((BPGRP, OTLVL, "GOTO: label = %ws", s));
  2385. DEBUG((BPGRP, OTLVL, "GOTO: fh = %d", fh));
  2386. filesize = GetFileSize(CRTTONT(fh), NULL);
  2387. //
  2388. // If extensions are enabled, see if they are using the command script
  2389. // equivalent of return, which is GOTO :EOF. If so, set the current
  2390. // position to the end of file and fall through to the normal end of
  2391. // command script logic.
  2392. //
  2393. p2 = EatWS(n->argptr,NULL);
  2394. if (fEnableExtensions &&
  2395. !_tcsnicmp( p2, GotoEofStr, 4 ) &&
  2396. (!p2[4] || _istspace( p2[4] ))
  2397. ) {
  2398. bdat->filepos = filesize;
  2399. GotoFlag = TRUE;
  2400. } else
  2401. for (;;) {
  2402. CheckCtrlC();
  2403. if (
  2404. //
  2405. // If we've read beyond where we started in the file and it's the second pass
  2406. //
  2407. ((bdat->filepos = SetFilePointer( CRTTONT( fh ), 0, NULL, FILE_CURRENT )) >= savepos
  2408. && !frstpass)
  2409. //
  2410. // or if we couldn't read from the batch file
  2411. //
  2412. || ReadBufFromInput( CRTTONT( fh ), TmpBuf, BUFFERLENGTH, (LPDWORD)&cnt ) == 0
  2413. //
  2414. // or if there was nothing to read in the batch file (i.e., EOF)
  2415. //
  2416. || cnt == 0
  2417. //
  2418. // or we detected EOF some other way
  2419. //
  2420. || cnt == EOF
  2421. //
  2422. // or if we read a NULL line ???
  2423. //
  2424. || TmpBuf[0] == NULLC
  2425. //
  2426. // or if the label to go to is empty
  2427. //
  2428. || s[0] == NULLC) {
  2429. //
  2430. // If we are at EOF for the first time, then seek back to the beginning of the
  2431. // CMD file and continue scanning
  2432. //
  2433. if (cnt == 0 && frstpass) {
  2434. SetFilePointer( CRTTONT( fh ), 0L, NULL, FILE_BEGIN );
  2435. frstpass = FALSE;
  2436. continue;
  2437. }
  2438. //
  2439. // Terminate this batch file
  2440. //
  2441. EndAllLocals(bdat);
  2442. CurrentBatchFile = bdat->backptr;
  2443. PutStdErr(MSG_MISSING_BAT_LABEL, ONEARG, s);
  2444. DEBUG((BPGRP, OTLVL, "GOTO: Returning FAILURE, CurrentBatchFile = %lx", CurrentBatchFile));
  2445. gotoretcode = FAILURE;
  2446. break;
  2447. }
  2448. //
  2449. // Make sure input line is NUL terminated
  2450. //
  2451. TmpBuf[cnt] = NULLC;
  2452. DEBUG((BPGRP, OTLVL, "GOTO: Got %d bytes @ %lx", cnt, TmpBuf));
  2453. //
  2454. // If there's no :, then we just skip off to the next block of input
  2455. //
  2456. if (!(p1 = mystrchr( TmpBuf, COLON )))
  2457. continue;
  2458. DEBUG((BPGRP, OTLVL, "GOTO: Seeking through the buffer"));
  2459. //
  2460. // Walk through the input buffer looking for end-of-lines and
  2461. // testing to see if there's a label next
  2462. //
  2463. do {
  2464. DEBUG((BPGRP, OTLVL, "GOTO: Found COLON @ %lx.",p1));
  2465. DEBUG((BPGRP, OTLVL, "GOTO: Backing up to NLN."));
  2466. //
  2467. // Back up to the position of the previous EOL or beginning
  2468. // of the buffer
  2469. //
  2470. p2 = p1++;
  2471. while (*p2 != NLN && p2 != &TmpBuf[0]) {
  2472. --p2;
  2473. }
  2474. DEBUG((BPGRP, OTLVL, "GOTO: Found NLN @ %lx.",p1));
  2475. DEBUG((BPGRP, OTLVL, "GOTO: Trashing white space."));
  2476. if (*p2 != COLON)
  2477. ++p2;
  2478. p3 = EatWS(p2,NULL); /* Fwd to 1st non-whtspc */
  2479. DEBUG((BPGRP,OTLVL,"GOTO: Found '%c' @ %lx.",*p2,p2));
  2480. if (*p3 == COLON) {
  2481. DEBUG((BPGRP, OTLVL, "GOTO: Possible label."));
  2482. //
  2483. // Scan forward for the end of the current line
  2484. //
  2485. p1 = mystrchr( p2, NLN );
  2486. //
  2487. // If we don't have a newline and we haven't read up to EOF, then we need to
  2488. // back up to the beginning of the line in the file and attempt to read it in
  2489. // in one entire block. Of course, there's a problem if the line is longer
  2490. // than the buffer. In this case, we simply treat the longer chars as being
  2491. // in the next line. Tough.
  2492. //
  2493. if (p1 == NULL
  2494. && SetFilePointer( CRTTONT( fh ), 0, NULL, FILE_CURRENT ) != filesize
  2495. && cnt != BUFFERLENGTH ) {
  2496. DEBUG((BPGRP, OTLVL, "GOTO: No NLN!"));
  2497. Backup = (long)(cnt - (p2 - &TmpBuf[0]));
  2498. #if defined(FE_SB) && defined(UNICODE) // eGoto()
  2499. if (IsDBCSCodePage()) {
  2500. // We should decrement file pointer in MBCS byte count.
  2501. // Because the file is described by MBCS string.
  2502. Backup = WideCharToMultiByte( CurrentCP, 0, TmpBuf, Backup, NULL, 0, NULL, NULL);
  2503. }
  2504. #endif // defined(FE_SB) && defined(UNICODE)
  2505. SetFilePointer(CRTTONT(fh), -Backup, NULL, FILE_CURRENT);
  2506. DEBUG((BPGRP, OTLVL, "GOTO: Rewound %ld", Backup));
  2507. break; /* Read more */
  2508. }
  2509. ParseLabel( p3, t, sizeof( t ) / sizeof( t[0] ), FALSE ); /* FALSE = target */
  2510. DEBUG((BPGRP,OTLVL,"GOTO: Found label %ws at %lx.",t,p1));
  2511. if (_tcsicmp(s, t) == 0) {
  2512. DEBUG((BPGRP,OTLVL,"GOTO: A match!"));
  2513. GotoFlag = (n->flag & CMDNODE_FLAG_GOTO) != 0;
  2514. DEBUG((BPGRP,OTLVL,"GOTO: NLN at %lx",p1));
  2515. DEBUG((BPGRP,OTLVL,"GOTO: File pos is %04lx",bdat->filepos));
  2516. DEBUG((BPGRP,OTLVL,"GOTO: Adding %lx - %lx = %lx bytes",p1+1,&TmpBuf[0],(p1+1)-&TmpBuf[0]));
  2517. #if defined(FE_SB) // eGoto()
  2518. // We should increment file pointer in MBCS byte count.
  2519. // Because the file is described by MBCS string.
  2520. if ( !p1 ) {
  2521. #ifdef UNICODE
  2522. if (IsDBCSCodePage()) {
  2523. long cbMbcs;
  2524. cbMbcs = WideCharToMultiByte( CurrentCP, 0, TmpBuf, cnt,
  2525. NULL, 0, NULL, NULL);
  2526. bdat->filepos += cbMbcs;
  2527. } else
  2528. bdat->filepos += (long)cnt; /* @@4 */
  2529. #else
  2530. bdat->filepos += (long)cnt; /* @@4 */
  2531. #endif
  2532. } else {
  2533. #ifdef UNICODE
  2534. if (IsDBCSCodePage()) {
  2535. long cbMbcs;
  2536. cbMbcs = WideCharToMultiByte(CurrentCP,0,TmpBuf,(int)(++p1 - &TmpBuf[0]),
  2537. NULL,0,NULL,NULL);
  2538. bdat->filepos += cbMbcs;
  2539. } else
  2540. bdat->filepos += (long)(++p1 - &TmpBuf[0]);
  2541. #else
  2542. bdat->filepos += (long)(++p1 - &TmpBuf[0]);
  2543. #endif
  2544. }
  2545. #else
  2546. if ( !p1 ) { /* @@4 */
  2547. bdat->filepos += (long)cnt; /* @@4 */
  2548. } else { /* @@4 */
  2549. bdat->filepos += (long)(++p1 - &TmpBuf[0]);
  2550. }
  2551. #endif // defined(FE_SB)
  2552. DEBUG((BPGRP,OTLVL,"GOTO: File pos changed to %04lx",bdat->filepos));
  2553. break;
  2554. }
  2555. }
  2556. DEBUG((BPGRP,OTLVL,"GOTO: Next do loop iteration."));
  2557. } while (p1 = mystrchr(p1,COLON));
  2558. DEBUG((BPGRP,OTLVL,"GOTO: Out of do loop GotoFlag = %d.",GotoFlag));
  2559. if (GotoFlag == TRUE)
  2560. break;
  2561. DEBUG((BPGRP,OTLVL,"GOTO: Next for loop iteration."));
  2562. }
  2563. DEBUG((BPGRP,OTLVL,"GOTO: Out of for loop retcode = %d.",gotoretcode));
  2564. Cclose(fh); /* M023 */
  2565. return(gotoretcode);
  2566. }
  2567. /*** eIf - controls the execution of an If statement
  2568. *
  2569. * Purpose:
  2570. * Execute the IF conditional. If the conditional function returns a
  2571. * nonzero value, execute the body of the if statement. Otherwise,
  2572. * execute the body of the else.
  2573. *
  2574. * int eIf(struct ifnode *n)
  2575. *
  2576. * Args:
  2577. * n - the node containing the if statement
  2578. *
  2579. * Returns:
  2580. * The retcode from which ever body (ifbody or elsebody) is executed.
  2581. *
  2582. */
  2583. int eIf(struct ifnode *pIfNode)
  2584. {
  2585. int i;
  2586. struct cmdnode *n;
  2587. BOOLEAN bNot;
  2588. DEBUG((BPGRP, IFLVL, "IF: cond type = %d", pIfNode->cond->type));
  2589. /* The following checks the syntax of an errorlevel arg
  2590. to ensure that only numeric digits are specified.
  2591. */
  2592. n = pIfNode->cond;
  2593. if (n->type == NOTTYP) {
  2594. bNot = TRUE;
  2595. n = (struct cmdnode *)n->argptr;
  2596. } else {
  2597. bNot = FALSE;
  2598. }
  2599. if (n->type == ERRTYP || n->type == CMDVERTYP) {
  2600. for (i = 0; n->argptr[i] != 0; i++) {
  2601. if (i == 0 && n->type == ERRTYP && n->argptr[i] == MINUS) {
  2602. continue;
  2603. }
  2604. if (!_istdigit(n->argptr[i])) {
  2605. PutStdErr(MSG_SYNERR_GENL, ONEARG, n->argptr);
  2606. return(FAILURE);
  2607. }
  2608. }
  2609. }
  2610. if (bNot ^ (BOOLEAN)((*GetFuncPtr(n->type))(n) != 0)) {
  2611. DEBUG((BPGRP, IFLVL, "IF: Executing IF body."));
  2612. return(Dispatch(RIO_OTHER,pIfNode->ifbody)); /* M000 */
  2613. } else {
  2614. DEBUG((BPGRP, IFLVL, "IF: Executing ELSE body."));
  2615. return(Dispatch(RIO_OTHER,pIfNode->elsebody)); /* M000 */
  2616. }
  2617. return(SUCCESS);
  2618. }
  2619. /*** eErrorLevel - executes an errrorlevel If conditional
  2620. *
  2621. * Purpose:
  2622. * If LastRetCode >= the errorlevel in the node, return 1. If not,
  2623. * return 0.
  2624. *
  2625. * int eErrorLevel(struct cmdnode *n)
  2626. *
  2627. * Args:
  2628. * n - parse tree node containing the errorlevel command
  2629. *
  2630. * Returns:
  2631. * See above.
  2632. *
  2633. */
  2634. int eErrorLevel(n)
  2635. struct cmdnode *n;
  2636. {
  2637. DEBUG((BPGRP, IFLVL, "ERRORLEVEL: argptr = `%ws' LRC = %d", n->argptr, LastRetCode));
  2638. return(_tcstol(n->argptr, NULL, 10) <= LastRetCode);
  2639. }
  2640. /*** eCmdExtVer - executes an CMDEXTVERSION If conditional
  2641. *
  2642. * Purpose:
  2643. * If CMDEXTVERSION >= the value in the node, return 1. If not,
  2644. * return 0. This routine is never called unless command extensions
  2645. * are enabled.
  2646. *
  2647. * int eCmdExtVer(struct cmdnode *n)
  2648. *
  2649. * Args:
  2650. * n - parse tree node containing the CMDEXTVERSION command
  2651. *
  2652. * Returns:
  2653. * See above.
  2654. *
  2655. */
  2656. int eCmdExtVer(n)
  2657. struct cmdnode *n;
  2658. {
  2659. DEBUG((BPGRP, IFLVL, "CMDEXTVERSION: argptr = `%ws' VER = %d", n->argptr, CMDEXTVERSION));
  2660. return(_tcstol(n->argptr, NULL, 10) <= CMDEXTVERSION);
  2661. }
  2662. /*** eDefined - execute the DEFINED conditional of an if statement
  2663. *
  2664. * Purpose:
  2665. * Return 1 if the environment variable in node n exists. Otherwise return 0.
  2666. * This routine is never called unless command extensions are enabled.
  2667. *
  2668. * int eDefined(struct cmdnode *n)
  2669. *
  2670. * Args:
  2671. * n - parse tree node containing the exist command
  2672. *
  2673. * Returns:
  2674. * See above.
  2675. *
  2676. */
  2677. int eDefined(n)
  2678. struct cmdnode *n;
  2679. {
  2680. return(GetEnvVar(n->argptr)!= NULL);
  2681. }
  2682. /*** eExist - execute the exist conditional of an if statement
  2683. *
  2684. * Purpose:
  2685. * Return 1 if the file in node n exists. Otherwise return 0.
  2686. *
  2687. * int eExist(struct cmdnode *n)
  2688. *
  2689. * Args:
  2690. * n - parse tree node containing the exist command
  2691. *
  2692. * Returns:
  2693. * See above.
  2694. *
  2695. */
  2696. int eExist(n)
  2697. struct cmdnode *n;
  2698. {
  2699. return(exists(n->argptr));
  2700. }
  2701. /*** eNot - execute the not condition of an if statement
  2702. *
  2703. * Purpose:
  2704. * Return the negated result of the if conditional pointed to by
  2705. * n->argptr.
  2706. *
  2707. * int eNot(struct cmdnode *n)
  2708. *
  2709. * Args:
  2710. * n - parse tree node containing the not command
  2711. *
  2712. * Returns:
  2713. * See above.
  2714. *
  2715. */
  2716. int eNot(n)
  2717. struct cmdnode *n;
  2718. {
  2719. UNREFERENCED_PARAMETER( n );
  2720. #if DBG
  2721. cmd_printf( TEXT("CMD: should never get here\n") );
  2722. DebugBreak();
  2723. #endif
  2724. return 0;
  2725. }
  2726. /*** eStrCmp - execute an if statement string comparison
  2727. *
  2728. * Purpose:
  2729. * Return a nonzero value if the 2 strings in the node are equal.
  2730. * Otherwise return 0.
  2731. *
  2732. * int eStrCmp(struct cmdnode *n)
  2733. *
  2734. * Args:
  2735. * n - the parse tree node containing the string comparison command
  2736. *
  2737. * Returns:
  2738. * See above.
  2739. *
  2740. */
  2741. int eStrCmp(n)
  2742. struct cmdnode *n;
  2743. {
  2744. DEBUG((BPGRP, IFLVL, "STRCMP: returning %d", !_tcscmp(n->cmdline, n->argptr)));
  2745. //
  2746. // If the parse node says to ignore case, do a case insensitive compare
  2747. // otherwise case sensitive. The ignore case will never be set unless
  2748. // command extensions are enabled.
  2749. //
  2750. if (n->flag & CMDNODE_FLAG_IF_IGNCASE)
  2751. return(!lstrcmpi(n->cmdline, n->argptr));
  2752. else
  2753. return(!lstrcmp(n->cmdline, n->argptr));
  2754. }
  2755. /*** eGenCmp - execute an if statement comparison - general case
  2756. *
  2757. * Purpose:
  2758. * Return a nonzero value if comparison condition is met.
  2759. * Otherwise return 0. This routine is never called unless
  2760. * command extensions are enabled.
  2761. *
  2762. * int eStrCmp(struct cmdnode *n)
  2763. *
  2764. * Args:
  2765. * n - the parse tree node containing the string comparison command
  2766. *
  2767. * Returns:
  2768. * See above.
  2769. *
  2770. */
  2771. int eGenCmp(n)
  2772. struct cmdnode *n;
  2773. {
  2774. TCHAR *s1, *s2;
  2775. LONG n1, n2, iCompare;
  2776. n1 = _tcstol(n->cmdline, &s1, 0);
  2777. n2 = _tcstol(n->argptr, &s2, 0);
  2778. if (*s1 == NULLC && *s2 == NULLC)
  2779. iCompare = n1 - n2;
  2780. else
  2781. if (n->flag & CMDNODE_FLAG_IF_IGNCASE)
  2782. iCompare = lstrcmpi(n->cmdline, n->argptr);
  2783. else
  2784. iCompare = lstrcmp(n->cmdline, n->argptr);
  2785. switch (n->cmdarg) {
  2786. case CMDNODE_ARG_IF_EQU:
  2787. return iCompare == 0;
  2788. case CMDNODE_ARG_IF_NEQ:
  2789. return iCompare != 0;
  2790. case CMDNODE_ARG_IF_LSS:
  2791. return iCompare < 0;
  2792. case CMDNODE_ARG_IF_LEQ:
  2793. return iCompare <= 0;
  2794. case CMDNODE_ARG_IF_GTR:
  2795. return iCompare > 0;
  2796. case CMDNODE_ARG_IF_GEQ:
  2797. return iCompare >= 0;
  2798. }
  2799. return 0;
  2800. }
  2801. /*** ePause - execute the Pause command
  2802. *
  2803. * Purpose:
  2804. * Print a message and pause until a character is typed.
  2805. *
  2806. * int ePause(struct cmdnode *n)
  2807. *
  2808. * Args:
  2809. * n - parse tree node containing the pause command
  2810. *
  2811. * Returns:
  2812. * SUCCESS always.
  2813. *
  2814. * Notes:
  2815. * M025 - Altered to use DOSREAD for pause response and to use
  2816. * new function SetKMode to insure that if STDIN is KBD, it will
  2817. * will be in raw mode when DOSREAD accesses it.
  2818. * M041 - Changed to use single byte var for input buffer.
  2819. * - Changed to do direct KB read if STDIN == KBD.
  2820. *
  2821. */
  2822. int ePause(n)
  2823. struct cmdnode *n;
  2824. {
  2825. ULONG cnt; // Count of response bytes
  2826. TCHAR c; // Retrieval buffer
  2827. UNREFERENCED_PARAMETER( n );
  2828. DEBUG((BPGRP, OTLVL, "PAUSE"));
  2829. PutStdOut(MSG_STRIKE_ANY_KEY, NOARGS);
  2830. if (FileIsDevice(STDIN) && (flgwd & 1)) {
  2831. FlushConsoleInputBuffer( GetStdHandle(STD_INPUT_HANDLE) );
  2832. c = (TCHAR)_getch();
  2833. if (c == 0x3) {
  2834. SetCtrlC();
  2835. }
  2836. } else {
  2837. ReadBufFromInput(
  2838. GetStdHandle(STD_INPUT_HANDLE),
  2839. (TCHAR*)&c, 1, (LPDWORD)&cnt);
  2840. }
  2841. cmd_printf(CrLf);
  2842. return(SUCCESS);
  2843. }
  2844. /*** eShift - execute the Shift command
  2845. *
  2846. * Purpose:
  2847. * If a batch job is being executed, shift the batch job's vars one to the
  2848. * left. The value for %0 is never shifted. The value for %1 is lost.
  2849. * If there are args that have not been assigned to a variable, the next
  2850. * one is assigned to %9. Otherwise, %9's value is NULLed.
  2851. *
  2852. * If no batch job is in progress, just return.
  2853. *
  2854. * int eShift(struct cmdnode *n)
  2855. *
  2856. * Returns:
  2857. * SUCCESS always.
  2858. *
  2859. * Notes:
  2860. * As of Modification number M004, the value of %0 is now included in
  2861. * in the shift command.
  2862. */
  2863. int eShift(n)
  2864. struct cmdnode *n;
  2865. {
  2866. struct batdata *bdat;
  2867. TCHAR *s;
  2868. int iStart;
  2869. int i;
  2870. DEBUG((BPGRP, OTLVL, "SHIFT: CurrentBatchFile = %lx", CurrentBatchFile));
  2871. if (CurrentBatchFile) {
  2872. bdat = CurrentBatchFile;
  2873. //
  2874. // If extensions are enabled, look for /n switch that specifies
  2875. // the starting index of the shift. Zero is the default starting
  2876. // index.
  2877. //
  2878. iStart = 0;
  2879. if (fEnableExtensions && n->argptr) {
  2880. s = EatWS( n->argptr, NULL );
  2881. if (s[0] == SWITCHAR && (s[1] >= L'0' && s[1] < L'9')) {
  2882. iStart = s[1] - L'0';
  2883. } else if (_tcslen(s)) {
  2884. PutStdErr(MSG_SHIFT_BAD_ARG, NOARGS);
  2885. LastRetCode = FAILURE;
  2886. return FAILURE;
  2887. }
  2888. }
  2889. for (i = iStart; i < 9; i++) {
  2890. bdat->aptrs[i] = bdat->aptrs[i+1];
  2891. bdat->alens[i] = bdat->alens[i+1];
  2892. DEBUG((BPGRP, OTLVL, "SHIFT: #%d addr = %lx len = %d", i, bdat->aptrs[i], bdat->alens[i]));
  2893. }
  2894. if ((bdat->args) && (*bdat->args)) {
  2895. bdat->aptrs[9] = bdat->args;
  2896. bdat->alens[9] = i = mystrlen(bdat->args);
  2897. bdat->args += i+1;
  2898. DEBUG((BPGRP, OTLVL, "SHIFT: #9 %lx len = %d args = %ws", bdat->aptrs[9], bdat->alens[9], bdat->args));
  2899. } else {
  2900. bdat->aptrs[9] = NULL;
  2901. bdat->alens[9] = 0;
  2902. DEBUG((BPGRP, OTLVL, "SHIFT: #9 was NULLed."));
  2903. }
  2904. }
  2905. return(SUCCESS);
  2906. }
  2907. /*** eSetlocal - Begin Local treatment of environment commands
  2908. *
  2909. * Purpose:
  2910. * To prevent the export of environment alterations to COMMAND's
  2911. * current environment by saving copies of the current directory
  2912. * and environment in use at the time.
  2913. *
  2914. * int eSetlocal(struct cmdnode *n)
  2915. *
  2916. * Args:
  2917. * n - the parse tree node containing the SETLOCAL command
  2918. *
  2919. * Returns:
  2920. * Always returns SUCCESS.
  2921. *
  2922. * Notes:
  2923. * - All directory and environment alterations occuring after the
  2924. * execution of this command will affect only the copies made and
  2925. * hence will be local to this batch file (and child processes
  2926. * invoked by this batch file) until a subsequent ENDLOCAL command
  2927. * is executed.
  2928. * - The data stack level, referenced by CurrentBatchFile->stacksize, does not
  2929. * include the memory malloc'd for saving the directory & environment.
  2930. * As a result, the next call to Parser() would free up these items.
  2931. * To prevent this, the data stack pointer in the current batch data
  2932. * structure, is set to a level beyond these two items; including also
  2933. * some memory malloc'd in functions between the last call to Parser()
  2934. * and the current execution of eSetlocal(). This memory will only be
  2935. * freed when Parser() is called following termination of the current
  2936. * batch file. To attempt to save the current stack level and restore
  2937. * it in eEndlocal() works only if both commands occur in the same
  2938. * file. If eEndlocal() comes in a nested file, the resulting freeing
  2939. * of memory by Parser() would also eliminate even the batch data
  2940. * structures occuring between the two.
  2941. *
  2942. */
  2943. int eSetlocal(n)
  2944. struct cmdnode *n;
  2945. {
  2946. struct batsaveddata *p;
  2947. TCHAR *tas; /* Tokenized argument list */
  2948. if (CurrentBatchFile) {
  2949. if (CurrentBatchFile->SavedEnvironmentCount < CMD_MAX_SAVED_ENV) { // Check also CurrentBatchFile
  2950. DEBUG((BPGRP, OTLVL, "SLOC: Performing localizing"));
  2951. p = HeapAlloc( GetProcessHeap( ), HEAP_ZERO_MEMORY, sizeof( *p ));
  2952. if (!p)
  2953. return FAILURE;
  2954. p->dircpy = HeapAlloc( GetProcessHeap( ),
  2955. HEAP_ZERO_MEMORY,
  2956. mystrlen( CurDrvDir )*sizeof( TCHAR )+sizeof( TCHAR ));
  2957. if (!p->dircpy)
  2958. return FAILURE;
  2959. else
  2960. mystrcpy(p->dircpy, CurDrvDir);
  2961. p->envcpy = CopyEnv();
  2962. if (!p->envcpy)
  2963. return FAILURE;
  2964. //
  2965. // Save this in case it is modified, so it can be
  2966. // restored when the matching ENDLOCAL is executed.
  2967. //
  2968. p->fEnableExtensions = fEnableExtensions;
  2969. p->fDelayedExpansion = fDelayedExpansion;
  2970. CurrentBatchFile->saveddata[CurrentBatchFile->SavedEnvironmentCount] = p;
  2971. CurrentBatchFile->SavedEnvironmentCount += 1;
  2972. if (CurrentBatchFile->stacksize < (CurrentBatchFile->stackmin = DCount)) {
  2973. CurrentBatchFile->stacksize = DCount;
  2974. }
  2975. //
  2976. // If there is addional text on the command line, see
  2977. // if it matches various keywords that enable or disable
  2978. // features inside scripts.
  2979. //
  2980. // We do this regardless
  2981. // of where extensions are currently enabled, so we can
  2982. // use this mechanism to temporarily turn on/off extensions
  2983. // from inside of a command script as needed. The original
  2984. // CMD.EXE ignored any extra text on the SETLOCAL command
  2985. // line, did not declare an error and did not set ERRORLEVEL
  2986. // Now it looks for the extra text and declares and error
  2987. // if it does not match one of the acceptable keywords and
  2988. // sets ERRORLEVEL to 1 if it does not.
  2989. //
  2990. // Very minor incompatibility with old command scripts that
  2991. // that should not effect anybody.
  2992. //
  2993. tas = TokStr(n->argptr, NULL, TS_NOFLAGS);
  2994. LastRetCode = SUCCESS;
  2995. while (*tas != NULLC) {
  2996. if (!_tcsicmp( tas, TEXT("ENABLEEXTENSIONS"))) {
  2997. fEnableExtensions = TRUE;
  2998. } else if (!_tcsicmp( tas, TEXT("DISABLEEXTENSIONS"))) {
  2999. fEnableExtensions = FALSE;
  3000. } else if (!_tcsicmp( tas, TEXT( "ENABLEDELAYEDEXPANSION" ))) {
  3001. fDelayedExpansion = TRUE;
  3002. } else if (!_tcsicmp( tas, TEXT( "DISABLEDELAYEDEXPANSION" ))) {
  3003. fDelayedExpansion = FALSE;
  3004. } else if (*tas != NULLC) {
  3005. PutStdErr(MSG_SETLOCAL_BAD_ARG, NOARGS);
  3006. LastRetCode = FAILURE;
  3007. return FAILURE;
  3008. }
  3009. tas += mystrlen( tas ) + 1;
  3010. }
  3011. } else {
  3012. PutStdErr(MSG_MAX_SETLOCAL,NOARGS);
  3013. return FAILURE;
  3014. }
  3015. }
  3016. DEBUG((BPGRP, OTLVL, "SLOC: Exiting"));
  3017. return(SUCCESS);
  3018. }
  3019. /*** eEndlocal - End Local treatment of environment commands
  3020. *
  3021. * Purpose:
  3022. * To reestablish the export of environment alterations to COMMAND's
  3023. * current environment. Once this command is encountered, the current
  3024. * directory and the current environment in use at the time of the
  3025. * initial SETLOCAL command will be restored from their copies.
  3026. *
  3027. * int eEndlocal(struct cmdnode *n)
  3028. *
  3029. * Args:
  3030. * n - the parse tree node containing the ENDLOCAL command
  3031. *
  3032. * Returns:
  3033. * Always returns SUCCESS.
  3034. *
  3035. * Notes:
  3036. * Issuance of an ENDLOCAL command without a previous SETLOCAL command
  3037. * is bad programming practice but not considered an error.
  3038. *
  3039. */
  3040. int eEndlocal(n)
  3041. struct cmdnode *n;
  3042. {
  3043. struct batdata *bdat = CurrentBatchFile;
  3044. UNREFERENCED_PARAMETER( n );
  3045. ElclWork( bdat );
  3046. return(SUCCESS);
  3047. }
  3048. void EndAllLocals( struct batdata *bdat )
  3049. {
  3050. //
  3051. // If a restricted token was created to run this batch file then close it.
  3052. // Also, revert to the process token. The matching impersonate was done in
  3053. // SetBat.
  3054. //
  3055. if (bdat->hRestrictedToken != NULL) {
  3056. RevertToSelf();
  3057. CloseHandle(bdat->hRestrictedToken);
  3058. bdat->hRestrictedToken = NULL;
  3059. }
  3060. while (bdat->SavedEnvironmentCount != 0) {
  3061. ElclWork( bdat );
  3062. }
  3063. }
  3064. /*** ElclWork - Restore copied directory and environment
  3065. *
  3066. * Purpose:
  3067. * If the current batch data structure contains valid pointers to
  3068. * copies of the current directory and environment, restore them.
  3069. *
  3070. * int ElclWork(struct batdata *bdat)
  3071. *
  3072. * Args:
  3073. * bdat - the batch data structure containing copied dir/env pointers
  3074. *
  3075. * Returns:
  3076. * Always returns SUCCESS.
  3077. *
  3078. * Notes:
  3079. * The level of stacked data, ie. CurrentBatchFile->stacksize, cannot be restored
  3080. * to its pre-SETLOCAL level in case this command is occuring in a
  3081. * later nested batch file. To do so would free the memory containing
  3082. * its own batch data structure. Only when the current batch file
  3083. * terminates and is popped off the stack, will Parser() free up the
  3084. * memory containing the copies. Issuance of an ENDLOCAL command
  3085. * without a previous SETLOCAL command is bad programming practice
  3086. * but not considered an error.
  3087. *
  3088. */
  3089. void ElclWork( struct batdata *bdat )
  3090. {
  3091. TCHAR c;
  3092. struct batsaveddata *p;
  3093. if (bdat == NULL) {
  3094. return;
  3095. }
  3096. if (bdat->SavedEnvironmentCount == 0) {
  3097. return;
  3098. }
  3099. bdat->SavedEnvironmentCount--;
  3100. p = bdat->saveddata[bdat->SavedEnvironmentCount];
  3101. bdat->saveddata[bdat->SavedEnvironmentCount] = NULL;
  3102. if (p == NULL) {
  3103. return;
  3104. }
  3105. c = _toupper( *p->dircpy );
  3106. if (CurDrvDir[0] != c) {
  3107. ChangeDrive( c - 0x20 );
  3108. }
  3109. //
  3110. // Restore the state saved in the setlocal
  3111. //
  3112. ChangeDir( p->dircpy);
  3113. HeapFree( GetProcessHeap( ), 0, p->dircpy );
  3114. ResetEnv( p->envcpy );
  3115. FreeEnv( p->envcpy );
  3116. fEnableExtensions = p->fEnableExtensions;
  3117. fDelayedExpansion = p->fDelayedExpansion;
  3118. HeapFree( GetProcessHeap( ), 0, p );
  3119. }
  3120. /*** eCall - begin the execution of the Call command
  3121. *
  3122. * Purpose:
  3123. * This is Command's interface to the Call function. It just calls
  3124. * CallWork with its command node, and sets LastRetCode.
  3125. *
  3126. * int eCall(struct cmdnode *n)
  3127. *
  3128. * Args:
  3129. * n - the parse tree node containing the copy command
  3130. *
  3131. * Returns:
  3132. * Whatever CallWork() returns.
  3133. *
  3134. */
  3135. int eCall(n)
  3136. struct cmdnode *n;
  3137. {
  3138. int CallWork();
  3139. return(LastRetCode = CallWork(n->argptr)); /* @@ */
  3140. }
  3141. /*** CallWork - Execute another batch file as a subroutine (M009 - New)
  3142. *
  3143. * Purpose:
  3144. * Parse the argument portion of the current node. If it is a batch
  3145. * file invocation, call BatProc() with the newly parsed node.
  3146. *
  3147. * int CallWork(TCHAR *fname)
  3148. *
  3149. * Args:
  3150. * fname - pointer to the batch file to be CALLed
  3151. *
  3152. * Returns:
  3153. * The process return code of the child batch file or
  3154. * SUCCESS if null node or
  3155. * FAILURE if PARSERROR or unable to exec as batch file.
  3156. *
  3157. * Notes:
  3158. * The CALLing of batch files is much the same as the proposed
  3159. * "new-style" batch file concept, except with regard to localizing
  3160. * environment and directory alterations.
  3161. *
  3162. */
  3163. int ColonIsToken;
  3164. int CallWork(fname)
  3165. TCHAR *fname;
  3166. {
  3167. struct node *c; /* New node for CALL statement */
  3168. TCHAR *flptr; /* Ptr to file location */
  3169. int i; /* Work variable */
  3170. TCHAR *t1, *t2, /* M041 - Temp pointer */
  3171. *aptr; /* M041 - New arg pointer */
  3172. TCHAR *temp_parm; /* @@4a */
  3173. unsigned rc;
  3174. DEBUG((BPGRP,OTLVL,"CALL: entered"));
  3175. if (fname == NULL) {
  3176. return( FAILURE );
  3177. }
  3178. if (!(flptr = mkstr(MAX_PATH*sizeof(TCHAR)))) /* Filespec to run */
  3179. return(FAILURE);
  3180. /* Note that in reparsing the argument portion of the current statement
  3181. * we do not have to concern ourselves with redirection. It was already
  3182. * set up when the CALL statement was dispatch()'ed.
  3183. * M041 - We do, however, have to "re-escape" any escape characters
  3184. * before reparsing or they will disappear.
  3185. */
  3186. aptr = fname; /* Initialize it */
  3187. if (t1 = mystrchr(fname, ESCHAR)) {
  3188. if (!(aptr = mkstr(((mystrlen(fname) * 2) + 1) * sizeof(TCHAR))))
  3189. return(FAILURE);
  3190. t2 = aptr;
  3191. t1 = fname;
  3192. while (*t1)
  3193. if ((*t2++ = *t1++) == ESCHAR)
  3194. *t2++ = ESCHAR;
  3195. *t2 = NULLC;
  3196. if (!(aptr = resize(aptr, (mystrlen(aptr) + 1)*sizeof(TCHAR))))
  3197. return(FAILURE);
  3198. }
  3199. i = DCount; /* Valid data ptr for parser */
  3200. DEBUG((BPGRP,OTLVL,"CALL: Parsing %ws",fname));
  3201. ColonIsToken = 1;
  3202. c=Parser(READSTRING, (INT_PTR)aptr, i);
  3203. ColonIsToken = 0;
  3204. if (c == (struct node *) PARSERROR) {
  3205. DEBUG((BPGRP,OTLVL,"CALL: Parse error, returning failure"));
  3206. /*@@5c */
  3207. if (!(temp_parm = mkstr(((mystrlen(aptr) * 2) + 1) * sizeof(TCHAR))))
  3208. return(FAILURE);
  3209. /*@@5a */mystrcpy(temp_parm, aptr);
  3210. _tcsupr(temp_parm);
  3211. /*@@5a */
  3212. /*@@5a */if ( (!_tcscmp(temp_parm, TEXT(" IF" ))) ||
  3213. /*@@5a */ (!_tcscmp(temp_parm, TEXT(" FOR" ))) )
  3214. /*@@5a */
  3215. {
  3216. /*@@5a */
  3217. PutStdErr( MSG_SYNERR_GENL, ONEARG, aptr ); /* @@4 */
  3218. /*@@5a */
  3219. }
  3220. return(FAILURE);
  3221. }
  3222. if (c == (struct node *) EOF) {
  3223. DEBUG((BPGRP,OTLVL,"CALL: Found EOF, returning success"));
  3224. return(SUCCESS);
  3225. }
  3226. DEBUG((BPGRP,OTLVL,"CALL: Parsed OK, looking for batch file"));
  3227. //
  3228. // If extensions are enable, check for the new form of the CALL
  3229. // statement:
  3230. //
  3231. // CALL :label args...
  3232. //
  3233. // which is basically a form of subroutine call within command scripts.
  3234. // If the target of the CALL begins with a COLON then do nothing
  3235. // here and let BatProc take care of it when it is called below.
  3236. //
  3237. // Otherwise, execute the old code, which will search for a command
  3238. // script file or executable.
  3239. //
  3240. if (fEnableExtensions && *((struct cmdnode *)c)->cmdline == COLON) {
  3241. //
  3242. // The new form is only valid inside of a command script, so
  3243. // declare an error if the user entered it from the command line
  3244. //
  3245. if (CurrentBatchFile == NULL) {
  3246. PutStdErr( MSG_CALL_LABEL_INVALID, NOARGS );
  3247. return(FAILURE);
  3248. }
  3249. } else
  3250. if ((mystrchr(((struct cmdnode *)c)->cmdline, STAR) || /* M035 */
  3251. mystrchr(((struct cmdnode *)c)->cmdline, QMARK) ||
  3252. (i = SearchForExecutable((struct cmdnode *)c, flptr)) != SFE_ISBAT)) {
  3253. rc = FindFixAndRun( (struct cmdnode *)c );
  3254. return(rc); /*@@5*/
  3255. }
  3256. DEBUG((BPGRP,OTLVL,"CALL: Found batch file"));
  3257. rc = BatProc((struct cmdnode *)c, flptr, BT_CALL);
  3258. /* @@6a If rc is zero, return LastRetCode because it might != 0 */
  3259. return(rc ? rc : LastRetCode);
  3260. }
  3261. /*** eBreak - begin the execution of the BREAK command
  3262. *
  3263. * Purpose:
  3264. * Does nothing as it is only here for compatibility. If extensions are
  3265. * enabled and running on Windows NT, then enters a hard coded breakpoint
  3266. * if this process is being debugged by a debugger.
  3267. *
  3268. * int eExtproc(struct cmdnode *n)
  3269. *
  3270. * Args:
  3271. * n - the parse tree node containing the copy command
  3272. *
  3273. * Returns:
  3274. * SUCCESS;
  3275. *
  3276. */
  3277. int eBreak(struct cmdnode *n)
  3278. {
  3279. UNREFERENCED_PARAMETER( n );
  3280. #if !defined( WIN95_CMD ) && DBG
  3281. if (fEnableExtensions &&
  3282. lpIsDebuggerPresent != NULL && // Only true on NT
  3283. (*lpIsDebuggerPresent)()) {
  3284. DebugBreak();
  3285. }
  3286. #endif
  3287. return(SUCCESS);
  3288. }
  3289. BOOL
  3290. ReadBufFromFile(
  3291. HANDLE h,
  3292. TCHAR *pBuf,
  3293. int cch,
  3294. int *pcch)
  3295. {
  3296. int cb;
  3297. UCHAR *pch = AnsiBuf;
  3298. int cchNew;
  3299. DWORD fPos;
  3300. fPos = SetFilePointer(h, 0, NULL, FILE_CURRENT);
  3301. if (ReadFile(h, AnsiBuf, cch, pcch, NULL) == 0)
  3302. return 0;
  3303. if (*pcch == 0)
  3304. return 0;
  3305. /* check for lead character at end of line */
  3306. cb = cchNew = *pcch;
  3307. while (cb > 0) {
  3308. if ( (cb >=3 ) &&
  3309. ( (*pch == '\n' && *(pch+1) == '\r') ||
  3310. (*pch == '\r' && *(pch+1) == '\n') ) ) {
  3311. *(pch+2) = '\000';
  3312. cchNew = (int)(pch - AnsiBuf) + 2;
  3313. SetFilePointer(h, fPos+cchNew, NULL, FILE_BEGIN);
  3314. break;
  3315. } else if (is_dbcsleadchar(*pch)) {
  3316. if (cb == 1) {
  3317. if (ReadFile(h, pch+1, 1, &cb, NULL) == 0 || cb == 0) {
  3318. *pcch = 0;
  3319. return 0;
  3320. }
  3321. cchNew++;
  3322. break;
  3323. }
  3324. cb -= 2;
  3325. pch += 2;
  3326. } else {
  3327. cb--;
  3328. pch++;
  3329. }
  3330. }
  3331. #ifdef UNICODE
  3332. cch = MultiByteToWideChar(CurrentCP, MB_PRECOMPOSED, AnsiBuf, cchNew, pBuf, cch);
  3333. #else
  3334. memmove(pBuf, AnsiBuf, cchNew);
  3335. cch = cchNew;
  3336. #endif
  3337. *pcch = cch;
  3338. return cch;
  3339. }
  3340. BOOL
  3341. ReadBufFromConsole(
  3342. HANDLE h,
  3343. TCHAR* pBuf,
  3344. int cch,
  3345. int *pcch)
  3346. {
  3347. CONSOLE_READCONSOLE_CONTROL InputControl;
  3348. BOOL ReadConsoleResult, bTouched, bPathCompletion, bHaveHScrollBar, bHaveVScrollBar;
  3349. PTCHAR PrevBuf;
  3350. DWORD cchPrevBuf;
  3351. DWORD cchRead;
  3352. CONSOLE_SCREEN_BUFFER_INFO csbi;
  3353. COORD InitialCursorPosition;
  3354. HANDLE hOut;
  3355. DWORD cchBuf;
  3356. ULONG i, iCompletionCh, iCR;
  3357. DWORD nLines, nCols;
  3358. //
  3359. // Original code just called ReadConsole with the passed parameters.
  3360. // Now, we attempt to call the new improved ReadConsole with an extra
  3361. // parameter to enable intermediate wakeups from the read to process
  3362. // a file completion control character. This new feature is only
  3363. // enabled if all of the following are true:
  3364. // Command extensions are enabled
  3365. // User has defined a command completion control character
  3366. // Standard Output Handle is a console output handle
  3367. //
  3368. // If any of the above are not true, do it the old way.
  3369. //
  3370. hOut = GetStdHandle( STD_OUTPUT_HANDLE );
  3371. if (hOut == INVALID_HANDLE_VALUE)
  3372. hOut = CRTTONT( STDOUT );
  3373. if (!fEnableExtensions
  3374. || chCompletionCtrl >= SPACE
  3375. || chPathCompletionCtrl >= SPACE
  3376. || !GetConsoleScreenBufferInfo( hOut, &csbi ) ) {
  3377. ReadConsoleResult = ReadConsole(h, pBuf, cch, pcch, NULL);
  3378. #if defined(RICHARDW)
  3379. Mirror( ReadConsoleResult, pBuf, *pcch );
  3380. #endif
  3381. return ReadConsoleResult;
  3382. }
  3383. InitialCursorPosition = csbi.dwCursorPosition;
  3384. nLines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
  3385. nCols = csbi.srWindow.Right - csbi.srWindow.Left + 1;
  3386. bHaveHScrollBar = ((SHORT)nCols != csbi.dwSize.X);
  3387. bHaveVScrollBar = ((SHORT)nLines != csbi.dwSize.Y);
  3388. //
  3389. // All conditions are met, so set up the extra parameter to
  3390. // ReadConsole to tell it what control character(s) are to
  3391. // cause the read to return with intermediate results.
  3392. //
  3393. InputControl.nLength = sizeof(CONSOLE_READCONSOLE_CONTROL);
  3394. InputControl.nInitialChars = 0;
  3395. InputControl.dwCtrlWakeupMask = (1 << chCompletionCtrl);
  3396. InputControl.dwCtrlWakeupMask |= (1 << chPathCompletionCtrl);
  3397. InputControl.dwControlKeyState = 0;
  3398. //
  3399. // We will now loop until the user type enter, processing any
  3400. // intermediate wakeups as file completion requests.
  3401. //
  3402. DoCompleteInitialize();
  3403. PrevBuf = NULL;
  3404. cchPrevBuf = 0;
  3405. while (TRUE) {
  3406. //
  3407. // Read a line of input from the console.
  3408. //
  3409. ReadConsoleResult = ReadConsole(h, pBuf, cch, pcch, &InputControl);
  3410. #if defined( RICHARDW )
  3411. Mirror( ReadConsoleResult, pBuf, *pcch );
  3412. #endif
  3413. cchRead = *pcch;
  3414. if (CtrlCSeen) {
  3415. ResetCtrlC( );
  3416. if (PrevBuf)
  3417. HeapFree(GetProcessHeap(), 0, PrevBuf);
  3418. PrevBuf = NULL;
  3419. }
  3420. //
  3421. // If the read failed for any reason, we are done.
  3422. //
  3423. if (!ReadConsoleResult)
  3424. break;
  3425. //
  3426. // Make sure the result buffer is null terminated. If the buffer
  3427. // contains a carriage return, then the use must have hit enter, so
  3428. // break out of the loop to return the command line to the caller.
  3429. //
  3430. bPathCompletion = FALSE;
  3431. iCR = iCompletionCh = 0xFFFFFFFF;
  3432. for (i=0; i<(ULONG)*pcch; i++) {
  3433. if (pBuf[i] == CR) {
  3434. iCR = i;
  3435. break;
  3436. } else
  3437. if (pBuf[i] == chCompletionCtrl) {
  3438. iCompletionCh = i;
  3439. break;
  3440. } else
  3441. if (pBuf[i] == chPathCompletionCtrl) {
  3442. iCompletionCh = i;
  3443. bPathCompletion = TRUE;
  3444. break;
  3445. }
  3446. }
  3447. if (iCR != 0xFFFFFFFF) {
  3448. break;
  3449. }
  3450. //
  3451. // Use did not hit enter, so they must have hit the file completion
  3452. // control character. Find where they did this and terminate the
  3453. // result buffer at that point. If not found, then assume they hit
  3454. // enter and break out of the loop to return what we have.
  3455. //
  3456. if (iCompletionCh == 0xFFFFFFFF) {
  3457. break;
  3458. }
  3459. //
  3460. // Found the file completion control character. Dont count it as read.
  3461. // Null terminate the buffer and see if the buffer contents before
  3462. // the completion character is the same as what we displayed last.
  3463. //
  3464. *pcch = iCompletionCh;
  3465. pBuf[iCompletionCh] = NULLC;
  3466. if (PrevBuf == NULL || _tcscmp(pBuf, PrevBuf))
  3467. bTouched = TRUE;
  3468. else
  3469. bTouched = FALSE;
  3470. //
  3471. // If we know we are processing a command that only takes directory
  3472. // names are arguments, force completion code to only match directory
  3473. // names.
  3474. //
  3475. if (!bPathCompletion && iCompletionCh > 2) {
  3476. if (!_tcsnicmp(pBuf, TEXT("cd "), 3)
  3477. || !_tcsnicmp(pBuf, TEXT("rd "), 3)
  3478. || !_tcsnicmp(pBuf, TEXT("md "), 3)
  3479. || !_tcsnicmp(pBuf, TEXT("chdir "), 6)
  3480. || !_tcsnicmp(pBuf, TEXT("rmdir "), 6)
  3481. || !_tcsnicmp(pBuf, TEXT("mkdir "), 6)
  3482. || !_tcsnicmp(pBuf, TEXT("pushd "), 6)
  3483. ) {
  3484. bPathCompletion = TRUE;
  3485. }
  3486. }
  3487. //
  3488. // Call the file completion code with the input buffer, current length,
  3489. // whether the user had the shift key down or not (SHIFT means backwards)
  3490. // and whether or not the user modified the input buffer since the last
  3491. // time it was displayed. If the user did not modify what was last displayed
  3492. // then that tells the file completion code to display the next matching
  3493. // file name from the list as opposed to recalculating the list of matching
  3494. // files.
  3495. //
  3496. if ( DoComplete( pBuf,
  3497. iCompletionCh,
  3498. cch,
  3499. !(InputControl.dwControlKeyState & SHIFT_PRESSED),
  3500. bPathCompletion,
  3501. bTouched
  3502. )
  3503. ) {
  3504. //
  3505. // Recompute the position of the start of the command line, since
  3506. // it might have scrolled around since when we first wrote it out.
  3507. //
  3508. if (GetConsoleScreenBufferInfo( hOut, &csbi )) {
  3509. //
  3510. // Walk backwards from the current cursor position to determine the
  3511. // proper initial position for screen blanking and for the next
  3512. // ReadConsole
  3513. //
  3514. // The row (Y) of the next input is based on the number of lines
  3515. // consumed by the prompt plus the length of what the user has input.
  3516. // There is no need to round at all since any remainder is simply
  3517. // how far on the screen we are.
  3518. //
  3519. InitialCursorPosition.Y =
  3520. (SHORT) (csbi.dwCursorPosition.Y
  3521. - (InitialCursorPosition.X + iCompletionCh) / csbi.dwSize.X);
  3522. }
  3523. //
  3524. // Completion found a new file name and put it in the buffer.
  3525. // Update the length of valid characters in the buffer, redisplay
  3526. // the buffer at the cursor position we started, so the user can
  3527. // see the file name found
  3528. //
  3529. cchBuf = _tcslen(pBuf);
  3530. SetConsoleCursorPosition( hOut, InitialCursorPosition );
  3531. FillConsoleOutputCharacter( hOut,
  3532. TEXT( ' ' ),
  3533. cchRead,
  3534. InitialCursorPosition,
  3535. &cchRead );
  3536. WriteConsole(hOut, pBuf, cchBuf, &cchBuf, NULL);
  3537. InputControl.nInitialChars = cchBuf;
  3538. } else {
  3539. //
  3540. // File completion had nothing to had, so just beep and redo the read.
  3541. //
  3542. MessageBeep( 0xFFFFFFFF );
  3543. InputControl.nInitialChars = _tcslen(pBuf);
  3544. }
  3545. //
  3546. // Done with file completion. Free any previous buffer copy and
  3547. // allocate a copy of the current input buffer so we will know if the
  3548. // user has changed it or not.
  3549. //
  3550. if (PrevBuf)
  3551. HeapFree(GetProcessHeap(), 0, PrevBuf);
  3552. cchPrevBuf = _tcslen(pBuf);
  3553. PrevBuf = HeapAlloc(GetProcessHeap(), 0, (cchPrevBuf+1) * sizeof(TCHAR));
  3554. if (PrevBuf == NULL) {
  3555. return FALSE;
  3556. }
  3557. _tcscpy(PrevBuf, pBuf);
  3558. }
  3559. //
  3560. // All done. Free any buffer copy and return the result of the read
  3561. // to the caller
  3562. //
  3563. if (PrevBuf)
  3564. HeapFree(GetProcessHeap(), 0, PrevBuf);
  3565. return ReadConsoleResult;
  3566. }
  3567. BOOL
  3568. ReadBufFromInput(
  3569. HANDLE h,
  3570. TCHAR *pBuf,
  3571. int cch,
  3572. int *pcch)
  3573. {
  3574. unsigned htype;
  3575. htype = GetFileType(h);
  3576. htype &= ~FILE_TYPE_REMOTE;
  3577. if (htype == FILE_TYPE_CHAR)
  3578. return ReadBufFromConsole(h, pBuf, cch, pcch);
  3579. else
  3580. return ReadBufFromFile(h, pBuf, cch, pcch);
  3581. }