Source code of Windows XP (NT5)
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.

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