w32proc.c 92.3 KB
Newer Older
1
/* Process support for GNU Emacs on the Microsoft Windows API.
2
   Copyright (C) 1992, 1995, 1999-2013 Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
3

4 5
This file is part of GNU Emacs.

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

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

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

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
27
#include <ctype.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
28
#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
#include <config.h>

36 37 38 39 40 41
#undef signal
#undef wait
#undef spawnve
#undef select
#undef kill

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

Eli Zaretskii's avatar
Eli Zaretskii committed
48 49 50 51 52
#ifdef HAVE_LANGINFO_CODESET
#include <nl_types.h>
#include <langinfo.h>
#endif

Richard M. Stallman's avatar
Richard M. Stallman committed
53
#include "lisp.h"
Geoff Voelker's avatar
Geoff Voelker committed
54
#include "w32.h"
Daniel Colascione's avatar
Daniel Colascione committed
55
#include "w32common.h"
Geoff Voelker's avatar
Geoff Voelker committed
56
#include "w32heap.h"
Richard M. Stallman's avatar
Richard M. Stallman committed
57
#include "systime.h"
58 59
#include "syswait.h"
#include "process.h"
60
#include "syssignal.h"
61
#include "w32term.h"
Eli Zaretskii's avatar
Eli Zaretskii committed
62
#include "dispextern.h"		/* for xstrcasecmp */
63
#include "coding.h"
64

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

Geoff Voelker's avatar
Geoff Voelker committed
70
Lisp_Object Qhigh, Qlow;
71

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

75 76 77 78
static sigset_t sig_mask;

static CRITICAL_SECTION crit_sig;

79
/* Improve on the CRT 'signal' implementation so that we could record
80
   the SIGCHLD handler and fake interval timers.  */
81
signal_handler
82
sys_signal (int sig, signal_handler handler)
Richard M. Stallman's avatar
Richard M. Stallman committed
83 84
{
  signal_handler old;
85

86
  /* SIGCHLD is needed for supporting subprocesses, see sys_kill
87 88
     below.  SIGALRM and SIGPROF are used by setitimer.  All the
     others are the only ones supported by the MS runtime.  */
89
  if (!(sig == SIGCHLD || sig == SIGSEGV || sig == SIGILL
90 91
	|| sig == SIGFPE || sig == SIGABRT || sig == SIGTERM
	|| sig == SIGALRM || sig == SIGPROF))
Richard M. Stallman's avatar
Richard M. Stallman committed
92 93 94 95 96
    {
      errno = EINVAL;
      return SIG_ERR;
    }
  old = sig_handlers[sig];
97 98 99 100 101 102 103 104
  /* 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;
105
      if (!(sig == SIGCHLD || sig == SIGALRM || sig == SIGPROF))
106 107
	signal (sig, handler);
    }
Richard M. Stallman's avatar
Richard M. Stallman committed
108 109 110
  return old;
}

111 112 113 114
/* Emulate sigaction. */
int
sigaction (int sig, const struct sigaction *act, struct sigaction *oact)
{
115 116 117 118 119 120 121
  signal_handler old = SIG_DFL;
  int retval = 0;

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

123
  if (old == SIG_ERR)
124 125
    {
      errno = EINVAL;
126
      retval = -1;
127 128 129 130 131 132 133
    }
  if (oact)
    {
      oact->sa_handler = old;
      oact->sa_flags = 0;
      oact->sa_mask = empty_mask;
    }
134
  return retval;
135 136
}

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
/* 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;
    }
  if (signo > sizeof (*set) * BITS_PER_CHAR)
    emacs_abort ();

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

233 234
pid_t
getpgrp (void)
235
{
236
  return getpid ();
237 238
}

239
pid_t
240
tcgetpgrp (int fd)
241 242 243 244 245 246 247 248 249 250
{
  return getpid ();
}

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

251 252 253 254 255 256
pid_t
setsid (void)
{
  return getpid ();
}

257 258 259 260 261 262 263 264 265
/* 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 {
266 267 268
  volatile ULONGLONG expire;
  volatile ULONGLONG reload;
  volatile int terminate;
269 270 271 272 273
  int type;
  HANDLE caller_thread;
  HANDLE timer_thread;
};

274
static ULONGLONG ticks_now;
275
static struct itimer_data real_itimer, prof_itimer;
276
static ULONGLONG clocks_min;
277 278 279
/* If non-zero, itimers are disabled.  Used during shutdown, when we
   delete the critical sections used by the timer threads.  */
static int disable_itimers;
280 281 282

static CRITICAL_SECTION crit_real, crit_prof;

Eli Zaretskii's avatar
Eli Zaretskii committed
283
/* GetThreadTimes is not available on Windows 9X and possibly also on 2K.  */
284 285 286 287 288 289 290 291 292
typedef BOOL (WINAPI *GetThreadTimes_Proc) (
  HANDLE hThread,
  LPFILETIME lpCreationTime,
  LPFILETIME lpExitTime,
  LPFILETIME lpKernelTime,
  LPFILETIME lpUserTime);

static GetThreadTimes_Proc s_pfn_Get_Thread_Times;

293 294 295
#define MAX_SINGLE_SLEEP    30
#define TIMER_TICKS_PER_SEC 1000

296 297 298 299 300 301 302 303 304 305
/* 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;
306 307
  /* The functions below return times in 100-ns units.  */
  const int tscale = 10 * TIMER_TICKS_PER_SEC;
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325

  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 =
326 327
	    temp_creation.QuadPart / tscale + temp_kernel.QuadPart / tscale
	    + temp_user.QuadPart / tscale;
328 329 330 331 332
	}
      else
	DebPrint (("GetThreadTimes failed with error code %lu\n",
		   GetLastError ()));
    }
333

334 335 336 337 338 339 340 341 342 343
  if (use_system_time)
    {
      FILETIME current_ftime;
      ULARGE_INTEGER temp;

      GetSystemTimeAsFileTime (&current_ftime);

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

344
      retval = temp.QuadPart / tscale;
345 346 347 348 349 350
    }

  return retval;
}

/* Thread function for a timer thread.  */
351 352 353 354 355 356 357
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;
358
  const DWORD max_sleep = MAX_SINGLE_SLEEP * 1000 / TIMER_TICKS_PER_SEC;
359
  HANDLE hth = (which == ITIMER_REAL) ? NULL : itimer->caller_thread;
360 361 362 363 364

  while (1)
    {
      DWORD sleep_time;
      signal_handler handler;
365
      ULONGLONG now, expire, reload;
366 367 368 369 370 371 372 373 374

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

375
      if (expire == 0)
376 377 378 379 380 381
	{
	  /* We are idle.  */
	  Sleep (max_sleep);
	  continue;
	}

382
      if (expire > (now = w32_get_timer_time (hth)))
383 384 385 386 387 388 389 390 391 392
	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);
393
	  EnterCriticalSection (crit);
394
	  expire = itimer->expire;
395 396 397
	  LeaveCriticalSection (crit);
	  sleep_time =
	    (expire > (now = w32_get_timer_time (hth))) ? expire - now : 0;
398 399 400 401 402
	}
      if (itimer->terminate)
	return 0;
      if (sleep_time > 0)
	{
403
	  Sleep (sleep_time * 1000 / TIMER_TICKS_PER_SEC);
404 405
	  /* Always sleep past the expiration time, to make sure we
	     never call the handler _before_ the expiration time,
406
	     always slightly after it.  Sleep(5) makes sure we don't
407 408 409
	     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)
410
	    Sleep (5);
411 412
	}

413 414 415 416
      EnterCriticalSection (crit);
      expire = itimer->expire;
      LeaveCriticalSection (crit);
      if (expire == 0)
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
	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.  */
434 435
	  HANDLE th = itimer->caller_thread;
	  DWORD result = SuspendThread (th);
436 437

	  if (result == (DWORD)-1)
438 439
	    return 2;

440
	  handler (sig);
441
	  ResumeThread (th);
442 443 444 445 446
	}

      /* Update expiration time and loop.  */
      EnterCriticalSection (crit);
      expire = itimer->expire;
447 448 449 450 451
      if (expire == 0)
	{
	  LeaveCriticalSection (crit);
	  continue;
	}
452 453 454
      reload = itimer->reload;
      if (reload > 0)
	{
455
	  now = w32_get_timer_time (hth);
456 457
	  if (expire <= now)
	    {
458
	      ULONGLONG lag = now - expire;
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482

	      /* 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;
483 484
  DWORD err, exit_code = 255;
  BOOL status;
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527

  /* 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);

528 529 530 531
  /* We are going to delete the critical sections, so timers cannot
     work after this.  */
  disable_itimers = 1;

532 533 534 535 536 537 538 539 540
  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
541
  /* GetThreadTimes is not available on all versions of Windows, so
542 543 544 545 546 547 548 549
     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)
    s_pfn_Get_Thread_Times =
      (GetThreadTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
					   "GetThreadTimes");

550 551 552 553 554 555 556 557
  /* 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);
558 559

  disable_itimers = 0;
560 561 562 563 564 565
}

static int
start_timer_thread (int which)
{
  DWORD exit_code;
566
  HANDLE th;
567 568 569 570 571 572 573 574
  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;

575 576 577 578 579 580 581 582 583 584 585 586
  /* 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;
    }

587
  /* Start a new thread.  */
588 589 590 591 592 593 594
  if (!DuplicateHandle (GetCurrentProcess (), GetCurrentThread (),
			GetCurrentProcess (), &th, 0, FALSE,
			DUPLICATE_SAME_ACCESS))
    {
      errno = ESRCH;
      return -1;
    }
595 596
  itimer->terminate = 0;
  itimer->type = which;
597
  itimer->caller_thread = th;
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
  /* 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,
				       (void *)itimer, 0x00010000, NULL);

  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)
616
    SetThreadPriority (itimer->timer_thread, THREAD_PRIORITY_TIME_CRITICAL);
617

618 619 620
  return 0;
}

621 622 623 624 625 626
/* 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)
{
627 628 629
  volatile ULONGLONG *t_expire;
  volatile ULONGLONG *t_reload;
  ULONGLONG expire, reload;
630 631
  __int64 usecs;
  CRITICAL_SECTION *crit;
632
  struct itimer_data *itimer;
633

634 635 636
  if (disable_itimers)
    return -1;

637 638 639 640 641 642 643 644 645 646 647 648
  if (!value)
    {
      errno = EFAULT;
      return -1;
    }

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

649 650 651 652
  itimer = (which == ITIMER_REAL) ? &real_itimer : &prof_itimer;

  ticks_now = w32_get_timer_time ((which == ITIMER_REAL)
				  ? NULL
653
				  : GetCurrentThread ());
654 655 656

  t_expire = &itimer->expire;
  t_reload = &itimer->reload;
657 658 659 660 661 662 663 664 665 666
  crit = (which == ITIMER_REAL) ? &crit_real : &crit_prof;

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

  if (expire)
    expire -= ticks_now;

667 668 669
  value->it_value.tv_sec    = expire / TIMER_TICKS_PER_SEC;
  usecs =
    (expire % TIMER_TICKS_PER_SEC) * (__int64)1000000 / TIMER_TICKS_PER_SEC;
670
  value->it_value.tv_usec   = usecs;
671 672 673
  value->it_interval.tv_sec = reload / TIMER_TICKS_PER_SEC;
  usecs =
    (reload % TIMER_TICKS_PER_SEC) * (__int64)1000000 / TIMER_TICKS_PER_SEC;
674 675 676 677 678 679 680 681
  value->it_interval.tv_usec= usecs;

  return 0;
}

int
setitimer(int which, struct itimerval *value, struct itimerval *ovalue)
{
682 683
  volatile ULONGLONG *t_expire, *t_reload;
  ULONGLONG expire, reload, expire_old, reload_old;
684 685
  __int64 usecs;
  CRITICAL_SECTION *crit;
686
  struct itimerval tem, *ptem;
687

688 689 690
  if (disable_itimers)
    return -1;

691 692 693 694 695
  /* 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)
    {
696
      ULONGLONG t1, t2;
697

698 699
      for (t1 = w32_get_timer_time (NULL);
	   (t2 = w32_get_timer_time (NULL)) == t1; )
700 701 702 703 704
	;
      clocks_min = t2 - t1;
    }

  if (ovalue)
705
    ptem = ovalue;
706
  else
707
    ptem = &tem;
708

709 710
  if (getitimer (which, ptem)) /* also sets ticks_now */
    return -1;		       /* errno already set */
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729

  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;
    }

730
  reload = value->it_interval.tv_sec * TIMER_TICKS_PER_SEC;
731 732 733

  usecs = value->it_interval.tv_usec;
  if (value->it_interval.tv_sec == 0
734
      && usecs && usecs * TIMER_TICKS_PER_SEC < clocks_min * 1000000)
735 736 737
    reload = clocks_min;
  else
    {
738
      usecs *= TIMER_TICKS_PER_SEC;
739 740 741
      reload += usecs / 1000000;
    }

742
  expire = value->it_value.tv_sec * TIMER_TICKS_PER_SEC;
743 744
  usecs = value->it_value.tv_usec;
  if (value->it_value.tv_sec == 0
745
      && usecs * TIMER_TICKS_PER_SEC < clocks_min * 1000000)
746 747 748
    expire = clocks_min;
  else
    {
749
      usecs *= TIMER_TICKS_PER_SEC;
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
      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)
{
771 772
#ifdef HAVE_SETITIMER
  struct itimerval new_values, old_values;
773 774 775 776 777

  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;

778 779 780 781
  if (setitimer (ITIMER_REAL, &new_values, &old_values) < 0)
    return 0;
  return old_values.it_value.tv_sec;
#else
782
  return seconds;
783
#endif
784 785
}

786 787 788 789 790 791 792
/* 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 ];

793
static DWORD WINAPI reader_thread (void *arg);
794

Richard M. Stallman's avatar
Richard M. Stallman committed
795
/* Find an unused process slot.  */
796
child_process *
Richard M. Stallman's avatar
Richard M. Stallman committed
797 798 799
new_child (void)
{
  child_process *cp;
800
  DWORD id;
801

802
  for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
803
    if (!CHILD_ACTIVE (cp) && cp->procinfo.hProcess == NULL)
Paul Eggert's avatar
Paul Eggert committed
804
      goto Initialize;
805 806
  if (child_proc_count == MAX_CHILDREN)
    {
807
      int i = 0;
808
      child_process *dead_cp = NULL;
809

810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
      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)
	      {
825 826
		DebPrint (("new_child: Freeing slot of dead process %d, fd %d\n",
			   cp->procinfo.dwProcessId, cp->fd));
827 828 829 830
		CloseHandle (cp->procinfo.hProcess);
		cp->procinfo.hProcess = NULL;
		CloseHandle (cp->procinfo.hThread);
		cp->procinfo.hThread = NULL;
831 832 833 834 835 836
		/* 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
837
		  break;
838
		i++;
839 840
	      }
	  }
841 842 843 844 845
      if (dead_cp)
	{
	  cp = dead_cp;
	  goto Initialize;
	}
846
    }
847 848 849 850
  if (child_proc_count == MAX_CHILDREN)
    return NULL;
  cp = &child_procs[child_proc_count++];

Paul Eggert's avatar
Paul Eggert committed
851
 Initialize:
852 853 854 855 856 857
  /* 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);
858
  memset (cp, 0, sizeof (*cp));
859 860 861 862
  cp->fd = -1;
  cp->pid = -1;
  cp->procinfo.hProcess = NULL;
  cp->status = STATUS_READ_ERROR;
863 864
  cp->input_file = NULL;
  cp->pending_deletion = 0;
865 866 867 868 869 870 871 872

  /* 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)
        {
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
	  /* 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);
892 893 894 895 896 897 898 899
	  if (cp->thrd)
	    return cp;
	}
    }
  delete_child (cp);
  return NULL;
}

900
void
901 902 903 904 905 906 907
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)
908
      emacs_abort ();
909

910
  if (!CHILD_ACTIVE (cp) && cp->procinfo.hProcess == NULL)
911 912
    return;

913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
  /* Delete the child's temporary input file, if any, that is pending
     deletion.  */
  if (cp->input_file)
    {
      if (cp->pending_deletion)
	{
	  if (unlink (cp->input_file))
	    DebPrint (("delete_child.unlink (%s) failed, errno: %d\n",
		       cp->input_file, errno));
	  cp->pending_deletion = 0;
	}
      xfree (cp->input_file);
      cp->input_file = NULL;
    }

928 929 930 931 932 933 934 935 936 937
  /* 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);
938
#if 0
Paul Eggert's avatar
Paul Eggert committed
939
          /* We used to forcibly terminate the thread here, but it
940 941 942
             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.  */
943 944 945 946 947 948
	  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);
	    }
949
#endif
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
	}
      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--)
969 970
	if (CHILD_ACTIVE (&child_procs[i])
	    || child_procs[i].procinfo.hProcess != NULL)
971 972 973 974 975 976 977
	  {
	    child_proc_count = i + 1;
	    break;
	  }
    }
  if (i < 0)
    child_proc_count = 0;
Richard M. Stallman's avatar
Richard M. Stallman committed
978 979 980 981 982 983 984
}

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

986
  for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
987 988
    if ((CHILD_ACTIVE (cp) || cp->procinfo.hProcess != NULL)
	&& pid == cp->pid)
Richard M. Stallman's avatar
Richard M. Stallman committed
989 990 991 992
      return cp;
  return NULL;
}

993 994 995 996 997 998 999 1000 1001 1002 1003 1004
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
1005

1006 1007
/* 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
1008
   reading one char.  When the read completes, char_avail is signaled
1009
   to wake up the select emulator and the thread blocks itself again. */
1010
static DWORD WINAPI
Richard M. Stallman's avatar
Richard M. Stallman committed
1011 1012 1013
reader_thread (void *arg)
{
  child_process *cp;
1014

Richard M. Stallman's avatar
Richard M. Stallman committed
1015 1016
  /* Our identity */
  cp = (child_process *)arg;
1017

Richard M. Stallman's avatar
Richard M. Stallman committed
1018
  /* We have to wait for the go-ahead before we can start */
Geoff Voelker's avatar
Geoff Voelker committed
1019
  if (cp == NULL
Juanma Barranquero's avatar
Juanma Barranquero committed
1020 1021
      || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0
      || cp->fd < 0)
1022 1023
    return 1;

Richard M. Stallman's avatar
Richard M. Stallman committed
1024 1025
  for (;;)
    {
1026 1027
      int rc;

1028
      if (cp->fd >= 0 && fd_info[cp->fd].flags & FILE_LISTEN)
1029 1030 1031
	rc = _sys_wait_accept (cp->fd);
      else
	rc = _sys_read_ahead (cp->fd);
1032

1033 1034 1035 1036 1037
      /* 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;

1038 1039
      /* 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
1040 1041
      if (!SetEvent (cp->char_avail))
        {
1042 1043 1044
	  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));
1045 1046 1047 1048 1049
	  return 1;
	}

      if (rc == STATUS_READ_ERROR)
	return 1;
1050

Richard M. Stallman's avatar
Richard M. Stallman committed
1051
      /* If the read died, the child has died so let the thread die */
1052
      if (rc == STATUS_READ_FAILED)
Richard M. Stallman's avatar
Richard M. Stallman committed
1053
	break;
1054

1055 1056 1057 1058 1059
      /* 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
1060 1061 1062 1063 1064 1065 1066
      /* 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;
        }
1067 1068
      /* delete_child sets status to STATUS_READ_ERROR when it wants
	 us to exit.  */
1069 1070
      if (cp->status == STATUS_READ_ERROR)
	break;
Richard M. Stallman's avatar
Richard M. Stallman committed
1071 1072 1073 1074
    }
  return 0;
}

Geoff Voelker's avatar
Geoff Voelker committed
1075 1076 1077 1078 1079
/* 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;

1080
static BOOL
1081
create_child (char *exe, char *cmdline, char *env, int is_gui_app,
1082
	      int * pPid, child_process *cp)
Richard M. Stallman's avatar
Richard M. Stallman committed
1083 1084 1085
{
  STARTUPINFO start;
  SECURITY_ATTRIBUTES sec_attrs;
1086
#if 0
Richard M. Stallman's avatar
Richard M. Stallman committed
1087
  SECURITY_DESCRIPTOR sec_desc;
1088
#endif
1089
  DWORD flags;
Geoff Voelker's avatar
Geoff Voelker committed
1090
  char dir[ MAXPATHLEN ];
1091

1092
  if (cp == NULL) emacs_abort ();
1093

Richard M. Stallman's avatar
Richard M. Stallman committed
1094 1095
  memset (&start, 0, sizeof (start));
  start.cb = sizeof (start);
1096

1097
#ifdef HAVE_NTGUI
1098
  if (NILP (Vw32_start_process_show_window) && !is_gui_app)
1099 1100 1101
    start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  else
    start.dwFlags = STARTF_USESTDHANDLES;
1102 1103 1104 1105 1106 1107 1108
  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 */

1109
#if 0
Richard M. Stallman's avatar
Richard M. Stallman committed
1110 1111
  /* Explicitly specify no security */
  if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
1112
    goto EH_Fail;
Richard M. Stallman's avatar
Richard M. Stallman committed
1113
  if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
1114
    goto EH_Fail;
1115
#endif
Richard M. Stallman's avatar
Richard M. Stallman committed
1116
  sec_attrs.nLength = sizeof (sec_attrs);
1117
  sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
Richard M. Stallman's avatar
Richard M. Stallman committed
1118
  sec_attrs.bInheritHandle = FALSE;
1119

Geoff Voelker's avatar
Geoff Voelker committed
1120 1121
  strcpy (dir, process_dir);
  unixtodos_filename (dir);
1122 1123 1124 1125 1126 1127

  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
1128
  if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
1129
		      flags, env, dir, &start, &cp->procinfo))
1130 1131 1132 1133 1134 1135 1136 1137 1138
    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
1139

Richard M. Stallman's avatar
Richard M. Stallman committed
1140
  return TRUE;
Geoff Voelker's avatar
Geoff Voelker committed
1141

Richard M. Stallman's avatar
Richard M. Stallman committed
1142
 EH_Fail:
1143
  DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError ()););
Richard M. Stallman's avatar
Richard M. Stallman committed
1144 1145 1146 1147 1148 1149 1150 1151
  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.  */
1152
void
1153
register_child (pid_t pid, int fd)
Richard M. Stallman's avatar
Richard M. Stallman committed
1154 1155
{
  child_process *cp;
1156

1157
  cp = find_child_pid ((DWORD)pid);
Richard M. Stallman's avatar
Richard M. Stallman committed
1158 1159 1160 1161 1162
  if (cp == NULL)
    {
      DebPrint (("register_child unable to find pid %lu\n", pid));
      return;
    }
1163

Richard M. Stallman's avatar
Richard M. Stallman committed
1164 1165 1166
#ifdef FULL_DEBUG
  DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
#endif
1167

Richard M. Stallman's avatar
Richard M. Stallman committed
1168 1169
  cp->fd = fd;

1170 1171 1172 1173 1174 1175
  /* 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
1176
    {
1177
      DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
1178
      emacs_abort ();
Richard M. Stallman's avatar
Richard M. Stallman committed
1179
    }
1180 1181

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

1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
/* Record INFILE as an input file for process PID.  */
void
record_infile (pid_t pid, char *infile)
{
  child_process *cp;

  /* INFILE should never be NULL, since xstrdup would have signaled
     memory full condition in that case, see callproc.c where this
     function is called.  */
  eassert (infile);

  cp = find_child_pid ((DWORD)pid);
  if (cp == NULL)
    {
      DebPrint (("record_infile is unable to find pid %lu\n", pid));
      return;
    }

  cp->input_file = infile;
}

/* Mark the input file INFILE of the corresponding subprocess as
   temporary, to be deleted when the subprocess exits.  */
void
record_pending_deletion (char *infile)
{
  child_process *cp;

  eassert (infile);

  for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
    if (CHILD_ACTIVE (cp)
	&& cp->input_file && xstrcasecmp (cp->input_file, infile) == 0)
      {
	cp->pending_deletion = 1;
	break;
      }
}

1223
/* Called from waitpid when a process exits.  */
1224
static void
1225
reap_subprocess (child_process *cp)
Richard M. Stallman's avatar
Richard M. Stallman committed
1226
{
1227
  if (cp->procinfo.hProcess)
Richard M. Stallman's avatar
Richard M. Stallman committed
1228
    {
1229
      /* Reap the process */
Geoff Voelker's avatar
Geoff Voelker committed
1230 1231 1232
#ifdef FULL_DEBUG
      /* Process should have already died before we are called.  */
      if (WaitForSingleObject (cp->procinfo.hProcess, 0) != WAIT_OBJECT_0)