Source

xemacs-21.4 / src / process-nt.c

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
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
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
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
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
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
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
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
/* Asynchronous subprocess implementation for Win32
   Copyright (C) 1985, 1986, 1987, 1988, 1992, 1993, 1994, 1995
   Free Software Foundation, Inc.
   Copyright (C) 1995 Sun Microsystems, Inc.
   Copyright (C) 1995, 1996, 2000 Ben Wing.

This file is part of XEmacs.

XEmacs is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.

XEmacs 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 General Public License
for more details.

You should have received a copy of the GNU General Public License
along with XEmacs; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */

/* Written by Kirill M. Katsnelson <kkm@kis.ru>, April 1998 */

#include <config.h>
#include "lisp.h"

#include "buffer.h"
#include "console-msw.h"
#include "hash.h"
#include "lstream.h"
#include "nt.h"
#include "process.h"
#include "procimpl.h"
#include "sysdep.h"

#include <shellapi.h>
#ifdef __MINGW32__
#include <errno.h>
#endif
#include <signal.h>
#ifdef HAVE_SOCKETS
#include <winsock.h>
#endif

/* Arbitrary size limit for code fragments passed to run_in_other_process */
#define FRAGMENT_CODE_SIZE 32

/* Implementation-specific data. Pointed to by Lisp_Process->process_data */
struct nt_process_data
{
  HANDLE h_process;
  DWORD dwProcessId;
  HWND hwnd; /* console window */
  int need_enable_child_signals;
};

/* Control how args are quoted to ensure correct parsing by child
   process. */
Lisp_Object Vmswindows_quote_process_args;

/* Control whether create_child causes the process to inherit Emacs'
   console window, or be given a new one of its own.  The default is
   nil, to allow multiple DOS programs to run on Win95.  Having separate
   consoles also allows Emacs to cleanly terminate process groups.  */
Lisp_Object Vmswindows_start_process_share_console;

/* Control whether create_child cause the process to inherit Emacs'
   error mode setting.  The default is t, to minimize the possibility of
   subprocesses blocking when accessing unmounted drives.  */
Lisp_Object Vmswindows_start_process_inherit_error_mode;

#define NT_DATA(p) ((struct nt_process_data*)((p)->process_data))

/*-----------------------------------------------------------------------*/
/* Process helpers							 */
/*-----------------------------------------------------------------------*/

/* This one breaks process abstraction. Prototype is in console-msw.h,
   used by select_process method in event-msw.c */
HANDLE
get_nt_process_handle (Lisp_Process *p)
{
  return (NT_DATA (p)->h_process);
}

static struct Lisp_Process *
find_process_from_pid (DWORD pid)
{
  Lisp_Object tail, proc;

  for (tail = Vprocess_list; CONSP (tail); tail = XCDR (tail))
    {
      proc = XCAR (tail);
      if (NT_DATA (XPROCESS (proc))->dwProcessId == pid)
	return XPROCESS (proc);
    }
  return 0;
}


/*-----------------------------------------------------------------------*/
/* Running remote threads. See Microsoft Systems Journal 1994 Number 5	 */
/* Jeffrey Richter, Load Your 32-bit DLL into Another Process's Address..*/
/*-----------------------------------------------------------------------*/

typedef struct
{
  HANDLE h_process;
  HANDLE h_thread;
  LPVOID address;
} process_memory;

/*
 * Allocate SIZE bytes in H_PROCESS address space. Fill in PMC used
 * further by other routines. Return nonzero if successful.
 *
 * The memory in other process is allocated by creating a suspended
 * thread. Initial stack of that thread is used as the memory
 * block. The thread entry point is the routine ExitThread in
 * kernel32.dll, so the allocated memory is freed just by resuming the 
 * thread, which immediately terminates after that.
 */

static int 
alloc_process_memory (HANDLE h_process, size_t size,
		      process_memory* pmc)
{
  LPTHREAD_START_ROUTINE adr_ExitThread =
    (LPTHREAD_START_ROUTINE)
    GetProcAddress (GetModuleHandle ("kernel32"), "ExitThread");
  DWORD dw_unused;
  CONTEXT context;
  MEMORY_BASIC_INFORMATION mbi;

  pmc->h_process = h_process;
  pmc->h_thread = CreateRemoteThread (h_process, NULL, size,
				     adr_ExitThread, NULL,
				     CREATE_SUSPENDED, &dw_unused);
  if (pmc->h_thread == NULL)
    return 0;

  /* Get context, for thread's stack pointer */
  context.ContextFlags = CONTEXT_CONTROL;
  if (!GetThreadContext (pmc->h_thread, &context))
    goto failure;

  /* Determine base address of the committed range */
  if (sizeof(mbi) != VirtualQueryEx (h_process,
#if defined (_X86_)
				     (LPDWORD)context.Esp - 1,
#elif defined (_ALPHA_)
				     (LPDWORD)context.IntSp - 1,
#else
#error Unknown processor architecture
#endif
				     &mbi, sizeof(mbi)))
    goto failure;

  /* Change the page protection of the allocated memory to executable,
     read, and write. */
  if (!VirtualProtectEx (h_process, mbi.BaseAddress, size,
			 PAGE_EXECUTE_READWRITE, &dw_unused))
    goto failure;

  pmc->address = mbi.BaseAddress;
  return 1;

 failure:
  ResumeThread (pmc->h_thread);
  pmc->address = 0;
  return 0;
}

static void
free_process_memory (process_memory* pmc)
{
  ResumeThread (pmc->h_thread);
}

/*
 * Run ROUTINE in the context of process determined by H_PROCESS. The
 * routine is passed the address of DATA as parameter. The ROUTINE must
 * not be longer than ROUTINE_CODE_SIZE bytes. DATA_SIZE is the size of
 * DATA structure.
 *
 * Note that the code must be positionally independent, and compiled
 * without stack checks (they cause implicit calls into CRT so will
 * fail). DATA should not refer any data in calling process, as both
 * routine and its data are copied into remote process. Size of data
 * and code together should not exceed one page (4K on x86 systems).
 *
 * Return the value returned by ROUTINE, or (DWORD)-1 if call failed.
 */
static DWORD
run_in_other_process (HANDLE h_process,
		      LPTHREAD_START_ROUTINE routine,
		      LPVOID data, size_t data_size)
{
  process_memory pm;
  const size_t code_size = FRAGMENT_CODE_SIZE;
  /* Need at most 3 extra bytes of memory, for data alignment */
  size_t total_size = code_size + data_size + 3;
  LPVOID remote_data;
  HANDLE h_thread;
  DWORD dw_unused;

  /* Allocate memory */
  if (!alloc_process_memory (h_process, total_size, &pm))
    return (DWORD)-1;

  /* Copy code */
  if (!WriteProcessMemory (h_process, pm.address, (LPVOID)routine,
			   code_size, NULL))
    goto failure;

  /* Copy data */
  if (data_size)
    {
      remote_data = (LPBYTE)pm.address + ((code_size + 4) & ~3);
      if (!WriteProcessMemory (h_process, remote_data, data, data_size, NULL))
	goto failure;
    }
  else
    remote_data = NULL;

  /* Execute the remote copy of code, passing it remote data */
  h_thread = CreateRemoteThread (h_process, NULL, 0,
				 (LPTHREAD_START_ROUTINE) pm.address,
				 remote_data, 0, &dw_unused);
  if (h_thread == NULL)
    goto failure;

  /* Wait till thread finishes */
  WaitForSingleObject (h_thread, INFINITE);

  /* Free remote memory */
  free_process_memory (&pm);

  /* Return thread's exit code */
  {
    DWORD exit_code;
    GetExitCodeThread (h_thread, &exit_code);
    CloseHandle (h_thread);
    return exit_code;
  }

 failure:
  free_process_memory (&pm);
  return (DWORD)-1;
}

/*-----------------------------------------------------------------------*/
/* Sending signals							 */
/*-----------------------------------------------------------------------*/

/* ---------------------------- the NT way ------------------------------- */

/*
 * We handle the following signals:
 *
 * SIGKILL, SIGTERM, SIGQUIT, SIGHUP - These four translate to ExitProcess
 *    executed by the remote process
 * SIGINT - The remote process is sent CTRL_BREAK_EVENT
 *
 * The MSVC5.0 compiler feels free to re-order functions within a
 * compilation unit, so we have no way of finding out the size of the
 * following functions. Therefore these functions must not be larger than
 * FRAGMENT_CODE_SIZE.
 */

/*
 * Sending SIGKILL
 */
typedef struct
{
  void (WINAPI *adr_ExitProcess) (UINT);
} sigkill_data;

static DWORD WINAPI
sigkill_proc (sigkill_data* data)
{
  (*data->adr_ExitProcess)(255);
  return 1;
}

/*
 * Sending break or control c
 */
typedef struct
{
  BOOL (WINAPI *adr_GenerateConsoleCtrlEvent) (DWORD, DWORD);
  DWORD event;
} sigint_data;

static DWORD WINAPI
sigint_proc (sigint_data* data)
{
  return (*data->adr_GenerateConsoleCtrlEvent) (data->event, 0);
}

/*
 * Enabling signals
 */
typedef struct
{
  BOOL (WINAPI *adr_SetConsoleCtrlHandler) (LPVOID, BOOL);
} sig_enable_data;

static DWORD WINAPI
sig_enable_proc (sig_enable_data* data)
{
  (*data->adr_SetConsoleCtrlHandler) (NULL, FALSE);
  return 1;
}

/*
 * Send signal SIGNO to process H_PROCESS.
 * Return nonzero if successful.
 */

static int
send_signal_the_nt_way (struct nt_process_data *cp, int pid, int signo)
{
  HANDLE h_process;
  HMODULE h_kernel = GetModuleHandle ("kernel32");
  int close_process = 0;
  DWORD retval;
  
  assert (h_kernel != NULL);
  
  if (cp)
    {
      pid = cp->dwProcessId;
      h_process = cp->h_process;
    }
  else
    {
      close_process = 1;
      /* Try to open the process with required privileges */
      h_process = OpenProcess (PROCESS_CREATE_THREAD
			       | PROCESS_QUERY_INFORMATION 
			       | PROCESS_VM_OPERATION
			       | PROCESS_VM_WRITE,
			       FALSE, pid);
      if (!h_process)
	return 0;
    }

  switch (signo)
    {
    case SIGKILL:
    case SIGTERM:
    case SIGQUIT:
    case SIGHUP:
      {
	sigkill_data d;

	d.adr_ExitProcess =
	  (void (WINAPI *) (UINT)) GetProcAddress (h_kernel, "ExitProcess");
	assert (d.adr_ExitProcess);
	retval = run_in_other_process (h_process, 
				       (LPTHREAD_START_ROUTINE)sigkill_proc,
				       &d, sizeof (d));
	break;
      }
    case SIGINT:
      {
	sigint_data d;
	d.adr_GenerateConsoleCtrlEvent =
	  (BOOL (WINAPI *) (DWORD, DWORD))
	  GetProcAddress (h_kernel, "GenerateConsoleCtrlEvent");
	assert (d.adr_GenerateConsoleCtrlEvent);
	d.event = CTRL_C_EVENT;
	retval = run_in_other_process (h_process, 
				       (LPTHREAD_START_ROUTINE)sigint_proc,
				       &d, sizeof (d));
	break;
      }
    default:
      assert (0);
    }

  if (close_process)
    CloseHandle (h_process);
  return (int)retval > 0 ? 1 : 0;
}

/*
 * Enable CTRL_C_EVENT handling in a new child process
 */
static void
enable_child_signals (HANDLE h_process)
{
  HMODULE h_kernel = GetModuleHandle ("kernel32");
  sig_enable_data d;
  
  assert (h_kernel != NULL);
  d.adr_SetConsoleCtrlHandler =
    (BOOL (WINAPI *) (LPVOID, BOOL))
    GetProcAddress (h_kernel, "SetConsoleCtrlHandler");
  assert (d.adr_SetConsoleCtrlHandler);
  run_in_other_process (h_process, (LPTHREAD_START_ROUTINE)sig_enable_proc,
			&d, sizeof (d));
}
  
#pragma warning (default : 4113)

/* ---------------------------- the 95 way ------------------------------- */

static BOOL CALLBACK
find_child_console (HWND hwnd, struct nt_process_data *cp)
{
  DWORD thread_id;
  DWORD process_id;

  thread_id = GetWindowThreadProcessId (hwnd, &process_id);
  if (process_id == cp->dwProcessId)
    {
      char window_class[32];

      GetClassName (hwnd, window_class, sizeof (window_class));
      if (strcmp (window_class,
		  msw_windows9x_p ()
		  ? "tty"
		  : "ConsoleWindowClass") == 0)
	{
	  cp->hwnd = hwnd;
	  return FALSE;
	}
    }
  /* keep looking */
  return TRUE;
}

static int
send_signal_the_95_way (struct nt_process_data *cp, int pid, int signo)
{
  HANDLE h_process;
  int close_process = 0;
  int rc = 1;
  
  if (cp)
    {
      pid = cp->dwProcessId;
      h_process = cp->h_process;

      /* Try to locate console window for process. */
      EnumWindows (find_child_console, (LPARAM) cp);
    }
  else
    {
      close_process = 1;
      /* Try to open the process with required privileges */
      h_process = OpenProcess (PROCESS_TERMINATE, FALSE, pid);
      if (!h_process)
	return 0;
    }
    
  if (signo == SIGINT)
    {
      if (NILP (Vmswindows_start_process_share_console) && cp && cp->hwnd)
	{
	  BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
	  BYTE vk_break_code = VK_CANCEL;
	  BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
	  HWND foreground_window;

	  if (break_scan_code == 0)
	    {
	      /* Fake Ctrl-C if we can't manage Ctrl-Break. */
	      vk_break_code = 'C';
	      break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
	    }

	  foreground_window = GetForegroundWindow ();
	  if (foreground_window)
	    {
              /* NT 5.0, and apparently also Windows 98, will not allow
		 a Window to be set to foreground directly without the
		 user's involvement. The workaround is to attach
		 ourselves to the thread that owns the foreground
		 window, since that is the only thread that can set the
		 foreground window.  */
              DWORD foreground_thread, child_thread;
              foreground_thread =
		GetWindowThreadProcessId (foreground_window, NULL);
	      if (foreground_thread == GetCurrentThreadId ()
                  || !AttachThreadInput (GetCurrentThreadId (),
                                         foreground_thread, TRUE))
                foreground_thread = 0;

              child_thread = GetWindowThreadProcessId (cp->hwnd, NULL);
	      if (child_thread == GetCurrentThreadId ()
                  || !AttachThreadInput (GetCurrentThreadId (),
                                         child_thread, TRUE))
                child_thread = 0;

              /* Set the foreground window to the child.  */
              if (SetForegroundWindow (cp->hwnd))
                {
                  /* Generate keystrokes as if user had typed Ctrl-Break or
                     Ctrl-C.  */
                  keybd_event (VK_CONTROL, control_scan_code, 0, 0);
                  keybd_event (vk_break_code, break_scan_code,
		    (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY), 0);
                  keybd_event (vk_break_code, break_scan_code,
                    (vk_break_code == 'C' ? 0 : KEYEVENTF_EXTENDEDKEY)
                    | KEYEVENTF_KEYUP, 0);
                  keybd_event (VK_CONTROL, control_scan_code,
                               KEYEVENTF_KEYUP, 0);

                  /* Sleep for a bit to give time for Emacs frame to respond
                     to focus change events (if Emacs was active app).  */
                  Sleep (100);

                  SetForegroundWindow (foreground_window);
                }
              /* Detach from the foreground and child threads now that
                 the foreground switching is over.  */
              if (foreground_thread)
                AttachThreadInput (GetCurrentThreadId (),
                                   foreground_thread, FALSE);
              if (child_thread)
                AttachThreadInput (GetCurrentThreadId (),
                                   child_thread, FALSE);
            }
        }
      /* Ctrl-Break is NT equivalent of SIGINT.  */
      else if (!GenerateConsoleCtrlEvent (CTRL_BREAK_EVENT, pid))
        {
#if 0 /* FSF Emacs */
	  DebPrint (("sys_kill.GenerateConsoleCtrlEvent return %d "
		     "for pid %lu\n", GetLastError (), pid));
	  errno = EINVAL;
#endif
	  rc = 0;
	}
    }
  else
    {
      if (NILP (Vmswindows_start_process_share_console) && cp && cp->hwnd)
	{
#if 1
	  if (msw_windows9x_p ())
	    {
/*
   Another possibility is to try terminating the VDM out-right by
   calling the Shell VxD (id 0x17) V86 interface, function #4
   "SHELL_Destroy_VM", ie.

     mov edx,4
     mov ebx,vm_handle
     call shellapi

   First need to determine the current VM handle, and then arrange for
   the shellapi call to be made from the system vm (by using
   Switch_VM_and_callback).

   Could try to invoke DestroyVM through CallVxD.

*/
#if 0
	      /* On Win95, posting WM_QUIT causes the 16-bit subsystem
		 to hang when cmdproxy is used in conjunction with
		 command.com for an interactive shell.  Posting
		 WM_CLOSE pops up a dialog that, when Yes is selected,
		 does the same thing.  TerminateProcess is also less
		 than ideal in that subprocesses tend to stick around
		 until the machine is shutdown, but at least it
		 doesn't freeze the 16-bit subsystem.  */
	      PostMessage (cp->hwnd, WM_QUIT, 0xff, 0);
#endif
	      if (!TerminateProcess (h_process, 0xff))
		{
#if 0 /* FSF Emacs */
		  DebPrint (("sys_kill.TerminateProcess returned %d "
			     "for pid %lu\n", GetLastError (), pid));
		  errno = EINVAL;
#endif
		  rc = 0;
		}
	    }
	  else
#endif
	    PostMessage (cp->hwnd, WM_CLOSE, 0, 0);
	}
      /* Kill the process.  On W32 this doesn't kill child processes
	 so it doesn't work very well for shells which is why it's not
	 used in every case.  */
      else if (!TerminateProcess (h_process, 0xff))
        {
#if 0 /* FSF Emacs */
	  DebPrint (("sys_kill.TerminateProcess returned %d "
		     "for pid %lu\n", GetLastError (), pid));
	  errno = EINVAL;
#endif
	  rc = 0;
        }
    }

  if (close_process)
    CloseHandle (h_process);

  return rc;
}

/* -------------------------- all-OS functions ---------------------------- */

static int
send_signal (struct nt_process_data *cp, int pid, int signo)
{
  return send_signal_the_nt_way (cp, pid, signo)
    || send_signal_the_95_way (cp, pid, signo);
}

/*
 * Signal error if SIGNO is not supported
 */
static void
validate_signal_number (int signo)
{
  if (signo != SIGKILL && signo != SIGTERM
      && signo != SIGQUIT && signo != SIGINT
      && signo != SIGHUP)
    signal_simple_error ("Signal number not supported", make_int (signo));
}
  
/*-----------------------------------------------------------------------*/
/* Process methods							 */
/*-----------------------------------------------------------------------*/

/*
 * Allocate and initialize Lisp_Process->process_data
 */

static void
nt_alloc_process_data (Lisp_Process *p)
{
  p->process_data = xnew_and_zero (struct nt_process_data);
}

static void
nt_finalize_process_data (Lisp_Process *p, int for_disksave)
{
  assert (!for_disksave);
  if (NT_DATA (p)->h_process)
    CloseHandle (NT_DATA (p)->h_process);
}

/*
 * Initialize XEmacs process implementation once
 */
static void
nt_init_process (void)
{
  /* Initialize winsock */
  WSADATA wsa_data;
  /* Request Winsock v1.1 Note the order: (minor=1, major=1) */
  WSAStartup (MAKEWORD (1,1), &wsa_data);
}

/*
 * Fork off a subprocess. P is a pointer to newly created subprocess
 * object. If this function signals, the caller is responsible for
 * deleting (and finalizing) the process object.
 *
 * The method must return PID of the new process, a (positive??? ####) number
 * which fits into Lisp_Int. No return value indicates an error, the method
 * must signal an error instead.
 */

static void
signal_cannot_launch (Lisp_Object image_file, DWORD err)
{
  mswindows_set_errno (err);
  signal_simple_error_2 ("Error starting", image_file, lisp_strerror (errno));
}

static void
ensure_console_window_exists (void)
{
  if (msw_windows9x_p ())
    msw_hide_console ();
}

int
compare_env (const void *strp1, const void *strp2)
{
  const char *str1 = *(const char**)strp1, *str2 = *(const char**)strp2;

  while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
    {
      if ((*str1) > (*str2))
	return 1;
      else if ((*str1) < (*str2))
	return -1;
      str1++, str2++;
    }

  if (*str1 == '=' && *str2 == '=')
    return 0;
  else if (*str1 == '=')
    return -1;
  else
    return 1;
}

static int
nt_create_process (Lisp_Process *p,
		   Lisp_Object *argv, int nargv,
		   Lisp_Object program, Lisp_Object cur_dir)
{
  /* Synched up with sys_spawnve in FSF 20.6.  Significantly different
     but still synchable. */
  HANDLE hmyshove, hmyslurp, hprocin, hprocout, hprocerr;
  Extbyte *command_line;
  BOOL do_io, windowed;
  char *proc_env;

  /* No need to DOS-ize the filename; expand-file-name (called prior)
     already does this. */

  /* Find out whether the application is windowed or not */
  {
    /* SHGetFileInfo tends to return ERROR_FILE_NOT_FOUND on most
       errors. This leads to bogus error message. */
    DWORD image_type;
    char *p = strrchr ((char *)XSTRING_DATA (program), '.');
    if (p != NULL &&
	(stricmp (p, ".exe") == 0 ||
	 stricmp (p, ".com") == 0 ||
	 stricmp (p, ".bat") == 0 ||
	 stricmp (p, ".cmd") == 0))
      {
	image_type = SHGetFileInfo ((char *)XSTRING_DATA (program), 0,NULL,
				    0, SHGFI_EXETYPE);
      }
    else
      {
	char progname[MAX_PATH];
	sprintf (progname, "%s.exe", (char *)XSTRING_DATA (program));
	image_type = SHGetFileInfo (progname, 0, NULL, 0, SHGFI_EXETYPE);
      }
    if (image_type == 0)
      signal_cannot_launch (program, (GetLastError () == ERROR_FILE_NOT_FOUND
				      ? ERROR_BAD_FORMAT : GetLastError ()));
    windowed = HIWORD (image_type) != 0;
  }

  /* Decide whether to do I/O on process handles, or just mark the
     process exited immediately upon successful launching. We do I/O if the
     process is a console one, or if it is windowed but windowed_process_io
     is non-zero */
  do_io = !windowed || windowed_process_io ;
  
  if (do_io)
    {
      /* Create two unidirectional named pipes */
      HANDLE htmp;
      SECURITY_ATTRIBUTES sa;

      sa.nLength = sizeof(sa);
      sa.bInheritHandle = TRUE;
      sa.lpSecurityDescriptor = NULL;

      CreatePipe (&hprocin, &hmyshove, &sa, 0);
      CreatePipe (&hmyslurp, &hprocout, &sa, 0);

      /* Duplicate the stdout handle for use as stderr */
      DuplicateHandle(GetCurrentProcess(), hprocout, GetCurrentProcess(),
		      &hprocerr, 0, TRUE, DUPLICATE_SAME_ACCESS);

      /* Stupid Win32 allows to create a pipe with *both* ends either
	 inheritable or not. We need process ends inheritable, and local
	 ends not inheritable. */
      DuplicateHandle (GetCurrentProcess(), hmyshove, GetCurrentProcess(),
		       &htmp, 0, FALSE,
		       DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS);
      hmyshove = htmp;
      DuplicateHandle (GetCurrentProcess(), hmyslurp, GetCurrentProcess(),
		       &htmp, 0, FALSE,
		       DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS);
      hmyslurp = htmp;
    }

  /* Convert an argv vector into Win32 style command line. */
  {
    int i;
    Bufbyte **quoted_args;
    int is_dos_app, is_cygnus_app;
    int do_quoting = 0;
    char escape_char = 0;

    nargv++; /* include program; we access argv offset by 1 below */
    quoted_args = alloca_array (Bufbyte *, nargv);

    /* Determine whether program is a 16-bit DOS executable, or a Win32
       executable that is implicitly linked to the Cygnus dll (implying it
       was compiled with the Cygnus GNU toolchain and hence relies on
       cygwin.dll to parse the command line - we use this to decide how to
       escape quote chars in command line args that must be quoted). */
    mswindows_executable_type (XSTRING_DATA (program),
			       &is_dos_app, &is_cygnus_app);

#if 0
    /* #### we need to port this. */
    /* On Windows 95, if cmdname is a DOS app, we invoke a helper
       application to start it by specifying the helper app as cmdname,
       while leaving the real app name as argv[0].  */
    if (is_dos_app)
      {
	cmdname = (char*) alloca (MAXPATHLEN);
	if (egetenv ("CMDPROXY"))
	  strcpy ((char*)cmdname, egetenv ("CMDPROXY"));
	else
	  {
	    strcpy ((char*)cmdname, XSTRING_DATA (Vinvocation_directory));
	    strcat ((char*)cmdname, "cmdproxy.exe");
	  }
      }
#endif
  
    /* we have to do some conjuring here to put argv and envp into the
       form CreateProcess wants...  argv needs to be a space separated/null
       terminated list of parameters, and envp is a null
       separated/double-null terminated list of parameters.

       Additionally, zero-length args and args containing whitespace or
       quote chars need to be wrapped in double quotes - for this to work,
       embedded quotes need to be escaped as well.  The aim is to ensure
       the child process reconstructs the argv array we start with
       exactly, so we treat quotes at the beginning and end of arguments
       as embedded quotes.

       The Win32 GNU-based library from Cygnus doubles quotes to escape
       them, while MSVC uses backslash for escaping.  (Actually the MSVC
       startup code does attempt to recognize doubled quotes and accept
       them, but gets it wrong and ends up requiring three quotes to get a
       single embedded quote!)  So by default we decide whether to use
       quote or backslash as the escape character based on whether the
       binary is apparently a Cygnus compiled app.

       Note that using backslash to escape embedded quotes requires
       additional special handling if an embedded quote is already
       preceded by backslash, or if an arg requiring quoting ends with
       backslash.  In such cases, the run of escape characters needs to be
       doubled.  For consistency, we apply this special handling as long
       as the escape character is not quote.
   
       Since we have no idea how large argv and envp are likely to be we
       figure out list lengths on the fly and allocate them.  */
  
    if (!NILP (Vmswindows_quote_process_args))
      {
	do_quoting = 1;
	/* Override escape char by binding mswindows-quote-process-args to
	   desired character, or use t for auto-selection.  */
	if (INTP (Vmswindows_quote_process_args))
	  escape_char = (char) XINT (Vmswindows_quote_process_args);
	else
	  escape_char = is_cygnus_app ? '"' : '\\';
      }
  
    /* do argv...  */
    for (i = 0; i < nargv; ++i)
      {
	Bufbyte *targ = XSTRING_DATA (i == 0 ? program : argv[i - 1]);
	Bufbyte *p = targ;
	int need_quotes = 0;
	int escape_char_run = 0;
	int arglen = 0;

	if (*p == 0)
	  need_quotes = 1;
	for ( ; *p; p++)
	  {
	    if (*p == '"')
	      {
		/* allow for embedded quotes to be escaped */
		arglen++;
		need_quotes = 1;
		/* handle the case where the embedded quote is already escaped */
		if (escape_char_run > 0)
		  {
		    /* To preserve the arg exactly, we need to double the
		       preceding escape characters (plus adding one to
		       escape the quote character itself).  */
		    arglen += escape_char_run;
		  }
	      }
	    else if (*p == ' ' || *p == '\t')
	      {
		need_quotes = 1;
	      }

	    if (*p == escape_char && escape_char != '"')
	      escape_char_run++;
	    else
	      escape_char_run = 0;
	  }
	if (need_quotes)
	  {
	    arglen += 2;
	    /* handle the case where the arg ends with an escape char - we
	       must not let the enclosing quote be escaped.  */
	    if (escape_char_run > 0)
	      arglen += escape_char_run;
	  }
	arglen += strlen (targ) + 1;

	quoted_args[i] = alloca_array (Bufbyte, arglen); 
      }

    for (i = 0; i < nargv; ++i)
      {
	Bufbyte *targ = XSTRING_DATA (i == 0 ? program : argv[i - 1]);
	Bufbyte *p = targ;
	int need_quotes = 0;
	Bufbyte *parg = quoted_args[i];

	if (*p == 0)
	  need_quotes = 1;

	if (do_quoting)
	  {
	    for ( ; *p; p++)
	      if (*p == ' ' || *p == '\t' || *p == '"')
		need_quotes = 1;
	  }
	if (need_quotes)
	  {
	    int escape_char_run = 0;
	    Bufbyte * first;
	    Bufbyte * last;

	    p = targ;
	    first = p;
	    last = p + strlen (p) - 1;
	    *parg++ = '"';
#if 0
	    /* This version does not escape quotes if they occur at the
	       beginning or end of the arg - this could lead to incorrect
	       behavior when the arg itself represents a command line
	       containing quoted args.  I believe this was originally done
	       as a hack to make some things work, before
	       `mswindows-quote-process-args' was added.  */
	    while (*p)
	      {
		if (*p == '"' && p > first && p < last)
		  *parg++ = escape_char;	/* escape embedded quotes */
		*parg++ = *p++;
	      }
#else
	    for ( ; *p; p++)
	      {
		if (*p == '"')
		  {
		    /* double preceding escape chars if any */
		    while (escape_char_run > 0)
		      {
			*parg++ = escape_char;
			escape_char_run--;
		      }
		    /* escape all quote chars, even at beginning or end */
		    *parg++ = escape_char;
		  }
		*parg++ = *p;

		if (*p == escape_char && escape_char != '"')
		  escape_char_run++;
		else
		  escape_char_run = 0;
	      }
	    /* double escape chars before enclosing quote */
	    while (escape_char_run > 0)
	      {
		*parg++ = escape_char;
		escape_char_run--;
	      }
#endif
	    *parg++ = '"';
	  }
	else
	  {
	    strcpy (parg, targ);
	    parg += strlen (targ);
	  }
	*parg = '\0';
      }

    {
      int total_cmdline_len = 0;
      Extcount *extargcount = (Extcount *) alloca_array (Extcount, nargv);
      Extbyte **extarg = (Extbyte **) alloca_array (Extbyte *, nargv);
      Extbyte *command_ptr;

      for (i = 0; i < nargv; ++i)
	{
	  TO_EXTERNAL_FORMAT (C_STRING, quoted_args[i], ALLOCA,
			      (extarg[i], extargcount[i]), Qmswindows_tstr);
	  /* account for space and terminating null */
	  total_cmdline_len += extargcount[i] + EITCHAR_SIZE;
	}

      command_line = alloca_array (char, total_cmdline_len);
      command_ptr = command_line;
      for (i = 0; i < nargv; ++i)
	{
	  memcpy (command_ptr, extarg[i], extargcount[i]);
	  command_ptr += extargcount[i];
	  EICOPY_TCHAR (command_ptr, ' ');
	  command_ptr += EITCHAR_SIZE;
	}
      EICOPY_TCHAR (command_ptr, '\0');
      command_ptr += EITCHAR_SIZE;
    }
  }
  /* Set `proc_env' to a nul-separated array of the strings in
     Vprocess_environment terminated by 2 nuls.  */
 
  {
    char **env;
    REGISTER Lisp_Object tem;
    REGISTER char **new_env;
    REGISTER int new_length = 0, i, new_space;
    char *penv;
    
    for (tem = Vprocess_environment;
 	 (CONSP (tem)
 	  && STRINGP (XCAR (tem)));
 	 tem = XCDR (tem))
      new_length++;

    /* FSF adds an extra env var to hold the current process ID of the
       Emacs process.  Apparently this is used only by emacsserver.c,
       which we have superseded to gnuserv.c. (#### Does it work under
       MS Windows?)

       sprintf (ppid_env_var_buffer, "EM_PARENT_PROCESS_ID=%d", 
         GetCurrentProcessId ());
       arglen += strlen (ppid_env_var_buffer) + 1;
       numenv++;
    */
    
    /* new_length + 1 to include terminating 0.  */
    env = new_env = alloca_array (char *, new_length + 1);
 
    /* Copy the Vprocess_environment strings into new_env.  */
    for (tem = Vprocess_environment;
 	 (CONSP (tem)
 	  && STRINGP (XCAR (tem)));
 	 tem = XCDR (tem))
      {
	char **ep = env;
	char *string = (char *) XSTRING_DATA (XCAR (tem));
	/* See if this string duplicates any string already in the env.
	   If so, don't put it in.
	   When an env var has multiple definitions,
	   we keep the definition that comes first in process-environment.  */
	for (; ep != new_env; ep++)
	  {
	    char *p = *ep, *q = string;
	    while (1)
	      {
		if (*q == 0)
		  /* The string is malformed; might as well drop it.  */
		  goto duplicate;
		if (*q != *p)
		  break;
		if (*q == '=')
		  goto duplicate;
		p++, q++;
	      }
	  }
	*new_env++ = string;
      duplicate: ;
      }
    *new_env = 0;
    
    /* Sort the environment variables */
    new_length = new_env - env;
    qsort (env, new_length, sizeof (char *), compare_env);
    
    /* Work out how much space to allocate */
    new_space = 0;
    for (i = 0; i < new_length; i++)
      {
 	new_space += strlen(env[i]) + 1;
      }
    new_space++;
    
    /* Allocate space and copy variables into it */
    penv = proc_env = (char*) alloca(new_space);
    for (i = 0; i < new_length; i++)
      {
 	strcpy(penv, env[i]);
 	penv += strlen(env[i]) + 1;
      }
    *penv = 0;
  }
  
  /* Create process */
  {
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    DWORD err;
    DWORD flags;

    xzero (si);
    si.dwFlags = STARTF_USESHOWWINDOW;
    si.wShowWindow = windowed ? SW_SHOWNORMAL : SW_HIDE;
    if (do_io)
      {
	si.hStdInput = hprocin;
	si.hStdOutput = hprocout;
	si.hStdError = hprocerr;
	si.dwFlags |= STARTF_USESTDHANDLES;
      }

    flags = CREATE_SUSPENDED;
    if (msw_windows9x_p ())
      flags |= (!NILP (Vmswindows_start_process_share_console)
		? CREATE_NEW_PROCESS_GROUP
		: CREATE_NEW_CONSOLE);
    else
      flags |= CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP;
    if (NILP (Vmswindows_start_process_inherit_error_mode))
      flags |= CREATE_DEFAULT_ERROR_MODE;

    ensure_console_window_exists ();

    err = (CreateProcess (NULL, command_line, NULL, NULL, TRUE, flags,
			  proc_env, (char *) XSTRING_DATA (cur_dir), &si, &pi)
	   ? 0 : GetLastError ());

    if (do_io)
      {
	/* These just have been inherited; we do not need a copy */
	CloseHandle (hprocin);
	CloseHandle (hprocout);
	CloseHandle (hprocerr);
      }
    
    /* Handle process creation failure */
    if (err)
      {
	if (do_io)
	  {
	    CloseHandle (hmyshove);
	    CloseHandle (hmyslurp);
	  }
	signal_cannot_launch (program, GetLastError ());
      }

    /* The process started successfully */
    if (do_io)
      {
	NT_DATA(p)->h_process = pi.hProcess;
	NT_DATA(p)->dwProcessId = pi.dwProcessId;
	init_process_io_handles (p, (void*)hmyslurp, (void*)hmyshove, 0);
      }
    else
      {
	/* Indicate as if the process has exited immediately. */
	p->status_symbol = Qexit;
	CloseHandle (pi.hProcess);
      }

    ResumeThread (pi.hThread);
    CloseHandle (pi.hThread);

    /* Remember to enable child signals later if this is not a windowed
       app.  Can't do it right now because that screws up the MKS Toolkit
       shell. */
    if (!windowed)
      {
	NT_DATA(p)->need_enable_child_signals = 10;
	kick_status_notify ();
      }

    return ((int)pi.dwProcessId);
  }
}

/* 
 * This method is called to update status fields of the process
 * structure. If the process has not existed, this method is expected
 * to do nothing.
 *
 * The method is called only for real child processes.  
 */

static void
nt_update_status_if_terminated (Lisp_Process* p)
{
  DWORD exit_code;

  if (NT_DATA(p)->need_enable_child_signals > 1)
    {
      NT_DATA(p)->need_enable_child_signals -= 1;
      kick_status_notify ();
    }
  else if (NT_DATA(p)->need_enable_child_signals == 1)
    {
      enable_child_signals(NT_DATA(p)->h_process);
      NT_DATA(p)->need_enable_child_signals = 0;
    }

  if (GetExitCodeProcess (NT_DATA(p)->h_process, &exit_code)
      && exit_code != STILL_ACTIVE)
    {
      p->tick++;
      p->core_dumped = 0;
      /* The exit code can be a code returned by process, or an
	 NTSTATUS value. We cannot accurately handle the latter since
	 it is a full 32 bit integer */
      if (exit_code & 0xC0000000)
	{
	  p->status_symbol = Qsignal;
	  p->exit_code = exit_code & 0x1FFFFFFF;
	}
      else
	{
	  p->status_symbol = Qexit;
	  p->exit_code = exit_code;
	}
    }
}

/*
 * Stuff the entire contents of LSTREAM to the process output pipe
 */

/* #### If only this function could be somehow merged with
   unix_send_process... */

static void
nt_send_process (Lisp_Object proc, struct lstream* lstream)
{
  volatile Lisp_Object vol_proc = proc;
  Lisp_Process *volatile p = XPROCESS (proc);

  /* use a reasonable-sized buffer (somewhere around the size of the
     stream buffer) so as to avoid inundating the stream with blocked
     data. */
  Bufbyte chunkbuf[512];
  Bytecount chunklen;

  while (1)
    {
      ssize_t writeret;

      chunklen = Lstream_read (lstream, chunkbuf, 512);
      if (chunklen <= 0)
	break; /* perhaps should abort() if < 0?
		  This should never happen. */

      /* Lstream_write() will never successfully write less than the
	 amount sent in.  In the worst case, it just buffers the
	 unwritten data. */
      writeret = Lstream_write (XLSTREAM (DATA_OUTSTREAM(p)), chunkbuf,
				chunklen);
      Lstream_flush (XLSTREAM (DATA_OUTSTREAM(p)));
      if (writeret < 0)
	{
	  p->status_symbol = Qexit;
	  p->exit_code = ERROR_BROKEN_PIPE;
	  p->core_dumped = 0;
	  p->tick++;
	  process_tick++;
	  deactivate_process (*((Lisp_Object *) (&vol_proc)));
	  error ("Broken pipe error sending to process %s; closed it",
		 XSTRING_DATA (p->name));
	}

      {
	int wait_ms = 25;
	while (Lstream_was_blocked_p (XLSTREAM (p->pipe_outstream)))
	  {
	    /* Buffer is full.  Wait, accepting input; that may allow
	       the program to finish doing output and read more.  */
	    Faccept_process_output (Qnil, Qzero, make_int (wait_ms));
	    Lstream_flush (XLSTREAM (p->pipe_outstream));
	    wait_ms = min (1000, 2 * wait_ms);
	  }
      }
    }
}

/*
 * Send a signal number SIGNO to PROCESS.
 * CURRENT_GROUP means send to the process group that currently owns
 * the terminal being used to communicate with PROCESS.
 * This is used for various commands in shell mode.
 * If NOMSG is zero, insert signal-announcements into process's buffers
 * right away.
 *
 * If we can, we try to signal PROCESS by sending control characters
 * down the pty.  This allows us to signal inferiors who have changed
 * their uid, for which killpg would return an EPERM error.
 *
 * The method signals an error if the given SIGNO is not valid
 */

static void
nt_kill_child_process (Lisp_Object proc, int signo,
		       int current_group, int nomsg)
{
  Lisp_Process *p = XPROCESS (proc);

  /* Enable child signals if necessary.  This may lose the first
     but it's better than nothing. */
  if (NT_DATA (p)->need_enable_child_signals > 0)
    {
      enable_child_signals (NT_DATA(p)->h_process);
      NT_DATA (p)->need_enable_child_signals = 0;
    }

  /* Signal error if SIGNO cannot be sent */
  validate_signal_number (signo);

  /* Send signal */
  if (!send_signal (NT_DATA (p), 0, signo))
    signal_simple_error ("Cannot send signal to process", proc);
}

/*
 * Kill any process in the system given its PID
 *
 * Returns zero if a signal successfully sent, or
 * negative number upon failure
 */
static int
nt_kill_process_by_pid (int pid, int signo)
{
  struct Lisp_Process *p;

  /* Signal error if SIGNO cannot be sent */
  validate_signal_number (signo);

  p = find_process_from_pid (pid);
  return send_signal (p ? NT_DATA (p) : 0, pid, signo) ? 0 : -1;
}

/*-----------------------------------------------------------------------*/
/* Sockets connections							 */
/*-----------------------------------------------------------------------*/
#ifdef HAVE_SOCKETS

/* #### Hey MS, how long Winsock 2 for '95 will be in beta? */

#define SOCK_TIMER_ID 666
#define XM_SOCKREPLY (WM_USER + 666)

static int
get_internet_address (Lisp_Object host, struct sockaddr_in *address,
		      Error_behavior errb)
{
  char buf [MAXGETHOSTSTRUCT];
  HWND hwnd;
  HANDLE hasync;
  int success = 0;

  address->sin_family = AF_INET;

  /* First check if HOST is already a numeric address */
  {
    unsigned long inaddr = inet_addr (XSTRING_DATA (host));
    if (inaddr != INADDR_NONE)
      {
	address->sin_addr.s_addr = inaddr;
	return 1;
      }
  }

  /* Create a window which will receive completion messages */
  hwnd = CreateWindow ("STATIC", NULL, WS_OVERLAPPED, 0, 0, 1, 1,
		       NULL, NULL, NULL, NULL);
  assert (hwnd);

  /* Post name resolution request */
  hasync = WSAAsyncGetHostByName (hwnd, XM_SOCKREPLY, XSTRING_DATA (host),
				  buf, sizeof (buf));
  if (hasync == NULL)
    goto done;

  /* Set a timer to poll for quit every 250 ms */
  SetTimer (hwnd, SOCK_TIMER_ID, 250, NULL);

  while (1)
    {
      MSG msg;
      GetMessage (&msg, hwnd, 0, 0);
      if (msg.message == XM_SOCKREPLY)
	{
	  /* Ok, got an answer */
	  if (WSAGETASYNCERROR(msg.lParam) == NO_ERROR)
	    success = 1;
	  else
	    {
	      warn_when_safe(Qstream, Qwarning,
			     "cannot get IP address for host \"%s\"",
			     XSTRING_DATA (host));
	    }
	  goto done;
	}
      else if (msg.message == WM_TIMER && msg.wParam == SOCK_TIMER_ID)
	{
	  if (QUITP)
	    {
	      WSACancelAsyncRequest (hasync);
	      KillTimer (hwnd, SOCK_TIMER_ID);
	      DestroyWindow (hwnd);
	      REALLY_QUIT;
	    }
	}
      DispatchMessage (&msg);
    }

 done:
  KillTimer (hwnd, SOCK_TIMER_ID);
  DestroyWindow (hwnd);
  if (success)
    {
      /* BUF starts with struct hostent */
      struct hostent* he = (struct hostent*) buf;
      address->sin_addr.s_addr = *(unsigned long*)he->h_addr_list[0];
    }
  return success;
}

static Lisp_Object
nt_canonicalize_host_name (Lisp_Object host)
{
  struct sockaddr_in address;

  if (!get_internet_address (host, &address, ERROR_ME_NOT))
    return host;

  if (address.sin_family == AF_INET)
    return build_string (inet_ntoa (address.sin_addr));
  else
    return host;
}

/* open a TCP network connection to a given HOST/SERVICE.  Treated
   exactly like a normal process when reading and writing.  Only
   differences are in status display and process deletion.  A network
   connection has no PID; you cannot signal it.  All you can do is
   deactivate and close it via delete-process */

static void
nt_open_network_stream (Lisp_Object name, Lisp_Object host,
			Lisp_Object service,
			Lisp_Object protocol, void** vinfd, void** voutfd)
{
  /* !!#### not Mule-ized */
  struct sockaddr_in address;
  SOCKET s;
  int port;
  int retval;

  CHECK_STRING (host);

  if (!EQ (protocol, Qtcp))
    signal_simple_error ("Unsupported protocol", protocol);

  if (INTP (service))
    port = htons ((unsigned short) XINT (service));
  else
    {
      struct servent *svc_info;
      CHECK_STRING (service);
      svc_info = getservbyname ((char *) XSTRING_DATA (service), "tcp");
      if (svc_info == 0)
	signal_simple_error ("Unknown service", service);
      port = svc_info->s_port;
    }

  get_internet_address (host, &address, ERROR_ME);
  address.sin_port = port;

  s = socket (address.sin_family, SOCK_STREAM, 0);
  if (s < 0)
    report_file_error ("error creating socket", list1 (name));

  /* We don't want to be blocked on connect */
  {
    unsigned long nonblock = 1;
    ioctlsocket (s, FIONBIO, &nonblock);
  }
  
  retval = connect (s, (struct sockaddr *) &address, sizeof (address));
  if (retval != NO_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
    goto connect_failed;
  /* Wait while connection is established */
  while (1)
    {
      fd_set fdset;
      struct timeval tv;
      int nsel;

      if (QUITP)
	{
	  closesocket (s);
	  REALLY_QUIT;
	}

      /* Poll for quit every 250 ms */
      tv.tv_sec = 0;
      tv.tv_usec = 250 * 1000;

      FD_ZERO (&fdset);
      FD_SET (s, &fdset);
      nsel = select (0, NULL, &fdset, &fdset, &tv);

      if (nsel > 0)
	{
	  /* Check: was connection successful or not? */
	  tv.tv_usec = 0;
	  nsel = select (0, NULL, NULL, &fdset, &tv);
	  if (nsel > 0)
	    goto connect_failed;
	  else
	    break;
	}
    }

  /* We are connected at this point */
  *vinfd = (void*)s;
  DuplicateHandle (GetCurrentProcess(), (HANDLE)s,
		   GetCurrentProcess(), (LPHANDLE)voutfd,
		   0, FALSE, DUPLICATE_SAME_ACCESS);
  return;

 connect_failed:  
  closesocket (s);
  if (INTP (service))
    {
      warn_when_safe (Qstream, Qwarning,
		      "failure to open network stream to host \"%s\" for service \"%d\"",
		      XSTRING_DATA (host),
		      (unsigned short) XINT (service));
    }
  else
    {
      warn_when_safe (Qstream, Qwarning,
		      "failure to open network stream to host \"%s\" for service \"%s\"",
		      XSTRING_DATA (host),
		      XSTRING_DATA (service));
    }
  report_file_error ("connection failed", list2 (host, name));
}

#endif

/*-----------------------------------------------------------------------*/
/* Initialization							 */
/*-----------------------------------------------------------------------*/

void
process_type_create_nt (void)
{
  PROCESS_HAS_METHOD (nt, alloc_process_data);
  PROCESS_HAS_METHOD (nt, finalize_process_data);
  PROCESS_HAS_METHOD (nt, init_process);
  PROCESS_HAS_METHOD (nt, create_process);
  PROCESS_HAS_METHOD (nt, update_status_if_terminated);
  PROCESS_HAS_METHOD (nt, send_process);
  PROCESS_HAS_METHOD (nt, kill_child_process);
  PROCESS_HAS_METHOD (nt, kill_process_by_pid);
#ifdef HAVE_SOCKETS
  PROCESS_HAS_METHOD (nt, canonicalize_host_name);
  PROCESS_HAS_METHOD (nt, open_network_stream);
#ifdef HAVE_MULTICAST
#error I won't do this until '95 has winsock2
  PROCESS_HAS_METHOD (nt, open_multicast_group);
#endif
#endif
}

void
syms_of_process_nt (void)
{
}

void
vars_of_process_nt (void)
{
  DEFVAR_LISP ("mswindows-quote-process-args",
	       &Vmswindows_quote_process_args /*
Non-nil enables quoting of process arguments to ensure correct parsing.
Because Windows does not directly pass argv arrays to child processes,
programs have to reconstruct the argv array by parsing the command
line string.  For an argument to contain a space, it must be enclosed
in double quotes or it will be parsed as multiple arguments.

If the value is a character, that character will be used to escape any
quote characters that appear, otherwise a suitable escape character
will be chosen based on the type of the program (normal or Cygwin).
*/ );								  
  Vmswindows_quote_process_args = Qt;

  DEFVAR_LISP ("mswindows-start-process-share-console",
	       &Vmswindows_start_process_share_console /*
When nil, new child processes are given a new console.
When non-nil, they share the Emacs console; this has the limitation of
allowing only only DOS subprocess to run at a time (whether started directly
or indirectly by Emacs), and preventing Emacs from cleanly terminating the
subprocess group, but may allow Emacs to interrupt a subprocess that doesn't
otherwise respond to interrupts from Emacs.
*/ );
  Vmswindows_start_process_share_console = Qnil;

  DEFVAR_LISP ("mswindows-start-process-inherit-error-mode",
	       &Vmswindows_start_process_inherit_error_mode /*
    "When nil, new child processes revert to the default error mode.
When non-nil, they inherit their error mode setting from Emacs, which stops
them blocking when trying to access unmounted drives etc.
*/ );
  Vmswindows_start_process_inherit_error_mode = Qt;
}