Tcl Source Code

Changes On Branch 0-day-21b0629c81
Login
EuroTcl/OpenACS 11 - 12 JULY 2024, VIENNA

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Changes In Branch 0-day-21b0629c81 Excluding Merge-Ins

This is equivalent to a diff from 19406e5bfb to 7f273d6639

2018-08-29
14:45
closes [21b0629c81] 0-day vulnerability - insufficient escape by exec of batch-files for windows check-in: 99af12fd19 user: sebres tags: core-8-5-branch
2018-08-23
10:26
code review, skip slow test winpipe-8.2 executed args from injectList particularly (normally winpipe... Closed-Leaf check-in: 7f273d6639 user: sebres tags: 0-day-21b0629c81
08:00
code review, restored backwards compatibility of the simplest escape of quote-chars (so reverted sev... check-in: 897a17c523 user: sebres tags: 0-day-21b0629c81
2018-08-20
14:35
win: fixes [21b0629c81] - exec/open process pipe under windows (0-day vulnerability - insufficient e... check-in: cc1a3445f7 user: sebres tags: 0-day-21b0629c81
2018-08-19
09:16
merge-mark check-in: 90a02cdaf2 user: jan.nijtmans tags: core-8-6-branch
2018-08-17
18:26
win: TclpCreateProcess or [exec process ...] - search for application extended with ".cmd" extension... check-in: 19406e5bfb user: sebres tags: core-8-5-branch
2018-07-26
16:46
test cases added to cover width overflow by format (should cause limit exceeded) check-in: 3b55e9c1e1 user: sebres tags: core-8-5-branch

Changes to library/tcltest/tcltest.tcl.

1238
1239
1240
1241
1242
1243
1244




1245
1246
1247
1248
1249
1250
1251
    ConstraintInitializer userInteraction {format 0}

    # Some tests must be skipped if the interpreter is not in
    # interactive mode

    ConstraintInitializer interactive \
	    {expr {[info exists ::tcl_interactive] && $::tcl_interactive}}





    # Some tests can only be run if the installation came from a CD
    # image instead of a web image.  Some tests must be skipped if you
    # are running as root on Unix.  Other tests can only be run if you
    # are running as root on Unix.

    ConstraintInitializer root {expr \







>
>
>
>







1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
    ConstraintInitializer userInteraction {format 0}

    # Some tests must be skipped if the interpreter is not in
    # interactive mode

    ConstraintInitializer interactive \
	    {expr {[info exists ::tcl_interactive] && $::tcl_interactive}}

    # Skip slow tests (to enable slow tests add parameter `-constraints slowTest`)

    ConstraintInitializer slowTest {format 0}

    # Some tests can only be run if the installation came from a CD
    # image instead of a web image.  Some tests must be skipped if you
    # are running as root on Unix.  Other tests can only be run if you
    # are running as root on Unix.

    ConstraintInitializer root {expr \

Changes to tests/winPipe.test.

304
305
306
307
308
309
310



311
312
313
314





































315
316
317
318
319
320
321
    puts -nonewline $f $big$big$big$big
    flush $f
    after 100 { lappend x timeout }
    vwait x
    lappend x [catch {close $f} msg] $msg
} {writable timeout 0 {}}




set path(echoArgs.tcl) [makeFile {
    puts "[list $argv0 $argv]"
} echoArgs.tcl]







































### validate the raw output of BuildCommandLine().
###
test winpipe-7.1 {BuildCommandLine: null arguments} {win exec} {
    exec $env(COMSPEC) /c echo foo "" bar
} {foo "" bar}
test winpipe-7.2 {BuildCommandLine: null arguments} {win exec} {







>
>
>
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
    puts -nonewline $f $big$big$big$big
    flush $f
    after 100 { lappend x timeout }
    vwait x
    lappend x [catch {close $f} msg] $msg
} {writable timeout 0 {}}

proc _testExecArgs {single args} {
    variable path
    if {![info exists path(echoArgs.tcl)] || ![file exists $path(echoArgs.tcl)]} {
	set path(echoArgs.tcl) [makeFile {
	    puts "[list [file tail $argv0] {*}$argv]"
	} echoArgs.tcl]
    }
    if {![info exists path(echoArgs.bat)] || ![file exists $path(echoArgs.bat)]} {
	set path(echoArgs.bat) [makeFile "@[file native [interpreter]] $path(echoArgs.tcl) %*" "echoArgs.bat"]
    }
    set cmds [list [list [interpreter] $path(echoArgs.tcl)]]
    if {!($single & 2)} {
	lappend cmds [list $path(echoArgs.bat)]
    } else {
	if {![info exists path(echoArgs2.bat)] || ![file exists $path(echoArgs2.bat)]} {
	    file mkdir [file join [temporaryDirectory] test(Dir)Check]
	    set path(echoArgs2.bat) [makeFile "@[file native [interpreter]] $path(echoArgs.tcl) %*" \
		"test(Dir)Check/echo(Cmd)Test Args & Batch.bat"]
	}
	lappend cmds [list $path(echoArgs2.bat)]
    }
    set broken {}
    foreach args $args {
	if {$single & 1} {
	    # enclose single test-arg between 1st/3rd to be sure nothing is truncated 
	    # (e. g. to cover unexpected trim by nts-zero case, and args don't recombined):
	    set args [list "1st" $args "3rd"]
	}
	set args [list {*}$args]; # normalized canonical list
	foreach cmd $cmds {
	    set e [linsert $args 0 [file tail $path(echoArgs.tcl)]]
	    tcltest::DebugPuts 4 "  ## test exec [file extension [lindex $cmd 0]] ($cmd) for\n  ##   $args"
	    if {[catch {
		exec {*}$cmd {*}$args
	    } r]} {
		set r "ERROR: $r"
	    }
	    if {$r ne $e} {
		append broken "\[ERROR\]: exec [file extension [lindex $cmd 0]] on $args\n  -- result:\n$r\n  -- expected:\n$e\n"
	    }
	}
    }
    return $broken
}

### validate the raw output of BuildCommandLine().
###
test winpipe-7.1 {BuildCommandLine: null arguments} {win exec} {
    exec $env(COMSPEC) /c echo foo "" bar
} {foo "" bar}
test winpipe-7.2 {BuildCommandLine: null arguments} {win exec} {
365
366
367
368
369
370
371


































































372
373
374
375

376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397












398
399



400








401
402

403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421

422
423
424
425
426
427
428
429






430



431

432
433
434
435
436
437
438
439
440
441
442
443

444
445
} {foo "\ \\\\\\\"" bar}
test winpipe-7.17 {BuildCommandLine: special chars #4} {win exec} {
    exec $env(COMSPEC) /c echo foo \{ bar
} "foo \{ bar"
test winpipe-7.18 {BuildCommandLine: special chars #5} {win exec} {
    exec $env(COMSPEC) /c echo foo \} bar
} "foo \} bar"



































































### validate the pass-thru from BuildCommandLine() to the crt's parse_cmdline().
###
test winpipe-8.1 {BuildCommandLine/parse_cmdline pass-thru: null arguments} {win exec} {

    exec [interpreter] $path(echoArgs.tcl) foo "" bar
} [list $path(echoArgs.tcl) [list foo {} bar]]
test winpipe-8.2 {BuildCommandLine/parse_cmdline pass-thru: null arguments} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) foo {} bar
} [list $path(echoArgs.tcl) [list foo {} bar]]
test winpipe-8.3 {BuildCommandLine/parse_cmdline pass-thru: dbl quote quoting #1} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) foo "\"" bar
} [list $path(echoArgs.tcl) [list foo "\"" bar]]
test winpipe-8.4 {BuildCommandLine/parse_cmdline pass-thru: dbl quote quoting #2} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) foo {""} bar
} [list $path(echoArgs.tcl) [list foo {""} bar]]
test winpipe-8.5 {BuildCommandLine/parse_cmdline pass-thru: dbl quote quoting #3} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) foo "\" " bar
} [list $path(echoArgs.tcl) [list foo "\" " bar]]
test winpipe-8.6 {BuildCommandLine/parse_cmdline pass-thru: dbl quote quoting #4} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) foo {a="b"} bar
} [list $path(echoArgs.tcl) [list foo {a="b"} bar]]
test winpipe-8.7 {BuildCommandLine/parse_cmdline pass-thru: dbl quote quoting #5} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) foo {a = "b"} bar
} [list $path(echoArgs.tcl) [list foo {a = "b"} bar]]
test winpipe-8.8 {BuildCommandLine/parse_cmdline pass-thru: dbl quote quoting #6} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) {"hello"} {""hello""} {"""hello"""} {"\"hello\""} {he llo} {he " llo}












} [list $path(echoArgs.tcl) [list {"hello"} {""hello""} {"""hello"""} {"\"hello\""} {he llo} {he " llo}]]
test winpipe-8.9 {BuildCommandLine/parse_cmdline pass-thru: N backslashes followed a quote rule #1} {win exec} {



    exec [interpreter] $path(echoArgs.tcl) foo \\ bar








} [list $path(echoArgs.tcl) [list foo \\ bar]]
test winpipe-8.10 {BuildCommandLine/parse_cmdline pass-thru: N backslashes followed a quote rule #2} {win exec} {

    exec [interpreter] $path(echoArgs.tcl) foo \\\\ bar
} [list $path(echoArgs.tcl) [list foo \\\\ bar]]
test winpipe-8.11 {BuildCommandLine/parse_cmdline pass-thru: N backslashes followed a quote rule #3} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) foo \\\ \\ bar
} [list $path(echoArgs.tcl) [list foo \\\ \\ bar]]
test winpipe-8.12 {BuildCommandLine/parse_cmdline pass-thru: N backslashes followed a quote rule #4} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) foo \\\ \\\\ bar
} [list $path(echoArgs.tcl) [list foo \\\ \\\\ bar]]
test winpipe-8.13 {BuildCommandLine/parse_cmdline pass-thru: N backslashes followed a quote rule #5} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) foo \\\ \\\\\\ bar
} [list $path(echoArgs.tcl) [list foo \\\ \\\\\\ bar]]
test winpipe-8.14 {BuildCommandLine/parse_cmdline pass-thru: N backslashes followed a quote rule #6} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) foo \\\ \\\" bar
} [list $path(echoArgs.tcl) [list foo \\\ \\\" bar]]
test winpipe-8.15 {BuildCommandLine/parse_cmdline pass-thru: N backslashes followed a quote rule #7} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) foo \\\ \\\\\" bar
} [list $path(echoArgs.tcl) [list foo \\\ \\\\\" bar]]
test winpipe-8.16 {BuildCommandLine/parse_cmdline pass-thru: N backslashes followed a quote rule #8} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) foo \\\ \\\\\\\" bar

} [list $path(echoArgs.tcl) [list foo \\\ \\\\\\\" bar]]
test winpipe-8.17 {BuildCommandLine/parse_cmdline pass-thru: special chars #1} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) foo \{ bar
} [list $path(echoArgs.tcl) [list foo \{ bar]]
test winpipe-8.18 {BuildCommandLine/parse_cmdline pass-thru: special chars #2} {win exec} {
    exec [interpreter] $path(echoArgs.tcl) foo \} bar
} [list $path(echoArgs.tcl) [list foo \} bar]]
test winpipe-8.19 {ensure parse_cmdline isn't doing wildcard replacement} {win exec} {






    exec [interpreter] $path(echoArgs.tcl) foo * makefile.?c bar



} [list $path(echoArgs.tcl) [list foo * makefile.?c bar]]


# restore old values for env(TMP) and env(TEMP)

if {[catch {set env(TMP) $env_tmp}]} {
    unset env(TMP)
}
if {[catch {set env(TEMP) $env_temp}]} {
    unset env(TEMP)
}

# cleanup
file delete big little stdout stderr nothing echoArgs.tcl

::tcltest::cleanupTests
return







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



|
>
|
|
<
<
|
<
<
|
<
<
|
<
<
|
<
<
|
<
<
|
<
|
>
>
>
>
>
>
>
>
>
>
>
>
|
|
>
>
>
|
>
>
>
>
>
>
>
>
|
|
>
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
>
|
|
|
|
|
|
|
|
>
>
>
>
>
>
|
>
>
>
|
>











|
>


405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484


485


486


487


488


489


490

491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522

523
524
525
526
527
528
529
530
531
532
533
534
535
536

537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
} {foo "\ \\\\\\\"" bar}
test winpipe-7.17 {BuildCommandLine: special chars #4} {win exec} {
    exec $env(COMSPEC) /c echo foo \{ bar
} "foo \{ bar"
test winpipe-7.18 {BuildCommandLine: special chars #5} {win exec} {
    exec $env(COMSPEC) /c echo foo \} bar
} "foo \} bar"

set injectList {
    {test"whoami}     {test""whoami}
    {test"""whoami}   {test""""whoami}

    "test\"whoami\\"     "test\"\"whoami\\"
    "test\"\"\"whoami\\" "test\"\"\"\"whoami\\"

    {test\\&\\test}    {test"\\&\\test}
    {"test\\&\\test}   {"test"\\&\\"test"}
    {test\\"&"\\test}  {test"\\"&"\\test}
    {"test\\"&"\\test} {"test"\\"&"\\"test"}

    {test\"&whoami}    {test"\"&whoami}
    {test""\"&whoami}  {test"""\"&whoami}
    {test\"\&whoami}   {test"\"\&whoami}
    {test""\"\&whoami} {test"""\"\&whoami}

    {test&whoami}    {test|whoami}
    {"test&whoami}   {"test|whoami}
    {test"&whoami}   {test"|whoami}
    {"test"&whoami}  {"test"|whoami}
    {""test"&whoami} {""test"|whoami}

    {test&echo "}    {test|echo "}
    {"test&echo "}   {"test|echo "}
    {test"&echo "}   {test"|echo "}
    {"test"&echo "}  {"test"|echo "}
    {""test"&echo "} {""test"|echo "}

    {test&echo ""}    {test|echo ""}
    {"test&echo ""}   {"test|echo ""}
    {test"&echo ""}   {test"|echo ""}
    {"test"&echo ""}  {"test"|echo ""}
    {""test"&echo ""} {""test"|echo ""}

    {test>whoami}    {test<whoami}
    {"test>whoami}   {"test<whoami}
    {test">whoami}   {test"<whoami}
    {"test">whoami}  {"test"<whoami}
    {""test">whoami} {""test"<whoami}
    {test(whoami)}   {test(whoami)}
    {test"(whoami)}  {test"(whoami)}
    {test^whoami}    {test^^echo ^^^}
    {test"^whoami}   {test"^^echo ^^^}
    {test"^echo ^^^"} {test""^echo" ^^^"}

    {test%USERDOMAIN%\%USERNAME%}
    {test" %USERDOMAIN%\%USERNAME%}
    {test%USERDOMAIN%\\%USERNAME%}
    {test" %USERDOMAIN%\\%USERNAME%}
    {test%USERDOMAIN%&%USERNAME%}
    {test" %USERDOMAIN%&%USERNAME%}
    {test%USERDOMAIN%\&\%USERNAME%}
    {test" %USERDOMAIN%\&\%USERNAME%}

    {test%USERDOMAIN%\&\test}
    {test" %USERDOMAIN%\&\test}
    {test%USERDOMAIN%\\&\\test}
    {test" %USERDOMAIN%\\&\\test}

    {test%USERDOMAIN%\&\"test}
    {test" %USERDOMAIN%\&\"test}
    {test%USERDOMAIN%\\&\\"test}
    {test" %USERDOMAIN%\\&\\"test}
}

### validate the pass-thru from BuildCommandLine() to the crt's parse_cmdline().
###
test winpipe-8.1 {BuildCommandLine/parse_cmdline pass-thru: dumped arguments are equal original} \
-constraints {win exec} -body {
    _testExecArgs 0 \
	[list foo "" bar] \


	[list foo {} bar] \


	[list foo "\"" bar] \


	[list foo {""} bar] \


	[list foo "\" " bar] \


	[list foo {a="b"} bar] \


	[list foo {a = "b"} bar] \

	[list {"hello"} {""hello""} {"""hello"""} {"\"hello\""} {he llo} {he " llo}] \
	[list foo \\ bar] \
	[list foo \\\\ bar] \
	[list foo \\\ \\ bar] \
	[list foo \\\ \\\\ bar] \
	[list foo \\\ \\\\\\ bar] \
	[list foo \\\ \\\" bar] \
	[list foo \\\ \\\\\" bar] \
	[list foo \\\ \\\\\\\" bar] \
	[list foo \{ bar] \
	[list foo \} bar] \
	[list foo * makefile.?c bar]
} -result {}

test winpipe-8.2 {BuildCommandLine/parse_cmdline pass-thru: check injection on special meta-chars (particular)} \
-constraints {win exec slowTest} -body {
    _testExecArgs 1 {*}$injectList
} -result {}

test winpipe-8.3 {BuildCommandLine/parse_cmdline pass-thru: check injection on special meta-chars (jointly)} \
-constraints {win exec} -body {
    _testExecArgs 0 \
	[list START     {*}$injectList END] \
	[list "START\"" {*}$injectList END] \
	[list START     {*}$injectList "\"END"] \
	[list "START\"" {*}$injectList "\"END"]
} -result {}

test winpipe-8.4 {BuildCommandLine/parse_cmdline pass-thru: check injection on special meta-chars (command/jointly args)} \
-constraints {win exec} -body {
    _testExecArgs 2 \
	[list START     {*}$injectList END] \

	[list "START\"" {*}$injectList END] \
	[list START     {*}$injectList "\"END"] \
	[list "START\"" {*}$injectList "\"END"]
} -result {}

test winpipe-8.5 {BuildCommandLine/parse_cmdline pass-thru: check injection on special meta-chars (random mix)} \
-constraints {win exec} -body {
    set lst {}
    set maps {
	{\&|^<>!()%}
	{\&|^<>!()% }
	{"\&|^<>!()%}
	{"\&|^<>!()% }
	{"""""\\\\\&|^<>!()%}

	{"""""\\\\\&|^<>!()% }
    }
    set i 0
    time {
	set args {[incr i].}
	time {
	    set map [lindex $maps [expr {int(rand()*[llength $maps])}]]
	    # be sure arg has some prefix (avoid special handling, like |& etc)
	    set a {x}
	    while {[string length $a] < 50} {
		append a [string index $map [expr {int(rand()*[string length $map])}]]
	    }
	    lappend args $a
	} 20
	lappend lst $args
    } 10
    _testExecArgs 0 {*}$lst
} -result {} -cleanup {
    unset -nocomplain lst args a map maps
}

rename _testExecArgs {}

# restore old values for env(TMP) and env(TEMP)

if {[catch {set env(TMP) $env_tmp}]} {
    unset env(TMP)
}
if {[catch {set env(TEMP) $env_temp}]} {
    unset env(TEMP)
}

# cleanup
file delete big little stdout stderr nothing echoArgs.tcl echoArgs.bat 
file delete -force [file join [temporaryDirectory] test(Dir)Check]
::tcltest::cleanupTests
return

Changes to win/tclWinPipe.c.

1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
    if (applType == APPL_NONE) {
	TclWinConvertError(GetLastError());
	Tcl_AppendResult(interp, "couldn't execute \"", originalName,
		"\": ", Tcl_PosixError(interp), (char *) NULL);
	return APPL_NONE;
    }

    if ((applType == APPL_DOS) || (applType == APPL_WIN3X)) {
	/*
	 * Replace long path name of executable with short path name for
	 * 16-bit applications. Otherwise the application may not be able to
	 * correctly parse its own command line to separate off the
	 * application name from the arguments.
	 */








|







1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
    if (applType == APPL_NONE) {
	TclWinConvertError(GetLastError());
	Tcl_AppendResult(interp, "couldn't execute \"", originalName,
		"\": ", Tcl_PosixError(interp), (char *) NULL);
	return APPL_NONE;
    }

    if (applType == APPL_WIN3X) {
	/*
	 * Replace long path name of executable with short path name for
	 * 16-bit applications. Otherwise the application may not be able to
	 * correctly parse its own command line to separate off the
	 * application name from the arguments.
	 */

1522
1523
1524
1525
1526
1527
1528
1529















1530

































































1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541












1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562

1563
1564
1565
1566
1567
1568




1569

1570


1571
1572
1573

1574



1575















1576

1577
1578




1579
1580

1581
1582
1583
1584
1585
1586
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
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */
















static void

































































BuildCommandLine(
    const char *executable,	/* Full path of executable (including
				 * extension). Replacement for argv[0]. */
    int argc,			/* Number of arguments. */
    const char **argv,		/* Argument strings in UTF. */
    Tcl_DString *linePtr)	/* Initialized Tcl_DString that receives the
				 * command line (TCHAR). */
{
    const char *arg, *start, *special;
    int quote, i;
    Tcl_DString ds;













    Tcl_DStringInit(&ds);

    /*
     * Prime the path. Add a space separator if we were primed with something.
     */

    Tcl_DStringAppend(&ds, Tcl_DStringValue(linePtr), -1);
    if (Tcl_DStringLength(linePtr) > 0) {
	Tcl_DStringAppend(&ds, " ", 1);
    }

    for (i = 0; i < argc; i++) {
	if (i == 0) {
	    arg = executable;
	} else {
	    arg = argv[i];
	    Tcl_DStringAppend(&ds, " ", 1);
	}

	quote = 0;

	if (arg[0] == '\0') {
	    quote = 1;
	} else {
	    int count;
	    Tcl_UniChar ch;
	    for (start = arg; *start != '\0'; start += count) {




		count = Tcl_UtfToUniChar(start, &ch);

		if (Tcl_UniCharIsSpace(ch)) {	/* INTL: ISO space. */


		    quote = 1;
		    break;
		}

	    }



	}















	if (quote) {

	    Tcl_DStringAppend(&ds, "\"", 1);
	}




	start = arg;
	for (special = arg; ; ) {

	    if ((*special == '\\') && (special[1] == '\\' ||
		    special[1] == '"' || (quote && special[1] == '\0'))) {
		Tcl_DStringAppend(&ds, start, (int) (special - start));
		start = special;
		while (1) {
		    special++;
		    if (*special == '"' || (quote && *special == '\0')) {

			/*


			 * N backslashes followed a quote -> insert N * 2 + 1


			 * backslashes then a quote.
			 */







			Tcl_DStringAppend(&ds, start,
				(int) (special - start));
			break;
		    }

		    if (*special != '\\') {
			break;
		    }
		}
		Tcl_DStringAppend(&ds, start, (int) (special - start));

		start = special;

	    }
	    if (*special == '"') {
		Tcl_DStringAppend(&ds, start, (int) (special - start));
		Tcl_DStringAppend(&ds, "\\\"", 2);
		start = special + 1;
	    }

	    if (*special == '\0') {
		break;
	    }
	    special++;
	}
	Tcl_DStringAppend(&ds, start, (int) (special - start));
	if (quote) {

	    Tcl_DStringAppend(&ds, "\"", 1);
	}
    }
    Tcl_DStringFree(linePtr);
    Tcl_WinUtfToTChar(Tcl_DStringValue(&ds), Tcl_DStringLength(&ds), linePtr);
    Tcl_DStringFree(&ds);
}








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








|
|

>
>
>
>
>
>
>
>
>
>
>
>




















|
>

|



|
>
>
>
>

>
|
>
>
|
|
|
>
|
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>


>
>
>
>
|
|
>
|
<
|
<
<
|
|
>
|
>
>
|
>
>
|
<
>
>
>
>
>
>
|
|
|
|
|
>
|
<
<
<
|
>
|
>
|
|
|
<
|

>
|
|
|
<
<
<
|
>







1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
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
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706

1707


1708
1709
1710
1711
1712
1713
1714
1715
1716
1717

1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730



1731
1732
1733
1734
1735
1736
1737

1738
1739
1740
1741
1742
1743



1744
1745
1746
1747
1748
1749
1750
1751
1752
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static const char *
BuildCmdLineBypassBS(
    const char *current,
    const char **bspos
) {
    /* mark first backslash possition */
    if (!*bspos) {
	*bspos = current;
    }
    do {
	current++;
    } while (*current == '\\');
    return current;
}

static void
QuoteCmdLineBackslash(
    Tcl_DString *dsPtr,
    const char *start,
    const char *current,
    const char *bspos
) {
    if (!bspos) {
	if (current > start) { /* part before current (special) */
	    Tcl_DStringAppend(dsPtr, start, (int) (current - start));
	}
    } else {
    	if (bspos > start) { /* part before first backslash */
	    Tcl_DStringAppend(dsPtr, start, (int) (bspos - start));
	}
	while (bspos++ < current) { /* each backslash twice */
	    Tcl_DStringAppend(dsPtr, "\\\\", 2);
	}
    }
}

static const char *
QuoteCmdLinePart(
    Tcl_DString *dsPtr,
    const char *start,
    const char *special,
    const char *specMetaChars,
    const char **bspos
) {
    if (!*bspos) {
	/* rest before special (before quote) */
	QuoteCmdLineBackslash(dsPtr, start, special, NULL);
	start = special;
    } else {
	/* rest before first backslash and backslashes into new quoted block */
	QuoteCmdLineBackslash(dsPtr, start, *bspos, NULL);
	start = *bspos;
    }
    /* 
     * escape all special chars enclosed in quotes like `"..."`, note that here we 
     * don't must escape `\` (with `\`), because it's outside of the main quotes,
     * so `\` remains `\`, but important - not at end of part, because results as 
     * before the quote,  so `%\%\` should be escaped as `"%\%"\\`).
     */
    Tcl_DStringAppend(dsPtr, "\"", 1); /* opening escape quote-char */
    do {
    	*bspos = NULL;
	special++;
	if (*special == '\\') {
	    /* bypass backslashes (and mark first backslash possition)*/
	    special = BuildCmdLineBypassBS(special, bspos);
	    if (*special == '\0') break;
	}
    } while (*special && strchr(specMetaChars, *special));
    if (!*bspos) {
	/* unescaped rest before quote */
	QuoteCmdLineBackslash(dsPtr, start, special, NULL);
    } else {
	/* unescaped rest before first backslash (rather belongs to the main block) */
	QuoteCmdLineBackslash(dsPtr, start, *bspos, NULL);
    }
    Tcl_DStringAppend(dsPtr, "\"", 1); /* closing escape quote-char */
    return special;
}

static void
BuildCommandLine(
    const char *executable,	/* Full path of executable (including
				 * extension). Replacement for argv[0]. */
    int argc,			/* Number of arguments. */
    const char **argv,		/* Argument strings in UTF. */
    Tcl_DString *linePtr)	/* Initialized Tcl_DString that receives the
				 * command line (TCHAR). */
{
    const char *arg, *start, *special, *bspos;
    int quote = 0, i;
    Tcl_DString ds;

    /* characters to enclose in quotes if unpaired quote flag set */
    const static char *specMetaChars = "&|^<>!()%";
    /* characters to enclose in quotes in any case (regardless unpaired-flag) */
    const static char *specMetaChars2 = "%";

    /* Quote flags:
     *   CL_ESCAPE   - escape argument;
     *   CL_QUOTE    - enclose in quotes;
     *   CL_UNPAIRED - previous arguments chain contains unpaired quote-char;
     */
    enum {CL_ESCAPE = 1, CL_QUOTE = 2, CL_UNPAIRED = 4};

    Tcl_DStringInit(&ds);

    /*
     * Prime the path. Add a space separator if we were primed with something.
     */

    Tcl_DStringAppend(&ds, Tcl_DStringValue(linePtr), -1);
    if (Tcl_DStringLength(linePtr) > 0) {
	Tcl_DStringAppend(&ds, " ", 1);
    }

    for (i = 0; i < argc; i++) {
	if (i == 0) {
	    arg = executable;
	} else {
	    arg = argv[i];
	    Tcl_DStringAppend(&ds, " ", 1);
	}

	quote &= ~(CL_ESCAPE|CL_QUOTE); /* reset escape flags */
	bspos = NULL;
	if (arg[0] == '\0') {
	    quote = CL_QUOTE;
	} else {
	    int count;
	    Tcl_UniChar ch;
	    for (start = arg;
		*start != '\0' &&
		    (quote & (CL_ESCAPE|CL_QUOTE)) != (CL_ESCAPE|CL_QUOTE);
		start += count
	    ) {
		count = Tcl_UtfToUniChar(start, &ch);
		if (count > 1) continue;
		if (Tcl_UniCharIsSpace(ch)) {
		    quote |= CL_QUOTE; /* quote only */
		    if (bspos) { /* if backslash found - escape & quote */
			quote |= CL_ESCAPE;
			break;
		    }
		    continue;
		}
		if (strchr(specMetaChars, *start)) {
		    quote |= (CL_ESCAPE|CL_QUOTE); /*escape & quote */
		    break;
		}
		if (*start == '"') {
		    quote |= CL_ESCAPE; /* escape only */
		    continue;
		}
		if (*start == '\\') {
		    bspos = start;
		    if (quote & CL_QUOTE) { /* if quote - escape & quote */
			quote |= CL_ESCAPE;
			break;
		    }
		    continue;
		}
	    }
	    bspos = NULL;
	}
	if (quote & CL_QUOTE) {
	    /* start of argument (main opening quote-char) */
	    Tcl_DStringAppend(&ds, "\"", 1);
	}
	if (!(quote & CL_ESCAPE)) {
	    /* nothing to escape */
	    Tcl_DStringAppend(&ds, arg, -1);
	} else {
	    start = arg;
	    for (special = arg; *special != '\0'; ) {
		/* position of `\` is important before quote or at end (equal `\"` because quoted) */
		if (*special == '\\') {

		    /* bypass backslashes (and mark first backslash possition)*/


		    special = BuildCmdLineBypassBS(special, &bspos);
		    if (*special == '\0') break;
		}
		/* ["] */
		if (*special == '"') {
		    quote ^= CL_UNPAIRED; /* invert unpaired flag - observe unpaired quotes */
		    /* add part before (and escape backslashes before quote) */
		    QuoteCmdLineBackslash(&ds, start, special, bspos);
		    bspos = NULL;
		    /* escape using backslash */

		    Tcl_DStringAppend(&ds, "\\\"", 2);
		    start = ++special;
		    continue;
		}
		/* unpaired (escaped) quote causes special handling on meta-chars */
		if ((quote & CL_UNPAIRED) && strchr(specMetaChars, *special)) {
		    special = QuoteCmdLinePart(&ds, start, special, specMetaChars, &bspos);
		    /* start to current or first backslash */
		    start = !bspos ? special : bspos;
		    continue;
		}
		/* special case for % - should be enclosed always (paired also) */
		if (strchr(specMetaChars2, *special)) {



		    special = QuoteCmdLinePart(&ds, start, special, specMetaChars2, &bspos);
		    /* start to current or first backslash */
		    start = !bspos ? special : bspos;
		    continue;
		}
		/* other not special (and not meta) character */
		bspos = NULL; /* reset last backslash possition (not interesting) */

		special++;
	    }
	    /* rest of argument (and escape backslashes before closing main quote) */
	    QuoteCmdLineBackslash(&ds, start, special, 
	    	(quote & CL_QUOTE) ? bspos : NULL);
	}



	if (quote & CL_QUOTE) {
	    /* end of argument (main closing quote-char) */
	    Tcl_DStringAppend(&ds, "\"", 1);
	}
    }
    Tcl_DStringFree(linePtr);
    Tcl_WinUtfToTChar(Tcl_DStringValue(&ds), Tcl_DStringLength(&ds), linePtr);
    Tcl_DStringFree(&ds);
}