w32proc.c 69.9 KB
Newer Older
1
/* Process support for GNU Emacs on the Microsoft W32 API.
2 3
   Copyright (C) 1992, 1995, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
		 2006, 2007, 2008  Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
4

5 6
This file is part of GNU Emacs.

7
GNU Emacs is free software: you can redistribute it and/or modify
8
it under the terms of the GNU General Public License as published by
9 10
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
11 12 13 14 15 16 17

GNU Emacs 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
18
along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
19

20
/*
Richard M. Stallman's avatar
Richard M. Stallman committed
21 22 23 24 25 26 27 28
   Drew Bliss                   Oct 14, 1993
     Adapted from alarm.c by Tim Fleehart
*/

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <io.h>
29
#include <fcntl.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
30
#include <signal.h>
Jason Rumney's avatar
Jason Rumney committed
31
#include <sys/file.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
32

33
/* must include CRT headers *before* config.h */
Pavel Janík's avatar
Pavel Janík committed
34 35 36 37 38

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

39 40 41 42 43 44
#undef signal
#undef wait
#undef spawnve
#undef select
#undef kill

Richard M. Stallman's avatar
Richard M. Stallman committed
45
#include <windows.h>
46 47 48 49
#ifdef __GNUC__
/* This definition is missing from mingw32 headers. */
extern BOOL WINAPI IsValidLocale(LCID, DWORD);
#endif
Richard M. Stallman's avatar
Richard M. Stallman committed
50

Eli Zaretskii's avatar
Eli Zaretskii committed
51 52 53 54 55
#ifdef HAVE_LANGINFO_CODESET
#include <nl_types.h>
#include <langinfo.h>
#endif

Richard M. Stallman's avatar
Richard M. Stallman committed
56
#include "lisp.h"
Jason Rumney's avatar
Jason Rumney committed
57
#include "character.h"
Geoff Voelker's avatar
Geoff Voelker committed
58
#include "w32.h"
Geoff Voelker's avatar
Geoff Voelker committed
59
#include "w32heap.h"
Richard M. Stallman's avatar
Richard M. Stallman committed
60
#include "systime.h"
61 62
#include "syswait.h"
#include "process.h"
63
#include "syssignal.h"
64
#include "w32term.h"
Eli Zaretskii's avatar
Eli Zaretskii committed
65
#include "dispextern.h"		/* for xstrcasecmp */
66
#include "coding.h"
67

Eli Zaretskii's avatar
Eli Zaretskii committed
68 69 70 71 72
#define RVA_TO_PTR(var,section,filedata) \
  ((void *)((section)->PointerToRawData					\
	    + ((DWORD)(var) - (section)->VirtualAddress)		\
	    + (filedata).file_base))

73 74
/* Control whether spawnve quotes arguments as necessary to ensure
   correct parsing by child process.  Because not all uses of spawnve
Glenn Morris's avatar
Glenn Morris committed
75
   are careful about constructing argv arrays, we make this behavior
76
   conditional (off by default). */
77
Lisp_Object Vw32_quote_process_args;
78

79 80
/* Control whether create_child causes the process' window to be
   hidden.  The default is nil. */
81
Lisp_Object Vw32_start_process_show_window;
82

Geoff Voelker's avatar
Geoff Voelker committed
83 84 85 86 87 88
/* 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 Vw32_start_process_share_console;

89 90 91 92 93
/* 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 Vw32_start_process_inherit_error_mode;

94 95 96
/* Time to sleep before reading from a subprocess output pipe - this
   avoids the inefficiency of frequently reading small amounts of data.
   This is primarily necessary for handling DOS processes on Windows 95,
97
   but is useful for W32 processes on both Windows 95 and NT as well.  */
98
int w32_pipe_read_delay;
99

100 101
/* Control conversion of upper case file names to lower case.
   nil means no, t means yes. */
102
Lisp_Object Vw32_downcase_file_names;
103

Geoff Voelker's avatar
Geoff Voelker committed
104 105 106 107 108 109 110 111 112 113
/* Control whether stat() attempts to generate fake but hopefully
   "accurate" inode values, by hashing the absolute truenames of files.
   This should detect aliasing between long and short names, but still
   allows the possibility of hash collisions.  */
Lisp_Object Vw32_generate_fake_inodes;

/* Control whether stat() attempts to determine file type and link count
   exactly, at the expense of slower operation.  Since true hard links
   are supported on NTFS volumes, this is only relevant on NT.  */
Lisp_Object Vw32_get_true_file_attributes;
114
extern Lisp_Object Qlocal;
Geoff Voelker's avatar
Geoff Voelker committed
115 116

Lisp_Object Qhigh, Qlow;
117

Richard M. Stallman's avatar
Richard M. Stallman committed
118
#ifdef EMACSDEBUG
119
void _DebPrint (const char *fmt, ...)
Richard M. Stallman's avatar
Richard M. Stallman committed
120
{
121
  char buf[1024];
Richard M. Stallman's avatar
Richard M. Stallman committed
122 123 124 125 126 127 128 129 130
  va_list args;

  va_start (args, fmt);
  vsprintf (buf, fmt, args);
  va_end (args);
  OutputDebugString (buf);
}
#endif

131
typedef void (_CALLBACK_ *signal_handler)(int);
Richard M. Stallman's avatar
Richard M. Stallman committed
132 133 134 135 136

/* Signal handlers...SIG_DFL == 0 so this is initialized correctly.  */
static signal_handler sig_handlers[NSIG];

/* Fake signal implementation to record the SIGCHLD handler.  */
137
signal_handler
138
sys_signal (int sig, signal_handler handler)
Richard M. Stallman's avatar
Richard M. Stallman committed
139 140
{
  signal_handler old;
141

Richard M. Stallman's avatar
Richard M. Stallman committed
142 143 144 145 146 147 148 149 150 151
  if (sig != SIGCHLD)
    {
      errno = EINVAL;
      return SIG_ERR;
    }
  old = sig_handlers[sig];
  sig_handlers[sig] = handler;
  return old;
}

152 153 154 155 156 157 158 159 160 161
/* Defined in <process.h> which conflicts with the local copy */
#define _P_NOWAIT 1

/* Child process management list.  */
int child_proc_count = 0;
child_process child_procs[ MAX_CHILDREN ];
child_process *dead_child = NULL;

DWORD WINAPI reader_thread (void *arg);

Richard M. Stallman's avatar
Richard M. Stallman committed
162
/* Find an unused process slot.  */
163
child_process *
Richard M. Stallman's avatar
Richard M. Stallman committed
164 165 166
new_child (void)
{
  child_process *cp;
167
  DWORD id;
168

Richard M. Stallman's avatar
Richard M. Stallman committed
169 170
  for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
    if (!CHILD_ACTIVE (cp))
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
      goto Initialise;
  if (child_proc_count == MAX_CHILDREN)
    return NULL;
  cp = &child_procs[child_proc_count++];

 Initialise:
  memset (cp, 0, sizeof(*cp));
  cp->fd = -1;
  cp->pid = -1;
  cp->procinfo.hProcess = NULL;
  cp->status = STATUS_READ_ERROR;

  /* use manual reset event so that select() will function properly */
  cp->char_avail = CreateEvent (NULL, TRUE, FALSE, NULL);
  if (cp->char_avail)
    {
      cp->char_consumed = CreateEvent (NULL, FALSE, FALSE, NULL);
      if (cp->char_consumed)
        {
	  cp->thrd = CreateThread (NULL, 1024, reader_thread, cp, 0, &id);
	  if (cp->thrd)
	    return cp;
	}
    }
  delete_child (cp);
  return NULL;
}

199
void
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
delete_child (child_process *cp)
{
  int i;

  /* Should not be deleting a child that is still needed. */
  for (i = 0; i < MAXDESC; i++)
    if (fd_info[i].cp == cp)
      abort ();

  if (!CHILD_ACTIVE (cp))
    return;

  /* reap thread if necessary */
  if (cp->thrd)
    {
      DWORD rc;

      if (GetExitCodeThread (cp->thrd, &rc) && rc == STILL_ACTIVE)
        {
	  /* let the thread exit cleanly if possible */
	  cp->status = STATUS_READ_ERROR;
	  SetEvent (cp->char_consumed);
222 223 224 225 226
#if 0
          /* We used to forceably terminate the thread here, but it
             is normally unnecessary, and in abnormal cases, the worst that
             will happen is we have an extra idle thread hanging around
             waiting for the zombie process.  */
227 228 229 230 231 232
	  if (WaitForSingleObject (cp->thrd, 1000) != WAIT_OBJECT_0)
	    {
	      DebPrint (("delete_child.WaitForSingleObject (thread) failed "
			 "with %lu for fd %ld\n", GetLastError (), cp->fd));
	      TerminateThread (cp->thrd, 0);
	    }
233
#endif
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
	}
      CloseHandle (cp->thrd);
      cp->thrd = NULL;
    }
  if (cp->char_avail)
    {
      CloseHandle (cp->char_avail);
      cp->char_avail = NULL;
    }
  if (cp->char_consumed)
    {
      CloseHandle (cp->char_consumed);
      cp->char_consumed = NULL;
    }

  /* update child_proc_count (highest numbered slot in use plus one) */
  if (cp == child_procs + child_proc_count - 1)
    {
      for (i = child_proc_count-1; i >= 0; i--)
	if (CHILD_ACTIVE (&child_procs[i]))
	  {
	    child_proc_count = i + 1;
	    break;
	  }
    }
  if (i < 0)
    child_proc_count = 0;
Richard M. Stallman's avatar
Richard M. Stallman committed
261 262 263 264 265 266 267
}

/* Find a child by pid.  */
static child_process *
find_child_pid (DWORD pid)
{
  child_process *cp;
268

Richard M. Stallman's avatar
Richard M. Stallman committed
269 270 271 272 273 274 275
  for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
    if (CHILD_ACTIVE (cp) && pid == cp->pid)
      return cp;
  return NULL;
}


276 277
/* Thread proc for child process and socket reader threads. Each thread
   is normally blocked until woken by select() to check for input by
Glenn Morris's avatar
Glenn Morris committed
278
   reading one char.  When the read completes, char_avail is signaled
279
   to wake up the select emulator and the thread blocks itself again. */
280
DWORD WINAPI
Richard M. Stallman's avatar
Richard M. Stallman committed
281 282 283
reader_thread (void *arg)
{
  child_process *cp;
284

Richard M. Stallman's avatar
Richard M. Stallman committed
285 286
  /* Our identity */
  cp = (child_process *)arg;
287

Richard M. Stallman's avatar
Richard M. Stallman committed
288
  /* We have to wait for the go-ahead before we can start */
Geoff Voelker's avatar
Geoff Voelker committed
289 290
  if (cp == NULL
      || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
291 292
    return 1;

Richard M. Stallman's avatar
Richard M. Stallman committed
293 294
  for (;;)
    {
295 296
      int rc;

297 298 299 300
      if (fd_info[cp->fd].flags & FILE_LISTEN)
	rc = _sys_wait_accept (cp->fd);
      else
	rc = _sys_read_ahead (cp->fd);
301 302 303

      /* The name char_avail is a misnomer - it really just means the
	 read-ahead has completed, whether successfully or not. */
Richard M. Stallman's avatar
Richard M. Stallman committed
304 305 306 307
      if (!SetEvent (cp->char_avail))
        {
	  DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
		     GetLastError (), cp->fd));
308 309 310 311 312
	  return 1;
	}

      if (rc == STATUS_READ_ERROR)
	return 1;
313

Richard M. Stallman's avatar
Richard M. Stallman committed
314
      /* If the read died, the child has died so let the thread die */
315
      if (rc == STATUS_READ_FAILED)
Richard M. Stallman's avatar
Richard M. Stallman committed
316
	break;
317

Richard M. Stallman's avatar
Richard M. Stallman committed
318 319 320 321 322 323 324 325 326 327 328
      /* Wait until our input is acknowledged before reading again */
      if (WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0)
        {
	  DebPrint (("reader_thread.WaitForSingleObject failed with "
		     "%lu for fd %ld\n", GetLastError (), cp->fd));
	  break;
        }
    }
  return 0;
}

Geoff Voelker's avatar
Geoff Voelker committed
329 330 331 332 333
/* To avoid Emacs changing directory, we just record here the directory
   the new process should start in.  This is set just before calling
   sys_spawnve, and is not generally valid at any other time.  */
static char * process_dir;

334
static BOOL
335
create_child (char *exe, char *cmdline, char *env, int is_gui_app,
336
	      int * pPid, child_process *cp)
Richard M. Stallman's avatar
Richard M. Stallman committed
337 338 339
{
  STARTUPINFO start;
  SECURITY_ATTRIBUTES sec_attrs;
340
#if 0
Richard M. Stallman's avatar
Richard M. Stallman committed
341
  SECURITY_DESCRIPTOR sec_desc;
342
#endif
343
  DWORD flags;
Geoff Voelker's avatar
Geoff Voelker committed
344
  char dir[ MAXPATHLEN ];
345

346
  if (cp == NULL) abort ();
347

Richard M. Stallman's avatar
Richard M. Stallman committed
348 349
  memset (&start, 0, sizeof (start));
  start.cb = sizeof (start);
350

351
#ifdef HAVE_NTGUI
352
  if (NILP (Vw32_start_process_show_window) && !is_gui_app)
353 354 355
    start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  else
    start.dwFlags = STARTF_USESTDHANDLES;
356 357 358 359 360 361 362
  start.wShowWindow = SW_HIDE;

  start.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
  start.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
  start.hStdError = GetStdHandle (STD_ERROR_HANDLE);
#endif /* HAVE_NTGUI */

363
#if 0
Richard M. Stallman's avatar
Richard M. Stallman committed
364 365
  /* Explicitly specify no security */
  if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
366
    goto EH_Fail;
Richard M. Stallman's avatar
Richard M. Stallman committed
367
  if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
368
    goto EH_Fail;
369
#endif
Richard M. Stallman's avatar
Richard M. Stallman committed
370
  sec_attrs.nLength = sizeof (sec_attrs);
371
  sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
Richard M. Stallman's avatar
Richard M. Stallman committed
372
  sec_attrs.bInheritHandle = FALSE;
373

Geoff Voelker's avatar
Geoff Voelker committed
374 375
  strcpy (dir, process_dir);
  unixtodos_filename (dir);
376 377 378 379 380 381

  flags = (!NILP (Vw32_start_process_share_console)
	   ? CREATE_NEW_PROCESS_GROUP
	   : CREATE_NEW_CONSOLE);
  if (NILP (Vw32_start_process_inherit_error_mode))
    flags |= CREATE_DEFAULT_ERROR_MODE;
Richard M. Stallman's avatar
Richard M. Stallman committed
382
  if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
383
		      flags, env, dir, &start, &cp->procinfo))
384 385 386 387 388 389 390 391 392
    goto EH_Fail;

  cp->pid = (int) cp->procinfo.dwProcessId;

  /* Hack for Windows 95, which assigns large (ie negative) pids */
  if (cp->pid < 0)
    cp->pid = -cp->pid;

  /* pid must fit in a Lisp_Int */
Stefan Monnier's avatar
Stefan Monnier committed
393
  cp->pid = cp->pid & INTMASK;
394 395

  *pPid = cp->pid;
Geoff Voelker's avatar
Geoff Voelker committed
396

Richard M. Stallman's avatar
Richard M. Stallman committed
397
  return TRUE;
Geoff Voelker's avatar
Geoff Voelker committed
398

Richard M. Stallman's avatar
Richard M. Stallman committed
399
 EH_Fail:
400
  DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError()););
Richard M. Stallman's avatar
Richard M. Stallman committed
401 402 403 404 405 406 407 408
  return FALSE;
}

/* create_child doesn't know what emacs' file handle will be for waiting
   on output from the child, so we need to make this additional call
   to register the handle with the process
   This way the select emulator knows how to match file handles with
   entries in child_procs.  */
409
void
Richard M. Stallman's avatar
Richard M. Stallman committed
410 411 412
register_child (int pid, int fd)
{
  child_process *cp;
413

Richard M. Stallman's avatar
Richard M. Stallman committed
414 415 416 417 418 419
  cp = find_child_pid (pid);
  if (cp == NULL)
    {
      DebPrint (("register_child unable to find pid %lu\n", pid));
      return;
    }
420

Richard M. Stallman's avatar
Richard M. Stallman committed
421 422 423
#ifdef FULL_DEBUG
  DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
#endif
424

Richard M. Stallman's avatar
Richard M. Stallman committed
425 426
  cp->fd = fd;

427 428 429 430 431 432
  /* thread is initially blocked until select is called; set status so
     that select will release thread */
  cp->status = STATUS_READ_ACKNOWLEDGED;

  /* attach child_process to fd_info */
  if (fd_info[fd].cp != NULL)
Richard M. Stallman's avatar
Richard M. Stallman committed
433
    {
434 435
      DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
      abort ();
Richard M. Stallman's avatar
Richard M. Stallman committed
436
    }
437 438

  fd_info[fd].cp = cp;
Richard M. Stallman's avatar
Richard M. Stallman committed
439 440 441 442 443 444
}

/* When a process dies its pipe will break so the reader thread will
   signal failure to the select emulator.
   The select emulator then calls this routine to clean up.
   Since the thread signaled failure we can assume it is exiting.  */
445
static void
446
reap_subprocess (child_process *cp)
Richard M. Stallman's avatar
Richard M. Stallman committed
447
{
448
  if (cp->procinfo.hProcess)
Richard M. Stallman's avatar
Richard M. Stallman committed
449
    {
450
      /* Reap the process */
Geoff Voelker's avatar
Geoff Voelker committed
451 452 453 454 455
#ifdef FULL_DEBUG
      /* Process should have already died before we are called.  */
      if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)
	DebPrint (("reap_subprocess: child fpr fd %d has not died yet!", cp->fd));
#endif
456 457 458 459
      CloseHandle (cp->procinfo.hProcess);
      cp->procinfo.hProcess = NULL;
      CloseHandle (cp->procinfo.hThread);
      cp->procinfo.hThread = NULL;
Richard M. Stallman's avatar
Richard M. Stallman committed
460
    }
461 462 463 464 465 466 467

  /* For asynchronous children, the child_proc resources will be freed
     when the last pipe read descriptor is closed; for synchronous
     children, we must explicitly free the resources now because
     register_child has not been called. */
  if (cp->fd == -1)
    delete_child (cp);
Richard M. Stallman's avatar
Richard M. Stallman committed
468 469 470 471 472
}

/* Wait for any of our existing child processes to die
   When it does, close its handle
   Return the pid and fill in the status if non-NULL.  */
473

474
int
475
sys_wait (int *status)
Richard M. Stallman's avatar
Richard M. Stallman committed
476 477 478
{
  DWORD active, retval;
  int nh;
479
  int pid;
Richard M. Stallman's avatar
Richard M. Stallman committed
480 481
  child_process *cp, *cps[MAX_CHILDREN];
  HANDLE wait_hnd[MAX_CHILDREN];
482

Richard M. Stallman's avatar
Richard M. Stallman committed
483 484 485 486
  nh = 0;
  if (dead_child != NULL)
    {
      /* We want to wait for a specific child */
487
      wait_hnd[nh] = dead_child->procinfo.hProcess;
Richard M. Stallman's avatar
Richard M. Stallman committed
488
      cps[nh] = dead_child;
489
      if (!wait_hnd[nh]) abort ();
Richard M. Stallman's avatar
Richard M. Stallman committed
490
      nh++;
Geoff Voelker's avatar
Geoff Voelker committed
491 492
      active = 0;
      goto get_result;
Richard M. Stallman's avatar
Richard M. Stallman committed
493 494 495 496
    }
  else
    {
      for (cp = child_procs+(child_proc_count-1); cp >= child_procs; cp--)
497
	/* some child_procs might be sockets; ignore them */
498 499
	if (CHILD_ACTIVE (cp) && cp->procinfo.hProcess
	    && (cp->fd < 0 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0))
Richard M. Stallman's avatar
Richard M. Stallman committed
500
	  {
501
	    wait_hnd[nh] = cp->procinfo.hProcess;
Richard M. Stallman's avatar
Richard M. Stallman committed
502 503 504 505
	    cps[nh] = cp;
	    nh++;
	  }
    }
506

Richard M. Stallman's avatar
Richard M. Stallman committed
507 508 509 510 511 512
  if (nh == 0)
    {
      /* Nothing to wait on, so fail */
      errno = ECHILD;
      return -1;
    }
Geoff Voelker's avatar
Geoff Voelker committed
513 514 515 516 517 518 519 520

  do
    {
      /* Check for quit about once a second. */
      QUIT;
      active = WaitForMultipleObjects (nh, wait_hnd, FALSE, 1000);
    } while (active == WAIT_TIMEOUT);

Richard M. Stallman's avatar
Richard M. Stallman committed
521 522 523 524 525
  if (active == WAIT_FAILED)
    {
      errno = EBADF;
      return -1;
    }
Geoff Voelker's avatar
Geoff Voelker committed
526 527
  else if (active >= WAIT_OBJECT_0
	   && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
Richard M. Stallman's avatar
Richard M. Stallman committed
528 529 530
    {
      active -= WAIT_OBJECT_0;
    }
Geoff Voelker's avatar
Geoff Voelker committed
531 532
  else if (active >= WAIT_ABANDONED_0
	   && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
Richard M. Stallman's avatar
Richard M. Stallman committed
533 534 535
    {
      active -= WAIT_ABANDONED_0;
    }
Geoff Voelker's avatar
Geoff Voelker committed
536 537 538 539
  else
    abort ();

get_result:
Richard M. Stallman's avatar
Richard M. Stallman committed
540 541 542 543 544 545 546 547 548 549 550 551 552
  if (!GetExitCodeProcess (wait_hnd[active], &retval))
    {
      DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
		 GetLastError ()));
      retval = 1;
    }
  if (retval == STILL_ACTIVE)
    {
      /* Should never happen */
      DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
      errno = EINVAL;
      return -1;
    }
553 554

  /* Massage the exit code from the process to match the format expected
Karl Heuer's avatar
Karl Heuer committed
555
     by the WIFSTOPPED et al macros in syswait.h.  Only WIFSIGNALED and
556 557 558 559 560 561
     WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT.  */

  if (retval == STATUS_CONTROL_C_EXIT)
    retval = SIGINT;
  else
    retval <<= 8;
562

Richard M. Stallman's avatar
Richard M. Stallman committed
563
  cp = cps[active];
564 565 566 567
  pid = cp->pid;
#ifdef FULL_DEBUG
  DebPrint (("Wait signaled with process pid %d\n", cp->pid));
#endif
568

Richard M. Stallman's avatar
Richard M. Stallman committed
569 570
  if (status)
    {
571 572 573 574 575 576
      *status = retval;
    }
  else if (synch_process_alive)
    {
      synch_process_alive = 0;

577 578 579 580 581 582
      /* Report the status of the synchronous process.  */
      if (WIFEXITED (retval))
	synch_process_retcode = WRETCODE (retval);
      else if (WIFSIGNALED (retval))
	{
	  int code = WTERMSIG (retval);
583 584
	  char *signame;

585
	  synchronize_system_messages_locale ();
586 587
	  signame = strsignal (code);

588 589 590 591 592
	  if (signame == 0)
	    signame = "unknown";

	  synch_process_death = signame;
	}
593 594

      reap_subprocess (cp);
Richard M. Stallman's avatar
Richard M. Stallman committed
595
    }
Geoff Voelker's avatar
Geoff Voelker committed
596 597

  reap_subprocess (cp);
598

599
  return pid;
Richard M. Stallman's avatar
Richard M. Stallman committed
600 601
}

602 603 604 605 606 607 608
/* Old versions of w32api headers don't have separate 32-bit and
   64-bit defines, but the one they have matches the 32-bit variety.  */
#ifndef IMAGE_NT_OPTIONAL_HDR32_MAGIC
# define IMAGE_NT_OPTIONAL_HDR32_MAGIC IMAGE_NT_OPTIONAL_HDR_MAGIC
# define IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER
#endif

Geoff Voelker's avatar
Geoff Voelker committed
609
void
610
w32_executable_type (char * filename, int * is_dos_app, int * is_cygnus_app, int * is_gui_app)
611
{
Geoff Voelker's avatar
Geoff Voelker committed
612 613
  file_data executable;
  char * p;
614

Geoff Voelker's avatar
Geoff Voelker committed
615 616 617
  /* Default values in case we can't tell for sure.  */
  *is_dos_app = FALSE;
  *is_cygnus_app = FALSE;
618
  *is_gui_app = FALSE;
Geoff Voelker's avatar
Geoff Voelker committed
619 620 621

  if (!open_input_file (&executable, filename))
    return;
622

Geoff Voelker's avatar
Geoff Voelker committed
623
  p = strrchr (filename, '.');
624

Geoff Voelker's avatar
Geoff Voelker committed
625
  /* We can only identify DOS .com programs from the extension. */
626
  if (p && xstrcasecmp (p, ".com") == 0)
Geoff Voelker's avatar
Geoff Voelker committed
627
    *is_dos_app = TRUE;
628 629
  else if (p && (xstrcasecmp (p, ".bat") == 0
		 || xstrcasecmp (p, ".cmd") == 0))
Geoff Voelker's avatar
Geoff Voelker committed
630 631 632 633 634 635 636 637 638
    {
      /* A DOS shell script - it appears that CreateProcess is happy to
	 accept this (somewhat surprisingly); presumably it looks at
	 COMSPEC to determine what executable to actually invoke.
	 Therefore, we have to do the same here as well. */
      /* Actually, I think it uses the program association for that
	 extension, which is defined in the registry.  */
      p = egetenv ("COMSPEC");
      if (p)
639
	w32_executable_type (p, is_dos_app, is_cygnus_app, is_gui_app);
Geoff Voelker's avatar
Geoff Voelker committed
640 641
    }
  else
642
    {
Geoff Voelker's avatar
Geoff Voelker committed
643 644 645 646
      /* Look for DOS .exe signature - if found, we must also check that
	 it isn't really a 16- or 32-bit Windows exe, since both formats
	 start with a DOS program stub.  Note that 16-bit Windows
	 executables use the OS/2 1.x format. */
647

Geoff Voelker's avatar
Geoff Voelker committed
648 649 650 651 652 653 654 655 656
      IMAGE_DOS_HEADER * dos_header;
      IMAGE_NT_HEADERS * nt_header;

      dos_header = (PIMAGE_DOS_HEADER) executable.file_base;
      if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
	goto unwind;

      nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);

657
      if ((char *) nt_header > (char *) dos_header + executable.size)
658
	{
Geoff Voelker's avatar
Geoff Voelker committed
659 660
	  /* Some dos headers (pkunzip) have bogus e_lfanew fields.  */
	  *is_dos_app = TRUE;
661
	}
Geoff Voelker's avatar
Geoff Voelker committed
662 663 664 665 666 667 668
      else if (nt_header->Signature != IMAGE_NT_SIGNATURE
	       && LOWORD (nt_header->Signature) != IMAGE_OS2_SIGNATURE)
  	{
	  *is_dos_app = TRUE;
  	}
      else if (nt_header->Signature == IMAGE_NT_SIGNATURE)
  	{
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
          IMAGE_DATA_DIRECTORY *data_dir = NULL;
          if (nt_header->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
            {
              /* Ensure we are using the 32 bit structure.  */
              IMAGE_OPTIONAL_HEADER32 *opt
                = (IMAGE_OPTIONAL_HEADER32*) &(nt_header->OptionalHeader);
              data_dir = opt->DataDirectory;
              *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
            }
          /* MingW 3.12 has the required 64 bit structs, but in case older
             versions don't, only check 64 bit exes if we know how.  */
#ifdef IMAGE_NT_OPTIONAL_HDR64_MAGIC
          else if (nt_header->OptionalHeader.Magic
                   == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
            {
              IMAGE_OPTIONAL_HEADER64 *opt
                = (IMAGE_OPTIONAL_HEADER64*) &(nt_header->OptionalHeader);
              data_dir = opt->DataDirectory;
              *is_gui_app = (opt->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI);
            }
#endif
          if (data_dir)
            {
              /* Look for cygwin.dll in DLL import list. */
              IMAGE_DATA_DIRECTORY import_dir =
                data_dir[IMAGE_DIRECTORY_ENTRY_IMPORT];
              IMAGE_IMPORT_DESCRIPTOR * imports;
              IMAGE_SECTION_HEADER * section;

              section = rva_to_section (import_dir.VirtualAddress, nt_header);
              imports = RVA_TO_PTR (import_dir.VirtualAddress, section,
                                    executable);

              for ( ; imports->Name; imports++)
                {
                  char * dllname = RVA_TO_PTR (imports->Name, section,
                                               executable);
706

707 708 709 710 711 712 713 714 715 716
                  /* The exact name of the cygwin dll has changed with
                     various releases, but hopefully this will be reasonably
                     future proof.  */
                  if (strncmp (dllname, "cygwin", 6) == 0)
                    {
                      *is_cygnus_app = TRUE;
                      break;
                    }
                }
            }
Geoff Voelker's avatar
Geoff Voelker committed
717
  	}
718
    }
719

Geoff Voelker's avatar
Geoff Voelker committed
720 721
unwind:
  close_file_data (&executable);
722 723
}

724
int
725
compare_env (const void *strp1, const void *strp2)
726
{
727
  const char *str1 = *(const char **)strp1, *str2 = *(const char **)strp2;
728 729 730

  while (*str1 && *str2 && *str1 != '=' && *str2 != '=')
    {
731 732 733
      /* Sort order in command.com/cmd.exe is based on uppercasing
         names, so do the same here.  */
      if (toupper (*str1) > toupper (*str2))
734
	return 1;
735
      else if (toupper (*str1) < toupper (*str2))
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
	return -1;
      str1++, str2++;
    }

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

void
merge_and_sort_env (char **envp1, char **envp2, char **new_envp)
{
  char **optr, **nptr;
  int num;

  nptr = new_envp;
  optr = envp1;
  while (*optr)
    *nptr++ = *optr++;
  num = optr - envp1;

  optr = envp2;
  while (*optr)
    *nptr++ = *optr++;
  num += optr - envp2;

  qsort (new_envp, num, sizeof (char *), compare_env);

  *nptr = NULL;
}
Richard M. Stallman's avatar
Richard M. Stallman committed
769 770 771

/* When a new child process is created we need to register it in our list,
   so intercept spawn requests.  */
772
int
773
sys_spawnve (int mode, char *cmdname, char **argv, char **envp)
Richard M. Stallman's avatar
Richard M. Stallman committed
774
{
775
  Lisp_Object program, full;
Richard M. Stallman's avatar
Richard M. Stallman committed
776
  char *cmdline, *env, *parg, **targ;
777
  int arglen, numenv;
778 779
  int pid;
  child_process *cp;
780
  int is_dos_app, is_cygnus_app, is_gui_app;
Geoff Voelker's avatar
Geoff Voelker committed
781 782
  int do_quoting = 0;
  char escape_char;
783 784 785 786
  /* We pass our process ID to our children by setting up an environment
     variable in their environment.  */
  char ppid_env_var_buffer[64];
  char *extra_env[] = {ppid_env_var_buffer, NULL};
787 788 789 790 791 792 793 794
  /* These are the characters that cause an argument to need quoting.
     Arguments with whitespace characters need quoting to prevent the
     argument being split into two or more. Arguments with wildcards
     are also quoted, for consistency with posix platforms, where wildcards
     are not expanded if we run the program directly without a shell.
     Some extra whitespace characters need quoting in Cygwin programs,
     so this list is conditionally modified below.  */
  char *sepchars = " \t*?";
795

796 797 798 799 800 801
  /* We don't care about the other modes */
  if (mode != _P_NOWAIT)
    {
      errno = EINVAL;
      return -1;
    }
802 803 804 805 806 807

  /* Handle executable names without an executable suffix.  */
  program = make_string (cmdname, strlen (cmdname));
  if (NILP (Ffile_executable_p (program)))
    {
      struct gcpro gcpro1;
808

809 810
      full = Qnil;
      GCPRO1 (program);
811
      openp (Vexec_path, program, Vexec_suffixes, &full, make_number (X_OK));
812 813 814 815 816 817
      UNGCPRO;
      if (NILP (full))
	{
	  errno = EINVAL;
	  return -1;
	}
Geoff Voelker's avatar
Geoff Voelker committed
818
      program = full;
819 820
    }

Geoff Voelker's avatar
Geoff Voelker committed
821
  /* make sure argv[0] and cmdname are both in DOS format */
822
  cmdname = SDATA (program);
823 824
  unixtodos_filename (cmdname);
  argv[0] = cmdname;
825

826
  /* Determine whether program is a 16-bit DOS executable, or a w32
Geoff Voelker's avatar
Geoff Voelker committed
827 828 829
     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
830 831 832 833 834
     escape quote chars in command line args that must be quoted).

     Also determine whether it is a GUI app, so that we don't hide its
     initial window unless specifically requested.  */
  w32_executable_type (cmdname, &is_dos_app, &is_cygnus_app, &is_gui_app);
Geoff Voelker's avatar
Geoff Voelker committed
835 836 837 838 839

  /* 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)
840
    {
Geoff Voelker's avatar
Geoff Voelker committed
841 842 843 844 845
      cmdname = alloca (MAXPATHLEN);
      if (egetenv ("CMDPROXY"))
	strcpy (cmdname, egetenv ("CMDPROXY"));
      else
	{
846
	  strcpy (cmdname, SDATA (Vinvocation_directory));
Geoff Voelker's avatar
Geoff Voelker committed
847 848 849
	  strcat (cmdname, "cmdproxy.exe");
	}
      unixtodos_filename (cmdname);
850
    }
851

Richard M. Stallman's avatar
Richard M. Stallman committed
852 853 854 855
  /* 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.
856

Geoff Voelker's avatar
Geoff Voelker committed
857 858 859 860 861 862 863
     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.

864
     The w32 GNU-based library from Cygnus doubles quotes to escape
Geoff Voelker's avatar
Geoff Voelker committed
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
     them, while MSVC uses backslash for escaping.  (Actually the MSVC
     startup code does attempt to recognise 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
     preceeded 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 (Vw32_quote_process_args))
    {
      do_quoting = 1;
      /* Override escape char by binding w32-quote-process-args to
	 desired character, or use t for auto-selection.  */
      if (INTEGERP (Vw32_quote_process_args))
	escape_char = XINT (Vw32_quote_process_args);
      else
	escape_char = is_cygnus_app ? '"' : '\\';
    }
892 893

  /* Cygwin apps needs quoting a bit more often */
894 895 896
  if (escape_char == '"')
    sepchars = "\r\n\t\f '";

Richard M. Stallman's avatar
Richard M. Stallman committed
897 898 899 900 901
  /* do argv...  */
  arglen = 0;
  targ = argv;
  while (*targ)
    {
902
      char * p = *targ;
Geoff Voelker's avatar
Geoff Voelker committed
903 904
      int need_quotes = 0;
      int escape_char_run = 0;
905 906

      if (*p == 0)
Geoff Voelker's avatar
Geoff Voelker committed
907 908 909
	need_quotes = 1;
      for ( ; *p; p++)
	{
910 911 912 913
	  if (escape_char == '"' && *p == '\\')
	    /* If it's a Cygwin app, \ needs to be escaped.  */
	    arglen++;
	  else if (*p == '"')
Geoff Voelker's avatar
Geoff Voelker committed
914 915 916 917 918 919 920 921 922 923 924 925 926
	    {
	      /* 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;
		}
	    }
927
	  else if (strchr (sepchars, *p) != NULL)
Geoff Voelker's avatar
Geoff Voelker committed
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
	    {
	      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;
	}
Richard M. Stallman's avatar
Richard M. Stallman committed
945 946
      arglen += strlen (*targ++) + 1;
    }
947
  cmdline = alloca (arglen);
Richard M. Stallman's avatar
Richard M. Stallman committed
948 949 950 951
  targ = argv;
  parg = cmdline;
  while (*targ)
    {
952
      char * p = *targ;
Geoff Voelker's avatar
Geoff Voelker committed
953
      int need_quotes = 0;
954 955

      if (*p == 0)
Geoff Voelker's avatar
Geoff Voelker committed
956
	need_quotes = 1;
957

Geoff Voelker's avatar
Geoff Voelker committed
958
      if (do_quoting)
959 960
	{
	  for ( ; *p; p++)
961
	    if ((strchr (sepchars, *p) != NULL) || *p == '"')
Geoff Voelker's avatar
Geoff Voelker committed
962
	      need_quotes = 1;
963
	}
Geoff Voelker's avatar
Geoff Voelker committed
964
      if (need_quotes)
965
	{
Geoff Voelker's avatar
Geoff Voelker committed
966
	  int escape_char_run = 0;
967 968 969 970 971 972 973
	  char * first;
	  char * last;

	  p = *targ;
	  first = p;
	  last = p + strlen (p) - 1;
	  *parg++ = '"';
Geoff Voelker's avatar
Geoff Voelker committed
974 975 976
#if 0
	  /* This version does not escape quotes if they occur at the
	     beginning or end of the arg - this could lead to incorrect
Glenn Morris's avatar
Glenn Morris committed
977
	     behavior when the arg itself represents a command line
Geoff Voelker's avatar
Geoff Voelker committed
978 979 980
	     containing quoted args.  I believe this was originally done
	     as a hack to make some things work, before
	     `w32-quote-process-args' was added.  */
981 982 983
	  while (*p)
	    {
	      if (*p == '"' && p > first && p < last)
Geoff Voelker's avatar
Geoff Voelker committed
984
		*parg++ = escape_char;	/* escape embedded quotes */
985 986
	      *parg++ = *p++;
	    }
Geoff Voelker's avatar
Geoff Voelker committed
987 988 989 990 991 992 993 994 995 996 997 998 999 1000
#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;
		}
1001 1002
	      else if (escape_char == '"' && *p == '\\')
		*parg++ = '\\';
Geoff Voelker's avatar
Geoff Voelker committed
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
	      *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
1017 1018 1019 1020 1021 1022 1023
	  *parg++ = '"';
	}
      else
	{
	  strcpy (parg, *targ);
	  parg += strlen (*targ);
	}
Richard M. Stallman's avatar
Richard M. Stallman committed
1024
      *parg++ = ' ';
1025
      targ++;
Richard M. Stallman's avatar
Richard M. Stallman committed
1026 1027
    }
  *--parg = '\0';
1028

Richard M. Stallman's avatar
Richard M. Stallman committed
1029 1030 1031
  /* and envp...  */
  arglen = 1;
  targ = envp;
1032
  numenv = 1; /* for end null */
Richard M. Stallman's avatar
Richard M. Stallman committed
1033 1034 1035
  while (*targ)
    {
      arglen += strlen (*targ++) + 1;
1036
      numenv++;
Richard M. Stallman's avatar
Richard M. Stallman committed
1037
    }
1038
  /* extra env vars... */
1039
  sprintf (ppid_env_var_buffer, "EM_PARENT_PROCESS_ID=%d",
Richard M. Stallman's avatar
Richard M. Stallman committed
1040 1041
	   GetCurrentProcessId ());
  arglen += strlen (ppid_env_var_buffer) + 1;
1042
  numenv++;
Richard M. Stallman's avatar
Richard M. Stallman committed
1043