builtins.c 157 KB
Newer Older
1
/*
2
 * CMD - Wine-compatible command line interface - built-in functions.
3
 *
4
 * Copyright (C) 1999 D A Pickles
5
 * Copyright (C) 2007 J Edmeades
6
 *
7 8 9 10 11 12 13 14 15 16 17 18
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 21
 */

22 23
/*
 * FIXME:
24
 * - No support for pipes, shell parameters
25 26 27 28
 * - Lots of functionality missing from builtins
 * - Messages etc need international support
 */

29 30
#define WIN32_LEAN_AND_MEAN

31
#include "wcmd.h"
32
#include <shellapi.h>
33 34 35
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(cmd);
36

37
extern int defaultColor;
38
extern BOOL echo_mode;
39
extern BOOL interactive;
40

41
struct env_stack *pushd_directories;
42 43 44 45 46 47
const WCHAR dotW[]    = {'.','\0'};
const WCHAR dotdotW[] = {'.','.','\0'};
const WCHAR nullW[]   = {'\0'};
const WCHAR starW[]   = {'*','\0'};
const WCHAR slashW[]  = {'\\','\0'};
const WCHAR equalW[]  = {'=','\0'};
48 49
const WCHAR wildcardsW[] = {'*','?','\0'};
const WCHAR slashstarW[] = {'\\','*','\0'};
50
const WCHAR deviceW[] = {'\\','\\','.','\\','\0'};
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
const WCHAR inbuilt[][10] = {
        {'C','A','L','L','\0'},
        {'C','D','\0'},
        {'C','H','D','I','R','\0'},
        {'C','L','S','\0'},
        {'C','O','P','Y','\0'},
        {'C','T','T','Y','\0'},
        {'D','A','T','E','\0'},
        {'D','E','L','\0'},
        {'D','I','R','\0'},
        {'E','C','H','O','\0'},
        {'E','R','A','S','E','\0'},
        {'F','O','R','\0'},
        {'G','O','T','O','\0'},
        {'H','E','L','P','\0'},
        {'I','F','\0'},
        {'L','A','B','E','L','\0'},
        {'M','D','\0'},
        {'M','K','D','I','R','\0'},
        {'M','O','V','E','\0'},
        {'P','A','T','H','\0'},
        {'P','A','U','S','E','\0'},
        {'P','R','O','M','P','T','\0'},
        {'R','E','M','\0'},
        {'R','E','N','\0'},
        {'R','E','N','A','M','E','\0'},
        {'R','D','\0'},
        {'R','M','D','I','R','\0'},
        {'S','E','T','\0'},
        {'S','H','I','F','T','\0'},
81
        {'S','T','A','R','T','\0'},
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
        {'T','I','M','E','\0'},
        {'T','I','T','L','E','\0'},
        {'T','Y','P','E','\0'},
        {'V','E','R','I','F','Y','\0'},
        {'V','E','R','\0'},
        {'V','O','L','\0'},
        {'E','N','D','L','O','C','A','L','\0'},
        {'S','E','T','L','O','C','A','L','\0'},
        {'P','U','S','H','D','\0'},
        {'P','O','P','D','\0'},
        {'A','S','S','O','C','\0'},
        {'C','O','L','O','R','\0'},
        {'F','T','Y','P','E','\0'},
        {'M','O','R','E','\0'},
        {'C','H','O','I','C','E','\0'},
        {'E','X','I','T','\0'}
};
static const WCHAR externals[][10] = {
        {'A','T','T','R','I','B','\0'},
        {'X','C','O','P','Y','\0'}
};
103 104 105 106
static const WCHAR onW[]  = {'O','N','\0'};
static const WCHAR offW[] = {'O','F','F','\0'};
static const WCHAR parmY[] = {'/','Y','\0'};
static const WCHAR parmNoY[] = {'/','-','Y','\0'};
107
static const WCHAR eqeqW[]   = {'=','=','\0'};
108

109
static HINSTANCE hinst;
110
struct env_stack *saved_environment;
111 112
static BOOL verify_mode = FALSE;

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
/* set /a routines work from single character operators, but some of the
   operators are multiple character ones, especially the assignment ones.
   Temporarily represent these using the values below on the operator stack */
#define OP_POSITIVE     'P'
#define OP_NEGATIVE     'N'
#define OP_ASSSIGNMUL   'a'
#define OP_ASSSIGNDIV   'b'
#define OP_ASSSIGNMOD   'c'
#define OP_ASSSIGNADD   'd'
#define OP_ASSSIGNSUB   'e'
#define OP_ASSSIGNAND   'f'
#define OP_ASSSIGNNOT   'g'
#define OP_ASSSIGNOR    'h'
#define OP_ASSSIGNSHL   'i'
#define OP_ASSSIGNSHR   'j'

/* This maintains a stack of operators, holding both the operator precedence
   and the single character representation of the operator in question       */
typedef struct _OPSTACK
{
  int              precedence;
  WCHAR            op;
  struct _OPSTACK *next;
} OPSTACK;

/* This maintains a stack of values, where each value can either be a
139
   numeric value, or a string representing an environment variable     */
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
typedef struct _VARSTACK
{
  BOOL              isnum;
  WCHAR            *variable;
  int               value;
  struct _VARSTACK *next;
} VARSTACK;

/* This maintains a mapping between the calculated operator and the
   single character representation for the assignment operators.    */
static struct
{
  WCHAR op;
  WCHAR calculatedop;
} calcassignments[] =
{
  {'*', OP_ASSSIGNMUL},
  {'/', OP_ASSSIGNDIV},
  {'%', OP_ASSSIGNMOD},
  {'+', OP_ASSSIGNADD},
  {'-', OP_ASSSIGNSUB},
  {'&', OP_ASSSIGNAND},
  {'^', OP_ASSSIGNNOT},
  {'|', OP_ASSSIGNOR},
  {'<', OP_ASSSIGNSHL},
  {'>', OP_ASSSIGNSHR},
  {' ',' '}
};

169 170 171
/**************************************************************************
 * WCMD_ask_confirm
 *
172
 * Issue a message and ask for confirmation, waiting on a valid answer.
173 174 175 176 177 178
 *
 * Returns True if Y (or A) answer is selected
 *         If optionAll contains a pointer, ALL is allowed, and if answered
 *                   set to TRUE
 *
 */
179
static BOOL WCMD_ask_confirm (const WCHAR *message, BOOL showSureText,
180
                              BOOL *optionAll) {
181

182 183 184 185 186 187 188
    UINT msgid;
    WCHAR confirm[MAXSTRING];
    WCHAR options[MAXSTRING];
    WCHAR Ybuffer[MAXSTRING];
    WCHAR Nbuffer[MAXSTRING];
    WCHAR Abuffer[MAXSTRING];
    WCHAR answer[MAX_PATH] = {'\0'};
189 190
    DWORD count = 0;

191 192 193 194 195
    /* Load the translated valid answers */
    if (showSureText)
      LoadStringW(hinst, WCMD_CONFIRM, confirm, sizeof(confirm)/sizeof(WCHAR));
    msgid = optionAll ? WCMD_YESNOALL : WCMD_YESNO;
    LoadStringW(hinst, msgid, options, sizeof(options)/sizeof(WCHAR));
196 197 198
    LoadStringW(hinst, WCMD_YES, Ybuffer, sizeof(Ybuffer)/sizeof(WCHAR));
    LoadStringW(hinst, WCMD_NO,  Nbuffer, sizeof(Nbuffer)/sizeof(WCHAR));
    LoadStringW(hinst, WCMD_ALL, Abuffer, sizeof(Abuffer)/sizeof(WCHAR));
199

200 201 202
    /* Loop waiting on a valid answer */
    if (optionAll)
        *optionAll = FALSE;
203 204
    while (1)
    {
205
      WCMD_output_asis (message);
206 207 208
      if (showSureText)
        WCMD_output_asis (confirm);
      WCMD_output_asis (options);
209
      WCMD_ReadFile(GetStdHandle(STD_INPUT_HANDLE), answer, sizeof(answer)/sizeof(WCHAR), &count);
210
      answer[0] = toupperW(answer[0]);
211 212 213 214 215 216 217 218 219
      if (answer[0] == Ybuffer[0])
        return TRUE;
      if (answer[0] == Nbuffer[0])
        return FALSE;
      if (optionAll && answer[0] == Abuffer[0])
      {
        *optionAll = TRUE;
        return TRUE;
      }
220 221 222
    }
}

223 224 225 226 227 228
/****************************************************************************
 * WCMD_clear_screen
 *
 * Clear the terminal screen.
 */

229
void WCMD_clear_screen (void) {
230

231 232 233 234
  /* Emulate by filling the screen from the top left to bottom right with
        spaces, then moving the cursor to the top left afterwards */
  CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
  HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
235

236 237 238
  if (GetConsoleScreenBufferInfo(hStdOut, &consoleInfo))
  {
      COORD topLeft;
239
      DWORD screenSize, written;
Mike McCormack's avatar
Mike McCormack committed
240

241
      screenSize = consoleInfo.dwSize.X * (consoleInfo.dwSize.Y + 1);
242

243 244
      topLeft.X = 0;
      topLeft.Y = 0;
245 246
      FillConsoleOutputCharacterW(hStdOut, ' ', screenSize, topLeft, &written);
      FillConsoleOutputAttribute(hStdOut, consoleInfo.wAttributes, screenSize, topLeft, &written);
247 248
      SetConsoleCursorPosition(hStdOut, topLeft);
  }
249 250 251 252 253 254 255 256
}

/****************************************************************************
 * WCMD_change_tty
 *
 * Change the default i/o device (ie redirect STDin/STDout).
 */

257
void WCMD_change_tty (void) {
258

259
  WCMD_output_stderr (WCMD_LoadMessage(WCMD_NYI));
260 261 262

}

263 264 265 266 267
/****************************************************************************
 * WCMD_choice
 *
 */

268
void WCMD_choice (const WCHAR * args) {
269 270 271 272 273 274 275 276 277 278 279 280 281 282

    static const WCHAR bellW[] = {7,0};
    static const WCHAR commaW[] = {',',0};
    static const WCHAR bracket_open[] = {'[',0};
    static const WCHAR bracket_close[] = {']','?',0};
    WCHAR answer[16];
    WCHAR buffer[16];
    WCHAR *ptr = NULL;
    WCHAR *opt_c = NULL;
    WCHAR *my_command = NULL;
    WCHAR opt_default = 0;
    DWORD opt_timeout = 0;
    DWORD count;
    DWORD oldmode;
283
    BOOL have_console;
284 285 286 287 288 289
    BOOL opt_n = FALSE;
    BOOL opt_s = FALSE;

    have_console = GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &oldmode);
    errorlevel = 0;

290
    my_command = heap_strdupW(WCMD_skip_leading_spaces((WCHAR*) args));
291

292
    ptr = WCMD_skip_leading_spaces(my_command);
293 294 295 296 297 298 299 300 301 302
    while (*ptr == '/') {
        switch (toupperW(ptr[1])) {
            case 'C':
                ptr += 2;
                /* the colon is optional */
                if (*ptr == ':')
                    ptr++;

                if (!*ptr || isspaceW(*ptr)) {
                    WINE_FIXME("bad parameter %s for /C\n", wine_dbgstr_w(ptr));
303
                    heap_free(my_command);
304 305 306 307 308 309 310 311 312 313 314
                    return;
                }

                /* remember the allowed keys (overwrite previous /C option) */
                opt_c = ptr;
                while (*ptr && (!isspaceW(*ptr)))
                    ptr++;

                if (*ptr) {
                    /* terminate allowed chars */
                    *ptr = 0;
315
                    ptr = WCMD_skip_leading_spaces(&ptr[1]);
316 317 318 319 320 321
                }
                WINE_TRACE("answer-list: %s\n", wine_dbgstr_w(opt_c));
                break;

            case 'N':
                opt_n = TRUE;
322
                ptr = WCMD_skip_leading_spaces(&ptr[2]);
323 324 325 326
                break;

            case 'S':
                opt_s = TRUE;
327
                ptr = WCMD_skip_leading_spaces(&ptr[2]);
328 329 330 331 332 333 334 335 336 337 338 339
                break;

            case 'T':
                ptr = &ptr[2];
                /* the colon is optional */
                if (*ptr == ':')
                    ptr++;

                opt_default = *ptr++;

                if (!opt_default || (*ptr != ',')) {
                    WINE_FIXME("bad option %s for /T\n", opt_default ? wine_dbgstr_w(ptr) : "");
340
                    heap_free(my_command);
341 342 343 344 345 346 347 348 349 350 351 352 353
                    return;
                }
                ptr++;

                count = 0;
                while (((answer[count] = *ptr)) && isdigitW(*ptr) && (count < 15)) {
                    count++;
                    ptr++;
                }

                answer[count] = 0;
                opt_timeout = atoiW(answer);

354
                ptr = WCMD_skip_leading_spaces(ptr);
355 356 357 358
                break;

            default:
                WINE_FIXME("bad parameter: %s\n", wine_dbgstr_w(ptr));
359
                heap_free(my_command);
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
                return;
        }
    }

    if (opt_timeout)
        WINE_FIXME("timeout not supported: %c,%d\n", opt_default, opt_timeout);

    if (have_console)
        SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), 0);

    /* use default keys, when needed: localized versions of "Y"es and "No" */
    if (!opt_c) {
        LoadStringW(hinst, WCMD_YES, buffer, sizeof(buffer)/sizeof(WCHAR));
        LoadStringW(hinst, WCMD_NO, buffer + 1, sizeof(buffer)/sizeof(WCHAR) - 1);
        opt_c = buffer;
        buffer[2] = 0;
    }

    /* print the question, when needed */
    if (*ptr)
        WCMD_output_asis(ptr);

    if (!opt_s) {
        struprW(opt_c);
        WINE_TRACE("case insensitive answer-list: %s\n", wine_dbgstr_w(opt_c));
    }

    if (!opt_n) {
        /* print a list of all allowed answers inside brackets */
        WCMD_output_asis(bracket_open);
        ptr = opt_c;
        answer[1] = 0;
        while ((answer[0] = *ptr++)) {
            WCMD_output_asis(answer);
            if (*ptr)
                WCMD_output_asis(commaW);
        }
        WCMD_output_asis(bracket_close);
    }

    while (TRUE) {

        /* FIXME: Add support for option /T */
403
        answer[1] = 0; /* terminate single character string */
404
        WCMD_ReadFile(GetStdHandle(STD_INPUT_HANDLE), answer, 1, &count);
405 406 407 408 409 410 411

        if (!opt_s)
            answer[0] = toupperW(answer[0]);

        ptr = strchrW(opt_c, answer[0]);
        if (ptr) {
            WCMD_output_asis(answer);
412
            WCMD_output_asis(newlineW);
413 414 415 416 417
            if (have_console)
                SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), oldmode);

            errorlevel = (ptr - opt_c) + 1;
            WINE_TRACE("answer: %d\n", errorlevel);
418
            heap_free(my_command);
419 420 421 422 423 424 425 426 427 428 429
            return;
        }
        else
        {
            /* key not allowed: play the bell */
            WINE_TRACE("key not allowed: %s\n", wine_dbgstr_w(answer));
            WCMD_output_asis(bellW);
        }
    }
}

430 431 432 433 434 435 436 437 438
/****************************************************************************
 * WCMD_AppendEOF
 *
 * Adds an EOF onto the end of a file
 * Returns TRUE on success
 */
static BOOL WCMD_AppendEOF(WCHAR *filename)
{
    HANDLE h;
439
    DWORD bytes_written;
440 441 442 443 444 445 446 447 448 449 450 451

    char eof = '\x1a';

    WINE_TRACE("Appending EOF to %s\n", wine_dbgstr_w(filename));
    h = CreateFileW(filename, GENERIC_WRITE, 0, NULL,
                    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if (h == NULL) {
      WINE_ERR("Failed to open %s (%d)\n", wine_dbgstr_w(filename), GetLastError());
      return FALSE;
    } else {
      SetFilePointer (h, 0, NULL, FILE_END);
452
      if (!WriteFile(h, &eof, 1, &bytes_written, NULL)) {
453
        WINE_ERR("Failed to append EOF to %s (%d)\n", wine_dbgstr_w(filename), GetLastError());
454
        CloseHandle(h);
455 456 457 458 459 460 461
        return FALSE;
      }
      CloseHandle(h);
    }
    return TRUE;
}

462 463 464 465 466 467 468 469 470 471 472 473 474 475
/****************************************************************************
 * WCMD_ManualCopy
 *
 * Copies from a file
 *    optionally reading only until EOF (ascii copy)
 *    optionally appending onto an existing file (append)
 * Returns TRUE on success
 */
static BOOL WCMD_ManualCopy(WCHAR *srcname, WCHAR *dstname, BOOL ascii, BOOL append)
{
    HANDLE in,out;
    BOOL   ok;
    DWORD  bytesread, byteswritten;

476
    WINE_TRACE("Manual Copying %s to %s (append?%d)\n",
477 478 479 480 481 482 483 484 485 486 487 488 489 490
               wine_dbgstr_w(srcname), wine_dbgstr_w(dstname), append);

    in  = CreateFileW(srcname, GENERIC_READ, 0, NULL,
                      OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (in == NULL) {
      WINE_ERR("Failed to open %s (%d)\n", wine_dbgstr_w(srcname), GetLastError());
      return FALSE;
    }

    /* Open the output file, overwriting if not appending */
    out = CreateFileW(dstname, GENERIC_WRITE, 0, NULL,
                      append?OPEN_EXISTING:CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (out == NULL) {
      WINE_ERR("Failed to open %s (%d)\n", wine_dbgstr_w(dstname), GetLastError());
491
      CloseHandle(in);
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
      return FALSE;
    }

    /* Move to end of destination if we are going to append to it */
    if (append) {
      SetFilePointer(out, 0, NULL, FILE_END);
    }

    /* Loop copying data from source to destination until EOF read */
    do
    {
      char buffer[MAXSTRING];

      ok = ReadFile(in, buffer, MAXSTRING, &bytesread, NULL);
      if (ok) {

        /* Stop at first EOF */
        if (ascii) {
          char *ptr = (char *)memchr((void *)buffer, '\x1a', bytesread);
          if (ptr) bytesread = (ptr - buffer);
        }

        if (bytesread) {
          ok = WriteFile(out, buffer, bytesread, &byteswritten, NULL);
          if (!ok || byteswritten != bytesread) {
            WINE_ERR("Unexpected failure writing to %s, rc=%d\n",
                     wine_dbgstr_w(dstname), GetLastError());
          }
        }
      } else {
        WINE_ERR("Unexpected failure reading from %s, rc=%d\n",
                 wine_dbgstr_w(srcname), GetLastError());
      }
    } while (ok && bytesread > 0);

    CloseHandle(out);
    CloseHandle(in);
    return ok;
}

532 533 534 535
/****************************************************************************
 * WCMD_copy
 *
 * Copy a file or wildcarded set.
536 537 538 539
 * For ascii/binary type copies, it gets complex:
 *  Syntax on command line is
 *   ... /a | /b   filename  /a /b {[ + filename /a /b]}  [dest /a /b]
 *  Where first /a or /b sets 'mode in operation' until another is found
540
 *  once another is found, it applies to the file preceding the /a or /b
541
 *  In addition each filename can contain wildcards
542 543
 * To make matters worse, the + may be in the same parameter (i.e. no
 *  whitespace) or with whitespace separating it
544 545 546 547 548 549 550 551 552 553
 *
 * ASCII mode on read == read and stop at first EOF
 * ASCII mode on write == append EOF to destination
 * Binary == copy as-is
 *
 * Design of this is to build up a list of files which will be copied into a
 * list, then work through the list file by file.
 * If no destination is specified, it defaults to the name of the first file in
 * the list, but the current directory.
 *
554 555
 */

556
void WCMD_copy(WCHAR * args) {
557

558
  BOOL    opt_d, opt_v, opt_n, opt_z, opt_y, opt_noty;
559 560 561
  WCHAR  *thisparam;
  int     argno = 0;
  WCHAR  *rawarg;
562
  WIN32_FIND_DATAW fd;
563
  HANDLE  hff = INVALID_HANDLE_VALUE;
564 565 566
  int     binarymode = -1;            /* -1 means use the default, 1 is binary, 0 ascii */
  BOOL    concatnextfilename = FALSE; /* True if we have just processed a +             */
  BOOL    anyconcats         = FALSE; /* Have we found any + options                    */
567 568 569 570 571 572 573 574
  BOOL    appendfirstsource  = FALSE; /* Use first found filename as destination        */
  BOOL    writtenoneconcat   = FALSE; /* Remember when the first concatenated file done */
  BOOL    prompt;                     /* Prompt before overwriting                      */
  WCHAR   destname[MAX_PATH];         /* Used in calculating the destination name       */
  BOOL    destisdirectory = FALSE;    /* Is the destination a directory?                */
  BOOL    status;
  WCHAR   copycmd[4];
  DWORD   len;
575
  BOOL    dstisdevice = FALSE;
576
  static const WCHAR copyCmdW[] = {'C','O','P','Y','C','M','D','\0'};
577

578 579 580 581 582 583 584 585 586 587 588 589 590
  typedef struct _COPY_FILES
  {
    struct _COPY_FILES *next;
    BOOL                concatenate;
    WCHAR              *name;
    int                 binarycopy;
  } COPY_FILES;
  COPY_FILES *sourcelist    = NULL;
  COPY_FILES *lastcopyentry = NULL;
  COPY_FILES *destination   = NULL;
  COPY_FILES *thiscopy      = NULL;
  COPY_FILES *prevcopy      = NULL;

591 592 593
  /* Assume we were successful! */
  errorlevel = 0;

594
  /* If no args supplied at all, report an error */
595
  if (param1[0] == 0x00) {
596
    WCMD_output_stderr (WCMD_LoadMessage(WCMD_NOARG));
597
    errorlevel = 1;
598 599 600
    return;
  }

601
  opt_d = opt_v = opt_n = opt_z = opt_y = opt_noty = FALSE;
602 603

  /* Walk through all args, building up a list of files to process */
604
  thisparam = WCMD_parameter(args, argno++, &rawarg, TRUE, FALSE);
605 606 607 608 609 610 611 612 613 614 615 616 617
  while (*(thisparam)) {
    WCHAR *pos1, *pos2;
    BOOL inquotes;

    WINE_TRACE("Working on parameter '%s'\n", wine_dbgstr_w(thisparam));

    /* Handle switches */
    if (*thisparam == '/') {
        while (*thisparam == '/') {
        thisparam++;
        if (toupperW(*thisparam) == 'D') {
          opt_d = TRUE;
          if (opt_d) WINE_FIXME("copy /D support not implemented yet\n");
618 619 620 621
        } else if (toupperW(*thisparam) == 'Y') {
          opt_y = TRUE;
        } else if (toupperW(*thisparam) == '-' && toupperW(*(thisparam+1)) == 'Y') {
          opt_noty = TRUE;
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
        } else if (toupperW(*thisparam) == 'V') {
          opt_v = TRUE;
          if (opt_v) WINE_FIXME("copy /V support not implemented yet\n");
        } else if (toupperW(*thisparam) == 'N') {
          opt_n = TRUE;
          if (opt_n) WINE_FIXME("copy /N support not implemented yet\n");
        } else if (toupperW(*thisparam) == 'Z') {
          opt_z = TRUE;
          if (opt_z) WINE_FIXME("copy /Z support not implemented yet\n");
        } else if (toupperW(*thisparam) == 'A') {
          if (binarymode != 0) {
            binarymode = 0;
            WINE_TRACE("Subsequent files will be handled as ASCII\n");
            if (destination != NULL) {
              WINE_TRACE("file %s will be written as ASCII\n", wine_dbgstr_w(destination->name));
              destination->binarycopy = binarymode;
            } else if (lastcopyentry != NULL) {
              WINE_TRACE("file %s will be read as ASCII\n", wine_dbgstr_w(lastcopyentry->name));
              lastcopyentry->binarycopy = binarymode;
            }
          }
        } else if (toupperW(*thisparam) == 'B') {
          if (binarymode != 1) {
            binarymode = 1;
            WINE_TRACE("Subsequent files will be handled as binary\n");
            if (destination != NULL) {
              WINE_TRACE("file %s will be written as binary\n", wine_dbgstr_w(destination->name));
              destination->binarycopy = binarymode;
            } else if (lastcopyentry != NULL) {
              WINE_TRACE("file %s will be read as binary\n", wine_dbgstr_w(lastcopyentry->name));
              lastcopyentry->binarycopy = binarymode;
            }
          }
        } else {
          WINE_FIXME("Unexpected copy switch %s\n", wine_dbgstr_w(thisparam));
        }
        thisparam++;
      }

      /* This parameter was purely switches, get the next one */
662
      thisparam = WCMD_parameter(args, argno++, &rawarg, TRUE, FALSE);
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
      continue;
    }

    /* We have found something which is not a switch. If could be anything of the form
         sourcefilename (which could be destination too)
         + (when filename + filename syntex used)
         sourcefilename+sourcefilename
         +sourcefilename
         +/b[tests show windows then ignores to end of parameter]
     */

    if (*thisparam=='+') {
      if (lastcopyentry == NULL) {
        WCMD_output_stderr(WCMD_LoadMessage(WCMD_SYNTAXERR));
        errorlevel = 1;
        goto exitreturn;
      } else {
        concatnextfilename = TRUE;
        anyconcats         = TRUE;
      }

      /* Move to next thing to process */
      thisparam++;
686
      if (*thisparam == 0x00)
687
        thisparam = WCMD_parameter(args, argno++, &rawarg, TRUE, FALSE);
688 689 690 691
      continue;
    }

    /* We have found something to process - build a COPY_FILE block to store it */
692
    thiscopy = heap_alloc(sizeof(COPY_FILES));
693 694 695 696 697 698 699 700 701 702

    WINE_TRACE("Not a switch, but probably a filename/list %s\n", wine_dbgstr_w(thisparam));
    thiscopy->concatenate = concatnextfilename;
    thiscopy->binarycopy  = binarymode;
    thiscopy->next        = NULL;

    /* Time to work out the name. Allocate at least enough space (deliberately too much to
       leave space to append \* to the end) , then copy in character by character. Strip off
       quotes if we find them.                                                               */
    len = strlenW(thisparam) + (sizeof(WCHAR) * 5);  /* 5 spare characters, null + \*.*      */
703
    thiscopy->name = heap_alloc(len*sizeof(WCHAR));
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
    memset(thiscopy->name, 0x00, len);

    pos1 = thisparam;
    pos2 = thiscopy->name;
    inquotes = FALSE;
    while (*pos1 && (inquotes || (*pos1 != '+' && *pos1 != '/'))) {
      if (*pos1 == '"') {
        inquotes = !inquotes;
        pos1++;
      } else *pos2++ = *pos1++;
    }
    *pos2 = 0;
    WINE_TRACE("Calculated file name %s\n", wine_dbgstr_w(thiscopy->name));

    /* This is either the first source, concatenated subsequent source or destination */
    if (sourcelist == NULL) {
      WINE_TRACE("Adding as first source part\n");
      sourcelist = thiscopy;
      lastcopyentry = thiscopy;
    } else if (concatnextfilename) {
      WINE_TRACE("Adding to source file list to be concatenated\n");
      lastcopyentry->next = thiscopy;
      lastcopyentry = thiscopy;
    } else if (destination == NULL) {
      destination = thiscopy;
    } else {
      /* We have processed sources and destinations and still found more to do - invalid */
      WCMD_output_stderr(WCMD_LoadMessage(WCMD_SYNTAXERR));
      errorlevel = 1;
      goto exitreturn;
    }
    concatnextfilename    = FALSE;

    /* We either need to process the rest of the parameter or move to the next */
    if (*pos1 == '/' || *pos1 == '+') {
      thisparam = pos1;
      continue;
    } else {
742
      thisparam = WCMD_parameter(args, argno++, &rawarg, TRUE, FALSE);
743 744 745 746 747 748 749 750 751 752
    }
  }

  /* Ensure we have at least one source file */
  if (!sourcelist) {
    WCMD_output_stderr(WCMD_LoadMessage(WCMD_SYNTAXERR));
    errorlevel = 1;
    goto exitreturn;
  }

753 754 755 756 757
  /* Default whether automatic overwriting is on. If we are interactive then
     we prompt by default, otherwise we overwrite by default
     /-Y has the highest priority, then /Y and finally the COPYCMD env. variable */
  if (opt_noty) prompt = TRUE;
  else if (opt_y) prompt = FALSE;
758
  else {
759 760
    /* By default, we will force the overwrite in batch mode and ask for
     * confirmation in interactive mode. */
761
    prompt = interactive;
762 763 764
    /* If COPYCMD is set, then we force the overwrite with /Y and ask for
     * confirmation with /-Y. If COPYCMD is neither of those, then we use the
     * default behavior. */
765
    len = GetEnvironmentVariableW(copyCmdW, copycmd, sizeof(copycmd)/sizeof(WCHAR));
766 767
    if (len && len < (sizeof(copycmd)/sizeof(WCHAR))) {
      if (!lstrcmpiW (copycmd, parmY))
768
        prompt = FALSE;
769
      else if (!lstrcmpiW (copycmd, parmNoY))
770
        prompt = TRUE;
771
    }
772 773
  }

774
  /* Calculate the destination now - if none supplied, it's current dir +
775 776 777 778 779 780 781
     filename of first file in list*/
  if (destination == NULL) {

    WINE_TRACE("No destination supplied, so need to calculate it\n");
    strcpyW(destname, dotW);
    strcatW(destname, slashW);

782
    destination = heap_alloc(sizeof(COPY_FILES));
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
    if (destination == NULL) goto exitreturn;
    destination->concatenate = FALSE;           /* Not used for destination */
    destination->binarycopy  = binarymode;
    destination->next        = NULL;            /* Not used for destination */
    destination->name        = NULL;            /* To be filled in          */
    destisdirectory          = TRUE;

  } else {
    WCHAR *filenamepart;
    DWORD  attributes;

    WINE_TRACE("Destination supplied, processing to see if file or directory\n");

    /* Convert to fully qualified path/filename */
    GetFullPathNameW(destination->name, sizeof(destname)/sizeof(WCHAR), destname, &filenamepart);
    WINE_TRACE("Full dest name is '%s'\n", wine_dbgstr_w(destname));

    /* If parameter is a directory, ensure it ends in \ */
    attributes = GetFileAttributesW(destname);
802
    if (ends_with_backslash( destname ) ||
803 804 805 806
        ((attributes != INVALID_FILE_ATTRIBUTES) &&
         (attributes & FILE_ATTRIBUTE_DIRECTORY))) {

      destisdirectory = TRUE;
807
      if (!ends_with_backslash( destname )) strcatW(destname, slashW);
808 809 810 811 812
      WINE_TRACE("Directory, so full name is now '%s'\n", wine_dbgstr_w(destname));
    }
  }

  /* Normally, the destination is the current directory unless we are
813
     concatenating, in which case it's current directory plus first filename.
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
     Note that if the
     In addition by default it is a binary copy unless concatenating, when
     the copy defaults to an ascii copy (stop at EOF). We do not know the
     first source part yet (until we search) so flag as needing filling in. */

  if (anyconcats) {
    /* We have found an a+b type syntax, so destination has to be a filename
       and we need to default to ascii copying. If we have been supplied a
       directory as the destination, we need to defer calculating the name   */
    if (destisdirectory) appendfirstsource = TRUE;
    if (destination->binarycopy == -1) destination->binarycopy = 0;

  } else if (!destisdirectory) {
    /* We have been asked to copy to a filename. Default to ascii IF the
       source contains wildcards (true even if only one match)           */
829 830 831
    if (strpbrkW(sourcelist->name, wildcardsW) != NULL) {
      anyconcats = TRUE;  /* We really are concatenating to a single file */
      if (destination->binarycopy == -1) {
832
        destination->binarycopy = 0;
833 834 835
      }
    } else {
      if (destination->binarycopy == -1) {
836 837 838 839
        destination->binarycopy = 1;
      }
    }
  }
840

841
  /* Save away the destination name*/
842
  heap_free(destination->name);
843
  destination->name = heap_strdupW(destname);
844 845 846
  WINE_TRACE("Resolved destination is '%s' (calc later %d)\n",
             wine_dbgstr_w(destname), appendfirstsource);

847 848 849 850 851 852
  /* Remember if the destination is a device */
  if (strncmpW(destination->name, deviceW, strlenW(deviceW)) == 0) {
    WINE_TRACE("Destination is a device\n");
    dstisdevice = TRUE;
  }

853 854 855 856 857 858 859 860
  /* Now we need to walk the set of sources, and process each name we come to.
     If anyconcats is true, we are writing to one file, otherwise we are using
     the source name each time.
     If destination exists, prompt for overwrite the first time (if concatenating
     we ask each time until yes is answered)
     The first source file we come across must exist (when wildcards expanded)
     and if concatenating with overwrite prompts, each source file must exist
     until a yes is answered.                                                    */
861

862 863 864 865 866 867
  thiscopy = sourcelist;
  prevcopy = NULL;

  while (thiscopy != NULL) {

    WCHAR  srcpath[MAX_PATH];
868
    const  WCHAR *srcname;
869 870
    WCHAR *filenamepart;
    DWORD  attributes;
871
    BOOL   srcisdevice = FALSE;
872

873
    /* If it was not explicit, we now know whether we are concatenating or not and
874 875 876 877
       hence whether to copy as binary or ascii                                    */
    if (thiscopy->binarycopy == -1) thiscopy->binarycopy = !anyconcats;

    /* Convert to fully qualified path/filename in srcpath, file filenamepart pointing
878
       to where the filename portion begins (used for wildcard expansion).             */
879 880 881 882 883
    GetFullPathNameW(thiscopy->name, sizeof(srcpath)/sizeof(WCHAR), srcpath, &filenamepart);
    WINE_TRACE("Full src name is '%s'\n", wine_dbgstr_w(srcpath));

    /* If parameter is a directory, ensure it ends in \* */
    attributes = GetFileAttributesW(srcpath);
884
    if (ends_with_backslash( srcpath )) {
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905

      /* We need to know where the filename part starts, so append * and
         recalculate the full resulting path                              */
      strcatW(thiscopy->name, starW);
      GetFullPathNameW(thiscopy->name, sizeof(srcpath)/sizeof(WCHAR), srcpath, &filenamepart);
      WINE_TRACE("Directory, so full name is now '%s'\n", wine_dbgstr_w(srcpath));

    } else if ((strpbrkW(srcpath, wildcardsW) == NULL) &&
               (attributes != INVALID_FILE_ATTRIBUTES) &&
               (attributes & FILE_ATTRIBUTE_DIRECTORY)) {

      /* We need to know where the filename part starts, so append \* and
         recalculate the full resulting path                              */
      strcatW(thiscopy->name, slashstarW);
      GetFullPathNameW(thiscopy->name, sizeof(srcpath)/sizeof(WCHAR), srcpath, &filenamepart);
      WINE_TRACE("Directory, so full name is now '%s'\n", wine_dbgstr_w(srcpath));
    }

    WINE_TRACE("Copy source (calculated): path: '%s' (Concats: %d)\n",
                    wine_dbgstr_w(srcpath), anyconcats);

906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
    /* If the source is a device, just use it, otherwise search */
    if (strncmpW(srcpath, deviceW, strlenW(deviceW)) == 0) {
      WINE_TRACE("Source is a device\n");
      srcisdevice = TRUE;
      srcname  = &srcpath[4]; /* After the \\.\ prefix */
    } else {

      /* Loop through all source files */
      WINE_TRACE("Searching for: '%s'\n", wine_dbgstr_w(srcpath));
      hff = FindFirstFileW(srcpath, &fd);
      if (hff != INVALID_HANDLE_VALUE) {
        srcname = fd.cFileName;
      }
    }

    if (srcisdevice || hff != INVALID_HANDLE_VALUE) {
922 923 924
      do {
        WCHAR outname[MAX_PATH];
        BOOL  overwrite;
925 926

        /* Skip . and .., and directories */
927
        if (!srcisdevice && fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
928
          WINE_TRACE("Skipping directories\n");
929
        } else {
930

931 932
          /* Build final destination name */
          strcpyW(outname, destination->name);
933
          if (destisdirectory || appendfirstsource) strcatW(outname, srcname);
934 935

          /* Build source name */
936
          if (!srcisdevice) strcpyW(filenamepart, srcname);
937

938
          /* Do we just overwrite (we do if we are writing to a device) */
939
          overwrite = !prompt;
940
          if (dstisdevice || (anyconcats && writtenoneconcat)) {
941
            overwrite = TRUE;
942 943
          }

944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
          WINE_TRACE("Copying from : '%s'\n", wine_dbgstr_w(srcpath));
          WINE_TRACE("Copying to : '%s'\n", wine_dbgstr_w(outname));
          WINE_TRACE("Flags: srcbinary(%d), dstbinary(%d), over(%d), prompt(%d)\n",
                     thiscopy->binarycopy, destination->binarycopy, overwrite, prompt);

          /* Prompt before overwriting */
          if (!overwrite) {
            DWORD attributes = GetFileAttributesW(outname);
            if (attributes != INVALID_FILE_ATTRIBUTES) {
              WCHAR* question;
              question = WCMD_format_string(WCMD_LoadMessage(WCMD_OVERWRITE), outname);
              overwrite = WCMD_ask_confirm(question, FALSE, NULL);
              LocalFree(question);
            }
            else overwrite = TRUE;
          }

961
          /* If we needed to save away the first filename, do it */
962
          if (appendfirstsource && overwrite) {
963
            heap_free(destination->name);
964
            destination->name = heap_strdupW(outname);
965 966 967
            WINE_TRACE("Final resolved destination name : '%s'\n", wine_dbgstr_w(outname));
            appendfirstsource = FALSE;
            destisdirectory = FALSE;
968
          }
969

970 971 972 973
          /* Do the copy as appropriate */
          if (overwrite) {
            if (anyconcats && writtenoneconcat) {
              if (thiscopy->binarycopy) {
974
                status = WCMD_ManualCopy(srcpath, outname, FALSE, TRUE);
975
              } else {
976
                status = WCMD_ManualCopy(srcpath, outname, TRUE, TRUE);
977 978
              }
            } else if (!thiscopy->binarycopy) {
979
              status = WCMD_ManualCopy(srcpath, outname, TRUE, FALSE);
980 981
            } else if (srcisdevice) {
              status = WCMD_ManualCopy(srcpath, outname, FALSE, FALSE);
982 983
            } else {
              status = CopyFileW(srcpath, outname, FALSE);
984 985 986 987 988 989 990
            }
            if (!status) {
              WCMD_print_error ();
              errorlevel = 1;
            } else {
              WINE_TRACE("Copied successfully\n");
              if (anyconcats) writtenoneconcat = TRUE;
991

992 993 994 995 996
              /* Append EOF if ascii destination and we are not going to add more onto the end
                 Note: Testing shows windows has an optimization whereas if you have a binary
                 copy of a file to a single destination (ie concatenation) then it does not add
                 the EOF, hence the check on the source copy type below.                       */
              if (!destination->binarycopy && !anyconcats && !thiscopy->binarycopy) {
997 998 999 1000 1001
                if (!WCMD_AppendEOF(outname)) {
                  WCMD_print_error ();
                  errorlevel = 1;
                }
              }
1002 1003 1004
            }
          }
        }
1005 1006
      } while (!srcisdevice && FindNextFileW(hff, &fd) != 0);
      if (!srcisdevice) FindClose (hff);
1007 1008
    } else {
      /* Error if the first file was not found */
1009
      if (!anyconcats || !writtenoneconcat) {
1010 1011 1012 1013 1014 1015 1016
        WCMD_print_error ();
        errorlevel = 1;
      }
    }

    /* Step on to the next supplied source */
    thiscopy = thiscopy -> next;
1017
  }
1018

1019
  /* Append EOF if ascii destination and we were concatenating */
1020 1021 1022 1023 1024
  if (!errorlevel && !destination->binarycopy && anyconcats && writtenoneconcat) {
    if (!WCMD_AppendEOF(destination->name)) {
      WCMD_print_error ();
      errorlevel = 1;
    }
1025
  }
1026

1027
  /* Exit out of the routine, freeing any remaining allocated memory */
1028 1029 1030 1031 1032 1033 1034
exitreturn:

  thiscopy = sourcelist;
  while (thiscopy != NULL) {
    prevcopy = thiscopy;
    /* Free up this block*/
    thiscopy = thiscopy -> next;
1035 1036
    heap_free(prevcopy->name);
    heap_free(prevcopy);
1037 1038 1039 1040
  }

  /* Free up the destination memory */
  if (destination) {
1041 1042
    heap_free(destination->name);
    heap_free(destination);
1043 1044 1045
  }

  return;
1046 1047 1048 1049 1050
}

/****************************************************************************
 * WCMD_create_dir
 *
1051
 * Create a directory (and, if needed, any intermediate directories).
1052
 *
1053
 * Modifies its argument by replacing slashes temporarily with nulls.
1054 1055
 */

1056
static BOOL create_full_path(WCHAR* path)
1057
{
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    WCHAR *p, *start;

    /* don't mess with drive letter portion of path, if any */
    start = path;
    if (path[1] == ':')
        start = path+2;

    /* Strip trailing slashes. */
    for (p = path + strlenW(path) - 1; p != start && *p == '\\'; p--)
        *p = 0;

    /* Step through path, creating intermediate directories as needed. */
    /* First component includes drive letter, if any. */
    p = start;
    for (;;) {
        DWORD rv;
        /* Skip to end of component */
        while (*p == '\\') p++;
        while (*p && *p != '\\') p++;
        if (!*p) {
            /* path is now the original full path */
            return CreateDirectoryW(path, NULL);
1080
        }
1081 1082 1083 1084 1085 1086
        /* Truncate path, create intermediate directory, and restore path */
        *p = 0;
        rv = CreateDirectoryW(path, NULL);
        *p = '\\';
        if (!rv && GetLastError() != ERROR_ALREADY_EXISTS)
            return FALSE;
1087
    }
1088 1089
    /* notreached */
    return FALSE;
1090 1091
}

1092
void WCMD_create_dir (WCHAR *args) {
1093
    int   argno = 0;
1094
    WCHAR *argN = args;
1095

1096
    if (param1[0] == 0x00) {
1097
        WCMD_output_stderr(WCMD_LoadMessage(WCMD_NOARG));
1098 1099
        return;
    }
1100 1101
    /* Loop through all args */
    while (TRUE) {
1102
        WCHAR *thisArg = WCMD_parameter(args, argno++, &argN, FALSE, FALSE);
1103 1104 1105
        if (!argN) break;
        if (!create_full_path(thisArg)) {
            WCMD_print_error ();
1106
            errorlevel = 1;
1107 1108
        }
    }
1109 1110
}

1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
/* Parse the /A options given by the user on the commandline
 * into a bitmask of wanted attributes (*wantSet),
 * and a bitmask of unwanted attributes (*wantClear).
 */
static void WCMD_delete_parse_attributes(DWORD *wantSet, DWORD *wantClear) {
    static const WCHAR parmA[] = {'/','A','\0'};
    WCHAR *p;

    /* both are strictly 'out' parameters */
    *wantSet=0;
    *wantClear=0;

    /* For each /A argument */
    for (p=strstrW(quals, parmA); p != NULL; p=strstrW(p, parmA)) {
        /* Skip /A itself */
        p += 2;

        /* Skip optional : */
        if (*p == ':') p++;

        /* For each of the attribute specifier chars to this /A option */
        for (; *p != 0 && *p != '/'; p++) {
            BOOL negate = FALSE;
            DWORD mask  = 0;

            if (*p == '-') {
                negate=TRUE;
                p++;
            }

            /* Convert the attribute specifier to a bit in one of the masks */
            switch (*p) {
            case 'R': mask = FILE_ATTRIBUTE_READONLY; break;
            case 'H': mask = FILE_ATTRIBUTE_HIDDEN;   break;
            case 'S': mask = FILE_ATTRIBUTE_SYSTEM;   break;
            case 'A': mask = FILE_ATTRIBUTE_ARCHIVE;  break;
            default:
1148
                WCMD_output_stderr(WCMD_LoadMessage(WCMD_SYNTAXERR));
1149 1150 1151 1152 1153 1154 1155 1156 1157
            }
            if (negate)
                *wantClear |= mask;
            else
                *wantSet |= mask;
        }
    }
}

1158 1159 1160 1161 1162 1163 1164
/* If filename part of parameter is * or *.*,
 * and neither /Q nor /P options were given,
 * prompt the user whether to proceed.
 * Returns FALSE if user says no, TRUE otherwise.
 * *pPrompted is set to TRUE if the user is prompted.
 * (If /P supplied, del will prompt for individual files later.)
 */
1165
static BOOL WCMD_delete_confirm_wildcard(const WCHAR *filename, BOOL *pPrompted) {
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    static const WCHAR parmP[] = {'/','P','\0'};
    static const WCHAR parmQ[] = {'/','Q','\0'};

    if ((strstrW(quals, parmQ) == NULL) && (strstrW(quals, parmP) == NULL)) {
        static const WCHAR anyExt[]= {'.','*','\0'};
        WCHAR drive[10];
        WCHAR dir[MAX_PATH];
        WCHAR fname[MAX_PATH];
        WCHAR ext[MAX_PATH];
        WCHAR fpath[MAX_PATH];

        /* Convert path into actual directory spec */
        GetFullPathNameW(filename, sizeof(fpath)/sizeof(WCHAR), fpath, NULL);
        WCMD_splitpath(fpath, drive, dir, fname, ext);

        /* Only prompt for * and *.*, not *a, a*, *.a* etc */
        if ((strcmpW(fname, starW) == 0) &&
            (*ext == 0x00 || (strcmpW(ext, anyExt) == 0))) {

            WCHAR question[MAXSTRING];
            static const WCHAR fmt[] = {'%','s',' ','\0'};

            /* Caller uses this to suppress "file not found" warning later */
            *pPrompted = TRUE;

            /* Ask for confirmation */
            wsprintfW(question, fmt, fpath);
            return WCMD_ask_confirm(question, TRUE, NULL);
        }
    }
    /* No scary wildcard, or question suppressed, so it's ok to delete the file(s) */
    return TRUE;
}

1200 1201 1202 1203
/* Helper function for WCMD_delete().
 * Deletes a single file, directory, or wildcard.
 * If /S was given, does it recursively.
 * Returns TRUE if a file was deleted.
1204
 */
1205
static BOOL WCMD_delete_one (const WCHAR *thisArg) {
1206

1207 1208 1209
    static const WCHAR parmP[] = {'/','P','\0'};
    static const WCHAR parmS[] = {'/','S','\0'};
    static const WCHAR parmF[] = {'/','F','\0'};
1210 1211
    DWORD wanted_attrs;
    DWORD unwanted_attrs;
1212 1213 1214 1215 1216 1217 1218
    BOOL found = FALSE;
    WCHAR argCopy[MAX_PATH];
    WIN32_FIND_DATAW fd;
    HANDLE hff;
    WCHAR fpath[MAX_PATH];
    WCHAR *p;
    BOOL handleParm = TRUE;
1219 1220

    WCMD_delete_parse_attributes(&wanted_attrs, &unwanted_attrs);
1221

1222 1223 1224
    strcpyW(argCopy, thisArg);
    WINE_TRACE("del: Processing arg %s (quals:%s)\n",
               wine_dbgstr_w(argCopy), wine_dbgstr_w(quals));
1225

1226 1227 1228 1229
    if (!WCMD_delete_confirm_wildcard(argCopy, &found)) {
        /* Skip this arg if user declines to delete *.* */
        return FALSE;
    }
1230

1231 1232 1233 1234 1235 1236 1237
    /* First, try to delete in the current directory */
    hff = FindFirstFileW(argCopy, &fd);
    if (hff == INVALID_HANDLE_VALUE) {
      handleParm = FALSE;
    } else {
      found = TRUE;
    }
1238

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
    /* Support del <dirname> by just deleting all files dirname\* */
    if (handleParm
        && (strchrW(argCopy,'*') == NULL)
        && (strchrW(argCopy,'?') == NULL)
        && (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
    {
      WCHAR modifiedParm[MAX_PATH];
      static const WCHAR slashStar[] = {'\\','*','\0'};

      strcpyW(modifiedParm, argCopy);
      strcatW(modifiedParm, slashStar);
      FindClose(hff);
      found = TRUE;
      WCMD_delete_one(modifiedParm);

    } else if (handleParm) {
1255

1256 1257 1258 1259 1260 1261 1262
      /* Build the filename to delete as <supplied directory>\<findfirst filename> */
      strcpyW (fpath, argCopy);
      do {
        p = strrchrW (fpath, '\\');
        if (p != NULL) {
          *++p = '\0';
          strcatW (fpath, fd.cFileName);
1263
        }
1264 1265 1266
        else strcpyW (fpath, fd.cFileName);
        if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
          BOOL ok;
1267

1268 1269 1270 1271 1272 1273
          /* Handle attribute matching (/A) */
          ok =  ((fd.dwFileAttributes & wanted_attrs) == wanted_attrs)
             && ((fd.dwFileAttributes & unwanted_attrs) == 0);

          /* /P means prompt for each file */
          if (ok && strstrW (quals, parmP) != NULL) {
1274
            WCHAR* question;
1275

1276
            /* Ask for confirmation */
1277
            question = WCMD_format_string(WCMD_LoadMessage(WCMD_DELPROMPT), fpath);
1278
            ok = WCMD_ask_confirm(question, FALSE, NULL);
1279
            LocalFree(question);
1280
          }
1281

1282 1283 1284 1285 1286 1287 1288 1289
          /* Only proceed if ok to */
          if (ok) {

            /* If file is read only, and /A:r or /F supplied, delete it */
            if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY &&
                ((wanted_attrs & FILE_ATTRIBUTE_READONLY) ||
                strstrW (quals, parmF) != NULL)) {
                SetFileAttributesW(fpath, fd.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY);
1290
            }
1291 1292 1293 1294 1295

            /* Now do the delete */
            if (!DeleteFileW(fpath)) WCMD_print_error ();
          }

1296
        }
1297 1298 1299
      } while (FindNextFileW(hff, &fd) != 0);
      FindClose (hff);
    }
1300

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
    /* Now recurse into all subdirectories handling the parameter in the same way */
    if (strstrW (quals, parmS) != NULL) {

      WCHAR thisDir[MAX_PATH];
      int cPos;

      WCHAR drive[10];
      WCHAR dir[MAX_PATH];
      WCHAR fname[MAX_PATH];
      WCHAR ext[MAX_PATH];

      /* Convert path into actual directory spec */
      GetFullPathNameW(argCopy, sizeof(thisDir)/sizeof(WCHAR), thisDir, NULL);
      WCMD_splitpath(thisDir, drive, dir, fname, ext);

      strcpyW(thisDir, drive);
      strcatW(thisDir, dir);
      cPos = strlenW(thisDir);

      WINE_TRACE("Searching recursively in '%s'\n", wine_dbgstr_w(thisDir));

      /* Append '*' to the directory */
      thisDir[cPos] = '*';
      thisDir[cPos+1] = 0x00;

      hff = FindFirstFileW(thisDir, &fd);

      /* Remove residual '*' */
      thisDir[cPos] = 0x00;

      if (hff != INVALID_HANDLE_VALUE) {
        DIRECTORY_STACK *allDirs = NULL;
        DIRECTORY_STACK *lastEntry = NULL;

        do {
          if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
              (strcmpW(fd.cFileName, dotdotW) != 0) &&
              (strcmpW(fd.cFileName, dotW) != 0)) {

            DIRECTORY_STACK *nextDir;
            WCHAR subParm[MAX_PATH];

            /* Work out search parameter in sub dir */
            strcpyW (subParm, thisDir);
            strcatW (subParm, fd.cFileName);
            strcatW (subParm, slashW);
            strcatW (subParm, fname);
            strcatW (subParm, ext);
            WINE_TRACE("Recursive, Adding to search list '%s'\n", wine_dbgstr_w(subParm));

            /* Allocate memory, add to list */
1352
            nextDir = heap_alloc(sizeof(DIRECTORY_STACK));
1353 1354 1355 1356
            if (allDirs == NULL) allDirs = nextDir;
            if (lastEntry != NULL) lastEntry->next = nextDir;
            lastEntry = nextDir;
            nextDir->next = NULL;
1357
            nextDir->dirName = heap_strdupW(subParm);
1358
          }
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
        } while (FindNextFileW(hff, &fd) != 0);
        FindClose (hff);

        /* Go through each subdir doing the delete */
        while (allDirs != NULL) {
          DIRECTORY_STACK *tempDir;

          tempDir = allDirs->next;
          found |= WCMD_delete_one (allDirs->dirName);

1369 1370
          heap_free(allDirs->dirName);
          heap_free(allDirs);
1371
          allDirs = tempDir;
1372
        }
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
      }
    }

    return found;
}

/****************************************************************************
 * WCMD_delete
 *
 * Delete a file or wildcarded set.
 *
 * Note on /A:
 *  - Testing shows /A is repeatable, eg. /a-r /ar matches all files
 *  - Each set is a pattern, eg /ahr /as-r means
 *         readonly+hidden OR nonreadonly system files
 *  - The '-' applies to a single field, ie /a:-hr means read only
 *         non-hidden files
 */

1392
BOOL WCMD_delete (WCHAR *args) {
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
    int   argno;
    WCHAR *argN;
    BOOL  argsProcessed = FALSE;
    BOOL  foundAny      = FALSE;

    errorlevel = 0;

    for (argno=0; ; argno++) {
        BOOL found;
        WCHAR *thisArg;

        argN = NULL;
1405
        thisArg = WCMD_parameter (args, argno, &argN, FALSE, FALSE);
1406 1407 1408 1409 1410 1411 1412
        if (!argN)
            break;       /* no more parameters */
        if (argN[0] == '/')
            continue;    /* skip options */

        argsProcessed = TRUE;
        found = WCMD_delete_one(thisArg);
1413
        if (!found)
1414
            WCMD_output_stderr(WCMD_LoadMessage(WCMD_FILENOTFOUND), thisArg);
1415
        foundAny |= found;
1416 1417 1418
    }

    /* Handle no valid args */
1419
    if (!argsProcessed)
1420
        WCMD_output_stderr(WCMD_LoadMessage(WCMD_NOARG));
1421 1422

    return foundAny;
1423 1424
}

1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
/*
 * WCMD_strtrim
 *
 * Returns a trimmed version of s with all leading and trailing whitespace removed
 * Pre: s non NULL
 *
 */
static WCHAR *WCMD_strtrim(const WCHAR *s)
{
    DWORD len = strlenW(s);
    const WCHAR *start = s;
    WCHAR* result;

1438
    result = heap_alloc((len + 1) * sizeof(WCHAR));
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452

    while (isspaceW(*start)) start++;
    if (*start) {
        const WCHAR *end = s + len - 1;
        while (end > start && isspaceW(*end)) end--;
        memcpy(result, start, (end - start + 2) * sizeof(WCHAR));
        result[end - start + 1] = '\0';
    } else {
        result[0] = '\0';
    }

    return result;
}

1453 1454 1455 1456 1457 1458 1459
/****************************************************************************
 * WCMD_echo
 *
 * Echo input to the screen (or not). We don't try to emulate the bugs
 * in DOS (try typing "ECHO ON AGAIN" for an example).
 */

1460
void WCMD_echo (const WCHAR *args)
1461
{
1462
  int count;
1463
  const WCHAR *origcommand = args;
1464
  WCHAR *trimmed;
1465

1466
  if (   args[0]==' ' || args[0]=='\t' || args[0]=='.'
1467
      || args[0]==':' || args[0]==';'  || args[0]=='/')
1468
    args++;
1469

1470
  trimmed = WCMD_strtrim(args);
1471 1472 1473
  if (!trimmed) return;

  count = strlenW(trimmed);
1474
  if (count == 0 && origcommand[0]!='.' && origcommand[0]!=':'
1475
                 && origcommand[0]!=';' && origcommand[0]!='/') {
1476 1477
    if (echo_mode) WCMD_output (WCMD_LoadMessage(WCMD_ECHOPROMPT), onW);
    else WCMD_output (WCMD_LoadMessage(WCMD_ECHOPROMPT), offW);
1478
    heap_free(trimmed);
1479 1480
    return;
  }
1481 1482

  if (lstrcmpiW(trimmed, onW) == 0)
1483
    echo_mode = TRUE;
1484
  else if (lstrcmpiW(trimmed, offW) == 0)
1485
    echo_mode = FALSE;
1486
  else {
1487
    WCMD_output_asis (args);
1488
    WCMD_output_asis (newlineW);
1489
  }
1490
  heap_free(trimmed);
1491 1492
}

1493 1494 1495 1496 1497 1498 1499 1500
/*****************************************************************************
 * WCMD_part_execute
 *
 * Execute a command, and any && or bracketed follow on to the command. The
 * first command to be executed may not be at the front of the
 * commands->thiscommand string (eg. it may point after a DO or ELSE)
 */
static void WCMD_part_execute(CMD_LIST **cmdList, const WCHAR *firstcmd,
1501
                              BOOL isIF, BOOL executecmds)
1502 1503 1504 1505
{
  CMD_LIST *curPosition = *cmdList;
  int myDepth = (*cmdList)->bracketDepth;

1506
  WINE_TRACE("cmdList(%p), firstCmd(%s), doIt(%d)\n", cmdList, wine_dbgstr_w(firstcmd),
1507
             executecmds);
1508 1509 1510 1511 1512

  /* Skip leading whitespace between condition and the command */
  while (firstcmd && *firstcmd && (*firstcmd==' ' || *firstcmd=='\t')) firstcmd++;

  /* Process the first command, if there is one */
1513
  if (executecmds && firstcmd && *firstcmd) {
1514
    WCHAR *command = heap_strdupW(firstcmd);
1515
    WCMD_execute (firstcmd, (*cmdList)->redirects, cmdList, FALSE);
1516
    heap_free(command);
1517 1518 1519 1520 1521 1522 1523 1524
  }


  /* If it didn't move the position, step to next command */
  if (curPosition == *cmdList) *cmdList = (*cmdList)->nextcommand;

  /* Process any other parts of the command */
  if (*cmdList) {
1525
    BOOL processThese = executecmds;
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542

    while (*cmdList) {
      static const WCHAR ifElse[] = {'e','l','s','e'};

      /* execute all appropriate commands */
      curPosition = *cmdList;

      WINE_TRACE("Processing cmdList(%p) - delim(%d) bd(%d / %d)\n",
                 *cmdList,
                 (*cmdList)->prevDelim,
                 (*cmdList)->bracketDepth, myDepth);

      /* Execute any statements appended to the line */
      /* FIXME: Only if previous call worked for && or failed for || */
      if ((*cmdList)->prevDelim == CMD_ONFAILURE ||
          (*cmdList)->prevDelim == CMD_ONSUCCESS) {
        if (processThese && (*cmdList)->command) {
1543 1544
          WCMD_execute ((*cmdList)->command, (*cmdList)->redirects,
                        cmdList, FALSE);
1545 1546 1547 1548 1549 1550
        }
        if (curPosition == *cmdList) *cmdList = (*cmdList)->nextcommand;

      /* Execute any appended to the statement with (...) */
      } else if ((*cmdList)->bracketDepth > myDepth) {
        if (processThese) {
1551
          *cmdList = WCMD_process_commands(*cmdList, TRUE, FALSE);
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
          WINE_TRACE("Back from processing commands, (next = %p)\n", *cmdList);
        }
        if (curPosition == *cmdList) *cmdList = (*cmdList)->nextcommand;

      /* End of the command - does 'ELSE ' follow as the next command? */
      } else {
        if (isIF
            && WCMD_keyword_ws_found(ifElse, sizeof(ifElse)/sizeof(ifElse[0]),
                                     (*cmdList)->command)) {

          /* Swap between if and else processing */
1563
          processThese = !executecmds;
1564 1565 1566 1567 1568 1569 1570 1571 1572

          /* Process the ELSE part */
          if (processThese) {
            const int keyw_len = sizeof(ifElse)/sizeof(ifElse[0]) + 1;
            WCHAR *cmd = ((*cmdList)->command) + keyw_len;

            /* Skip leading whitespace between condition and the command */
            while (*cmd && (*cmd==' ' || *cmd=='\t')) cmd++;
            if (*cmd) {
1573
              WCMD_execute (cmd, (*cmdList)->redirects, cmdList, FALSE);
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
            }
          }
          if (curPosition == *cmdList) *cmdList = (*cmdList)->nextcommand;
        } else {
          WINE_TRACE("Found end of this IF statement (next = %p)\n", *cmdList);
          break;
        }
      }
    }
  }
  return;
}

1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
/*****************************************************************************
 * WCMD_parse_forf_options
 *
 * Parses the for /f 'options', extracting the values and validating the
 * keywords. Note all keywords are optional.
 * Parameters:
 *  options    [I] The unparsed parameter string
 *  eol        [O] Set to the comment character (eol=x)
 *  skip       [O] Set to the number of lines to skip (skip=xx)
 *  delims     [O] Set to the token delimiters (delims=)
 *  tokens     [O] Set to the requested tokens, as provided (tokens=)
 *  usebackq   [O] Set to TRUE if usebackq found
 *
 * Returns TRUE on success, FALSE on syntax error
 *
 */
static BOOL WCMD_parse_forf_options(WCHAR *options, WCHAR *eol, int *skip,
                                    WCHAR *delims, WCHAR *tokens, BOOL *usebackq)
{

  WCHAR *pos = options;
  int    len = strlenW(pos);
  static const WCHAR eolW[] = {'e','o','l','='};
  static const WCHAR skipW[] = {'s','k','i','p','='};
  static const WCHAR tokensW[] = {'t','o','k','e','n','s','='};
  static const WCHAR delimsW[] = {'d','e','l','i','m','s','='};
  static const WCHAR usebackqW[] = {'u','s','e','b','a','c','k','q'};
  static const WCHAR forf_defaultdelims[] = {' ', '\t', '\0'};
  static const WCHAR forf_defaulttokens[] = {'1', '\0'};

  /* Initialize to defaults */
  strcpyW(delims, forf_defaultdelims);
  strcpyW(tokens, forf_defaulttokens);
  *eol      = 0;
  *skip     = 0;
  *usebackq = FALSE;

  /* Strip (optional) leading and trailing quotes */
  if ((*pos == '"') && (pos[len-1] == '"')) {
    pos[len-1] = 0;
    pos++;
  }

  /* Process each keyword */
  while (pos && *pos) {
    if (*pos == ' ' || *pos == '\t') {
      pos++;

    /* Save End of line character (Ignore line if first token (based on delims) starts with it) */
    } else if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
                       pos, sizeof(eolW)/sizeof(WCHAR),
                       eolW, sizeof(eolW)/sizeof(WCHAR)) == CSTR_EQUAL) {
      *eol = *(pos + sizeof(eolW)/sizeof(WCHAR));
      pos = pos + sizeof(eolW)/sizeof(WCHAR) + 1;
1641
      WINE_TRACE("Found eol as %c(%x)\n", *eol, *eol);
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658

    /* Save number of lines to skip (Can be in base 10, hex (0x...) or octal (0xx) */
    } else if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
                       pos, sizeof(skipW)/sizeof(WCHAR),
                       skipW, sizeof(skipW)/sizeof(WCHAR)) == CSTR_EQUAL) {
      WCHAR *nextchar = NULL;
      pos = pos + sizeof(skipW)/sizeof(WCHAR);
      *skip = strtoulW(pos, &nextchar, 0);
      WINE_TRACE("Found skip as %d lines\n", *skip);
      pos = nextchar;

    /* Save if usebackq semantics are in effect */
    } else if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
                       pos, sizeof(usebackqW)/sizeof(WCHAR),
                       usebackqW, sizeof(usebackqW)/sizeof(WCHAR)) == CSTR_EQUAL) {
      *usebackq = TRUE;
      pos = pos + sizeof(usebackqW)/sizeof(WCHAR);
1659
      WINE_TRACE("Found usebackq\n");
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675

    /* Save the supplied delims. Slightly odd as space can be a delimiter but only
       if you finish the optionsroot string with delims= otherwise the space is
       just a token delimiter!                                                     */
    } else if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
                       pos, sizeof(delimsW)/sizeof(WCHAR),
                       delimsW, sizeof(delimsW)/sizeof(WCHAR)) == CSTR_EQUAL) {
      int i=0;

      pos = pos + sizeof(delimsW)/sizeof(WCHAR);
      while (*pos && *pos != ' ') {
        delims[i++] = *pos;
        pos++;
      }
      if (*pos==' ' && *(pos+1)==0) delims[i++] = *pos;
      delims[i++] = 0; /* Null terminate the delims */
1676
      WINE_TRACE("Found delims as '%s'\n", wine_dbgstr_w(delims));
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689

    /* Save the tokens being requested */
    } else if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
                       pos, sizeof(tokensW)/sizeof(WCHAR),
                       tokensW, sizeof(tokensW)/sizeof(WCHAR)) == CSTR_EQUAL) {
      int i=0;

      pos = pos + sizeof(tokensW)/sizeof(WCHAR);
      while (*pos && *pos != ' ') {
        tokens[i++] = *pos;
        pos++;
      }
      tokens[i++] = 0; /* Null terminate the tokens */
1690
      WINE_TRACE("Found tokens as '%s'\n", wine_dbgstr_w(tokens));
1691 1692 1693 1694 1695 1696 1697 1698 1699

    } else {
      WINE_WARN("Unexpected data in optionsroot: '%s'\n", wine_dbgstr_w(pos));
      return FALSE;
    }
  }
  return TRUE;
}

1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
/*****************************************************************************
 * WCMD_add_dirstowalk
 *
 * When recursing through directories (for /r), we need to add to the list of
 * directories still to walk, any subdirectories of the one we are processing.
 *
 * Parameters
 *  options    [I] The remaining list of directories still to process
 *
 * Note this routine inserts the subdirectories found between the entry being
1710
 * processed, and any other directory still to be processed, mimicking what
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
 * Windows does
 */
static void WCMD_add_dirstowalk(DIRECTORY_STACK *dirsToWalk) {
  DIRECTORY_STACK *remainingDirs = dirsToWalk;
  WCHAR fullitem[MAX_PATH];
  WIN32_FIND_DATAW fd;
  HANDLE hff;

  /* Build a generic search and add all directories on the list of directories
     still to walk                                                             */
  strcpyW(fullitem, dirsToWalk->dirName);
  strcatW(fullitem, slashstarW);
  hff = FindFirstFileW(fullitem, &fd);
  if (hff != INVALID_HANDLE_VALUE) {
    do {
      WINE_TRACE("Looking for subdirectories\n");
      if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
          (strcmpW(fd.cFileName, dotdotW) != 0) &&
          (strcmpW(fd.cFileName, dotW) != 0))
      {
        /* Allocate memory, add to list */
1732
        DIRECTORY_STACK *toWalk = heap_alloc(sizeof(DIRECTORY_STACK));
1733 1734 1735 1736
        WINE_TRACE("(%p->%p)\n", remainingDirs, remainingDirs->next);
        toWalk->next = remainingDirs->next;
        remainingDirs->next = toWalk;
        remainingDirs = toWalk;
1737
        toWalk->dirName = heap_alloc(sizeof(WCHAR) * (strlenW(dirsToWalk->dirName) + 2 + strlenW(fd.cFileName)));
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
        strcpyW(toWalk->dirName, dirsToWalk->dirName);
        strcatW(toWalk->dirName, slashW);
        strcatW(toWalk->dirName, fd.cFileName);
        WINE_TRACE("Added to stack %s (%p->%p)\n", wine_dbgstr_w(toWalk->dirName),
                   toWalk, toWalk->next);
      }
    } while (FindNextFileW(hff, &fd) != 0);
    WINE_TRACE("Finished adding all subdirectories\n");
    FindClose (hff);
  }
}

1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
/**************************************************************************
 * WCMD_for_nexttoken
 *
 * Parse the token= line, identifying the next highest number not processed
 * so far. Count how many tokens are referred (including duplicates) and
 * optionally return that, plus optionally indicate if the tokens= line
 * ends in a star.
 *
 * Parameters:
 *  lasttoken    [I]    - Identifies the token index of the last one
 *                           returned so far (-1 used for first loop)
 *  tokenstr     [I]    - The specified tokens= line
 *  firstCmd     [O]    - Optionally indicate how many tokens are listed
 *  doAll        [O]    - Optionally indicate if line ends with *
 *  duplicates   [O]    - Optionally indicate if there is any evidence of
 *                           overlaying tokens in the string
 * Note the caller should keep a running track of duplicates as the tokens
 * are recursively passed. If any have duplicates, then the * token should
 * not be honoured.
 */
static int WCMD_for_nexttoken(int lasttoken, WCHAR *tokenstr,
                              int *totalfound, BOOL *doall,
                              BOOL *duplicates)
{
  WCHAR *pos = tokenstr;
  int    nexttoken = -1;

  if (totalfound) *totalfound = 0;
  if (doall) *doall = FALSE;
  if (duplicates) *duplicates = FALSE;

  WINE_TRACE("Find next token after %d in %s was %d\n", lasttoken,
             wine_dbgstr_w(tokenstr), nexttoken);

  /* Loop through the token string, parsing it. Valid syntax is:
     token=m or x-y with comma delimiter and optionally * to finish*/
  while (*pos) {
    int nextnumber1, nextnumber2 = -1;
    WCHAR *nextchar;

    /* Get the next number */
    nextnumber1 = strtoulW(pos, &nextchar, 10);

1793
    /* If it is followed by a minus, it's a range, so get the next one as well */
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
    if (*nextchar == '-') {
      nextnumber2 = strtoulW(nextchar+1, &nextchar, 10);

      /* We want to return the lowest number that is higher than lasttoken
         but only if range is positive                                     */
      if (nextnumber2 >= nextnumber1 &&
          lasttoken < nextnumber2) {

        int nextvalue;
        if (nexttoken == -1) {
          nextvalue = max(nextnumber1, (lasttoken+1));
        } else {
          nextvalue = min(nexttoken, max(nextnumber1, (lasttoken+1)));
        }

        /* Flag if duplicates identified */
        if (nexttoken == nextvalue && duplicates) *duplicates = TRUE;

        nexttoken = nextvalue;
      }

      /* Update the running total for the whole range */
      if (nextnumber2 >= nextnumber1 && totalfound) {
        *totalfound = *totalfound + 1 + (nextnumber2 - nextnumber1);
      }

    } else {
      if (totalfound) (*totalfound)++;

      /* See if the number found is one we have already seen */
      if (nextnumber1 == nexttoken && duplicates) *duplicates = TRUE;

      /* We want to return the lowest number that is higher than lasttoken */
      if (lasttoken < nextnumber1 &&
         ((nexttoken == -1) || (nextnumber1 < nexttoken))) {
        nexttoken = nextnumber1;
      }

    }

    /* Remember if it is followed by a star, and if it is indicate a need to
       show all tokens, unless a duplicate has been found                    */
    if (*nextchar == '*') {
      if (doall) *doall = TRUE;
      if (totalfound) (*totalfound)++;
    }

    /* Step on to the next character */
    pos = nextchar;
    if (*pos) pos++;
  }

  /* Return result */
  if (nexttoken == -1) nexttoken = lasttoken;
  WINE_TRACE("Found next token after %d was %d\n", lasttoken, nexttoken);
  if (totalfound) WINE_TRACE("Found total tokens in total %d\n", *totalfound);
  if (doall && *doall) WINE_TRACE("Request for all tokens found\n");
  if (duplicates && *duplicates) WINE_TRACE("Duplicate numbers found\n");
  return nexttoken;
}

1855 1856 1857 1858
/**************************************************************************
 * WCMD_parse_line
 *
 * When parsing file or string contents (for /f), once the string to parse
1859
 * has been identified, handle the various options and call the do part
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
 * if appropriate.
 *
 * Parameters:
 *  cmdStart     [I]    - Identifies the list of commands making up the
 *                           for loop body (especially if brackets in use)
 *  firstCmd     [I]    - The textual start of the command after the DO
 *                           which is within the first item of cmdStart
 *  cmdEnd       [O]    - Identifies where to continue after the DO
 *  variable     [I]    - The variable identified on the for line
 *  buffer       [I]    - The string to parse
 *  doExecuted   [O]    - Set to TRUE if the DO is ever executed once
 *  forf_skip    [I/O]  - How many lines to skip first
1872
 *  forf_eol     [I]    - The 'end of line' (comment) character
1873
 *  forf_delims  [I]    - The delimiters to use when breaking the string apart
1874
 *  forf_tokens  [I]    - The tokens to use when breaking the string apart
1875
 */
1876
static void WCMD_parse_line(CMD_LIST    *cmdStart,
1877
                            const WCHAR *firstCmd,
1878
                            CMD_LIST   **cmdEnd,
1879
                            const WCHAR  variable,
1880 1881 1882
                            WCHAR       *buffer,
                            BOOL        *doExecuted,
                            int         *forf_skip,
1883
                            WCHAR        forf_eol,
1884 1885
                            WCHAR       *forf_delims,
                            WCHAR       *forf_tokens) {
1886

1887
  WCHAR *parm;
1888
  FOR_CONTEXT oldcontext;
1889 1890 1891 1892 1893 1894
  int varidx, varoffset;
  int nexttoken, lasttoken = -1;
  BOOL starfound = FALSE;
  BOOL thisduplicate = FALSE;
  BOOL anyduplicates = FALSE;
  int  totalfound;
1895 1896 1897 1898 1899 1900 1901

  /* Skip lines if requested */
  if (*forf_skip) {
    (*forf_skip)--;
    return;
  }

1902 1903 1904
  /* Save away any existing for variable context (e.g. nested for loops) */
  oldcontext = forloopcontext;

1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
  /* Extract the parameters based on the tokens= value (There will always
     be some value, as if it is not supplied, it defaults to tokens=1).
     Rough logic:
     Count how many tokens are named in the line, identify the lowest
     Empty (set to null terminated string) that number of named variables
     While lasttoken != nextlowest
       %letter = parameter number 'nextlowest'
       letter++ (if >26 or >52 abort)
       Go through token= string finding next lowest number
     If token ends in * set %letter = raw position of token(nextnumber+1)
   */
  lasttoken = -1;
  nexttoken = WCMD_for_nexttoken(lasttoken, forf_tokens, &totalfound,
                                 NULL, &thisduplicate);
1919 1920
  varidx = FOR_VAR_IDX(variable);

1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
  /* Empty out variables */
  for (varoffset=0;
       varidx >= 0 && varoffset<totalfound && ((varidx+varoffset)%26);
       varoffset++) {
    forloopcontext.variable[varidx + varoffset] = (WCHAR *)nullW;
    /* Stop if we walk beyond z or Z */
    if (((varidx+varoffset) % 26) == 0) break;
  }

  /* Loop extracting the tokens */
  varoffset = 0;
  WINE_TRACE("Parsing buffer into tokens: '%s'\n", wine_dbgstr_w(buffer));
  while (varidx >= 0 && (nexttoken > lasttoken)) {
    anyduplicates |= thisduplicate;

    /* Extract the token number requested and set into the next variable context */
    parm = WCMD_parameter_with_delims(buffer, (nexttoken-1), NULL, FALSE, FALSE, forf_delims);
    WINE_TRACE("Parsed token %d(%d) as parameter %s\n", nexttoken,
               varidx + varoffset, wine_dbgstr_w(parm));
    if (varidx >=0) {
      forloopcontext.variable[varidx + varoffset] = heap_strdupW(parm);
      varoffset++;
      if (((varidx + varoffset) %26) == 0) break;
    }

    /* Find the next token */
    lasttoken = nexttoken;
    nexttoken = WCMD_for_nexttoken(lasttoken, forf_tokens, NULL,
                                   &starfound, &thisduplicate);
  }

  /* If all the rest of the tokens were requested, and there is still space in
     the variable range, write them now                                        */
  if (!anyduplicates && starfound && varidx >= 0 && ((varidx+varoffset) % 26)) {
    nexttoken++;
    WCMD_parameter_with_delims(buffer, (nexttoken-1), &parm, FALSE, FALSE, forf_delims);
    WINE_TRACE("Parsed allremaining tokens (%d) as parameter %s\n",
               varidx + varoffset, wine_dbgstr_w(parm));
    forloopcontext.variable[varidx + varoffset] = heap_strdupW(parm);
  }

  /* Execute the body of the foor loop with these values */
  if (forloopcontext.variable[varidx] && forloopcontext.variable[varidx][0] != forf_eol) {
1964 1965
    CMD_LIST *thisCmdStart = cmdStart;
    *doExecuted = TRUE;
1966
    WCMD_part_execute(&thisCmdStart, firstCmd, FALSE, TRUE);
1967 1968 1969
    *cmdEnd = thisCmdStart;
  }

1970 1971 1972 1973 1974 1975 1976 1977 1978 1979
  /* Free the duplicated strings, and restore the context */
  if (varidx >=0) {
    int i;
    for (i=varidx; i<MAX_FOR_VARIABLES; i++) {
      if ((forloopcontext.variable[i] != oldcontext.variable[i]) &&
          (forloopcontext.variable[i] != nullW)) {
        heap_free(forloopcontext.variable[i]);
      }
    }
  }
1980 1981 1982

  /* Restore the original for variable contextx */
  forloopcontext = oldcontext;
1983 1984
}

1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
/**************************************************************************
 * WCMD_forf_getinputhandle
 *
 * Return a file handle which can be used for reading the input lines,
 * either to a specific file (which may be quote delimited as we have to
 * read the parameters in raw mode) or to a command which we need to
 * execute. The command being executed runs in its own shell and stores
 * its data in a temporary file.
 *
 * Parameters:
 *  usebackq     [I]    - Indicates whether usebackq is in effect or not
 *  itemStr      [I]    - The item to be handled, either a filename or
 *                           whole command string to execute
 *  iscmd        [I]    - Identifies whether this is a command or not
 *
 * Returns a file handle which can be used to read the input lines from.
 */
2002
static HANDLE WCMD_forf_getinputhandle(BOOL usebackq, WCHAR *itemstr, BOOL iscmd) {
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
  WCHAR  temp_str[MAX_PATH];
  WCHAR  temp_file[MAX_PATH];
  WCHAR  temp_cmd[MAXSTRING];
  HANDLE hinput = INVALID_HANDLE_VALUE;
  static const WCHAR redirOutW[]  = {'>','%','s','\0'};
  static const WCHAR cmdW[]       = {'C','M','D','\0'};
  static const WCHAR cmdslashcW[] = {'C','M','D','.','E','X','E',' ',
                                     '/','C',' ','"','%','s','"','\0'};

  /* Remove leading and trailing character */
  if ((iscmd && (itemstr[0] == '`' && usebackq)) ||
      (iscmd && (itemstr[0] == '\'' && !usebackq)) ||
      (!iscmd && (itemstr[0] == '"' && usebackq)))
  {
    itemstr[strlenW(itemstr)-1] = 0x00;
    itemstr++;
  }

  if (iscmd) {
    /* Get temp filename */
    GetTempPathW(sizeof(temp_str)/sizeof(WCHAR), temp_str);
    GetTempFileNameW(temp_str, cmdW, 0, temp_file);

    /* Redirect output to the temporary file */
    wsprintfW(temp_str, redirOutW, temp_file);
    wsprintfW(temp_cmd, cmdslashcW, itemstr);
    WINE_TRACE("Issuing '%s' with redirs '%s'\n",
               wine_dbgstr_w(temp_cmd), wine_dbgstr_w(temp_str));
2031
    WCMD_execute (temp_cmd, temp_str, NULL, FALSE);
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045

    /* Open the file, read line by line and process */
    hinput = CreateFileW(temp_file, GENERIC_READ, FILE_SHARE_READ,
                        NULL, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, NULL);

  } else {
    /* Open the file, read line by line and process */
    WINE_TRACE("Reading input to parse from '%s'\n", wine_dbgstr_w(itemstr));
    hinput = CreateFileW(itemstr, GENERIC_READ, FILE_SHARE_READ,
                        NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  }
  return hinput;
}

2046
/**************************************************************************
2047 2048 2049
 * WCMD_for
 *
 * Batch file loop processing.
2050 2051 2052 2053 2054 2055
 *
 * On entry: cmdList       contains the syntax up to the set
 *           next cmdList and all in that bracket contain the set data
 *           next cmdlist  contains the DO cmd
 *           following that is either brackets or && entries (as per if)
 *
2056 2057
 */

2058
void WCMD_for (WCHAR *p, CMD_LIST **cmdList) {
2059

2060
  WIN32_FIND_DATAW fd;
2061 2062
  HANDLE hff;
  int i;
2063 2064
  static const WCHAR inW[] = {'i','n'};
  static const WCHAR doW[] = {'d','o'};
2065 2066
  CMD_LIST *setStart, *thisSet, *cmdStart, *cmdEnd;
  WCHAR variable[4];
2067 2068
  int   varidx = -1;
  WCHAR *oldvariablevalue;
2069 2070
  WCHAR *firstCmd;
  int thisDepth;
2071 2072
  WCHAR optionsRoot[MAX_PATH];
  DIRECTORY_STACK *dirsToWalk = NULL;
2073 2074 2075
  BOOL   expandDirs  = FALSE;
  BOOL   useNumbers  = FALSE;
  BOOL   doFileset   = FALSE;
2076
  BOOL   doRecurse   = FALSE;
2077
  BOOL   doExecuted  = FALSE;  /* Has the 'do' part been executed */
2078 2079 2080
  LONG   numbers[3] = {0,0,0}; /* Defaults to 0 in native */
  int    itemNum;
  CMD_LIST *thisCmdStart;
2081
  int    parameterNo = 0;
2082 2083 2084 2085
  WCHAR  forf_eol = 0;
  int    forf_skip = 0;
  WCHAR  forf_delims[256];
  WCHAR  forf_tokens[MAXSTRING];
2086
  BOOL   forf_usebackq = FALSE;
2087 2088

  /* Handle optional qualifiers (multiple are allowed) */
2089
  WCHAR *thisArg = WCMD_parameter(p, parameterNo++, NULL, FALSE, FALSE);
2090 2091

  optionsRoot[0] = 0;
2092 2093 2094 2095 2096 2097
  while (thisArg && *thisArg == '/') {
      WINE_TRACE("Processing qualifier at %s\n", wine_dbgstr_w(thisArg));
      thisArg++;
      switch (toupperW(*thisArg)) {
      case 'D': expandDirs = TRUE; break;
      case 'L': useNumbers = TRUE; break;
2098 2099 2100 2101 2102 2103

      /* Recursive is special case - /R can have an optional path following it                */
      /* filenamesets are another special case - /F can have an optional options following it */
      case 'R':
      case 'F':
          {
2104 2105 2106 2107
              /* When recursing directories, use current directory as the starting point unless
                 subsequently overridden */
              doRecurse = (toupperW(*thisArg) == 'R');
              if (doRecurse) GetCurrentDirectoryW(sizeof(optionsRoot)/sizeof(WCHAR), optionsRoot);
2108

2109
              doFileset = (toupperW(*thisArg) == 'F');
2110

2111 2112
              /* Retrieve next parameter to see if is root/options (raw form required
                 with for /f, or unquoted in for /r)                                  */
2113
              thisArg = WCMD_parameter(p, parameterNo, NULL, doFileset, FALSE);
2114 2115 2116

              /* Next parm is either qualifier, path/options or variable -
                 only care about it if it is the path/options              */
2117 2118
              if (thisArg && *thisArg != '/' && *thisArg != '%') {
                  parameterNo++;
2119
                  strcpyW(optionsRoot, thisArg);
2120 2121 2122 2123
              }
              break;
          }
      default:
2124
          WINE_FIXME("for qualifier '%c' unhandled\n", *thisArg);
2125 2126
      }

2127
      /* Step to next token */
2128
      thisArg = WCMD_parameter(p, parameterNo++, NULL, FALSE, FALSE);
2129 2130 2131
  }

  /* Ensure line continues with variable */
2132
  if (!*thisArg || *thisArg != '%') {
2133
      WCMD_output_stderr (WCMD_LoadMessage(WCMD_SYNTAXERR));
2134 2135 2136
      return;
  }

2137 2138 2139 2140 2141 2142 2143 2144 2145
  /* With for /f parse the options if provided */
  if (doFileset) {
    if (!WCMD_parse_forf_options(optionsRoot, &forf_eol, &forf_skip,
                                 forf_delims, forf_tokens, &forf_usebackq))
    {
      WCMD_output_stderr (WCMD_LoadMessage(WCMD_SYNTAXERR));
      return;
    }

2146
  /* Set up the list of directories to recurse if we are going to */
2147
  } else if (doRecurse) {
2148
       /* Allocate memory, add to list */
2149
       dirsToWalk = heap_alloc(sizeof(DIRECTORY_STACK));
2150
       dirsToWalk->next = NULL;
2151
       dirsToWalk->dirName = heap_strdupW(optionsRoot);
2152 2153 2154
       WINE_TRACE("Starting with root directory %s\n", wine_dbgstr_w(dirsToWalk->dirName));
  }

2155
  /* Variable should follow */
2156
  strcpyW(variable, thisArg);
2157
  WINE_TRACE("Variable identified as %s\n", wine_dbgstr_w(variable));
2158
  varidx = FOR_VAR_IDX(variable[1]);
2159 2160

  /* Ensure line continues with IN */
2161
  thisArg = WCMD_parameter(p, parameterNo++, NULL, FALSE, FALSE);
2162 2163 2164 2165
  if (!thisArg
       || !(CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
                           thisArg, sizeof(inW)/sizeof(inW[0]), inW,
                           sizeof(inW)/sizeof(inW[0])) == CSTR_EQUAL)) {
2166
      WCMD_output_stderr (WCMD_LoadMessage(WCMD_SYNTAXERR));
2167
      return;
2168
  }
2169

2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
  /* Save away where the set of data starts and the variable */
  thisDepth = (*cmdList)->bracketDepth;
  *cmdList = (*cmdList)->nextcommand;
  setStart = (*cmdList);

  /* Skip until the close bracket */
  WINE_TRACE("Searching %p as the set\n", *cmdList);
  while (*cmdList &&
         (*cmdList)->command != NULL &&
         (*cmdList)->bracketDepth > thisDepth) {
    WINE_TRACE("Skipping %p which is part of the set\n", *cmdList);
    *cmdList = (*cmdList)->nextcommand;
  }
2183

2184 2185 2186 2187 2188
  /* Skip the close bracket, if there is one */
  if (*cmdList) *cmdList = (*cmdList)->nextcommand;

  /* Syntax error if missing close bracket, or nothing following it
     and once we have the complete set, we expect a DO              */
2189
  WINE_TRACE("Looking for 'do ' in %p\n", *cmdList);
2190
  if ((*cmdList == NULL)
2191 2192
      || !WCMD_keyword_ws_found(doW, sizeof(doW)/sizeof(doW[0]), (*cmdList)->command)) {

2193
      WCMD_output_stderr (WCMD_LoadMessage(WCMD_SYNTAXERR));
2194 2195 2196 2197 2198
      return;
  }

  cmdEnd   = *cmdList;

2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
  /* Loop repeatedly per-directory we are potentially walking, when in for /r
     mode, or once for the rest of the time.                                  */
  do {

    /* Save away the starting position for the commands (and offset for the
       first one)                                                           */
    cmdStart = *cmdList;
    firstCmd = (*cmdList)->command + 3; /* Skip 'do ' */
    itemNum  = 0;

    /* If we are recursing directories (ie /R), add all sub directories now, then
       prefix the root when searching for the item */
2211
    if (dirsToWalk) WCMD_add_dirstowalk(dirsToWalk);
2212

2213 2214 2215 2216 2217 2218 2219 2220 2221
    thisSet = setStart;
    /* Loop through all set entries */
    while (thisSet &&
           thisSet->command != NULL &&
           thisSet->bracketDepth >= thisDepth) {

      /* Loop through all entries on the same line */
      WCHAR *item;
      WCHAR *itemStart;
2222
      WCHAR buffer[MAXSTRING];
2223 2224 2225

      WINE_TRACE("Processing for set %p\n", thisSet);
      i = 0;
2226
      while (*(item = WCMD_parameter (thisSet->command, i, &itemStart, TRUE, FALSE))) {
2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239

        /*
         * If the parameter within the set has a wildcard then search for matching files
         * otherwise do a literal substitution.
         */
        static const WCHAR wildcards[] = {'*','?','\0'};
        thisCmdStart = cmdStart;

        itemNum++;
        WINE_TRACE("Processing for item %d '%s'\n", itemNum, wine_dbgstr_w(item));

        if (!useNumbers && !doFileset) {
            WCHAR fullitem[MAX_PATH];
2240
            int prefixlen = 0;
2241 2242 2243 2244 2245 2246 2247 2248

            /* Now build the item to use / search for in the specified directory,
               as it is fully qualified in the /R case */
            if (dirsToWalk) {
              strcpyW(fullitem, dirsToWalk->dirName);
              strcatW(fullitem, slashW);
              strcatW(fullitem, item);
            } else {
2249 2250
              WCHAR *prefix = strrchrW(item, '\\');
              if (prefix) prefixlen = (prefix - item) + 1;
2251 2252
              strcpyW(fullitem, item);
            }
2253

2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
            if (strpbrkW (fullitem, wildcards)) {
              hff = FindFirstFileW(fullitem, &fd);
              if (hff != INVALID_HANDLE_VALUE) {
                do {
                  BOOL isDirectory = FALSE;

                  if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) isDirectory = TRUE;

                  /* Handle as files or dirs appropriately, but ignore . and .. */
                  if (isDirectory == expandDirs &&
                      (strcmpW(fd.cFileName, dotdotW) != 0) &&
                      (strcmpW(fd.cFileName, dotW) != 0))
                  {
                      thisCmdStart = cmdStart;
                      WINE_TRACE("Processing FOR filename %s\n", wine_dbgstr_w(fd.cFileName));

                      if (doRecurse) {
                          strcpyW(fullitem, dirsToWalk->dirName);
                          strcatW(fullitem, slashW);
                          strcatW(fullitem, fd.cFileName);
                      } else {
2275 2276 2277
                          if (prefixlen) lstrcpynW(fullitem, item, prefixlen + 1);
                          fullitem[prefixlen] = 0x00;
                          strcatW(fullitem, fd.cFileName);
2278 2279
                      }
                      doExecuted = TRUE;
2280 2281 2282 2283 2284 2285 2286 2287 2288 2289

                      /* Save away any existing for variable context (e.g. nested for loops)
                         and restore it after executing the body of this for loop           */
                      if (varidx >= 0) {
                        oldvariablevalue = forloopcontext.variable[varidx];
                        forloopcontext.variable[varidx] = fullitem;
                      }
                      WCMD_part_execute (&thisCmdStart, firstCmd, FALSE, TRUE);
                      if (varidx >= 0) forloopcontext.variable[varidx] = oldvariablevalue;

2290 2291 2292 2293 2294 2295 2296
                      cmdEnd = thisCmdStart;
                  }
                } while (FindNextFileW(hff, &fd) != 0);
                FindClose (hff);
              }
            } else {
              doExecuted = TRUE;
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306

              /* Save away any existing for variable context (e.g. nested for loops)
                 and restore it after executing the body of this for loop           */
              if (varidx >= 0) {
                oldvariablevalue = forloopcontext.variable[varidx];
                forloopcontext.variable[varidx] = fullitem;
              }
              WCMD_part_execute (&thisCmdStart, firstCmd, FALSE, TRUE);
              if (varidx >= 0) forloopcontext.variable[varidx] = oldvariablevalue;

2307 2308
              cmdEnd = thisCmdStart;
            }
2309

2310 2311 2312 2313
        } else if (useNumbers) {
            /* Convert the first 3 numbers to signed longs and save */
            if (itemNum <=3) numbers[itemNum-1] = atolW(item);
            /* else ignore them! */
2314

2315
        /* Filesets - either a list of files, or a command to run and parse the output */
2316 2317
        } else if (doFileset && ((!forf_usebackq && *itemStart != '"') ||
                                 (forf_usebackq && *itemStart != '\''))) {
2318

2319
            HANDLE input;
2320
            WCHAR *itemparm;
2321

2322 2323
            WINE_TRACE("Processing for filespec from item %d '%s'\n", itemNum,
                       wine_dbgstr_w(item));
2324

2325 2326
            /* If backquote or single quote, we need to launch that command
               and parse the results - use a temporary file                 */
2327 2328
            if ((forf_usebackq && *itemStart == '`') ||
                (!forf_usebackq && *itemStart == '\'')) {
2329

2330
              /* Use itemstart because the command is the whole set, not just the first token */
2331
              itemparm = itemStart;
2332
            } else {
2333

2334
              /* Use item because the file to process is just the first item in the set */
2335
              itemparm = item;
2336
            }
2337
            input = WCMD_forf_getinputhandle(forf_usebackq, itemparm, (itemparm==itemStart));
2338

2339 2340 2341 2342 2343 2344
            /* Process the input file */
            if (input == INVALID_HANDLE_VALUE) {
              WCMD_print_error ();
              WCMD_output_stderr(WCMD_LoadMessage(WCMD_READFAIL), item);
              errorlevel = 1;
              return; /* FOR loop aborts at first failure here */
2345

2346
            } else {
2347

2348
              /* Read line by line until end of file */
2349
              while (WCMD_fgets(buffer, sizeof(buffer)/sizeof(WCHAR), input)) {
2350
                WCMD_parse_line(cmdStart, firstCmd, &cmdEnd, variable[1], buffer, &doExecuted,
2351
                                &forf_skip, forf_eol, forf_delims, forf_tokens);
2352 2353 2354
                buffer[0] = 0;
              }
              CloseHandle (input);
2355
            }
2356

2357 2358 2359 2360 2361 2362
            /* When we have processed the item as a whole command, abort future set processing */
            if (itemparm==itemStart) {
              thisSet = NULL;
              break;
            }

2363
        /* Filesets - A string literal */
2364 2365
        } else if (doFileset && ((!forf_usebackq && *itemStart == '"') ||
                                 (forf_usebackq && *itemStart == '\''))) {
2366

2367 2368 2369 2370 2371 2372 2373 2374 2375
          /* Remove leading and trailing character, ready to parse with delims= delimiters
             Note that the last quote is removed from the set and the string terminates
             there to mimic windows                                                        */
          WCHAR *strend = strrchrW(itemStart, forf_usebackq?'\'':'"');
          if (strend) {
            *strend = 0x00;
            itemStart++;
          }

2376
          /* Copy the item away from the global buffer used by WCMD_parameter */
2377
          strcpyW(buffer, itemStart);
2378
          WCMD_parse_line(cmdStart, firstCmd, &cmdEnd, variable[1], buffer, &doExecuted,
2379
                            &forf_skip, forf_eol, forf_delims, forf_tokens);
2380 2381 2382 2383

          /* Only one string can be supplied in the whole set, abort future set processing */
          thisSet = NULL;
          break;
2384 2385 2386 2387
        }

        WINE_TRACE("Post-command, cmdEnd = %p\n", cmdEnd);
        i++;
2388
      }
2389

2390
      /* Move onto the next set line */
2391
      if (thisSet) thisSet = thisSet->nextcommand;
2392
    }
2393

2394 2395 2396 2397
    /* If /L is provided, now run the for loop */
    if (useNumbers) {
        WCHAR thisNum[20];
        static const WCHAR fmt[] = {'%','d','\0'};
2398

2399 2400 2401 2402 2403
        WINE_TRACE("FOR /L provided range from %d to %d step %d\n",
                   numbers[0], numbers[2], numbers[1]);
        for (i=numbers[0];
             (numbers[1]<0)? i>=numbers[2] : i<=numbers[2];
             i=i + numbers[1]) {
2404

2405 2406
            sprintfW(thisNum, fmt, i);
            WINE_TRACE("Processing FOR number %s\n", wine_dbgstr_w(thisNum));
2407

2408 2409
            thisCmdStart = cmdStart;
            doExecuted = TRUE;
2410 2411 2412 2413 2414 2415 2416 2417 2418

            /* Save away any existing for variable context (e.g. nested for loops)
               and restore it after executing the body of this for loop           */
            if (varidx >= 0) {
              oldvariablevalue = forloopcontext.variable[varidx];
              forloopcontext.variable[varidx] = thisNum;
            }
            WCMD_part_execute (&thisCmdStart, firstCmd, FALSE, TRUE);
            if (varidx >= 0) forloopcontext.variable[varidx] = oldvariablevalue;
2419 2420 2421
        }
        cmdEnd = thisCmdStart;
    }
2422

2423 2424 2425
    /* If we are walking directories, move on to any which remain */
    if (dirsToWalk != NULL) {
      DIRECTORY_STACK *nextDir = dirsToWalk->next;
2426 2427
      heap_free(dirsToWalk->dirName);
      heap_free(dirsToWalk);
2428 2429 2430 2431 2432 2433 2434
      dirsToWalk = nextDir;
      if (dirsToWalk) WINE_TRACE("Moving to next directorty to iterate: %s\n",
                                 wine_dbgstr_w(dirsToWalk->dirName));
      else WINE_TRACE("Finished all directories.\n");
    }

  } while (dirsToWalk != NULL);
2435

2436 2437 2438 2439 2440 2441 2442
  /* Now skip over the do part if we did not perform the for loop so far.
     We store in cmdEnd the next command after the do block, but we only
     know this if something was run. If it has not been, we need to calculate
     it.                                                                      */
  if (!doExecuted) {
    thisCmdStart = cmdStart;
    WINE_TRACE("Skipping for loop commands due to no valid iterations\n");
2443
    WCMD_part_execute(&thisCmdStart, firstCmd, FALSE, FALSE);
2444 2445 2446
    cmdEnd = thisCmdStart;
  }

2447 2448 2449 2450 2451 2452 2453 2454 2455
  /* When the loop ends, either something like a GOTO or EXIT /b has terminated
     all processing, OR it should be pointing to the end of && processing OR
     it should be pointing at the NULL end of bracket for the DO. The return
     value needs to be the NEXT command to execute, which it either is, or
     we need to step over the closing bracket                                  */
  *cmdList = cmdEnd;
  if (cmdEnd && cmdEnd->command == NULL) *cmdList = cmdEnd->nextcommand;
}

2456 2457 2458 2459 2460 2461
/**************************************************************************
 * WCMD_give_help
 *
 *	Simple on-line help. Help text is stored in the resource file.
 */

2462
void WCMD_give_help (const WCHAR *args)
2463 2464
{
  size_t i;
2465

2466 2467
  args = WCMD_skip_leading_spaces((WCHAR*) args);
  if (strlenW(args) == 0) {
2468
    WCMD_output_asis (WCMD_LoadMessage(WCMD_ALLHELP));
2469 2470
  }
  else {
2471
    /* Display help message for builtin commands */
2472
    for (i=0; i<=WCMD_EXIT; i++) {
2473
      if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
2474
	  args, -1, inbuilt[i], -1) == CSTR_EQUAL) {
2475
	WCMD_output_asis (WCMD_LoadMessage(i));
2476
	return;
2477 2478
      }
    }
2479 2480 2481
    /* Launch the command with the /? option for external commands shipped with cmd.exe */
    for (i = 0; i <= (sizeof(externals)/sizeof(externals[0])); i++) {
      if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
2482
	  args, -1, externals[i], -1) == CSTR_EQUAL) {
2483 2484
        WCHAR cmd[128];
        static const WCHAR helpW[] = {' ', '/','?','\0'};
2485
        strcpyW(cmd, args);
2486
        strcatW(cmd, helpW);
2487
        WCMD_run_program(cmd, FALSE);
2488 2489 2490
        return;
      }
    }
2491
    WCMD_output (WCMD_LoadMessage(WCMD_NOCMDHELP), args);
2492 2493 2494 2495
  }
  return;
}

2496 2497 2498 2499 2500 2501 2502 2503 2504
/****************************************************************************
 * WCMD_go_to
 *
 * Batch file jump instruction. Not the most efficient algorithm ;-)
 * Prints error message if the specified label cannot be found - the file pointer is
 * then at EOF, effectively stopping the batch file.
 * FIXME: DOS is supposed to allow labels with spaces - we don't.
 */

2505
void WCMD_goto (CMD_LIST **cmdList) {
2506

2507
  WCHAR string[MAX_PATH];
2508 2509
  WCHAR *labelend = NULL;
  const WCHAR labelEndsW[] = {'>','<','|','&',' ',':','\t','\0'};
2510

2511
  /* Do not process any more parts of a processed multipart or multilines command */
2512
  if (cmdList) *cmdList = NULL;
2513

2514
  if (context != NULL) {
2515
    WCHAR *paramStart = param1, *str;
2516
    static const WCHAR eofW[] = {':','e','o','f','\0'};
2517

2518
    if (param1[0] == 0x00) {
2519
      WCMD_output_stderr(WCMD_LoadMessage(WCMD_NOARG));
2520 2521 2522
      return;
    }

2523
    /* Handle special :EOF label */
2524
    if (lstrcmpiW (eofW, param1) == 0) {
2525 2526 2527 2528
      context -> skip_rest = TRUE;
      return;
    }

2529
    /* Support goto :label as well as goto label plus remove trailing chars */
2530
    if (*paramStart == ':') paramStart++;
2531 2532 2533
    labelend = strpbrkW(paramStart, labelEndsW);
    if (labelend) *labelend = 0x00;
    WINE_TRACE("goto label: '%s'\n", wine_dbgstr_w(paramStart));
2534

2535
    SetFilePointer (context -> h, 0, NULL, FILE_BEGIN);
2536 2537
    while (*paramStart &&
           WCMD_fgets (string, sizeof(string)/sizeof(WCHAR), context -> h)) {
2538
      str = string;
2539 2540 2541 2542 2543

      /* Ignore leading whitespace or no-echo character */
      while (*str=='@' || isspaceW (*str)) str++;

      /* If the first real character is a : then this is a label */
2544 2545 2546
      if (*str == ':') {
        str++;

2547 2548 2549 2550 2551 2552 2553 2554 2555 2556
        /* Skip spaces between : and label */
        while (isspaceW (*str)) str++;
        WINE_TRACE("str before brk %s\n", wine_dbgstr_w(str));

        /* Label ends at whitespace or redirection characters */
        labelend = strpbrkW(str, labelEndsW);
        if (labelend) *labelend = 0x00;
        WINE_TRACE("comparing found label %s\n", wine_dbgstr_w(str));

        if (lstrcmpiW (str, paramStart) == 0) return;
2557
      }
2558
    }
2559
    WCMD_output_stderr(WCMD_LoadMessage(WCMD_NOTARGET));
2560
    context -> skip_rest = TRUE;
2561 2562 2563 2564
  }
  return;
}

2565 2566 2567 2568 2569 2570
/*****************************************************************************
 * WCMD_pushd
 *
 *	Push a directory onto the stack
 */

2571
void WCMD_pushd (const WCHAR *args)
2572
{
2573 2574
    struct env_stack *curdir;
    WCHAR *thisdir;
2575
    static const WCHAR parmD[] = {'/','D','\0'};
2576

2577
    if (strchrW(args, '/') != NULL) {
2578 2579 2580 2581 2582
      SetLastError(ERROR_INVALID_PARAMETER);
      WCMD_print_error();
      return;
    }

2583 2584 2585 2586 2587
    curdir  = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
    thisdir = LocalAlloc (LMEM_FIXED, 1024 * sizeof(WCHAR));
    if( !curdir || !thisdir ) {
      LocalFree(curdir);
      LocalFree(thisdir);
2588
      WINE_ERR ("out of memory\n");
2589 2590 2591
      return;
    }

2592
    /* Change directory using CD code with /D parameter */
2593
    strcpyW(quals, parmD);
2594
    GetCurrentDirectoryW (1024, thisdir);
2595
    errorlevel = 0;
2596
    WCMD_setshow_default(args);
2597
    if (errorlevel) {
2598 2599 2600 2601 2602 2603
      LocalFree(curdir);
      LocalFree(thisdir);
      return;
    } else {
      curdir -> next    = pushd_directories;
      curdir -> strings = thisdir;
2604
      if (pushd_directories == NULL) {
2605
        curdir -> u.stackdepth = 1;
2606
      } else {
2607
        curdir -> u.stackdepth = pushd_directories -> u.stackdepth + 1;
2608
      }
2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631
      pushd_directories = curdir;
    }
}


/*****************************************************************************
 * WCMD_popd
 *
 *	Pop a directory from the stack
 */

void WCMD_popd (void) {
    struct env_stack *temp = pushd_directories;

    if (!pushd_directories)
      return;

    /* pop the old environment from the stack, and make it the current dir */
    pushd_directories = temp->next;
    SetCurrentDirectoryW(temp->strings);
    LocalFree (temp->strings);
    LocalFree (temp);
}
2632

2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
/*******************************************************************
 * evaluate_if_comparison
 *
 * Evaluates an "if" comparison operation
 *
 * PARAMS
 *  leftOperand     [I] left operand, non NULL
 *  operator        [I] "if" binary comparison operator, non NULL
 *  rightOperand    [I] right operand, non NULL
 *  caseInsensitive [I] 0 for case sensitive comparison, anything else for insensitive
 *
 * RETURNS
 *  Success:  1 if operator applied to the operands evaluates to TRUE
 *            0 if operator applied to the operands evaluates to FALSE
 *  Failure: -1 if operator is not recognized
 */
static int evaluate_if_comparison(const WCHAR *leftOperand, const WCHAR *operator,
                                  const WCHAR *rightOperand, int caseInsensitive)
{
    WCHAR *endptr_leftOp, *endptr_rightOp;
    long int leftOperand_int, rightOperand_int;
    BOOL int_operands;
    static const WCHAR lssW[]  = {'l','s','s','\0'};
2656
    static const WCHAR leqW[]  = {'l','e','q','\0'};
2657
    static const WCHAR equW[]  = {'e','q','u','\0'};
2658
    static const WCHAR neqW[]  = {'n','e','q','\0'};
2659
    static const WCHAR geqW[]  = {'g','e','q','\0'};
2660
    static const WCHAR gtrW[]  = {'g','t','r','\0'};
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680

    /* == is a special case, as it always compares strings */
    if (!lstrcmpiW(operator, eqeqW))
        return caseInsensitive ? lstrcmpiW(leftOperand, rightOperand) == 0
                               : lstrcmpW (leftOperand, rightOperand) == 0;

    /* Check if we have plain integers (in decimal, octal or hexadecimal notation) */
    leftOperand_int = strtolW(leftOperand, &endptr_leftOp, 0);
    rightOperand_int = strtolW(rightOperand, &endptr_rightOp, 0);
    int_operands = (!*endptr_leftOp) && (!*endptr_rightOp);

    /* Perform actual (integer or string) comparison */
    if (!lstrcmpiW(operator, lssW)) {
        if (int_operands)
            return leftOperand_int < rightOperand_int;
        else
            return caseInsensitive ? lstrcmpiW(leftOperand, rightOperand) < 0
                                   : lstrcmpW (leftOperand, rightOperand) < 0;
    }

2681 2682 2683 2684 2685 2686 2687 2688
    if (!lstrcmpiW(operator, leqW)) {
        if (int_operands)
            return leftOperand_int <= rightOperand_int;
        else
            return caseInsensitive ? lstrcmpiW(leftOperand, rightOperand) <= 0
                                   : lstrcmpW (leftOperand, rightOperand) <= 0;
    }

2689 2690 2691 2692 2693 2694 2695 2696
    if (!lstrcmpiW(operator, equW)) {
        if (int_operands)
            return leftOperand_int == rightOperand_int;
        else
            return caseInsensitive ? lstrcmpiW(leftOperand, rightOperand) == 0
                                   : lstrcmpW (leftOperand, rightOperand) == 0;
    }

2697 2698 2699 2700 2701 2702 2703 2704
    if (!lstrcmpiW(operator, neqW)) {
        if (int_operands)
            return leftOperand_int != rightOperand_int;
        else
            return caseInsensitive ? lstrcmpiW(leftOperand, rightOperand) != 0
                                   : lstrcmpW (leftOperand, rightOperand) != 0;
    }

2705 2706 2707 2708 2709 2710 2711 2712
    if (!lstrcmpiW(operator, geqW)) {
        if (int_operands)
            return leftOperand_int >= rightOperand_int;
        else
            return caseInsensitive ? lstrcmpiW(leftOperand, rightOperand) >= 0
                                   : lstrcmpW (leftOperand, rightOperand) >= 0;
    }

2713 2714 2715 2716 2717 2718 2719 2720
    if (!lstrcmpiW(operator, gtrW)) {
        if (int_operands)
            return leftOperand_int > rightOperand_int;
        else
            return caseInsensitive ? lstrcmpiW(leftOperand, rightOperand) > 0
                                   : lstrcmpW (leftOperand, rightOperand) > 0;
    }

2721 2722 2723
    return -1;
}

2724 2725 2726 2727
/****************************************************************************
 * WCMD_if
 *
 * Batch file conditional.
2728 2729 2730 2731 2732 2733 2734 2735
 *
 * On entry, cmdlist will point to command containing the IF, and optionally
 *   the first command to execute (if brackets not found)
 *   If &&'s were found, this may be followed by a record flagged as isAmpersand
 *   If ('s were found, execute all within that bracket
 *   Command may optionally be followed by an ELSE - need to skip instructions
 *   in the else using the same logic
 *
2736
 * FIXME: Much more syntax checking needed!
2737
 */
2738 2739
void WCMD_if (WCHAR *p, CMD_LIST **cmdList)
{
2740 2741
  int negate; /* Negate condition */
  int test;   /* Condition evaluation result */
2742
  WCHAR condition[MAX_PATH], *command;
2743 2744 2745 2746
  static const WCHAR notW[]    = {'n','o','t','\0'};
  static const WCHAR errlvlW[] = {'e','r','r','o','r','l','e','v','e','l','\0'};
  static const WCHAR existW[]  = {'e','x','i','s','t','\0'};
  static const WCHAR defdW[]   = {'d','e','f','i','n','e','d','\0'};
2747
  static const WCHAR parmI[]   = {'/','I','\0'};
2748
  int caseInsensitive = (strstrW(quals, parmI) != NULL);
2749

2750 2751
  negate = !lstrcmpiW(param1,notW);
  strcpyW(condition, (negate ? param2 : param1));
2752 2753
  WINE_TRACE("Condition: %s\n", wine_dbgstr_w(condition));

2754
  if (!lstrcmpiW (condition, errlvlW)) {
2755
    WCHAR *param = WCMD_parameter(p, 1+negate, NULL, FALSE, FALSE);
2756 2757
    WCHAR *endptr;
    long int param_int = strtolW(param, &endptr, 10);
2758
    if (*endptr) goto syntax_err;
2759
    test = ((long int)errorlevel >= param_int);
2760
    WCMD_parameter(p, 2+negate, &command, FALSE, FALSE);
2761
  }
2762
  else if (!lstrcmpiW (condition, existW)) {
2763
    test = (GetFileAttributesW(WCMD_parameter(p, 1+negate, NULL, FALSE, FALSE))
2764
             != INVALID_FILE_ATTRIBUTES);
2765
    WCMD_parameter(p, 2+negate, &command, FALSE, FALSE);
2766
  }
2767
  else if (!lstrcmpiW (condition, defdW)) {
2768
    test = (GetEnvironmentVariableW(WCMD_parameter(p, 1+negate, NULL, FALSE, FALSE),
2769
                                    NULL, 0) > 0);
2770
    WCMD_parameter(p, 2+negate, &command, FALSE, FALSE);
2771
  }
2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
  else { /* comparison operation */
    WCHAR leftOperand[MAXSTRING], rightOperand[MAXSTRING], operator[MAXSTRING];
    WCHAR *paramStart;

    strcpyW(leftOperand, WCMD_parameter(p, negate+caseInsensitive, &paramStart, TRUE, FALSE));
    if (!*leftOperand)
      goto syntax_err;

    /* Note: '==' can't be returned by WCMD_parameter since '=' is a separator */
    p = paramStart + strlenW(leftOperand);
    while (*p == ' ' || *p == '\t')
      p++;

2785 2786 2787 2788 2789 2790
    if (!strncmpW(p, eqeqW, strlenW(eqeqW)))
      strcpyW(operator, eqeqW);
    else {
      strcpyW(operator, WCMD_parameter(p, 0, &paramStart, FALSE, FALSE));
      if (!*operator) goto syntax_err;
    }
2791 2792 2793 2794 2795 2796
    p += strlenW(operator);

    strcpyW(rightOperand, WCMD_parameter(p, 0, &paramStart, TRUE, FALSE));
    if (!*rightOperand)
      goto syntax_err;

2797 2798 2799
    test = evaluate_if_comparison(leftOperand, operator, rightOperand, caseInsensitive);
    if (test == -1)
      goto syntax_err;
2800 2801 2802

    p = paramStart + strlenW(rightOperand);
    WCMD_parameter(p, 0, &command, FALSE, FALSE);
2803
  }
2804 2805 2806

  /* Process rest of IF statement which is on the same line
     Note: This may process all or some of the cmdList (eg a GOTO) */
2807
  WCMD_part_execute(cmdList, command, TRUE, (test != negate));
2808 2809 2810 2811
  return;

syntax_err:
  WCMD_output_stderr(WCMD_LoadMessage(WCMD_SYNTAXERR));
2812 2813 2814 2815 2816 2817 2818 2819
}

/****************************************************************************
 * WCMD_move
 *
 * Move a file, directory tree or wildcarded set of files.
 */

2820 2821
void WCMD_move (void)
{
2822
  BOOL             status;
2823
  WIN32_FIND_DATAW fd;
2824
  HANDLE          hff;
2825 2826 2827 2828 2829 2830
  WCHAR            input[MAX_PATH];
  WCHAR            output[MAX_PATH];
  WCHAR            drive[10];
  WCHAR            dir[MAX_PATH];
  WCHAR            fname[MAX_PATH];
  WCHAR            ext[MAX_PATH];
2831

2832
  if (param1[0] == 0x00) {
2833
    WCMD_output_stderr(WCMD_LoadMessage(WCMD_NOARG));
2834 2835 2836
    return;
  }

2837 2838
  /* If no destination supplied, assume current directory */
  if (param2[0] == 0x00) {
2839
      strcpyW(param2, dotW);
2840 2841 2842
  }

  /* If 2nd parm is directory, then use original filename */
2843
  /* Convert partial path to full path */
2844 2845
  GetFullPathNameW(param1, sizeof(input)/sizeof(WCHAR), input, NULL);
  GetFullPathNameW(param2, sizeof(output)/sizeof(WCHAR), output, NULL);
2846 2847
  WINE_TRACE("Move from '%s'('%s') to '%s'\n", wine_dbgstr_w(input),
             wine_dbgstr_w(param1), wine_dbgstr_w(output));
2848 2849 2850 2851

  /* Split into components */
  WCMD_splitpath(input, drive, dir, fname, ext);

2852
  hff = FindFirstFileW(input, &fd);
2853 2854 2855 2856
  if (hff == INVALID_HANDLE_VALUE)
    return;

  do {
2857 2858
    WCHAR  dest[MAX_PATH];
    WCHAR  src[MAX_PATH];
2859
    DWORD attribs;
2860
    BOOL ok = TRUE;
2861

2862
    WINE_TRACE("Processing file '%s'\n", wine_dbgstr_w(fd.cFileName));
2863 2864

    /* Build src & dest name */
2865 2866
    strcpyW(src, drive);
    strcatW(src, dir);
2867 2868

    /* See if dest is an existing directory */
2869
    attribs = GetFileAttributesW(output);
2870 2871
    if (attribs != INVALID_FILE_ATTRIBUTES &&
       (attribs & FILE_ATTRIBUTE_DIRECTORY)) {
2872 2873 2874
      strcpyW(dest, output);
      strcatW(dest, slashW);
      strcatW(dest, fd.cFileName);
2875
    } else {
2876
      strcpyW(dest, output);
2877 2878
    }

2879
    strcatW(src, fd.cFileName);
2880

2881 2882
    WINE_TRACE("Source '%s'\n", wine_dbgstr_w(src));
    WINE_TRACE("Dest   '%s'\n", wine_dbgstr_w(dest));
2883

2884 2885 2886 2887
    /* If destination exists, prompt unless /Y supplied */
    if (GetFileAttributesW(dest) != INVALID_FILE_ATTRIBUTES) {
      BOOL force = FALSE;
      WCHAR copycmd[MAXSTRING];
2888
      DWORD len;
2889

2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900
      /* /-Y has the highest priority, then /Y and finally the COPYCMD env. variable */
      if (strstrW (quals, parmNoY))
        force = FALSE;
      else if (strstrW (quals, parmY))
        force = TRUE;
      else {
        static const WCHAR copyCmdW[] = {'C','O','P','Y','C','M','D','\0'};
        len = GetEnvironmentVariableW(copyCmdW, copycmd, sizeof(copycmd)/sizeof(WCHAR));
        force = (len && len < (sizeof(copycmd)/sizeof(WCHAR))
                     && ! lstrcmpiW (copycmd, parmY));
      }
2901

2902 2903
      /* Prompt if overwriting */
      if (!force) {
2904
        WCHAR* question;
2905

2906
        /* Ask for confirmation */
2907
        question = WCMD_format_string(WCMD_LoadMessage(WCMD_OVERWRITE), dest);
2908
        ok = WCMD_ask_confirm(question, FALSE, NULL);
2909
        LocalFree(question);
2910 2911 2912 2913 2914 2915 2916

        /* So delete the destination prior to the move */
        if (ok) {
          if (!DeleteFileW(dest)) {
            WCMD_print_error ();
            errorlevel = 1;
            ok = FALSE;
2917 2918 2919
          }
        }
      }
2920
    }
2921

2922 2923 2924
    if (ok) {
      status = MoveFileW(src, dest);
    } else {
2925
      status = TRUE;
2926 2927 2928 2929 2930 2931
    }

    if (!status) {
      WCMD_print_error ();
      errorlevel = 1;
    }
2932
  } while (FindNextFileW(hff, &fd) != 0);
2933

2934
  FindClose(hff);
2935 2936 2937 2938 2939
}

/****************************************************************************
 * WCMD_pause
 *
2940
 * Suspend execution of a batch script until a key is typed
2941 2942
 */

2943 2944 2945 2946
void WCMD_pause (void)
{
  DWORD oldmode;
  BOOL have_console;
2947
  DWORD count;
2948 2949 2950 2951 2952 2953
  WCHAR key;
  HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);

  have_console = GetConsoleMode(hIn, &oldmode);
  if (have_console)
      SetConsoleMode(hIn, 0);
2954

2955
  WCMD_output_asis(anykey);
2956 2957 2958
  WCMD_ReadFile(hIn, &key, 1, &count);
  if (have_console)
    SetConsoleMode(hIn, oldmode);
2959 2960 2961 2962 2963 2964 2965 2966
}

/****************************************************************************
 * WCMD_remove_dir
 *
 * Delete a directory.
 */

2967
void WCMD_remove_dir (WCHAR *args) {
2968

2969 2970
  int   argno         = 0;
  int   argsProcessed = 0;
2971
  WCHAR *argN          = args;
2972 2973
  static const WCHAR parmS[] = {'/','S','\0'};
  static const WCHAR parmQ[] = {'/','Q','\0'};
2974

2975 2976
  /* Loop through all args */
  while (argN) {
2977
    WCHAR *thisArg = WCMD_parameter (args, argno++, &argN, FALSE, FALSE);
2978
    if (argN && argN[0] != '/') {
2979 2980
      WINE_TRACE("rd: Processing arg %s (quals:%s)\n", wine_dbgstr_w(thisArg),
                 wine_dbgstr_w(quals));
2981
      argsProcessed++;
2982

2983 2984
      /* If subdirectory search not supplied, just try to remove
         and report error if it fails (eg if it contains a file) */
2985
      if (strstrW (quals, parmS) == NULL) {
2986
        if (!RemoveDirectoryW(thisArg)) WCMD_print_error ();
2987

2988 2989
      /* Otherwise use ShFileOp to recursively remove a directory */
      } else {
2990

2991
        SHFILEOPSTRUCTW lpDir;
2992

2993
        /* Ask first */
2994
        if (strstrW (quals, parmQ) == NULL) {
2995
          BOOL  ok;
2996 2997
          WCHAR  question[MAXSTRING];
          static const WCHAR fmt[] = {'%','s',' ','\0'};
2998

2999
          /* Ask for confirmation */
3000
          wsprintfW(question, fmt, thisArg);
3001
          ok = WCMD_ask_confirm(question, TRUE, NULL);
3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012

          /* Abort if answer is 'N' */
          if (!ok) return;
        }

        /* Do the delete */
        lpDir.hwnd   = NULL;
        lpDir.pTo    = NULL;
        lpDir.pFrom  = thisArg;
        lpDir.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI;
        lpDir.wFunc  = FO_DELETE;
3013 3014 3015 3016

        /* SHFileOperationW needs file list with a double null termination */
        thisArg[lstrlenW(thisArg) + 1] = 0x00;

3017
        if (SHFileOperationW(&lpDir)) WCMD_print_error ();
3018
      }
3019
    }
3020
  }
3021

3022 3023
  /* Handle no valid args */
  if (argsProcessed == 0) {
3024
    WCMD_output_stderr(WCMD_LoadMessage(WCMD_NOARG));
3025
    return;
3026
  }
3027

3028 3029 3030 3031 3032 3033 3034 3035
}

/****************************************************************************
 * WCMD_rename
 *
 * Rename a file.
 */

3036 3037
void WCMD_rename (void)
{
3038
  BOOL             status;
3039
  HANDLE          hff;
3040
  WIN32_FIND_DATAW fd;
3041 3042 3043 3044 3045 3046
  WCHAR            input[MAX_PATH];
  WCHAR           *dotDst = NULL;
  WCHAR            drive[10];
  WCHAR            dir[MAX_PATH];
  WCHAR            fname[MAX_PATH];
  WCHAR            ext[MAX_PATH];
3047

3048 3049 3050
  errorlevel = 0;

  /* Must be at least two args */
3051
  if (param1[0] == 0x00 || param2[0] == 0x00) {
3052
    WCMD_output_stderr(WCMD_LoadMessage(WCMD_NOARG));
3053
    errorlevel = 1;
3054 3055
    return;
  }
3056 3057

  /* Destination cannot contain a drive letter or directory separator */
3058
  if ((strchrW(param2,':') != NULL) || (strchrW(param2,'\\') != NULL)) {
3059 3060 3061 3062 3063 3064 3065
      SetLastError(ERROR_INVALID_PARAMETER);
      WCMD_print_error();
      errorlevel = 1;
      return;
  }

  /* Convert partial path to full path */
3066
  GetFullPathNameW(param1, sizeof(input)/sizeof(WCHAR), input, NULL);
3067 3068 3069
  WINE_TRACE("Rename from '%s'('%s') to '%s'\n", wine_dbgstr_w(input),
             wine_dbgstr_w(param1), wine_dbgstr_w(param2));
  dotDst = strchrW(param2, '.');
3070 3071 3072 3073

  /* Split into components */
  WCMD_splitpath(input, drive, dir, fname, ext);

3074
  hff = FindFirstFileW(input, &fd);
3075 3076 3077 3078
  if (hff == INVALID_HANDLE_VALUE)
    return;

 do {
3079 3080 3081
    WCHAR  dest[MAX_PATH];
    WCHAR  src[MAX_PATH];
    WCHAR *dotSrc = NULL;
3082 3083
    int   dirLen;

3084
    WINE_TRACE("Processing file '%s'\n", wine_dbgstr_w(fd.cFileName));
3085 3086 3087 3088 3089

    /* FIXME: If dest name or extension is *, replace with filename/ext
       part otherwise use supplied name. This supports:
          ren *.fred *.jim
          ren jim.* fred.* etc
3090
       However, windows has a more complex algorithm supporting eg
3091
          ?'s and *'s mid name                                         */
3092
    dotSrc = strchrW(fd.cFileName, '.');
3093 3094

    /* Build src & dest name */
3095 3096 3097 3098 3099
    strcpyW(src, drive);
    strcatW(src, dir);
    strcpyW(dest, src);
    dirLen = strlenW(src);
    strcatW(src, fd.cFileName);
3100 3101 3102

    /* Build name */
    if (param2[0] == '*') {
3103
      strcatW(dest, fd.cFileName);
3104 3105
      if (dotSrc) dest[dirLen + (dotSrc - fd.cFileName)] = 0x00;
    } else {
3106
      strcatW(dest, param2);
3107 3108 3109 3110 3111
      if (dotDst) dest[dirLen + (dotDst - param2)] = 0x00;
    }

    /* Build Extension */
    if (dotDst && (*(dotDst+1)=='*')) {
3112
      if (dotSrc) strcatW(dest, dotSrc);
3113
    } else if (dotDst) {
3114
      strcatW(dest, dotDst);
3115 3116
    }

3117 3118
    WINE_TRACE("Source '%s'\n", wine_dbgstr_w(src));
    WINE_TRACE("Dest   '%s'\n", wine_dbgstr_w(dest));
3119

3120
    status = MoveFileW(src, dest);
3121 3122 3123 3124 3125

    if (!status) {
      WCMD_print_error ();
      errorlevel = 1;
    }
3126
  } while (FindNextFileW(hff, &fd) != 0);
3127

3128
  FindClose(hff);
3129 3130
}

3131 3132 3133 3134 3135
/*****************************************************************************
 * WCMD_dupenv
 *
 * Make a copy of the environment.
 */
3136
static WCHAR *WCMD_dupenv( const WCHAR *env )
3137 3138 3139 3140 3141 3142 3143 3144 3145
{
  WCHAR *env_copy;
  int len;

  if( !env )
    return NULL;

  len = 0;
  while ( env[len] )
3146
    len += (strlenW(&env[len]) + 1);
3147 3148 3149 3150

  env_copy = LocalAlloc (LMEM_FIXED, (len+1) * sizeof (WCHAR) );
  if (!env_copy)
  {
3151
    WINE_ERR("out of memory\n");
3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
    return env_copy;
  }
  memcpy (env_copy, env, len*sizeof (WCHAR));
  env_copy[len] = 0;

  return env_copy;
}

/*****************************************************************************
 * WCMD_setlocal
 *
 *  setlocal pushes the environment onto a stack
 *  Save the environment as unicode so we don't screw anything up.
 */
3166
void WCMD_setlocal (const WCHAR *s) {
3167 3168
  WCHAR *env;
  struct env_stack *env_copy;
3169
  WCHAR cwd[MAX_PATH];
3170 3171 3172 3173 3174 3175 3176
  BOOL newdelay;
  static const WCHAR ondelayW[]     = {'E','N','A','B','L','E','D','E','L','A',
                                       'Y','E','D','E','X','P','A','N','S','I',
                                       'O','N','\0'};
  static const WCHAR offdelayW[]    = {'D','I','S','A','B','L','E','D','E','L',
                                       'A','Y','E','D','E','X','P','A','N','S',
                                       'I','O','N','\0'};
3177

3178 3179 3180
  /* setlocal does nothing outside of batch programs */
  if (!context) return;

3181 3182
  /* DISABLEEXTENSIONS ignored */

3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193
  /* ENABLEDELAYEDEXPANSION / DISABLEDELAYEDEXPANSION could be parm1 or parm2
     (if both ENABLEEXTENSIONS and ENABLEDELAYEDEXPANSION supplied for example) */
  if (!strcmpiW(param1, ondelayW) || !strcmpiW(param2, ondelayW)) {
    newdelay = TRUE;
  } else if (!strcmpiW(param1, offdelayW) || !strcmpiW(param2, offdelayW)) {
    newdelay = FALSE;
  } else {
    newdelay = delayedsubst;
  }
  WINE_TRACE("Setting delayed expansion to %d\n", newdelay);

3194 3195 3196
  env_copy = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
  if( !env_copy )
  {
3197
    WINE_ERR ("out of memory\n");
3198 3199 3200 3201 3202 3203 3204
    return;
  }

  env = GetEnvironmentStringsW ();
  env_copy->strings = WCMD_dupenv (env);
  if (env_copy->strings)
  {
3205
    env_copy->batchhandle = context->h;
3206
    env_copy->next = saved_environment;
3207 3208
    env_copy->delayedsubst = delayedsubst;
    delayedsubst = newdelay;
3209
    saved_environment = env_copy;
3210 3211

    /* Save the current drive letter */
3212
    GetCurrentDirectoryW(MAX_PATH, cwd);
3213
    env_copy->u.cwd = cwd[0];
3214 3215 3216 3217 3218
  }
  else
    LocalFree (env_copy);

  FreeEnvironmentStringsW (env);
3219

3220 3221 3222 3223 3224 3225
}

/*****************************************************************************
 * WCMD_endlocal
 *
 *  endlocal pops the environment off a stack
3226
 *  Note: When searching for '=', search from WCHAR position 1, to handle
3227
 *        special internal environment variables =C:, =D: etc
3228 3229 3230 3231 3232 3233
 */
void WCMD_endlocal (void) {
  WCHAR *env, *old, *p;
  struct env_stack *temp;
  int len, n;

3234 3235 3236 3237 3238 3239
  /* setlocal does nothing outside of batch programs */
  if (!context) return;

  /* setlocal needs a saved environment from within the same context (batch
     program) as it was saved in                                            */
  if (!saved_environment || saved_environment->batchhandle != context->h)
3240 3241 3242 3243 3244 3245 3246 3247
    return;

  /* pop the old environment from the stack */
  temp = saved_environment;
  saved_environment = temp->next;

  /* delete the current environment, totally */
  env = GetEnvironmentStringsW ();
3248
  old = WCMD_dupenv (env);
3249 3250
  len = 0;
  while (old[len]) {
3251 3252
    n = strlenW(&old[len]) + 1;
    p = strchrW(&old[len] + 1, '=');
3253 3254 3255 3256 3257 3258 3259 3260 3261
    if (p)
    {
      *p++ = 0;
      SetEnvironmentVariableW (&old[len], NULL);
    }
    len += n;
  }
  LocalFree (old);
  FreeEnvironmentStringsW (env);
3262

3263 3264 3265
  /* restore old environment */
  env = temp->strings;
  len = 0;
3266 3267
  delayedsubst = temp->delayedsubst;
  WINE_TRACE("Delayed expansion now %d\n", delayedsubst);
3268
  while (env[len]) {
3269 3270
    n = strlenW(&env[len]) + 1;
    p = strchrW(&env[len] + 1, '=');
3271 3272 3273 3274 3275 3276 3277
    if (p)
    {
      *p++ = 0;
      SetEnvironmentVariableW (&env[len], p);
    }
    len += n;
  }
3278 3279

  /* Restore current drive letter */
3280
  if (IsCharAlphaW(temp->u.cwd)) {
3281 3282 3283 3284
    WCHAR envvar[4];
    WCHAR cwd[MAX_PATH];
    static const WCHAR fmt[] = {'=','%','c',':','\0'};

3285 3286
    wsprintfW(envvar, fmt, temp->u.cwd);
    if (GetEnvironmentVariableW(envvar, cwd, MAX_PATH)) {
3287
      WINE_TRACE("Resetting cwd to %s\n", wine_dbgstr_w(cwd));
3288
      SetCurrentDirectoryW(cwd);
3289 3290 3291
    }
  }

3292 3293 3294 3295
  LocalFree (env);
  LocalFree (temp);
}

3296 3297 3298 3299 3300 3301
/*****************************************************************************
 * WCMD_setshow_default
 *
 *	Set/Show the current default directory
 */

3302
void WCMD_setshow_default (const WCHAR *args) {
3303

3304
  BOOL status;
3305 3306 3307
  WCHAR string[1024];
  WCHAR cwd[1024];
  WCHAR *pos;
3308
  WIN32_FIND_DATAW fd;
3309
  HANDLE hff;
3310
  static const WCHAR parmD[] = {'/','D','\0'};
3311

3312
  WINE_TRACE("Request change to directory '%s'\n", wine_dbgstr_w(args));
3313 3314

  /* Skip /D and trailing whitespace if on the front of the command line */
3315 3316
  if (strlenW(args) >= 2 &&
      CompareStringW(LOCALE_USER_DEFAULT,
3317
                     NORM_IGNORECASE | SORT_STRINGSORT,
3318 3319 3320 3321
                     args, 2, parmD, -1) == CSTR_EQUAL) {
    args += 2;
    while (*args && (*args==' ' || *args=='\t'))
      args++;
3322 3323
  }

3324
  GetCurrentDirectoryW(sizeof(cwd)/sizeof(WCHAR), cwd);
3325
  if (strlenW(args) == 0) {
3326
    strcatW (cwd, newlineW);
3327
    WCMD_output_asis (cwd);
3328 3329
  }
  else {
3330 3331 3332
    /* Remove any double quotes, which may be in the
       middle, eg. cd "C:\Program Files"\Microsoft is ok */
    pos = string;
3333 3334 3335
    while (*args) {
      if (*args != '"') *pos++ = *args;
      args++;
3336
    }
3337
    while (pos > string && (*(pos-1) == ' ' || *(pos-1) == '\t'))
3338
      pos--;
3339 3340
    *pos = 0x00;

3341
    /* Search for appropriate directory */
3342
    WINE_TRACE("Looking for directory '%s'\n", wine_dbgstr_w(string));
3343
    hff = FindFirstFileW(string, &fd);
3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363
    if (hff != INVALID_HANDLE_VALUE) {
      do {
        if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
          WCHAR fpath[MAX_PATH];
          WCHAR drive[10];
          WCHAR dir[MAX_PATH];
          WCHAR fname[MAX_PATH];
          WCHAR ext[MAX_PATH];
          static const WCHAR fmt[] = {'%','s','%','s','%','s','\0'};

          /* Convert path into actual directory spec */
          GetFullPathNameW(string, sizeof(fpath)/sizeof(WCHAR), fpath, NULL);
          WCMD_splitpath(fpath, drive, dir, fname, ext);

          /* Rebuild path */
          wsprintfW(string, fmt, drive, dir, fd.cFileName);
          break;
        }
      } while (FindNextFileW(hff, &fd) != 0);
      FindClose(hff);
3364 3365
    }

3366
    /* Change to that directory */
3367
    WINE_TRACE("Really changing to directory '%s'\n", wine_dbgstr_w(string));
3368

3369
    status = SetCurrentDirectoryW(string);
3370
    if (!status) {
3371
      errorlevel = 1;
3372 3373
      WCMD_print_error ();
      return;
3374 3375
    } else {

3376 3377 3378
      /* Save away the actual new directory, to store as current location */
      GetCurrentDirectoryW (sizeof(string)/sizeof(WCHAR), string);

3379 3380
      /* Restore old directory if drive letter would change, and
           CD x:\directory /D (or pushd c:\directory) not supplied */
3381
      if ((strstrW(quals, parmD) == NULL) &&
3382
          (param1[1] == ':') && (toupper(param1[0]) != toupper(cwd[0]))) {
3383
        SetCurrentDirectoryW(cwd);
3384
      }
3385
    }
3386

3387 3388 3389 3390
    /* Set special =C: type environment variable, for drive letter of
       change of directory, even if path was restored due to missing
       /D (allows changing drive letter when not resident on that
       drive                                                          */
3391
    if ((string[1] == ':') && IsCharAlphaW(string[0])) {
3392 3393 3394
      WCHAR env[4];
      strcpyW(env, equalW);
      memcpy(env+1, string, 2 * sizeof(WCHAR));
3395
      env[3] = 0x00;
3396
      WINE_TRACE("Setting '%s' to '%s'\n", wine_dbgstr_w(env), wine_dbgstr_w(string));
3397
      SetEnvironmentVariableW(env, string);
3398 3399
    }

3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410
   }
  return;
}

/****************************************************************************
 * WCMD_setshow_date
 *
 * Set/Show the system date
 * FIXME: Can't change date yet
 */

3411
void WCMD_setshow_date (void) {
3412

3413
  WCHAR curdate[64], buffer[64];
3414
  DWORD count;
3415
  static const WCHAR parmT[] = {'/','T','\0'};
3416

3417
  if (strlenW(param1) == 0) {
3418
    if (GetDateFormatW(LOCALE_USER_DEFAULT, 0, NULL, NULL,
3419
		curdate, sizeof(curdate)/sizeof(WCHAR))) {
3420
      WCMD_output (WCMD_LoadMessage(WCMD_CURRENTDATE), curdate);
3421
      if (strstrW (quals, parmT) == NULL) {
3422
        WCMD_output (WCMD_LoadMessage(WCMD_NEWDATE));
3423
        WCMD_ReadFile(GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer)/sizeof(WCHAR), &count);
3424
        if (count > 2) {
3425
          WCMD_output_stderr (WCMD_LoadMessage(WCMD_NYI));
3426
        }
3427 3428 3429 3430 3431
      }
    }
    else WCMD_print_error ();
  }
  else {
3432
    WCMD_output_stderr (WCMD_LoadMessage(WCMD_NYI));
3433 3434 3435
  }
}

3436 3437
/****************************************************************************
 * WCMD_compare
3438 3439
 * Note: Native displays 'fred' before 'fred ', so need to only compare up to
 *       the equals sign.
3440
 */
3441
static int WCMD_compare( const void *a, const void *b )
3442 3443
{
    int r;
3444
    const WCHAR * const *str_a = a, * const *str_b = b;
3445
    r = CompareStringW( LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
3446
	  *str_a, strcspnW(*str_a, equalW), *str_b, strcspnW(*str_b, equalW) );
3447 3448 3449 3450 3451 3452 3453 3454 3455
    if( r == CSTR_LESS_THAN ) return -1;
    if( r == CSTR_GREATER_THAN ) return 1;
    return 0;
}

/****************************************************************************
 * WCMD_setshow_sortenv
 *
 * sort variables into order for display
3456 3457
 * Optionally only display those who start with a stub
 * returns the count displayed
3458
 */
3459
static int WCMD_setshow_sortenv(const WCHAR *s, const WCHAR *stub)
3460
{
3461
  UINT count=0, len=0, i, displayedcount=0, stublen=0;
3462
  const WCHAR **str;
3463

3464
  if (stub) stublen = strlenW(stub);
3465

3466 3467
  /* count the number of strings, and the total length */
  while ( s[len] ) {
3468
    len += (strlenW(&s[len]) + 1);
3469 3470 3471 3472
    count++;
  }

  /* add the strings to an array */
3473
  str = LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, count * sizeof (WCHAR*) );
3474
  if( !str )
3475
    return 0;
3476 3477
  str[0] = s;
  for( i=1; i<count; i++ )
3478
    str[i] = str[i-1] + strlenW(str[i-1]) + 1;
3479 3480

  /* sort the array */
3481
  qsort( str, count, sizeof (WCHAR*), WCMD_compare );
3482 3483

  /* print it */
3484
  for( i=0; i<count; i++ ) {
3485
    if (!stub || CompareStringW(LOCALE_USER_DEFAULT,
3486
                                NORM_IGNORECASE | SORT_STRINGSORT,
3487
                                str[i], stublen, stub, -1) == CSTR_EQUAL) {
3488 3489 3490
      /* Don't display special internal variables */
      if (str[i][0] != '=') {
        WCMD_output_asis(str[i]);
3491
        WCMD_output_asis(newlineW);
3492 3493
        displayedcount++;
      }
3494
    }
3495
  }
3496 3497

  LocalFree( str );
3498
  return displayedcount;
3499 3500
}

3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703
/****************************************************************************
 * WCMD_getprecedence
 * Return the precedence of a particular operator
 */
static int WCMD_getprecedence(const WCHAR in)
{
  switch (in) {
    case '!':
    case '~':
    case OP_POSITIVE:
    case OP_NEGATIVE:
      return 8;
    case '*':
    case '/':
    case '%':
      return 7;
    case '+':
    case '-':
      return 6;
    case '<':
    case '>':
      return 5;
    case '&':
      return 4;
    case '^':
      return 3;
    case '|':
      return 2;
    case '=':
    case OP_ASSSIGNMUL:
    case OP_ASSSIGNDIV:
    case OP_ASSSIGNMOD:
    case OP_ASSSIGNADD:
    case OP_ASSSIGNSUB:
    case OP_ASSSIGNAND:
    case OP_ASSSIGNNOT:
    case OP_ASSSIGNOR:
    case OP_ASSSIGNSHL:
    case OP_ASSSIGNSHR:
      return 1;
    default:
      return 0;
  }
}

/****************************************************************************
 * WCMD_pushnumber
 * Push either a number or name (environment variable) onto the supplied
 * stack
 */
static void WCMD_pushnumber(WCHAR *var, int num, VARSTACK **varstack) {
  VARSTACK *thisstack = heap_alloc(sizeof(VARSTACK));
  thisstack->isnum = (var == NULL);
  if (var) {
    thisstack->variable = var;
    WINE_TRACE("Pushed variable %s\n", wine_dbgstr_w(var));
  } else {
    thisstack->value = num;
    WINE_TRACE("Pushed number %d\n", num);
  }
  thisstack->next = *varstack;
  *varstack = thisstack;
}

/****************************************************************************
 * WCMD_peeknumber
 * Returns the value of the top number or environment variable on the stack
 * and leaves the item on the stack.
 */
static int WCMD_peeknumber(VARSTACK **varstack) {
  int result = 0;
  VARSTACK *thisvar;

  if (varstack) {
    thisvar = *varstack;
    if (!thisvar->isnum) {
      WCHAR tmpstr[MAXSTRING];
      if (GetEnvironmentVariableW(thisvar->variable, tmpstr, MAXSTRING)) {
        result = strtoulW(tmpstr,NULL,0);
      }
      WINE_TRACE("Envvar %s converted to %d\n", wine_dbgstr_w(thisvar->variable), result);
    } else {
      result = thisvar->value;
    }
  }
  WINE_TRACE("Peeked number %d\n", result);
  return result;
}

/****************************************************************************
 * WCMD_popnumber
 * Returns the value of the top number or environment variable on the stack
 * and removes the item from the stack.
 */
static int WCMD_popnumber(VARSTACK **varstack) {
  int result = 0;
  VARSTACK *thisvar;

  if (varstack) {
    thisvar = *varstack;
    result = WCMD_peeknumber(varstack);
    if (!thisvar->isnum) heap_free(thisvar->variable);
    *varstack = thisvar->next;
    heap_free(thisvar);
  }
  WINE_TRACE("Popped number %d\n", result);
  return result;
}

/****************************************************************************
 * WCMD_pushoperator
 * Push an operator onto the supplied stack
 */
static void WCMD_pushoperator(WCHAR op, int precedence, OPSTACK **opstack) {
  OPSTACK *thisstack = heap_alloc(sizeof(OPSTACK));
  thisstack->precedence = precedence;
  thisstack->op = op;
  thisstack->next = *opstack;
  WINE_TRACE("Pushed operator %c\n", op);
  *opstack = thisstack;
}

/****************************************************************************
 * WCMD_popoperator
 * Returns the operator from the top of the stack and removes the item from
 * the stack.
 */
static WCHAR WCMD_popoperator(OPSTACK **opstack) {
  WCHAR result = 0;
  OPSTACK *thisop;

  if (opstack) {
    thisop = *opstack;
    result = thisop->op;
    *opstack = thisop->next;
    heap_free(thisop);
  }
  WINE_TRACE("Popped operator %c\n", result);
  return result;
}

/****************************************************************************
 * WCMD_reduce
 * Actions the top operator on the stack against the first and sometimes
 * second value on the variable stack, and pushes the result
 * Returns non-zero on error.
 */
static int WCMD_reduce(OPSTACK **opstack, VARSTACK **varstack) {
  OPSTACK *thisop;
  int var1,var2;
  int rc = 0;

  if (!*opstack || !*varstack) {
    WINE_TRACE("No operators for the reduce\n");
    return WCMD_NOOPERATOR;
  }

  /* Remove the top operator */
  thisop = *opstack;
  *opstack = (*opstack)->next;
  WINE_TRACE("Reducing the stacks - processing operator %c\n", thisop->op);

  /* One variable operators */
  var1 = WCMD_popnumber(varstack);
  switch (thisop->op) {
  case '!': WCMD_pushnumber(NULL, !var1, varstack);
            break;
  case '~': WCMD_pushnumber(NULL, ~var1, varstack);
            break;
  case OP_POSITIVE: WCMD_pushnumber(NULL, var1, varstack);
            break;
  case OP_NEGATIVE: WCMD_pushnumber(NULL, -var1, varstack);
            break;
  }

  /* Two variable operators */
  if (!*varstack) {
    WINE_TRACE("No operands left for the reduce?\n");
    return WCMD_NOOPERAND;
  }
  switch (thisop->op) {
  case '!':
  case '~':
  case OP_POSITIVE:
  case OP_NEGATIVE:
            break; /* Handled above */
  case '*': var2 = WCMD_popnumber(varstack);
            WCMD_pushnumber(NULL, var2*var1, varstack);
            break;
  case '/': var2 = WCMD_popnumber(varstack);
            if (var1 == 0) return WCMD_DIVIDEBYZERO;
            WCMD_pushnumber(NULL, var2/var1, varstack);
            break;
  case '+': var2 = WCMD_popnumber(varstack);
            WCMD_pushnumber(NULL, var2+var1, varstack);
            break;
  case '-': var2 = WCMD_popnumber(varstack);
            WCMD_pushnumber(NULL, var2-var1, varstack);
            break;
  case '&': var2 = WCMD_popnumber(varstack);
            WCMD_pushnumber(NULL, var2&var1, varstack);
            break;
  case '%': var2 = WCMD_popnumber(varstack);
3704
            if (var1 == 0) return WCMD_DIVIDEBYZERO;
3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815
            WCMD_pushnumber(NULL, var2%var1, varstack);
            break;
  case '^': var2 = WCMD_popnumber(varstack);
            WCMD_pushnumber(NULL, var2^var1, varstack);
            break;
  case '<': var2 = WCMD_popnumber(varstack);
            /* Shift left has to be a positive number, 0-31 otherwise 0 is returned,
               which differs from the compiler (for example gcc) so being explicit. */
            if (var1 < 0 || var1 >= (8 * sizeof(INT))) {
              WCMD_pushnumber(NULL, 0, varstack);
            } else {
              WCMD_pushnumber(NULL, var2<<var1, varstack);
            }
            break;
  case '>': var2 = WCMD_popnumber(varstack);
            WCMD_pushnumber(NULL, var2>>var1, varstack);
            break;
  case '|': var2 = WCMD_popnumber(varstack);
            WCMD_pushnumber(NULL, var2|var1, varstack);
            break;

  case OP_ASSSIGNMUL:
  case OP_ASSSIGNDIV:
  case OP_ASSSIGNMOD:
  case OP_ASSSIGNADD:
  case OP_ASSSIGNSUB:
  case OP_ASSSIGNAND:
  case OP_ASSSIGNNOT:
  case OP_ASSSIGNOR:
  case OP_ASSSIGNSHL:
  case OP_ASSSIGNSHR:
        {
          int i = 0;

          /* The left of an equals must be one variable */
          if (!(*varstack) || (*varstack)->isnum) {
            return WCMD_NOOPERAND;
          }

          /* Make the number stack grow by inserting the value of the variable */
          var2 = WCMD_peeknumber(varstack);
          WCMD_pushnumber(NULL, var2, varstack);
          WCMD_pushnumber(NULL, var1, varstack);

          /* Make the operand stack grow by pushing the assign operator plus the
             operator to perform                                                 */
          while (calcassignments[i].op != ' ' &&
                 calcassignments[i].calculatedop != thisop->op) {
            i++;
          }
          if (calcassignments[i].calculatedop == ' ') {
            WINE_ERR("Unexpected operator %c\n", thisop->op);
            return WCMD_NOOPERATOR;
          }
          WCMD_pushoperator('=', WCMD_getprecedence('='), opstack);
          WCMD_pushoperator(calcassignments[i].op,
                            WCMD_getprecedence(calcassignments[i].op), opstack);
          break;
        }

  case '=':
        {
          WCHAR  intFormat[] = {'%','d','\0'};
          WCHAR  result[MAXSTRING];

          /* Build the result, then push it onto the stack */
          sprintfW(result, intFormat, var1);
          WINE_TRACE("Assigning %s a value %s\n", wine_dbgstr_w((*varstack)->variable),
                     wine_dbgstr_w(result));
          SetEnvironmentVariableW((*varstack)->variable, result);
          var2 = WCMD_popnumber(varstack);
          WCMD_pushnumber(NULL, var1, varstack);
          break;
        }

  default:  WINE_ERR("Unrecognized operator %c\n", thisop->op);
  }

  heap_free(thisop);
  return rc;
}


/****************************************************************************
 * WCMD_handleExpression
 * Handles an expression provided to set /a - If it finds brackets, it uses
 * recursion to process the parts in brackets.
 */
static int WCMD_handleExpression(WCHAR **expr, int *ret, int depth)
{
  static const WCHAR mathDelims[] = {' ','\t','(',')','!','~','-','*','/','%',
                                     '+','<','>','&','^','|','=',',','\0' };
  int       rc = 0;
  WCHAR    *pos;
  BOOL      lastwasnumber = FALSE;  /* FALSE makes a minus at the start of the expression easier to handle */
  OPSTACK  *opstackhead = NULL;
  VARSTACK *varstackhead = NULL;
  WCHAR     foundhalf = 0;

  /* Initialize */
  WINE_TRACE("Handling expression '%s'\n", wine_dbgstr_w(*expr));
  pos = *expr;

  /* Iterate through until whole expression is processed */
  while (pos && *pos) {
    BOOL treatasnumber;

    /* Skip whitespace to get to the next character to process*/
    while (*pos && (*pos==' ' || *pos=='\t')) pos++;
    if (!*pos) goto exprreturn;

3816
    /* If we have found anything other than an operator then it's a number/variable */
3817 3818 3819 3820 3821
    if (strchrW(mathDelims, *pos) == NULL) {
      WCHAR *parmstart, *parm, *dupparm;
      WCHAR *nextpos;

      /* Cannot have an expression with var/number twice, without an operator
3822
         in-between, nor or number following a half constructed << or >> operator */
3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004
      if (lastwasnumber || foundhalf) {
        rc = WCMD_NOOPERATOR;
        goto exprerrorreturn;
      }
      lastwasnumber = TRUE;

      if (isdigitW(*pos)) {
        /* For a number - just push it onto the stack */
        int num = strtoulW(pos, &nextpos, 0);
        WCMD_pushnumber(NULL, num, &varstackhead);
        pos = nextpos;

        /* Verify the number was validly formed */
        if (*nextpos && (strchrW(mathDelims, *nextpos) == NULL)) {
          rc = WCMD_BADHEXOCT;
          goto exprerrorreturn;
        }
      } else {

        /* For a variable - just push it onto the stack */
        parm = WCMD_parameter_with_delims(pos, 0, &parmstart, FALSE, FALSE, mathDelims);
        dupparm = heap_strdupW(parm);
        WCMD_pushnumber(dupparm, 0, &varstackhead);
        pos = parmstart + strlenW(dupparm);
      }
      continue;
    }

    /* We have found an operator. Some operators are one character, some two, and the minus
       and plus signs need special processing as they can be either operators or just influence
       the parameter which follows them                                                         */
    if (foundhalf && (*pos != foundhalf)) {
      /* Badly constructed operator pair */
      rc = WCMD_NOOPERATOR;
      goto exprerrorreturn;
    }

    treatasnumber = FALSE; /* We are processing an operand */
    switch (*pos) {

    /* > and < are special as they are double character operators (and spaces can be between them!)
       If we see these for the first time, set a flag, and second time around we continue.
       Note these double character operators are stored as just one of the characters on the stack */
    case '>':
    case '<': if (!foundhalf) {
                foundhalf = *pos;
                pos++;
                break;
              }
              /* We have found the rest, so clear up the knowledge of the half completed part and
                 drop through to normal operator processing                                       */
              foundhalf = 0;
              /* drop through */

    case '=': if (*pos=='=') {
                /* = is special cased as if the last was an operator then we may have e.g. += or
                   *= etc which we need to handle by replacing the operator that is on the stack
                   with a calculated assignment equivalent                                       */
                if (!lastwasnumber && opstackhead) {
                  int i = 0;
                  while (calcassignments[i].op != ' ' && calcassignments[i].op != opstackhead->op) {
                    i++;
                  }
                  if (calcassignments[i].op == ' ') {
                    rc = WCMD_NOOPERAND;
                    goto exprerrorreturn;
                  } else {
                    /* Remove the operator on the stack, it will be replaced with a ?= equivalent
                       when the general operator handling happens further down.                   */
                    *pos = calcassignments[i].calculatedop;
                    WCMD_popoperator(&opstackhead);
                  }
                }
              }
              /* Drop though */

    /* + and - are slightly special as they can be a numeric prefix, if they follow an operator
       so if they do, convert the +/- (arithmetic) to +/- (numeric prefix for positive/negative) */
    case '+': if (!lastwasnumber && *pos=='+') *pos = OP_POSITIVE;
              /* drop through */
    case '-': if (!lastwasnumber && *pos=='-') *pos = OP_NEGATIVE;
              /* drop through */

    /* Normal operators - push onto stack unless precedence means we have to calculate it now */
    case '!': /* drop through */
    case '~': /* drop through */
    case '/': /* drop through */
    case '%': /* drop through */
    case '&': /* drop through */
    case '^': /* drop through */
    case '*': /* drop through */
    case '|':
               /* General code for handling most of the operators - look at the
                  precedence of the top item on the stack, and see if we need to
                  action the stack before we push something else onto it.        */
               {
                 int precedence = WCMD_getprecedence(*pos);
                 WINE_TRACE("Found operator %c precedence %d (head is %d)\n", *pos,
                            precedence, !opstackhead?-1:opstackhead->precedence);

                 /* In general, for things with the same precedence, reduce immediately
                    except for assignments and unary operators which do not             */
                 while (!rc && opstackhead &&
                        ((opstackhead->precedence > precedence) ||
                         ((opstackhead->precedence == precedence) &&
                            (precedence != 1) && (precedence != 8)))) {
                   rc = WCMD_reduce(&opstackhead, &varstackhead);
                 }
                 if (rc) goto exprerrorreturn;
                 WCMD_pushoperator(*pos, precedence, &opstackhead);
                 pos++;
                 break;
               }

    /* comma means start a new expression, ie calculate what we have */
    case ',':
               {
                 int prevresult = -1;
                 WINE_TRACE("Found expression delimiter - reducing exising stacks\n");
                 while (!rc && opstackhead) {
                   rc = WCMD_reduce(&opstackhead, &varstackhead);
                 }
                 if (rc) goto exprerrorreturn;
                 /* If we have anything other than one number left, error
                    otherwise throw the number away                      */
                 if (!varstackhead || varstackhead->next) {
                   rc = WCMD_NOOPERATOR;
                   goto exprerrorreturn;
                 }
                 prevresult = WCMD_popnumber(&varstackhead);
                 WINE_TRACE("Expression resolved to %d\n", prevresult);
                 heap_free(varstackhead);
                 varstackhead = NULL;
                 pos++;
                 break;
               }

    /* Open bracket - use iteration to parse the inner expression, then continue */
    case '(' : {
                 int exprresult = 0;
                 pos++;
                 rc = WCMD_handleExpression(&pos, &exprresult, depth+1);
                 if (rc) goto exprerrorreturn;
                 WCMD_pushnumber(NULL, exprresult, &varstackhead);
                 break;
               }

    /* Close bracket - we have finished this depth, calculate and return */
    case ')' : {
                 pos++;
                 treatasnumber = TRUE; /* Things in brackets result in a number */
                 if (depth == 0) {
                   rc = WCMD_BADPAREN;
                   goto exprerrorreturn;
                 }
                 goto exprreturn;
               }

    default:
        WINE_ERR("Unrecognized operator %c\n", *pos);
        pos++;
    }
    lastwasnumber = treatasnumber;
  }

exprreturn:
  *expr = pos;

  /* We need to reduce until we have a single number (or variable) on the
     stack and set the return value to that                               */
  while (!rc && opstackhead) {
    rc = WCMD_reduce(&opstackhead, &varstackhead);
  }
  if (rc) goto exprerrorreturn;

  /* If we have anything other than one number left, error
      otherwise throw the number away                      */
  if (!varstackhead || varstackhead->next) {
    rc = WCMD_NOOPERATOR;
    goto exprerrorreturn;
  }

4005
  /* Now get the number (and convert if it's just a variable name) */
4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016
  *ret = WCMD_popnumber(&varstackhead);

exprerrorreturn:
  /* Free all remaining memory */
  while (opstackhead) WCMD_popoperator(&opstackhead);
  while (varstackhead) WCMD_popnumber(&varstackhead);

  WINE_TRACE("Returning result %d, rc %d\n", *ret, rc);
  return rc;
}

4017 4018 4019 4020 4021 4022
/****************************************************************************
 * WCMD_setshow_env
 *
 * Set/Show the environment variables
 */

4023
void WCMD_setshow_env (WCHAR *s) {
4024

4025
  LPVOID env;
4026
  WCHAR *p;
4027
  BOOL status;
4028
  static const WCHAR parmP[] = {'/','P','\0'};
4029 4030
  static const WCHAR parmA[] = {'/','A','\0'};
  WCHAR string[MAXSTRING];
4031

4032
  if (param1[0] == 0x00 && quals[0] == 0x00) {
4033
    env = GetEnvironmentStringsW();
4034
    WCMD_setshow_sortenv( env, NULL );
4035
    return;
4036
  }
4037 4038

  /* See if /P supplied, and if so echo the prompt, and read in a reply */
4039
  if (CompareStringW(LOCALE_USER_DEFAULT,
4040
                     NORM_IGNORECASE | SORT_STRINGSORT,
4041
                     s, 2, parmP, -1) == CSTR_EQUAL) {
4042 4043 4044
    DWORD count;

    s += 2;
4045
    while (*s && (*s==' ' || *s=='\t')) s++;
4046 4047 4048 4049 4050 4051 4052
    /* set /P "var=value"jim ignores anything after the last quote */
    if (*s=='\"') {
      WCHAR *lastquote;
      lastquote = WCMD_strip_quotes(s);
      if (lastquote) *lastquote = 0x00;
      WINE_TRACE("set: Stripped command line '%s'\n", wine_dbgstr_w(s));
    }
4053 4054

    /* If no parameter, or no '=' sign, return an error */
4055
    if (!(*s) || ((p = strchrW (s, '=')) == NULL )) {
4056
      WCMD_output_stderr(WCMD_LoadMessage(WCMD_NOARG));
4057 4058 4059 4060 4061
      return;
    }

    /* Output the prompt */
    *p++ = '\0';
4062
    if (strlenW(p) != 0) WCMD_output_asis(p);
4063 4064

    /* Read the reply */
4065
    WCMD_ReadFile(GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string)/sizeof(WCHAR), &count);
4066 4067 4068
    if (count > 1) {
      string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
      if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
4069 4070
      WINE_TRACE("set /p: Setting var '%s' to '%s'\n", wine_dbgstr_w(s),
                 wine_dbgstr_w(string));
4071
      status = SetEnvironmentVariableW(s, string);
4072 4073
    }

4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113
  /* See if /A supplied, and if so calculate the results of all the expressions */
  } else if (CompareStringW(LOCALE_USER_DEFAULT,
                            NORM_IGNORECASE | SORT_STRINGSORT,
                            s, 2, parmA, -1) == CSTR_EQUAL) {
    /* /A supplied, so evaluate expressions and set variables appropriately */
    /* Syntax is set /a var=1,var2=var+4 etc, and it echos back the result  */
    /* of the final computation                                             */
    int result = 0;
    int rc = 0;
    WCHAR *thisexpr;
    WCHAR *src,*dst;

    /* Remove all quotes before doing any calculations */
    thisexpr = heap_alloc((strlenW(s+2)+1) * sizeof(WCHAR));
    src = s+2;
    dst = thisexpr;
    while (*src) {
      if (*src != '"') *dst++ = *src;
      src++;
    }
    *dst = 0;

    /* Now calculate the results of the expression */
    src = thisexpr;
    rc = WCMD_handleExpression(&src, &result, 0);
    heap_free(thisexpr);

    /* If parsing failed, issue the error message */
    if (rc > 0) {
      WCMD_output_stderr(WCMD_LoadMessage(rc));
      return;
    }

    /* If we have no context (interactive or cmd.exe /c) print the final result */
    if (!context) {
      static const WCHAR fmt[] = {'%','d','\0'};
      sprintfW(string, fmt, result);
      WCMD_output_asis(string);
    }

4114
  } else {
4115
    DWORD gle;
4116

4117 4118 4119 4120 4121 4122 4123 4124
    /* set "var=value"jim ignores anything after the last quote */
    if (*s=='\"') {
      WCHAR *lastquote;
      lastquote = WCMD_strip_quotes(s);
      if (lastquote) *lastquote = 0x00;
      WINE_TRACE("set: Stripped command line '%s'\n", wine_dbgstr_w(s));
    }

4125
    p = strchrW (s, '=');
4126
    if (p == NULL) {
4127
      env = GetEnvironmentStringsW();
4128
      if (WCMD_setshow_sortenv( env, s ) == 0) {
4129
        WCMD_output_stderr(WCMD_LoadMessage(WCMD_MISSINGENV), s);
4130
        errorlevel = 1;
4131
      }
4132 4133 4134
      return;
    }
    *p++ = '\0';
4135

4136
    if (strlenW(p) == 0) p = NULL;
4137 4138
    WINE_TRACE("set: Setting var '%s' to '%s'\n", wine_dbgstr_w(s),
               wine_dbgstr_w(p));
4139
    status = SetEnvironmentVariableW(s, p);
4140 4141 4142
    gle = GetLastError();
    if ((!status) & (gle == ERROR_ENVVAR_NOT_FOUND)) {
      errorlevel = 1;
4143
    } else if (!status) WCMD_print_error();
4144
    else errorlevel = 0;
4145 4146 4147 4148 4149 4150 4151 4152 4153
  }
}

/****************************************************************************
 * WCMD_setshow_path
 *
 * Set/Show the path environment variable
 */

4154
void WCMD_setshow_path (const WCHAR *args) {
4155

4156
  WCHAR string[1024];
4157
  DWORD status;
4158 4159
  static const WCHAR pathW[] = {'P','A','T','H','\0'};
  static const WCHAR pathEqW[] = {'P','A','T','H','=','\0'};
4160

4161
  if (strlenW(param1) == 0 && strlenW(param2) == 0) {
4162
    status = GetEnvironmentVariableW(pathW, string, sizeof(string)/sizeof(WCHAR));
4163
    if (status != 0) {
4164
      WCMD_output_asis ( pathEqW);
4165
      WCMD_output_asis ( string);
4166
      WCMD_output_asis ( newlineW);
4167 4168
    }
    else {
4169
      WCMD_output_stderr(WCMD_LoadMessage(WCMD_NOPATH));
4170 4171 4172
    }
  }
  else {
4173 4174
    if (*args == '=') args++; /* Skip leading '=' */
    status = SetEnvironmentVariableW(pathW, args);
4175 4176 4177 4178 4179 4180 4181 4182 4183 4184
    if (!status) WCMD_print_error();
  }
}

/****************************************************************************
 * WCMD_setshow_prompt
 *
 * Set or show the command prompt.
 */

4185
void WCMD_setshow_prompt (void) {
4186

4187 4188
  WCHAR *s;
  static const WCHAR promptW[] = {'P','R','O','M','P','T','\0'};
4189

4190
  if (strlenW(param1) == 0) {
4191
    SetEnvironmentVariableW(promptW, NULL);
4192 4193 4194
  }
  else {
    s = param1;
4195
    while ((*s == '=') || (*s == ' ') || (*s == '\t')) s++;
4196
    if (strlenW(s) == 0) {
4197
      SetEnvironmentVariableW(promptW, NULL);
4198
    }
4199
    else SetEnvironmentVariableW(promptW, s);
4200 4201 4202 4203 4204 4205 4206 4207 4208 4209
  }
}

/****************************************************************************
 * WCMD_setshow_time
 *
 * Set/Show the system time
 * FIXME: Can't change time yet
 */

4210
void WCMD_setshow_time (void) {
4211

4212
  WCHAR curtime[64], buffer[64];
4213 4214
  DWORD count;
  SYSTEMTIME st;
4215
  static const WCHAR parmT[] = {'/','T','\0'};
4216

4217
  if (strlenW(param1) == 0) {
4218
    GetLocalTime(&st);
4219
    if (GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, NULL,
4220
		curtime, sizeof(curtime)/sizeof(WCHAR))) {
4221
      WCMD_output (WCMD_LoadMessage(WCMD_CURRENTTIME), curtime);
4222
      if (strstrW (quals, parmT) == NULL) {
4223
        WCMD_output (WCMD_LoadMessage(WCMD_NEWTIME));
4224
        WCMD_ReadFile(GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer)/sizeof(WCHAR), &count);
4225
        if (count > 2) {
4226
          WCMD_output_stderr (WCMD_LoadMessage(WCMD_NYI));
4227
        }
4228 4229 4230 4231 4232
      }
    }
    else WCMD_print_error ();
  }
  else {
4233
    WCMD_output_stderr (WCMD_LoadMessage(WCMD_NYI));
4234 4235 4236 4237 4238 4239 4240
  }
}

/****************************************************************************
 * WCMD_shift
 *
 * Shift batch parameters.
4241
 * Optional /n says where to start shifting (n=0-8)
4242 4243
 */

4244
void WCMD_shift (const WCHAR *args) {
4245
  int start;
4246

4247
  if (context != NULL) {
4248
    WCHAR *pos = strchrW(args, '/');
4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266
    int   i;

    if (pos == NULL) {
      start = 0;
    } else if (*(pos+1)>='0' && *(pos+1)<='8') {
      start = (*(pos+1) - '0');
    } else {
      SetLastError(ERROR_INVALID_PARAMETER);
      WCMD_print_error();
      return;
    }

    WINE_TRACE("Shifting variables, starting at %d\n", start);
    for (i=start;i<=8;i++) {
      context -> shift_count[i] = context -> shift_count[i+1] + 1;
    }
    context -> shift_count[9] = context -> shift_count[9] + 1;
  }
4267 4268 4269

}

4270 4271 4272
/****************************************************************************
 * WCMD_start
 */
4273
void WCMD_start(const WCHAR *args)
4274 4275 4276 4277 4278 4279 4280 4281 4282 4283
{
    static const WCHAR exeW[] = {'\\','c','o','m','m','a','n','d',
                                 '\\','s','t','a','r','t','.','e','x','e',0};
    WCHAR file[MAX_PATH];
    WCHAR *cmdline;
    STARTUPINFOW st;
    PROCESS_INFORMATION pi;

    GetWindowsDirectoryW( file, MAX_PATH );
    strcatW( file, exeW );
4284
    cmdline = heap_alloc( (strlenW(file) + strlenW(args) + 2) * sizeof(WCHAR) );
4285
    strcpyW( cmdline, file );
4286
    strcatW( cmdline, spaceW );
4287
    strcatW( cmdline, args );
4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305

    memset( &st, 0, sizeof(STARTUPINFOW) );
    st.cb = sizeof(STARTUPINFOW);

    if (CreateProcessW( file, cmdline, NULL, NULL, TRUE, 0, NULL, NULL, &st, &pi ))
    {
        WaitForSingleObject( pi.hProcess, INFINITE );
        GetExitCodeProcess( pi.hProcess, &errorlevel );
        if (errorlevel == STILL_ACTIVE) errorlevel = 0;
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
    }
    else
    {
        SetLastError(ERROR_FILE_NOT_FOUND);
        WCMD_print_error ();
        errorlevel = 9009;
    }
4306
    heap_free(cmdline);
4307 4308
}

4309 4310 4311 4312 4313
/****************************************************************************
 * WCMD_title
 *
 * Set the console title
 */
4314 4315
void WCMD_title (const WCHAR *args) {
  SetConsoleTitleW(args);
4316 4317
}

4318 4319 4320 4321 4322 4323
/****************************************************************************
 * WCMD_type
 *
 * Copy a file to standard output.
 */

4324
void WCMD_type (WCHAR *args) {
4325

4326
  int   argno         = 0;
4327
  WCHAR *argN          = args;
4328
  BOOL  writeHeaders  = FALSE;
4329

4330
  if (param1[0] == 0x00) {
4331
    WCMD_output_stderr(WCMD_LoadMessage(WCMD_NOARG));
4332 4333
    return;
  }
4334 4335 4336 4337 4338 4339

  if (param2[0] != 0x00) writeHeaders = TRUE;

  /* Loop through all args */
  errorlevel = 0;
  while (argN) {
4340
    WCHAR *thisArg = WCMD_parameter (args, argno++, &argN, FALSE, FALSE);
4341 4342

    HANDLE h;
4343
    WCHAR buffer[512];
4344 4345 4346 4347
    DWORD count;

    if (!argN) break;

4348
    WINE_TRACE("type: Processing arg '%s'\n", wine_dbgstr_w(thisArg));
4349
    h = CreateFileW(thisArg, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
4350 4351 4352
		FILE_ATTRIBUTE_NORMAL, NULL);
    if (h == INVALID_HANDLE_VALUE) {
      WCMD_print_error ();
4353
      WCMD_output_stderr(WCMD_LoadMessage(WCMD_READFAIL), thisArg);
4354 4355 4356
      errorlevel = 1;
    } else {
      if (writeHeaders) {
4357
        static const WCHAR fmt[] = {'\n','%','1','\n','\n','\0'};
4358
        WCMD_output(fmt, thisArg);
4359
      }
4360
      while (WCMD_ReadFile(h, buffer, sizeof(buffer)/sizeof(WCHAR) - 1, &count)) {
4361 4362 4363 4364 4365 4366
        if (count == 0) break;	/* ReadFile reports success on EOF! */
        buffer[count] = 0;
        WCMD_output_asis (buffer);
      }
      CloseHandle (h);
    }
4367 4368 4369
  }
}

4370 4371 4372 4373 4374 4375
/****************************************************************************
 * WCMD_more
 *
 * Output either a file or stdin to screen in pages
 */

4376
void WCMD_more (WCHAR *args) {
4377 4378

  int   argno         = 0;
4379
  WCHAR *argN         = args;
4380 4381 4382
  WCHAR  moreStr[100];
  WCHAR  moreStrPage[100];
  WCHAR  buffer[512];
4383
  DWORD count;
4384 4385 4386 4387 4388
  static const WCHAR moreStart[] = {'-','-',' ','\0'};
  static const WCHAR moreFmt[]   = {'%','s',' ','-','-','\n','\0'};
  static const WCHAR moreFmt2[]  = {'%','s',' ','(','%','2','.','2','d','%','%',
                                    ')',' ','-','-','\n','\0'};
  static const WCHAR conInW[]    = {'C','O','N','I','N','$','\0'};
4389 4390 4391

  /* Prefix the NLS more with '-- ', then load the text */
  errorlevel = 0;
4392
  strcpyW(moreStr, moreStart);
4393
  LoadStringW(hinst, WCMD_MORESTR, &moreStr[3],
4394
              (sizeof(moreStr)/sizeof(WCHAR))-3);
4395 4396 4397 4398 4399

  if (param1[0] == 0x00) {

    /* Wine implements pipes via temporary files, and hence stdin is
       effectively reading from the file. This means the prompts for
4400
       more are satisfied by the next line from the input (file). To
4401 4402
       avoid this, ensure stdin is to the console                    */
    HANDLE hstdin  = GetStdHandle(STD_INPUT_HANDLE);
4403
    HANDLE hConIn = CreateFileW(conInW, GENERIC_READ | GENERIC_WRITE,
4404 4405
                         FILE_SHARE_READ, NULL, OPEN_EXISTING,
                         FILE_ATTRIBUTE_NORMAL, 0);
Jason Edmeades's avatar
Jason Edmeades committed
4406
    WINE_TRACE("No parms - working probably in pipe mode\n");
4407 4408 4409
    SetStdHandle(STD_INPUT_HANDLE, hConIn);

    /* Warning: No easy way of ending the stream (ctrl+z on windows) so
4410
       once you get in this bit unless due to a pipe, it's going to end badly...  */
4411
    wsprintfW(moreStrPage, moreFmt, moreStr);
4412 4413

    WCMD_enter_paged_mode(moreStrPage);
4414
    while (WCMD_ReadFile(hstdin, buffer, (sizeof(buffer)/sizeof(WCHAR))-1, &count)) {
4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429
      if (count == 0) break;	/* ReadFile reports success on EOF! */
      buffer[count] = 0;
      WCMD_output_asis (buffer);
    }
    WCMD_leave_paged_mode();

    /* Restore stdin to what it was */
    SetStdHandle(STD_INPUT_HANDLE, hstdin);
    CloseHandle(hConIn);

    return;
  } else {
    BOOL needsPause = FALSE;

    /* Loop through all args */
Jason Edmeades's avatar
Jason Edmeades committed
4430
    WINE_TRACE("Parms supplied - working through each file\n");
4431 4432 4433
    WCMD_enter_paged_mode(moreStrPage);

    while (argN) {
4434
      WCHAR *thisArg = WCMD_parameter (args, argno++, &argN, FALSE, FALSE);
4435 4436 4437 4438 4439 4440 4441
      HANDLE h;

      if (!argN) break;

      if (needsPause) {

        /* Wait */
4442
        wsprintfW(moreStrPage, moreFmt2, moreStr, 100);
4443 4444
        WCMD_leave_paged_mode();
        WCMD_output_asis(moreStrPage);
4445
        WCMD_ReadFile(GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer)/sizeof(WCHAR), &count);
4446 4447 4448 4449
        WCMD_enter_paged_mode(moreStrPage);
      }


4450
      WINE_TRACE("more: Processing arg '%s'\n", wine_dbgstr_w(thisArg));
4451
      h = CreateFileW(thisArg, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
4452 4453 4454
		FILE_ATTRIBUTE_NORMAL, NULL);
      if (h == INVALID_HANDLE_VALUE) {
        WCMD_print_error ();
4455
        WCMD_output_stderr(WCMD_LoadMessage(WCMD_READFAIL), thisArg);
4456 4457 4458 4459 4460 4461 4462
        errorlevel = 1;
      } else {
        ULONG64 curPos  = 0;
        ULONG64 fileLen = 0;
        WIN32_FILE_ATTRIBUTE_DATA   fileInfo;

        /* Get the file size */
4463
        GetFileAttributesExW(thisArg, GetFileExInfoStandard, (void*)&fileInfo);
4464 4465 4466
        fileLen = (((ULONG64)fileInfo.nFileSizeHigh) << 32) + fileInfo.nFileSizeLow;

        needsPause = TRUE;
4467
        while (WCMD_ReadFile(h, buffer, (sizeof(buffer)/sizeof(WCHAR))-1, &count)) {
4468 4469 4470 4471 4472
          if (count == 0) break;	/* ReadFile reports success on EOF! */
          buffer[count] = 0;
          curPos += count;

          /* Update % count (would be used in WCMD_output_asis as prompt) */
4473
          wsprintfW(moreStrPage, moreFmt2, moreStr, (int) min(99, (curPos * 100)/fileLen));
4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484

          WCMD_output_asis (buffer);
        }
        CloseHandle (h);
      }
    }

    WCMD_leave_paged_mode();
  }
}

4485 4486 4487 4488
/****************************************************************************
 * WCMD_verify
 *
 * Display verify flag.
4489 4490
 * FIXME: We don't actually do anything with the verify flag other than toggle
 * it...
4491 4492
 */

4493
void WCMD_verify (const WCHAR *args) {
4494

4495
  int count;
4496

4497
  count = strlenW(args);
4498
  if (count == 0) {
4499 4500
    if (verify_mode) WCMD_output (WCMD_LoadMessage(WCMD_VERIFYPROMPT), onW);
    else WCMD_output (WCMD_LoadMessage(WCMD_VERIFYPROMPT), offW);
4501 4502
    return;
  }
4503
  if (lstrcmpiW(args, onW) == 0) {
4504
    verify_mode = TRUE;
4505 4506
    return;
  }
4507
  else if (lstrcmpiW(args, offW) == 0) {
4508
    verify_mode = FALSE;
4509 4510
    return;
  }
4511
  else WCMD_output_stderr(WCMD_LoadMessage(WCMD_VERIFYERR));
4512 4513 4514 4515 4516 4517 4518 4519
}

/****************************************************************************
 * WCMD_version
 *
 * Display version info.
 */

4520
void WCMD_version (void) {
4521

4522
  WCMD_output_asis (version_string);
4523 4524 4525 4526 4527 4528

}

/****************************************************************************
 * WCMD_volume
 *
4529 4530 4531
 * Display volume information (set_label = FALSE)
 * Additionally set volume label (set_label = TRUE)
 * Returns 1 on success, 0 otherwise
4532 4533
 */

4534 4535
int WCMD_volume(BOOL set_label, const WCHAR *path)
{
4536
  DWORD count, serial;
4537
  WCHAR string[MAX_PATH], label[MAX_PATH], curdir[MAX_PATH];
4538
  BOOL status;
4539

4540
  if (strlenW(path) == 0) {
4541
    status = GetCurrentDirectoryW(sizeof(curdir)/sizeof(WCHAR), curdir);
4542 4543 4544 4545
    if (!status) {
      WCMD_print_error ();
      return 0;
    }
4546
    status = GetVolumeInformationW(NULL, label, sizeof(label)/sizeof(WCHAR),
4547
                                   &serial, NULL, NULL, NULL, 0);
4548 4549
  }
  else {
4550 4551
    static const WCHAR fmt[] = {'%','s','\\','\0'};
    if ((path[1] != ':') || (strlenW(path) != 2)) {
4552
      WCMD_output_stderr(WCMD_LoadMessage(WCMD_SYNTAXERR));
4553 4554
      return 0;
    }
4555 4556
    wsprintfW (curdir, fmt, path);
    status = GetVolumeInformationW(curdir, label, sizeof(label)/sizeof(WCHAR),
4557
                                   &serial, NULL,
4558 4559 4560 4561 4562 4563
    	NULL, NULL, 0);
  }
  if (!status) {
    WCMD_print_error ();
    return 0;
  }
4564 4565 4566 4567 4568 4569 4570 4571 4572 4573
  if (label[0] != '\0') {
    WCMD_output (WCMD_LoadMessage(WCMD_VOLUMELABEL),
      	curdir[0], label);
  }
  else {
    WCMD_output (WCMD_LoadMessage(WCMD_VOLUMENOLABEL),
      	curdir[0]);
  }
  WCMD_output (WCMD_LoadMessage(WCMD_VOLUMESERIALNO),
    	HIWORD(serial), LOWORD(serial));
4574
  if (set_label) {
4575
    WCMD_output (WCMD_LoadMessage(WCMD_VOLUMEPROMPT));
4576
    WCMD_ReadFile(GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string)/sizeof(WCHAR), &count);
4577 4578 4579 4580
    if (count > 1) {
      string[count-1] = '\0';		/* ReadFile output is not null-terminated! */
      if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
    }
4581
    if (strlenW(path) != 0) {
4582
      if (!SetVolumeLabelW(curdir, string)) WCMD_print_error ();
4583 4584
    }
    else {
4585
      if (!SetVolumeLabelW(NULL, string)) WCMD_print_error ();
4586 4587 4588 4589
    }
  }
  return 1;
}
4590 4591 4592 4593 4594 4595 4596 4597

/**************************************************************************
 * WCMD_exit
 *
 * Exit either the process, or just this batch program
 *
 */

4598
void WCMD_exit (CMD_LIST **cmdList) {
4599

4600 4601
    static const WCHAR parmB[] = {'/','B','\0'};
    int rc = atoiW(param1); /* Note: atoi of empty parameter is 0 */
4602

4603
    if (context && lstrcmpiW(quals, parmB) == 0) {
4604 4605
        errorlevel = rc;
        context -> skip_rest = TRUE;
4606
        *cmdList = NULL;
4607 4608 4609 4610
    } else {
        ExitProcess(rc);
    }
}
4611

4612 4613 4614 4615

/*****************************************************************************
 * WCMD_assoc
 *
4616 4617
 *	Lists or sets file associations  (assoc = TRUE)
 *      Lists or sets file types         (assoc = FALSE)
4618
 */
4619
void WCMD_assoc (const WCHAR *args, BOOL assoc) {
4620 4621 4622

    HKEY    key;
    DWORD   accessOptions = KEY_READ;
4623
    WCHAR   *newValue;
4624
    LONG    rc = ERROR_SUCCESS;
4625
    WCHAR    keyValue[MAXSTRING];
4626 4627
    DWORD   valueLen = MAXSTRING;
    HKEY    readKey;
4628 4629
    static const WCHAR shOpCmdW[] = {'\\','S','h','e','l','l','\\',
                                     'O','p','e','n','\\','C','o','m','m','a','n','d','\0'};
4630 4631 4632

    /* See if parameter includes '=' */
    errorlevel = 0;
4633
    newValue = strchrW(args, '=');
4634 4635 4636
    if (newValue) accessOptions |= KEY_WRITE;

    /* Open a key to HKEY_CLASSES_ROOT for enumerating */
4637 4638
    if (RegOpenKeyExW(HKEY_CLASSES_ROOT, nullW, 0,
                      accessOptions, &key) != ERROR_SUCCESS) {
4639 4640 4641 4642
      WINE_FIXME("Unexpected failure opening HKCR key: %d\n", GetLastError());
      return;
    }

4643
    /* If no parameters then list all associations */
4644
    if (*args == 0x00) {
4645 4646 4647 4648
      int index = 0;

      /* Enumerate all the keys */
      while (rc != ERROR_NO_MORE_ITEMS) {
4649
        WCHAR  keyName[MAXSTRING];
4650 4651 4652 4653
        DWORD nameLen;

        /* Find the next value */
        nameLen = MAXSTRING;
4654
        rc = RegEnumKeyExW(key, index++, keyName, &nameLen, NULL, NULL, NULL, NULL);
4655 4656 4657

        if (rc == ERROR_SUCCESS) {

4658 4659 4660 4661 4662
          /* Only interested in extension ones if assoc, or others
             if not assoc                                          */
          if ((keyName[0] == '.' && assoc) ||
              (!(keyName[0] == '.') && (!assoc)))
          {
4663 4664 4665
            WCHAR subkey[MAXSTRING];
            strcpyW(subkey, keyName);
            if (!assoc) strcatW(subkey, shOpCmdW);
4666

4667
            if (RegOpenKeyExW(key, subkey, 0, accessOptions, &readKey) == ERROR_SUCCESS) {
4668

4669
              valueLen = sizeof(keyValue)/sizeof(WCHAR);
4670
              rc = RegQueryValueExW(readKey, NULL, NULL, NULL, (LPBYTE)keyValue, &valueLen);
4671
              WCMD_output_asis(keyName);
4672
              WCMD_output_asis(equalW);
4673 4674 4675 4676
              /* If no default value found, leave line empty after '=' */
              if (rc == ERROR_SUCCESS) {
                WCMD_output_asis(keyValue);
              }
4677
              WCMD_output_asis(newlineW);
4678
              RegCloseKey(readKey);
4679 4680 4681 4682 4683 4684 4685
            }
          }
        }
      }

    } else {

4686
      /* Parameter supplied - if no '=' on command line, it's a query */
4687
      if (newValue == NULL) {
4688 4689
        WCHAR *space;
        WCHAR subkey[MAXSTRING];
4690 4691

        /* Query terminates the parameter at the first space */
4692
        strcpyW(keyValue, args);
4693
        space = strchrW(keyValue, ' ');
4694 4695
        if (space) *space=0x00;

4696
        /* Set up key name */
4697 4698
        strcpyW(subkey, keyValue);
        if (!assoc) strcatW(subkey, shOpCmdW);
4699

4700
        if (RegOpenKeyExW(key, subkey, 0, accessOptions, &readKey) == ERROR_SUCCESS) {
4701

4702
          rc = RegQueryValueExW(readKey, NULL, NULL, NULL, (LPBYTE)keyValue, &valueLen);
4703
          WCMD_output_asis(args);
4704
          WCMD_output_asis(equalW);
4705 4706
          /* If no default value found, leave line empty after '=' */
          if (rc == ERROR_SUCCESS) WCMD_output_asis(keyValue);
4707
          WCMD_output_asis(newlineW);
4708 4709 4710
          RegCloseKey(readKey);

        } else {
4711
          WCHAR  msgbuffer[MAXSTRING];
4712 4713

          /* Load the translated 'File association not found' */
4714
          if (assoc) {
4715
            LoadStringW(hinst, WCMD_NOASSOC, msgbuffer, sizeof(msgbuffer)/sizeof(WCHAR));
4716
          } else {
4717
            LoadStringW(hinst, WCMD_NOFTYPE, msgbuffer, sizeof(msgbuffer)/sizeof(WCHAR));
4718
          }
4719
          WCMD_output_stderr(msgbuffer, keyValue);
4720 4721 4722
          errorlevel = 2;
        }

4723
      /* Not a query - it's a set or clear of a value */
4724 4725
      } else {

4726
        WCHAR subkey[MAXSTRING];
4727

4728 4729 4730 4731
        /* Get pointer to new value */
        *newValue = 0x00;
        newValue++;

4732
        /* Set up key name */
4733
        strcpyW(subkey, args);
4734
        if (!assoc) strcatW(subkey, shOpCmdW);
4735 4736

        /* If nothing after '=' then clear value - only valid for ASSOC */
4737 4738
        if (*newValue == 0x00) {

4739
          if (assoc) rc = RegDeleteKeyW(key, args);
4740
          if (assoc && rc == ERROR_SUCCESS) {
4741
            WINE_TRACE("HKCR Key '%s' deleted\n", wine_dbgstr_w(args));
4742

4743
          } else if (assoc && rc != ERROR_FILE_NOT_FOUND) {
4744 4745 4746 4747
            WCMD_print_error();
            errorlevel = 2;

          } else {
4748
            WCHAR  msgbuffer[MAXSTRING];
4749 4750

            /* Load the translated 'File association not found' */
4751
            if (assoc) {
4752
              LoadStringW(hinst, WCMD_NOASSOC, msgbuffer,
4753
                          sizeof(msgbuffer)/sizeof(WCHAR));
4754
            } else {
4755
              LoadStringW(hinst, WCMD_NOFTYPE, msgbuffer,
4756
                          sizeof(msgbuffer)/sizeof(WCHAR));
4757
            }
4758
            WCMD_output_stderr(msgbuffer, keyValue);
4759 4760 4761 4762 4763
            errorlevel = 2;
          }

        /* It really is a set value = contents */
        } else {
4764
          rc = RegCreateKeyExW(key, subkey, 0, NULL, REG_OPTION_NON_VOLATILE,
4765 4766
                              accessOptions, NULL, &readKey, NULL);
          if (rc == ERROR_SUCCESS) {
4767
            rc = RegSetValueExW(readKey, NULL, 0, REG_SZ,
4768 4769
                                (LPBYTE)newValue,
                                sizeof(WCHAR) * (strlenW(newValue) + 1));
4770 4771 4772 4773 4774 4775 4776
            RegCloseKey(readKey);
          }

          if (rc != ERROR_SUCCESS) {
            WCMD_print_error();
            errorlevel = 2;
          } else {
4777
            WCMD_output_asis(args);
4778
            WCMD_output_asis(equalW);
4779
            WCMD_output_asis(newValue);
4780
            WCMD_output_asis(newlineW);
4781 4782 4783 4784 4785 4786 4787 4788
          }
        }
      }
    }

    /* Clean up */
    RegCloseKey(key);
}
4789 4790 4791 4792

/****************************************************************************
 * WCMD_color
 *
4793
 * Colors the terminal screen.
4794 4795 4796 4797 4798 4799 4800
 */

void WCMD_color (void) {

  CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
  HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);

4801
  if (param1[0] != 0x00 && strlenW(param1) > 2) {
4802
    WCMD_output_stderr(WCMD_LoadMessage(WCMD_ARGERR));
4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820
    return;
  }

  if (GetConsoleScreenBufferInfo(hStdOut, &consoleInfo))
  {
      COORD topLeft;
      DWORD screenSize;
      DWORD color = 0;

      screenSize = consoleInfo.dwSize.X * (consoleInfo.dwSize.Y + 1);

      topLeft.X = 0;
      topLeft.Y = 0;

      /* Convert the color hex digits */
      if (param1[0] == 0x00) {
        color = defaultColor;
      } else {
4821
        color = strtoulW(param1, NULL, 16);
4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835
      }

      /* Fail if fg == bg color */
      if (((color & 0xF0) >> 4) == (color & 0x0F)) {
        errorlevel = 1;
        return;
      }

      /* Set the current screen contents and ensure all future writes
         remain this color                                             */
      FillConsoleOutputAttribute(hStdOut, color, screenSize, topLeft, &screenSize);
      SetConsoleTextAttribute(hStdOut, color);
  }
}