w32proc.c 118 KB
Newer Older
1
/* Process support for GNU Emacs on the Microsoft Windows API.
2

3
Copyright (C) 1992, 1995, 1999-2020 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 <https://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
   Drew Bliss                   Oct 14, 1993
     Adapted from alarm.c by Tim Fleehart
*/

25 26
#define DEFER_MS_W32_H
#include <config.h>
27

28
#include <mingw_time.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
29 30 31
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
32
#include <ctype.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
33
#include <io.h>
34
#include <fcntl.h>
35
#include <unistd.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
36
#include <signal.h>
Jason Rumney's avatar
Jason Rumney committed
37
#include <sys/file.h>
38
#include <mbstring.h>
39
#include <locale.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
40

41 42
/* Include CRT headers *before* ms-w32.h.  */
#include <ms-w32.h>
Pavel Janík's avatar
Pavel Janík committed
43

44 45 46 47 48 49
#undef signal
#undef wait
#undef spawnve
#undef select
#undef kill

Richard M. Stallman's avatar
Richard M. Stallman committed
50 51
#include <windows.h>

52 53 54 55 56
#ifdef HAVE_LANGINFO_CODESET
#include <nl_types.h>
#include <langinfo.h>
#endif

Richard M. Stallman's avatar
Richard M. Stallman committed
57
#include "lisp.h"
58
#include "w32.h"
59
#include "w32common.h"
Geoff Voelker's avatar
Geoff Voelker committed
60
#include "w32heap.h"
61
#include "syswait.h"	/* for WNOHANG */
62
#include "syssignal.h"
63
#include "w32term.h"
64
#include "coding.h"
65

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

71
extern BOOL g_b_init_compare_string_w;
72 73
extern BOOL g_b_init_debug_break_process;

74
int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
75
		const struct timespec *, const sigset_t *);
76

Richard M. Stallman's avatar
Richard M. Stallman committed
77 78 79
/* Signal handlers...SIG_DFL == 0 so this is initialized correctly.  */
static signal_handler sig_handlers[NSIG];

80 81 82 83
static sigset_t sig_mask;

static CRITICAL_SECTION crit_sig;

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
/* Catch memory allocation before the heap allocation scheme is set
   up.  These functions should never be called, unless code is added
   early on in 'main' that runs before init_heap is called.  */
_Noreturn void * malloc_before_init (size_t);
_Noreturn void * realloc_before_init (void *, size_t);
_Noreturn void   free_before_init (void *);

_Noreturn void *
malloc_before_init (size_t size)
{
  fprintf (stderr,
	   "error: 'malloc' called before setting up heap allocation; exiting.\n");
  exit (-1);
}

_Noreturn void *
realloc_before_init (void *ptr, size_t size)
{
  fprintf (stderr,
	   "error: 'realloc' called before setting up heap allocation; exiting.\n");
  exit (-1);
}

_Noreturn void
free_before_init (void *ptr)
{
  fprintf (stderr,
	   "error: 'free' called before setting up heap allocation; exiting.\n");
  exit (-1);
}
Daniel Colascione's avatar
Daniel Colascione committed
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

extern BOOL ctrl_c_handler (unsigned long type);

/* MinGW64 doesn't add a leading underscore to external symbols,
   whereas configure.ac sets up LD_SWITCH_SYSTEM_TEMACS to force the
   entry point at __start, with two underscores.  */
#ifdef __MINGW64__
#define _start __start
#endif

extern void mainCRTStartup (void);

/* Startup code for running on NT.  When we are running as the dumped
   version, we need to bootstrap our heap and .bss section into our
   address space before we can actually hand off control to the startup
   code supplied by NT (primarily because that code relies upon malloc ()).  */
void _start (void);

void
_start (void)
{

#if 1
  /* Give us a way to debug problems with crashes on startup when
     running under the MSVC profiler. */
  if (GetEnvironmentVariable ("EMACS_DEBUG", NULL, 0) > 0)
    DebugBreak ();
#endif

143 144 145 146
  the_malloc_fn = malloc_before_init;
  the_realloc_fn = realloc_before_init;
  the_free_fn = free_before_init;

Daniel Colascione's avatar
Daniel Colascione committed
147 148 149 150 151 152 153 154 155 156 157 158 159
  /* Cache system info, e.g., the NT page size.  */
  cache_system_info ();

  /* This prevents ctrl-c's in shells running while we're suspended from
     having us exit.  */
  SetConsoleCtrlHandler ((PHANDLER_ROUTINE) ctrl_c_handler, TRUE);

  /* Prevent Emacs from being locked up (eg. in batch mode) when
     accessing devices that aren't mounted (eg. removable media drives).  */
  SetErrorMode (SEM_FAILCRITICALERRORS);
  mainCRTStartup ();
}

160
/* Improve on the CRT 'signal' implementation so that we could record
161
   the SIGCHLD handler and fake interval timers.  */
162
signal_handler
163
sys_signal (int sig, signal_handler handler)
Richard M. Stallman's avatar
Richard M. Stallman committed
164 165
{
  signal_handler old;
166

167
  /* SIGCHLD is needed for supporting subprocesses, see sys_kill
168 169
     below.  SIGALRM and SIGPROF are used by setitimer.  All the
     others are the only ones supported by the MS runtime.  */
170
  if (!(sig == SIGINT || sig == SIGSEGV || sig == SIGILL
171
	|| sig == SIGFPE || sig == SIGABRT || sig == SIGTERM
172
	|| sig == SIGCHLD || sig == SIGALRM || sig == SIGPROF))
Richard M. Stallman's avatar
Richard M. Stallman committed
173 174 175 176 177
    {
      errno = EINVAL;
      return SIG_ERR;
    }
  old = sig_handlers[sig];
178 179 180 181 182 183 184 185
  /* SIGABRT is treated specially because w32.c installs term_ntproc
     as its handler, so we don't want to override that afterwards.
     Aborting Emacs works specially anyway: either by calling
     emacs_abort directly or through terminate_due_to_signal, which
     calls emacs_abort through emacs_raise.  */
  if (!(sig == SIGABRT && old == term_ntproc))
    {
      sig_handlers[sig] = handler;
186
      if (!(sig == SIGCHLD || sig == SIGALRM || sig == SIGPROF))
187 188
	signal (sig, handler);
    }
Richard M. Stallman's avatar
Richard M. Stallman committed
189 190 191
  return old;
}

192 193 194 195
/* Emulate sigaction. */
int
sigaction (int sig, const struct sigaction *act, struct sigaction *oact)
{
196 197 198 199 200 201 202
  signal_handler old = SIG_DFL;
  int retval = 0;

  if (act)
    old = sys_signal (sig, act->sa_handler);
  else if (oact)
    old = sig_handlers[sig];
203

204
  if (old == SIG_ERR)
205 206
    {
      errno = EINVAL;
207
      retval = -1;
208 209 210 211 212 213 214
    }
  if (oact)
    {
      oact->sa_handler = old;
      oact->sa_flags = 0;
      oact->sa_mask = empty_mask;
    }
215
  return retval;
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
/* Emulate signal sets and blocking of signals used by timers.  */

int
sigemptyset (sigset_t *set)
{
  *set = 0;
  return 0;
}

int
sigaddset (sigset_t *set, int signo)
{
  if (!set)
    {
      errno = EINVAL;
      return -1;
    }
  if (signo < 0 || signo >= NSIG)
    {
      errno = EINVAL;
      return -1;
    }

  *set |= (1U << signo);

  return 0;
}

int
sigfillset (sigset_t *set)
{
  if (!set)
    {
      errno = EINVAL;
      return -1;
    }

  *set = 0xFFFFFFFF;
  return 0;
}

int
sigprocmask (int how, const sigset_t *set, sigset_t *oset)
{
  if (!(how == SIG_BLOCK || how == SIG_UNBLOCK || how == SIG_SETMASK))
    {
      errno = EINVAL;
      return -1;
    }

  if (oset)
    *oset = sig_mask;

  if (!set)
    return 0;

  switch (how)
    {
    case SIG_BLOCK:
      sig_mask |= *set;
      break;
    case SIG_SETMASK:
      sig_mask = *set;
      break;
    case SIG_UNBLOCK:
      /* FIXME: Catch signals that are blocked and reissue them when
	 they are unblocked.  Important for SIGALRM and SIGPROF only.  */
      sig_mask &= ~(*set);
      break;
    }

  return 0;
}

int
pthread_sigmask (int how, const sigset_t *set, sigset_t *oset)
{
  if (sigprocmask (how, set, oset) == -1)
    return EINVAL;
  return 0;
}

int
sigismember (const sigset_t *set, int signo)
{
  if (signo < 0 || signo >= NSIG)
    {
      errno = EINVAL;
      return -1;
    }
308
  if (signo > sizeof (*set) * CHAR_BIT)
309 310 311 312 313
    emacs_abort ();

  return (*set & (1U << signo)) != 0;
}

314 315
pid_t
getpgrp (void)
316
{
317
  return getpid ();
318 319
}

320
pid_t
321
tcgetpgrp (int fd)
322 323 324 325 326 327 328 329 330 331
{
  return getpid ();
}

int
setpgid (pid_t pid, pid_t pgid)
{
  return 0;
}

332 333 334 335 336 337
pid_t
setsid (void)
{
  return getpid ();
}

338 339 340 341 342 343 344 345 346
/* Emulations of interval timers.

   Limitations: only ITIMER_REAL and ITIMER_PROF are supported.

   Implementation: a separate thread is started for each timer type,
   the thread calls the appropriate signal handler when the timer
   expires, after stopping the thread which installed the timer.  */

struct itimer_data {
347 348 349
  volatile ULONGLONG expire;
  volatile ULONGLONG reload;
  volatile int terminate;
350 351 352 353 354
  int type;
  HANDLE caller_thread;
  HANDLE timer_thread;
};

355
static ULONGLONG ticks_now;
356
static struct itimer_data real_itimer, prof_itimer;
357
static ULONGLONG clocks_min;
358 359 360
/* If non-zero, itimers are disabled.  Used during shutdown, when we
   delete the critical sections used by the timer threads.  */
static int disable_itimers;
361 362 363

static CRITICAL_SECTION crit_real, crit_prof;

Eli Zaretskii's avatar
Eli Zaretskii committed
364
/* GetThreadTimes is not available on Windows 9X and possibly also on 2K.  */
365 366 367 368 369 370 371 372 373
typedef BOOL (WINAPI *GetThreadTimes_Proc) (
  HANDLE hThread,
  LPFILETIME lpCreationTime,
  LPFILETIME lpExitTime,
  LPFILETIME lpKernelTime,
  LPFILETIME lpUserTime);

static GetThreadTimes_Proc s_pfn_Get_Thread_Times;

374 375 376
#define MAX_SINGLE_SLEEP    30
#define TIMER_TICKS_PER_SEC 1000

377 378 379 380 381 382 383 384 385 386
/* Return a suitable time value, in 1-ms units, for THREAD, a handle
   to a thread.  If THREAD is NULL or an invalid handle, return the
   current wall-clock time since January 1, 1601 (UTC).  Otherwise,
   return the sum of kernel and user times used by THREAD since it was
   created, plus its creation time.  */
static ULONGLONG
w32_get_timer_time (HANDLE thread)
{
  ULONGLONG retval;
  int use_system_time = 1;
387 388
  /* The functions below return times in 100-ns units.  */
  const int tscale = 10 * TIMER_TICKS_PER_SEC;
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406

  if (thread && thread != INVALID_HANDLE_VALUE
      && s_pfn_Get_Thread_Times != NULL)
    {
      FILETIME creation_ftime, exit_ftime, kernel_ftime, user_ftime;
      ULARGE_INTEGER temp_creation, temp_kernel, temp_user;

      if (s_pfn_Get_Thread_Times (thread, &creation_ftime, &exit_ftime,
				  &kernel_ftime, &user_ftime))
	{
	  use_system_time = 0;
	  temp_creation.LowPart = creation_ftime.dwLowDateTime;
	  temp_creation.HighPart = creation_ftime.dwHighDateTime;
	  temp_kernel.LowPart = kernel_ftime.dwLowDateTime;
	  temp_kernel.HighPart = kernel_ftime.dwHighDateTime;
	  temp_user.LowPart = user_ftime.dwLowDateTime;
	  temp_user.HighPart = user_ftime.dwHighDateTime;
	  retval =
407 408
	    temp_creation.QuadPart / tscale + temp_kernel.QuadPart / tscale
	    + temp_user.QuadPart / tscale;
409 410 411 412 413
	}
      else
	DebPrint (("GetThreadTimes failed with error code %lu\n",
		   GetLastError ()));
    }
414

415 416 417 418 419 420 421 422 423 424
  if (use_system_time)
    {
      FILETIME current_ftime;
      ULARGE_INTEGER temp;

      GetSystemTimeAsFileTime (&current_ftime);

      temp.LowPart = current_ftime.dwLowDateTime;
      temp.HighPart = current_ftime.dwHighDateTime;

425
      retval = temp.QuadPart / tscale;
426 427 428 429 430 431
    }

  return retval;
}

/* Thread function for a timer thread.  */
432 433 434 435 436 437 438
static DWORD WINAPI
timer_loop (LPVOID arg)
{
  struct itimer_data *itimer = (struct itimer_data *)arg;
  int which = itimer->type;
  int sig = (which == ITIMER_REAL) ? SIGALRM : SIGPROF;
  CRITICAL_SECTION *crit = (which == ITIMER_REAL) ? &crit_real : &crit_prof;
439
  const DWORD max_sleep = MAX_SINGLE_SLEEP * 1000 / TIMER_TICKS_PER_SEC;
440
  HANDLE hth = (which == ITIMER_REAL) ? NULL : itimer->caller_thread;
441 442 443 444 445

  while (1)
    {
      DWORD sleep_time;
      signal_handler handler;
446
      ULONGLONG now, expire, reload;
447 448 449 450 451 452 453 454 455

      /* Load new values if requested by setitimer.  */
      EnterCriticalSection (crit);
      expire = itimer->expire;
      reload = itimer->reload;
      LeaveCriticalSection (crit);
      if (itimer->terminate)
	return 0;

456
      if (expire == 0)
457 458 459 460 461 462
	{
	  /* We are idle.  */
	  Sleep (max_sleep);
	  continue;
	}

463
      if (expire > (now = w32_get_timer_time (hth)))
464 465 466 467 468 469 470 471 472 473
	sleep_time = expire - now;
      else
	sleep_time = 0;
      /* Don't sleep too long at a time, to be able to see the
	 termination flag without too long a delay.  */
      while (sleep_time > max_sleep)
	{
	  if (itimer->terminate)
	    return 0;
	  Sleep (max_sleep);
474
	  EnterCriticalSection (crit);
475
	  expire = itimer->expire;
476 477 478
	  LeaveCriticalSection (crit);
	  sleep_time =
	    (expire > (now = w32_get_timer_time (hth))) ? expire - now : 0;
479 480 481 482 483
	}
      if (itimer->terminate)
	return 0;
      if (sleep_time > 0)
	{
484
	  Sleep (sleep_time * 1000 / TIMER_TICKS_PER_SEC);
485 486
	  /* Always sleep past the expiration time, to make sure we
	     never call the handler _before_ the expiration time,
487
	     always slightly after it.  Sleep(5) makes sure we don't
488 489 490
	     hog the CPU by calling 'w32_get_timer_time' with high
	     frequency, and also let other threads work.  */
	  while (w32_get_timer_time (hth) < expire)
491
	    Sleep (5);
492 493
	}

494 495 496 497
      EnterCriticalSection (crit);
      expire = itimer->expire;
      LeaveCriticalSection (crit);
      if (expire == 0)
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
	continue;

      /* Time's up.  */
      handler = sig_handlers[sig];
      if (!(handler == SIG_DFL || handler == SIG_IGN || handler == SIG_ERR)
	  /* FIXME: Don't ignore masked signals.  Instead, record that
	     they happened and reissue them when the signal is
	     unblocked.  */
	  && !sigismember (&sig_mask, sig)
	  /* Simulate masking of SIGALRM and SIGPROF when processing
	     fatal signals.  */
	  && !fatal_error_in_progress
	  && itimer->caller_thread)
	{
	  /* Simulate a signal delivered to the thread which installed
	     the timer, by suspending that thread while the handler
	     runs.  */
515 516
	  HANDLE th = itimer->caller_thread;
	  DWORD result = SuspendThread (th);
517 518

	  if (result == (DWORD)-1)
519 520
	    return 2;

521
	  handler (sig);
522
	  ResumeThread (th);
523 524 525 526 527
	}

      /* Update expiration time and loop.  */
      EnterCriticalSection (crit);
      expire = itimer->expire;
528 529 530 531 532
      if (expire == 0)
	{
	  LeaveCriticalSection (crit);
	  continue;
	}
533 534 535
      reload = itimer->reload;
      if (reload > 0)
	{
536
	  now = w32_get_timer_time (hth);
537 538
	  if (expire <= now)
	    {
539
	      ULONGLONG lag = now - expire;
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563

	      /* If we missed some opportunities (presumably while
		 sleeping or while the signal handler ran), skip
		 them.  */
	      if (lag > reload)
		expire = now - (lag % reload);

	      expire += reload;
	    }
	}
      else
	expire = 0;	/* become idle */
      itimer->expire = expire;
      LeaveCriticalSection (crit);
    }
  return 0;
}

static void
stop_timer_thread (int which)
{
  struct itimer_data *itimer =
    (which == ITIMER_REAL) ? &real_itimer : &prof_itimer;
  int i;
564
  DWORD err = 0, exit_code = 255;
565
  BOOL status;
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

  /* Signal the thread that it should terminate.  */
  itimer->terminate = 1;

  if (itimer->timer_thread == NULL)
    return;

  /* Wait for the timer thread to terminate voluntarily, then kill it
     if it doesn't.  This loop waits twice more than the maximum
     amount of time a timer thread sleeps, see above.  */
  for (i = 0; i < MAX_SINGLE_SLEEP / 5; i++)
    {
      if (!((status = GetExitCodeThread (itimer->timer_thread, &exit_code))
	    && exit_code == STILL_ACTIVE))
	break;
      Sleep (10);
    }
  if ((status == FALSE && (err = GetLastError ()) == ERROR_INVALID_HANDLE)
      || exit_code == STILL_ACTIVE)
    {
      if (!(status == FALSE && err == ERROR_INVALID_HANDLE))
	TerminateThread (itimer->timer_thread, 0);
    }

  /* Clean up.  */
  CloseHandle (itimer->timer_thread);
  itimer->timer_thread = NULL;
  if (itimer->caller_thread)
    {
      CloseHandle (itimer->caller_thread);
      itimer->caller_thread = NULL;
    }
}

/* This is called at shutdown time from term_ntproc.  */
void
term_timers (void)
{
  if (real_itimer.timer_thread)
    stop_timer_thread (ITIMER_REAL);
  if (prof_itimer.timer_thread)
    stop_timer_thread (ITIMER_PROF);

609 610 611 612
  /* We are going to delete the critical sections, so timers cannot
     work after this.  */
  disable_itimers = 1;

613 614 615 616 617 618 619 620 621
  DeleteCriticalSection (&crit_real);
  DeleteCriticalSection (&crit_prof);
  DeleteCriticalSection (&crit_sig);
}

/* This is called at initialization time from init_ntproc.  */
void
init_timers (void)
{
Paul Eggert's avatar
Paul Eggert committed
622
  /* GetThreadTimes is not available on all versions of Windows, so
623 624 625 626
     need to probe for its availability dynamically, and call it
     through a pointer.  */
  s_pfn_Get_Thread_Times = NULL; /* in case dumped Emacs comes with a value */
  if (os_subtype != OS_9X)
627 628
    s_pfn_Get_Thread_Times = (GetThreadTimes_Proc)
      get_proc_addr (GetModuleHandle ("kernel32.dll"), "GetThreadTimes");
629

630 631 632 633 634 635 636 637
  /* Make sure we start with zeroed out itimer structures, since
     dumping may have left there traces of threads long dead.  */
  memset (&real_itimer, 0, sizeof real_itimer);
  memset (&prof_itimer, 0, sizeof prof_itimer);

  InitializeCriticalSection (&crit_real);
  InitializeCriticalSection (&crit_prof);
  InitializeCriticalSection (&crit_sig);
638 639

  disable_itimers = 0;
640 641 642 643 644
}

static int
start_timer_thread (int which)
{
645
  DWORD exit_code, tid;
646
  HANDLE th;
647 648 649 650 651 652 653 654
  struct itimer_data *itimer =
    (which == ITIMER_REAL) ? &real_itimer : &prof_itimer;

  if (itimer->timer_thread
      && GetExitCodeThread (itimer->timer_thread, &exit_code)
      && exit_code == STILL_ACTIVE)
    return 0;

655 656 657 658 659 660 661 662 663 664 665 666
  /* Clean up after possibly exited thread.  */
  if (itimer->timer_thread)
    {
      CloseHandle (itimer->timer_thread);
      itimer->timer_thread = NULL;
    }
  if (itimer->caller_thread)
    {
      CloseHandle (itimer->caller_thread);
      itimer->caller_thread = NULL;
    }

667
  /* Start a new thread.  */
668 669 670 671 672 673 674
  if (!DuplicateHandle (GetCurrentProcess (), GetCurrentThread (),
			GetCurrentProcess (), &th, 0, FALSE,
			DUPLICATE_SAME_ACCESS))
    {
      errno = ESRCH;
      return -1;
    }
675 676
  itimer->terminate = 0;
  itimer->type = which;
677
  itimer->caller_thread = th;
678 679 680 681 682
  /* Request that no more than 64KB of stack be reserved for this
     thread, to avoid reserving too much memory, which would get in
     the way of threads we start to wait for subprocesses.  See also
     new_child below.  */
  itimer->timer_thread = CreateThread (NULL, 64 * 1024, timer_loop,
683
				       (void *)itimer, 0x00010000, &tid);
684 685 686 687 688 689 690 691 692 693 694 695

  if (!itimer->timer_thread)
    {
      CloseHandle (itimer->caller_thread);
      itimer->caller_thread = NULL;
      errno = EAGAIN;
      return -1;
    }

  /* This is needed to make sure that the timer thread running for
     profiling gets CPU as soon as the Sleep call terminates. */
  if (which == ITIMER_PROF)
696
    SetThreadPriority (itimer->timer_thread, THREAD_PRIORITY_TIME_CRITICAL);
697

698 699 700
  return 0;
}

701 702 703 704 705 706
/* Most of the code of getitimer and setitimer (but not of their
   subroutines) was shamelessly stolen from itimer.c in the DJGPP
   library, see www.delorie.com/djgpp.  */
int
getitimer (int which, struct itimerval *value)
{
707 708 709
  volatile ULONGLONG *t_expire;
  volatile ULONGLONG *t_reload;
  ULONGLONG expire, reload;
710 711
  __int64 usecs;
  CRITICAL_SECTION *crit;
712
  struct itimer_data *itimer;
713

714 715 716
  if (disable_itimers)
    return -1;

717 718 719 720 721 722 723 724 725 726 727 728
  if (!value)
    {
      errno = EFAULT;
      return -1;
    }

  if (which != ITIMER_REAL && which != ITIMER_PROF)
    {
      errno = EINVAL;
      return -1;
    }

729 730 731 732
  itimer = (which == ITIMER_REAL) ? &real_itimer : &prof_itimer;

  ticks_now = w32_get_timer_time ((which == ITIMER_REAL)
				  ? NULL
733
				  : GetCurrentThread ());
734 735 736

  t_expire = &itimer->expire;
  t_reload = &itimer->reload;
737 738 739 740 741 742 743 744 745 746
  crit = (which == ITIMER_REAL) ? &crit_real : &crit_prof;

  EnterCriticalSection (crit);
  reload = *t_reload;
  expire = *t_expire;
  LeaveCriticalSection (crit);

  if (expire)
    expire -= ticks_now;

747 748 749
  value->it_value.tv_sec    = expire / TIMER_TICKS_PER_SEC;
  usecs =
    (expire % TIMER_TICKS_PER_SEC) * (__int64)1000000 / TIMER_TICKS_PER_SEC;
750
  value->it_value.tv_usec   = usecs;
751 752 753
  value->it_interval.tv_sec = reload / TIMER_TICKS_PER_SEC;
  usecs =
    (reload % TIMER_TICKS_PER_SEC) * (__int64)1000000 / TIMER_TICKS_PER_SEC;
754 755 756 757 758 759 760 761
  value->it_interval.tv_usec= usecs;

  return 0;
}

int
setitimer(int which, struct itimerval *value, struct itimerval *ovalue)
{
762 763
  volatile ULONGLONG *t_expire, *t_reload;
  ULONGLONG expire, reload, expire_old, reload_old;
764 765
  __int64 usecs;
  CRITICAL_SECTION *crit;
766
  struct itimerval tem, *ptem;
767

768 769 770
  if (disable_itimers)
    return -1;

771 772 773 774 775
  /* Posix systems expect timer values smaller than the resolution of
     the system clock be rounded up to the clock resolution.  First
     time we are called, measure the clock tick resolution.  */
  if (!clocks_min)
    {
776
      ULONGLONG t1, t2;
777

778 779
      for (t1 = w32_get_timer_time (NULL);
	   (t2 = w32_get_timer_time (NULL)) == t1; )
780 781 782 783 784
	;
      clocks_min = t2 - t1;
    }

  if (ovalue)
785
    ptem = ovalue;
786
  else
787
    ptem = &tem;
788

789 790
  if (getitimer (which, ptem)) /* also sets ticks_now */
    return -1;		       /* errno already set */
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809

  t_expire =
    (which == ITIMER_REAL) ? &real_itimer.expire : &prof_itimer.expire;
  t_reload =
    (which == ITIMER_REAL) ? &real_itimer.reload : &prof_itimer.reload;

  crit = (which == ITIMER_REAL) ? &crit_real : &crit_prof;

  if (!value
      || (value->it_value.tv_sec == 0 && value->it_value.tv_usec == 0))
    {
      EnterCriticalSection (crit);
      /* Disable the timer.  */
      *t_expire = 0;
      *t_reload = 0;
      LeaveCriticalSection (crit);
      return 0;
    }

810
  reload = value->it_interval.tv_sec * TIMER_TICKS_PER_SEC;
811 812 813

  usecs = value->it_interval.tv_usec;
  if (value->it_interval.tv_sec == 0
814
      && usecs && usecs * TIMER_TICKS_PER_SEC < clocks_min * 1000000)
815 816 817
    reload = clocks_min;
  else
    {
818
      usecs *= TIMER_TICKS_PER_SEC;
819 820 821
      reload += usecs / 1000000;
    }

822
  expire = value->it_value.tv_sec * TIMER_TICKS_PER_SEC;
823 824
  usecs = value->it_value.tv_usec;
  if (value->it_value.tv_sec == 0
825
      && usecs * TIMER_TICKS_PER_SEC < clocks_min * 1000000)
826 827 828
    expire = clocks_min;
  else
    {
829
      usecs *= TIMER_TICKS_PER_SEC;
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
      expire += usecs / 1000000;
    }

  expire += ticks_now;

  EnterCriticalSection (crit);
  expire_old = *t_expire;
  reload_old = *t_reload;
  if (!(expire == expire_old && reload == reload_old))
    {
      *t_reload = reload;
      *t_expire = expire;
    }
  LeaveCriticalSection (crit);

  return start_timer_thread (which);
}

int
alarm (int seconds)
{
851 852
#ifdef HAVE_SETITIMER
  struct itimerval new_values, old_values;
853 854 855 856 857

  new_values.it_value.tv_sec = seconds;
  new_values.it_value.tv_usec = 0;
  new_values.it_interval.tv_sec = new_values.it_interval.tv_usec = 0;

858 859 860 861
  if (setitimer (ITIMER_REAL, &new_values, &old_values) < 0)
    return 0;
  return old_values.it_value.tv_sec;
#else
862
  return seconds;
863
#endif
864 865
}

866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885


/* Here's an overview of how support for subprocesses and
   network/serial streams is implemented on MS-Windows.

   The management of both subprocesses and network/serial streams
   circles around the child_procs[] array, which can record up to the
   grand total of MAX_CHILDREN (= 32) of these.  (The reasons for the
   32 limitation will become clear below.)  Each member of
   child_procs[] is a child_process structure, defined on w32.h.

   A related data structure is the fd_info[] array, which holds twice
   as many members, 64, and records the information about file
   descriptors used for communicating with subprocesses and
   network/serial devices.  Each member of the array is the filedesc
   structure, which records the Windows handle for communications,
   such as the read end of the pipe to a subprocess, a socket handle,
   etc.

   Both these arrays reference each other: there's a member of
886
   child_process structure that records the corresponding file
887 888 889 890 891 892 893 894 895 896
   descriptor, and there's a member of filedesc structure that holds a
   pointer to the corresponding child_process.

   Whenever Emacs starts a subprocess or opens a network/serial
   stream, the function new_child is called to prepare a new
   child_process structure.  new_child looks for the first vacant slot
   in the child_procs[] array, initializes it, and starts a "reader
   thread" that will watch the output of the subprocess/stream and its
   status.  (If no vacant slot can be found, new_child returns a
   failure indication to its caller, and the higher-level Emacs
897
   primitive that called it will then fail with EMFILE or EAGAIN.)
898 899 900 901 902

   The reader thread started by new_child communicates with the main
   (a.k.a. "Lisp") thread via two event objects and a status, all of
   them recorded by the members of the child_process structure in
   child_procs[].  The event objects serve as semaphores between the
903
   reader thread and the 'pselect' emulation in sys_select, as follows:
904 905 906 907 908 909 910 911 912 913 914 915

     . Initially, the reader thread is waiting for the char_consumed
       event to become signaled by sys_select, which is an indication
       for the reader thread to go ahead and try reading more stuff
       from the subprocess/stream.

     . The reader thread then attempts to read by calling a
       blocking-read function.  When the read call returns, either
       successfully or with some failure indication, the reader thread
       updates the status of the read accordingly, and signals the 2nd
       event object, char_avail, on whose handle sys_select is
       waiting.  This tells sys_select that the file descriptor
916
       allocated for the subprocess or the stream is ready to be
917 918 919 920
       read from.

   When the subprocess exits or the network/serial stream is closed,
   the reader thread sets the status accordingly and exits.  It also
921 922
   exits when the main thread sets the status to STATUS_READ_ERROR
   and/or the char_avail and char_consumed event handles become NULL;
923 924 925 926
   this is how delete_child, called by Emacs when a subprocess or a
   stream is terminated, terminates the reader thread as part of
   deleting the child_process object.

927 928
   The sys_select function emulates the Posix 'pselect' functionality;
   it is needed because the Windows 'select' function supports only
929 930 931 932 933 934 935 936 937 938 939 940 941 942
   network sockets, while Emacs expects 'pselect' to work for any file
   descriptor, including pipes and serial streams.

   When sys_select is called, it uses the information in fd_info[]
   array to convert the file descriptors which it was asked to watch
   into Windows handles.  In general, the handle to watch is the
   handle of the char_avail event of the child_process structure that
   corresponds to the file descriptor.  In addition, for subprocesses,
   sys_select watches one more handle: the handle for the subprocess,
   so that it could emulate the SIGCHLD signal when the subprocess
   exits.

   If file descriptor zero (stdin) doesn't have its bit set in the
   'rfds' argument to sys_select, the function always watches for
943 944
   keyboard interrupts, to be able to interrupt the wait and return
   when the user presses C-g.
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

   Having collected the handles to watch, sys_select calls
   WaitForMultipleObjects to wait for any one of them to become
   signaled.  Since WaitForMultipleObjects can only watch up to 64
   handles, Emacs on Windows is limited to maximum 32 child_process
   objects (since a subprocess consumes 2 handles to be watched, see
   above).

   When any of the handles become signaled, sys_select does whatever
   is appropriate for the corresponding child_process object:

     . If it's a handle to the char_avail event, sys_select marks the
       corresponding bit in 'rfds', and Emacs will then read from that
       file descriptor.

     . If it's a handle to the process, sys_select calls the SIGCHLD
       handler, to inform Emacs of the fact that the subprocess
       exited.

   The waitpid emulation works very similar to sys_select, except that
   it only watches handles of subprocesses, and doesn't synchronize
   with the reader thread.

   Because socket descriptors on Windows are handles, while Emacs
   expects them to be file descriptors, all low-level I/O functions,
   such as 'read' and 'write', and all socket operations, like
   'connect', 'recvfrom', 'accept', etc., are redirected to the
   corresponding 'sys_*' functions, which must convert a file
   descriptor to a handle using the fd_info[] array, and then invoke
   the corresponding Windows API on the handle.  Most of these
   redirected 'sys_*' functions are implemented on w32.c.

   When the file descriptor was produced by functions such as 'open',
   the corresponding handle is obtained by calling _get_osfhandle.  To
   produce a file descriptor for a socket handle, which has no file
   descriptor as far as Windows is concerned, the function
   socket_to_fd opens the null device; the resulting file descriptor
   will never be used directly in any I/O API, but serves as an index
   into the fd_info[] array, where the socket handle is stored.  The
   SOCK_HANDLE macro retrieves the handle when given the file
   descriptor.

   The function sys_kill emulates the Posix 'kill' functionality to
   terminate other processes.  It does that by attaching to the
   foreground window of the process and sending a Ctrl-C or Ctrl-BREAK
   signal to the process; if that doesn't work, then it calls
   TerminateProcess to forcibly terminate the process.  Note that this
   only terminates the immediate process whose PID was passed to
   sys_kill; it doesn't terminate the child processes of that process.
   This means, for example, that an Emacs subprocess run through a
   shell might not be killed, because sys_kill will only terminate the
   shell.  (In practice, however, such problems are very rare.)  */

998 999 1000 1001 1002 1003 1004
/* 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 ];

1005
static DWORD WINAPI reader_thread (void *arg);
1006

Richard M. Stallman's avatar
Richard M. Stallman committed
1007
/* Find an unused process slot.  */
1008
child_process *
Richard M. Stallman's avatar
Richard M. Stallman committed
1009 1010 1011
new_child (void)
{
  child_process *cp;
1012
  DWORD id;
1013

1014
  for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
1015
    if (!CHILD_ACTIVE (cp) && cp->procinfo.hProcess == NULL)
Paul Eggert's avatar
Paul Eggert committed
1016
      goto Initialize;
1017 1018
  if (child_proc_count == MAX_CHILDREN)
    {
1019
      int i = 0;
1020
      child_process *dead_cp = NULL;
1021

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
      DebPrint (("new_child: No vacant slots, looking for dead processes\n"));
      for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
	if (!CHILD_ACTIVE (cp) && cp->procinfo.hProcess)
	  {
	    DWORD status = 0;

	    if (!GetExitCodeProcess (cp->procinfo.hProcess, &status))
	      {
		DebPrint (("new_child.GetExitCodeProcess: error %lu for PID %lu\n",
			   GetLastError (), cp->procinfo.dwProcessId));
		status = STILL_ACTIVE;
	      }
	    if (status != STILL_ACTIVE
		|| WaitForSingleObject (cp->procinfo.hProcess, 0) == WAIT_OBJECT_0)
	      {
1037 1038
		DebPrint (("new_child: Freeing slot of dead process %d, fd %d\n",
			   cp->procinfo.dwProcessId, cp->fd));
1039 1040 1041 1042
		CloseHandle (cp->procinfo.hProcess);
		cp->procinfo.hProcess = NULL;
		CloseHandle (cp->procinfo.hThread);
		cp->procinfo.hThread = NULL;
1043 1044 1045 1046 1047 1048
		/* Free up to 2 dead slots at a time, so that if we
		   have a lot of them, they will eventually all be
		   freed when the tornado ends.  */
		if (i == 0)
		  dead_cp = cp;
		else
1049
		  break;
1050
		i++;
1051 1052
	      }
	  }
1053 1054 1055 1056 1057
      if (dead_cp)
	{
	  cp = dead_cp;
	  goto Initialize;
	}
1058
    }
1059 1060 1061 1062
  if (child_proc_count == MAX_CHILDREN)
    return NULL;
  cp = &child_procs[child_proc_count++];

Paul Eggert's avatar
Paul Eggert committed
1063
 Initialize:
1064 1065 1066 1067 1068 1069
  /* Last opportunity to avoid leaking handles before we forget them
     for good.  */
  if (cp->procinfo.hProcess)
    CloseHandle (cp->procinfo.hProcess);
  if (cp->procinfo.hThread)
    CloseHandle (cp->procinfo.hThread);
1070
  memset (cp, 0, sizeof (*cp));
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
  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)
        {
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
	  /* The 0x00010000 flag is STACK_SIZE_PARAM_IS_A_RESERVATION.
	     It means that the 64K stack we are requesting in the 2nd
	     argument is how much memory should be reserved for the
	     stack.  If we don't use this flag, the memory requested
	     by the 2nd argument is the amount actually _committed_,
	     but Windows reserves 8MB of memory for each thread's
	     stack.  (The 8MB figure comes from the -stack
	     command-line argument we pass to the linker when building
	     Emacs, but that's because we need a large stack for
	     Emacs's main thread.)  Since we request 2GB of reserved
	     memory at startup (see w32heap.c), which is close to the
	     maximum memory available for a 32-bit process on Windows,
	     the 8MB reservation for each thread causes failures in
	     starting subprocesses, because we create a thread running
	     reader_thread for each subprocess.  As 8MB of stack is
	     way too much for reader_thread, forcing Windows to
	     reserve less wins the day.  */
	  cp->thrd = CreateThread (NULL, 64 * 1024, reader_thread, cp,
				   0x00010000, &id);
1102 1103 1104 1105 1106 1107 1108 1109
	  if (cp->thrd)
	    return cp;
	}
    }
  delete_child (cp);
  return NULL;
}

1110
void
1111 1112 1113 1114 1115 1116 1117
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)
1118
      emacs_abort ();
1119

1120
  if (!CHILD_ACTIVE (cp) && cp->procinfo.hProcess == NULL)
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
    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);
1133
#if 0
Paul Eggert's avatar
Paul Eggert committed
1134
          /* We used to forcibly terminate the thread here, but it
1135 1136 1137
             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.  */
1138 1139 1140 1141 1142 1143
	  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);
	    }
1144
#endif
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
	}
      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--)
1164 1165
	if (CHILD_ACTIVE (&child_procs[i])
	    || child_procs[i].procinfo.hProcess != NULL)
1166 1167 1168 1169 1170 1171 1172
	  {
	    child_proc_count = i + 1;
	    break;
	  }
    }
  if (i < 0)
    child_proc_count = 0;
Richard M. Stallman's avatar
Richard M. Stallman committed
1173 1174 1175 1176 1177 1178 1179
}

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

1181
  for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
1182 1183
    if ((CHILD_ACTIVE (cp) || cp->procinfo.hProcess != NULL)
	&& pid == cp->pid)
Richard M. Stallman's avatar
Richard M. Stallman committed
1184 1185 1186 1187
      return cp;
  return NULL;
}

1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
void
release_listen_threads (void)
{
  int i;

  for (i = child_proc_count - 1; i >= 0; i--)
    {
      if (CHILD_ACTIVE (&child_procs[i])
	  && (fd_info[child_procs[i].fd].flags & FILE_LISTEN))
	child_procs[i].status = STATUS_READ_ERROR;
    }
}
Richard M. Stallman's avatar
Richard M. Stallman committed
1200

1201 1202
/* Thread proc for child process and socket reader threads. Each thread
   is normally blocked until woken by select() to check for input by
1203
   reading one char.  When the read completes, char_avail is signaled
1204
   to wake up the select emulator and the thread blocks itself again. */
1205
static DWORD WINAPI
Richard M. Stallman's avatar
Richard M. Stallman committed
1206 1207 1208
reader_thread (void *arg)
{
  child_process *cp;
1209

Richard M. Stallman's avatar
Richard M. Stallman committed
1210 1211
  /* Our identity */
  cp = (child_process *)arg;
1212

Richard M. Stallman's avatar
Richard M. Stallman committed
1213
  /* We have to wait for the go-ahead before we can start */
Geoff Voelker's avatar
Geoff Voelker committed
1214
  if (cp == NULL
Juanma Barranquero's avatar
Juanma Barranquero committed
1215 1216
      || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0
      || cp->fd < 0)
1217 1218
    return 1;

Richard M. Stallman's avatar
Richard M. Stallman committed
1219 1220
  for (;;)
    {
1221 1222
      int rc;

1223 1224 1225
      if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_CONNECT) != 0)
	rc = _sys_wait_connect (cp->fd);
      else if (cp->fd >= 0 && (fd_info[cp->fd].flags & FILE_LISTEN) != 0)
1226 1227 1228
	rc = _sys_wait_accept (cp->fd);
      else
	rc = _sys_read_ahead (cp->fd);
1229

1230 1231 1232 1233 1234
      /* Don't bother waiting for the event if we already have been
	 told to exit by delete_child.  */
      if (cp->status == STATUS_READ_ERROR || !cp->char_avail)
	break;

1235 1236
      /* 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
1237 1238
      if (!SetEvent (cp->char_avail))
        {
1239 1240 1241
	  DebPrint (("reader_thread.SetEvent(0x%x) failed with %lu for fd %ld (PID %d)\n",
		     (DWORD_PTR)cp->char_avail, GetLastError (),
		     cp->fd, cp->pid));
1242 1243 1244
	  return 1;
	}

1245 1246
      if (rc == STATUS_READ_ERROR || rc == STATUS_CONNECT_FAILED)
	return 2;
1247

Richard M. Stallman's avatar
Richard M. Stallman committed
1248
      /* If the read died, the child has died so let the thread die */
1249
      if (rc == STATUS_READ_FAILED)
Richard M. Stallman's avatar
Richard M. Stallman committed
1250
	break;
1251

1252 1253 1254 1255 1256
      /* Don't bother waiting for the acknowledge if we already have
	 been told to exit by delete_child.  */
      if (cp->status == STATUS_READ_ERROR || !cp->char_consumed)
	break;

Richard M. Stallman's avatar
Richard M. Stallman committed
1257 1258 1259 1260 1261 1262 1263
      /* 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;
        }
1264 1265
      /* delete_child sets status to STATUS_READ_ERROR when it wants
	 us to exit.  */
1266 1267
      if (cp->status == STATUS_READ_ERROR)
	break;
Richard M. Stallman's avatar
Richard M. Stallman committed
1268 1269 1270 1271
    }
  return 0;
}

1272 1273 1274 1275
/* 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.
   Note that this directory's name is UTF-8 encoded.  */
Geoff Voelker's avatar
Geoff Voelker committed
1276 1277
static char * process_dir;

1278
static BOOL
1279
create_child (char *exe, char *cmdline, char *env, int is_gui_app,
1280
	      pid_t * pPid, child_process *cp)
Richard M. Stallman's avatar
Richard M. Stallman committed
1281 1282 1283
{
  STARTUPINFO start;
  SECURITY_ATTRIBUTES sec_attrs;
1284
#if 0
Richard M. Stallman's avatar
Richard M. Stallman committed
1285
  SECURITY_DESCRIPTOR sec_desc;
1286
#endif
1287
  DWORD flags;
1288 1289
  char dir[ MAX_PATH ];
  char *p;
1290
  const char *ext;
1291

1292
  if (cp == NULL) emacs_abort ();
1293

Richard M. Stallman's avatar
Richard M. Stallman committed
1294 1295
  memset (&start, 0, sizeof (start));
  start.cb = sizeof (start);
1296

1297
#ifdef HAVE_NTGUI
1298
  if (NILP (Vw32_start_process_show_window) && !is_gui_app)
1299 1300 1301
    start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  else
    start.dwFlags = STARTF_USESTDHANDLES;
1302 1303 1304 1305 1306 1307 1308
  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 */

1309
#if 0
Richard M. Stallman's avatar
Richard M. Stallman committed
1310 1311
  /* Explicitly specify no security */
  if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
1312
    goto EH_Fail;
Richard M. Stallman's avatar
Richard M. Stallman committed
1313
  if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
1314
    goto EH_Fail;
1315
#endif
Richard M. Stallman's avatar
Richard M. Stallman committed
1316
  sec_attrs.nLength = sizeof (sec_attrs);
1317
  sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
Richard M. Stallman's avatar
Richard M. Stallman committed
1318
  sec_attrs.bInheritHandle = FALSE;
1319

1320 1321 1322 1323 1324 1325 1326 1327
  filename_to_ansi (process_dir, dir);
  /* Can't use unixtodos_filename here, since that needs its file name
     argument encoded in UTF-8.  OTOH, process_dir, which _is_ in
     UTF-8, points, to the directory computed by our caller, and we
     don't want to modify that, either.  */
  for (p = dir; *p; p = CharNextA (p))
    if (*p == '/')
      *p = '\\';
1328

1329 1330 1331 1332 1333 1334 1335 1336 1337
  /* CreateProcess handles batch files as exe specially.  This special
     handling fails when both the batch file and arguments are quoted.
     We pass NULL as exe to avoid the special handling. */
  if (exe && cmdline[0] == '"' &&
      (ext = strrchr (exe, '.')) &&
      (xstrcasecmp (ext, ".bat") == 0
       || xstrcasecmp (ext, ".cmd") == 0))
      exe = NULL;

1338 1339 1340 1341 1342
  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;
1343 1344
  if (!CreateProcessA (exe, cmdline, &sec_attrs, NULL, TRUE,
		       flags, env, dir, &start, &cp->procinfo))
1345 1346 1347 1348 1349 1350 1351 1352 1353
    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;

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

Richard M. Stallman's avatar
Richard M. Stallman committed
1355
  return TRUE;
Geoff Voelker's avatar
Geoff Voelker committed
1356

Richard M. Stallman's avatar
Richard M. Stallman committed
1357
 EH_Fail:
1358
  DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError ()););
Richard M. Stallman's avatar
Richard M. Stallman committed
1359 1360 1361
  return FALSE;
}

1362
/* create_child doesn't know what emacs's file handle will be for waiting
Richard M. Stallman's avatar
Richard M. Stallman committed
1363 1364 1365 1366
   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.  */
1367
void
1368
register_child (pid_t pid, int fd)
Richard M. Stallman's avatar
Richard M. Stallman committed
1369 1370
{
  child_process *cp;
1371

1372
  cp = find_child_pid ((DWORD)pid);
Richard M. Stallman's avatar
Richard M. Stallman committed
1373 1374 1375 1376 1377
  if (cp == NULL)
    {
      DebPrint (("register_child unable to find pid %lu\n", pid));
      return;
    }
1378

Richard M. Stallman's avatar
Richard M. Stallman committed
1379 1380 1381
#ifdef FULL_DEBUG
  DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
#endif
1382

Richard M. Stallman's avatar
Richard M. Stallman committed
1383 1384
  cp->fd = fd;

1385 1386 1387 1388 1389 1390
  /* 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
1391
    {
1392
      DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
1393
      emacs_abort ();
Richard M. Stallman's avatar
Richard M. Stallman committed
1394
    }
1395 1396

  fd_info[fd].cp = cp;
Richard M. Stallman's avatar
Richard M. Stallman committed
1397 1398
}

1399
/* Called from waitpid when a process exits.  */
1400
static void
1401
reap_subprocess (child_process *cp)
Richard M. Stallman's avatar
Richard M. Stallman committed
1402
{
1403
  if (cp->procinfo.hProcess)
Richard M. Stallman's avatar
Richard M. Stallman committed
1404
    {
1405
      /* Reap the process */
Geoff Voelker's avatar
Geoff Voelker committed
1406 1407 1408
#ifdef FULL_DEBUG
      /* Process should have already died before we are called.  */
      if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)
1409
	DebPrint (("reap_subprocess: child for fd %d has not died yet!", cp->fd));
Geoff Voelker's avatar
Geoff Voelker committed
1410
#endif
1411 1412 1413 1414
      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
1415
    }
1416

1417 1418 1419 1420 1421
  /* If cp->fd was not closed yet, we might be still reading the
     process output, so don't free its resources just yet.  The call
     to delete_child on behalf of this subprocess will be made by
     sys_read when the subprocess output is fully read.  */
  if (cp->fd < 0)
1422
    delete_child (cp);
Richard M. Stallman's avatar
Richard M. Stallman committed
1423 1424
}

1425 1426 1427 1428
/* Wait for a child process specified by PID, or for any of our
   existing child processes (if PID is nonpositive) to die.  When it
   does, close its handle.  Return the pid of the process that died
   and fill in STATUS if non-NULL.  */
1429

1430 1431
pid_t
waitpid (pid_t pid, int *status, int options)
Richard M. Stallman's avatar
Richard M. Stallman committed
1432 1433 1434 1435 1436
{
  DWORD active, retval;
  int nh;
  child_process *cp, *cps[MAX_CHILDREN];
  HANDLE wait_hnd[MAX_CHILDREN];
1437 1438
  DWORD timeout_ms;
  int dont_wait = (options & WNOHANG) != 0;
1439

Richard M. Stallman's avatar
Richard M. Stallman committed
1440
  nh = 0;
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
  /* According to Posix:

     PID = -1 means status is requested for any child process.

     PID > 0 means status is requested for a single child process
     whose pid is PID.

     PID = 0 means status is requested for any child process whose
     process group ID is equal to that of the calling process.  But
     since Windows has only a limited support for process groups (only
     for console processes and only for the purposes of passing
     Ctrl-BREAK signal to them), and since we have no documented way
     of determining whether a given process belongs to our group, we
     treat 0 as -1.

     PID < -1 means status is requested for any child process whose
     process group ID is equal to the absolute value of PID.  Again,
     since we don't support process groups, we treat that as -1.  */
  if (pid > 0)
Richard M. Stallman's avatar
Richard M. Stallman committed
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
      int our_child = 0;

      /* We are requested to wait for a specific child.  */
      for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
	{
	  /* Some child_procs might be sockets; ignore them.  Also
	     ignore subprocesses whose output is not yet completely
	     read.  */
	  if (CHILD_ACTIVE (cp)
	      && cp->procinfo.hProcess
	      && cp->pid == pid)
	    {
	      our_child = 1;
	      break;
	    }
	}
      if (our_child)
	{
	  if (cp->fd < 0 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0)
	    {
	      wait_hnd[nh] = cp->procinfo.hProcess;
	      cps[nh] = cp;
	      nh++;
	    }
	  else if (dont_wait)
	    {
	      /* PID specifies our subprocess, but its status is not
		 yet available.  */
	      return 0;
	    }
	}
      if (nh == 0)
	{
	  /* No such child process, or nothing to wait for, so fail.  */
	  errno = ECHILD;
	  return -1;
	}
Richard M. Stallman's avatar
Richard M. Stallman committed
1498 1499 1500
    }
  else
    {
1501
      for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
	{
	  if (CHILD_ACTIVE (cp)
	      && cp->procinfo.hProcess
	      && (cp->fd < 0 || (fd_info[cp->fd].flags & FILE_AT_EOF) != 0))
	    {
	      wait_hnd[nh] = cp->procinfo.hProcess;
	      cps[nh] = cp;
	      nh++;
	    }
	}
      if (nh == 0)
	{
	  /* Nothing to wait on, so fail.  */
	  errno = ECHILD;
	  return -1;
	}
Richard M. Stallman's avatar
Richard M. Stallman committed
1518
    }
1519

1520 1521 1522 1523
  if (dont_wait)
    timeout_ms = 0;
  else
    timeout_ms = 1000;	/* check for quit about once a second. */
Geoff Voelker's avatar
Geoff Voelker committed
1524 1525 1526

  do
    {
1527 1528 1529 1530 1531
      /* When child_status_changed calls us with WNOHANG in OPTIONS,
	 we are supposed to be non-interruptible, so don't allow
	 quitting in that case.  */
      if (!dont_wait)
	maybe_quit ();
1532
      active = WaitForMultipleObjects (nh, wait_hnd, FALSE, timeout_ms);
1533
    } while (active == WAIT_TIMEOUT && !dont_wait);
Geoff Voelker's avatar
Geoff Voelker committed
1534

Richard M. Stallman's avatar
Richard M. Stallman committed
1535 1536 1537 1538 1539
  if (active == WAIT_FAILED)
    {
      errno = EBADF;
      return -1;
    }
1540 1541 1542 1543 1544 1545 1546 1547 1548
  else if (active == WAIT_TIMEOUT && dont_wait)
    {
      /* PID specifies our subprocess, but it didn't exit yet, so its
	 status is not yet available.  */
#ifdef FULL_DEBUG
      DebPrint (("Wait: PID %d not reap yet\n", cp->pid));
#endif
      return 0;
    }
Geoff Voelker's avatar
Geoff Voelker committed
1549 1550
  else if (active >= WAIT_OBJECT_0
	   && active < WAIT_OBJECT_0+MAXIMUM_WAIT_OBJECTS)
Richard M. Stallman's avatar
Richard M. Stallman committed
1551 1552 1553
    {
      active -= WAIT_OBJECT_0;
    }
Geoff Voelker's avatar
Geoff Voelker committed
1554 1555
  else if (active >= WAIT_ABANDONED_0
	   && active < WAIT_ABANDONED_0+MAXIMUM_WAIT_OBJECTS)
Richard M. Stallman's avatar
Richard M. Stallman committed
1556 1557 1558
    {
      active -= WAIT_ABANDONED_0;
    }
Geoff Voelker's avatar
Geoff Voelker committed
1559
  else
1560
    emacs_abort ();
Geoff Voelker's avatar
Geoff Voelker committed
1561

Richard M. Stallman's avatar
Richard M. Stallman committed
1562 1563 1564 1565 1566 1567 1568 1569
  if (!GetExitCodeProcess (wait_hnd[active], &retval))
    {
      DebPrint (("Wait.GetExitCodeProcess failed with %lu\n",
		 GetLastError ()));
      retval = 1;
    }
  if (retval == STILL_ACTIVE)
    {
1570 1571 1572 1573 1574
      /* Should never happen.  But it does, with invoking git-gui.exe
	 asynchronously.  So we punt, and just report this process as
	 exited with exit code 259, when we are called with WNOHANG
	 from child_status_changed, because in that case we already
	 _know_ the process has died.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
1575
      DebPrint (("Wait.WaitForMultipleObjects returned an active process\n"));
1576 1577 1578 1579 1580
      if (!(pid > 0 && dont_wait))
	{
	  errno = EINVAL;
	  return -1;
	}
Richard M. Stallman's avatar
Richard M. Stallman committed
1581
    }
1582 1583

  /* Massage the exit code from the process to match the format expected
Karl Heuer's avatar
Karl Heuer committed
1584
     by the WIFSTOPPED et al macros in syswait.h.  Only WIFSIGNALED and
1585 1586 1587 1588 1589 1590
     WIFEXITED are supported; WIFSTOPPED doesn't make sense under NT.  */

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

1592 1593
  if (pid > 0 && active != 0)
    emacs_abort ();
Richard M. Stallman's avatar
Richard M. Stallman committed
1594
  cp = cps[active];
1595 1596 1597 1598
  pid = cp->pid;
#ifdef FULL_DEBUG
  DebPrint (("Wait signaled with process pid %d\n", cp->pid));
#endif
1599

Richard M. Stallman's avatar
Richard M. Stallman committed
1600
  if (status)
1601
    *status = retval;
Geoff Voelker's avatar
Geoff Voelker committed
1602
  reap_subprocess (cp);
1603

1604
  return pid;
Richard M. Stallman's avatar
Richard M. Stallman committed
1605 1606
}

Daniel Colascione's avatar
Daniel Colascione committed
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
int
open_input_file (file_data *p_file, char *filename)
{
  HANDLE file;
  HANDLE file_mapping;
  void  *file_base;
  unsigned long size, upper_size;

  file = CreateFileA (filename, GENERIC_READ, FILE_SHARE_READ, NULL,
		      OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  if (file == INVALID_HANDLE_VALUE)
    return FALSE;

  size = GetFileSize (file, &upper_size);
  file_mapping = CreateFileMapping (file, NULL, PAGE_READONLY,
				    0, size, NULL);
  if (!file_mapping)
    return FALSE;

  file_base = MapViewOfFile (file_mapping, FILE_MAP_READ, 0, 0, size);
  if (file_base == 0)
    return FALSE;

  p_file->name = filename;
  p_file->size = size;
  p_file->file = file;
  p_file->file_mapping = file_mapping;
  p_file->file_base = file_base;

  return TRUE;
}

/* Return pointer to section header for section containing the given
   relative virtual address. */
IMAGE_SECTION_HEADER *
rva_to_section (DWORD_PTR rva, IMAGE_NT_HEADERS * nt_header)
{
  PIMAGE_SECTION_HEADER section;
  int i;

  section = IMAGE_FIRST_SECTION (nt_header);

  for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
    {
      /* Some linkers (eg. the NT SDK linker I believe) swapped the
	 meaning of these two values - or rather, they ignored
	 VirtualSize entirely and always set it to zero.  This affects
	 some very old exes (eg. gzip dated Dec 1993).  Since
	 w32_executable_type relies on this function to work reliably,
	 we need to cope with this.  */
      DWORD_PTR real_size = max (section->SizeOfRawData,
			     section->Misc.VirtualSize);
      if (rva >= section->VirtualAddress
	  && rva < section->VirtualAddress + real_size)
	return section;
      section++;
    }
  return NULL;
}

/* Close the system structures associated with the given file.  */
void
close_file_data (file_data *p_file)
{
  UnmapViewOfFile (p_file->file_base);
  CloseHandle (p_file->file_mapping);
  /* For the case of output files, set final size.  */
  SetFilePointer (p_file->file, p_file->size, NULL, FILE_BEGIN);
  SetEndOfFile (p_file->file);
  CloseHandle (p_file->file);
}

1679 1680 1681 1682 1683 1684 1685
/* 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

1686 1687
/* Implementation note: This function works with file names encoded in
   the current ANSI codepage.  */