w32proc.c 89.8 KB
Newer Older
1
/* Process support for GNU Emacs on the Microsoft Windows API.
2
   Copyright (C) 1992, 1995, 1999-2012  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 807 808
  if (child_proc_count == MAX_CHILDREN)
    return NULL;
  cp = &child_procs[child_proc_count++];

Paul Eggert's avatar
Paul Eggert committed
809
 Initialize:
810
  memset (cp, 0, sizeof (*cp));
811 812 813 814
  cp->fd = -1;
  cp->pid = -1;
  cp->procinfo.hProcess = NULL;
  cp->status = STATUS_READ_ERROR;
815 816
  cp->input_file = NULL;
  cp->pending_deletion = 0;
817 818 819 820 821 822 823 824

  /* 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)
        {
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
	  /* 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);
844 845 846 847 848 849 850 851
	  if (cp->thrd)
	    return cp;
	}
    }
  delete_child (cp);
  return NULL;
}

852
void
853 854 855 856 857 858 859
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)
860
      emacs_abort ();
861

862
  if (!CHILD_ACTIVE (cp) && cp->procinfo.hProcess == NULL)
863 864
    return;

865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
  /* 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;
    }

880 881 882 883 884 885 886 887 888 889
  /* 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);
890
#if 0
Paul Eggert's avatar
Paul Eggert committed
891
          /* We used to forcibly terminate the thread here, but it
892 893 894
             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.  */
895 896 897 898 899 900
	  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);
	    }
901
#endif
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
	}
      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--)
921 922
	if (CHILD_ACTIVE (&child_procs[i])
	    || child_procs[i].procinfo.hProcess != NULL)
923 924 925 926 927 928 929
	  {
	    child_proc_count = i + 1;
	    break;
	  }
    }
  if (i < 0)
    child_proc_count = 0;
Richard M. Stallman's avatar
Richard M. Stallman committed
930 931 932 933 934 935 936
}

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

938
  for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
939 940
    if ((CHILD_ACTIVE (cp) || cp->procinfo.hProcess != NULL)
	&& pid == cp->pid)
Richard M. Stallman's avatar
Richard M. Stallman committed
941 942 943 944 945
      return cp;
  return NULL;
}


946 947
/* 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
948
   reading one char.  When the read completes, char_avail is signaled
949
   to wake up the select emulator and the thread blocks itself again. */
950
static DWORD WINAPI
Richard M. Stallman's avatar
Richard M. Stallman committed
951 952 953
reader_thread (void *arg)
{
  child_process *cp;
954

Richard M. Stallman's avatar
Richard M. Stallman committed
955 956
  /* Our identity */
  cp = (child_process *)arg;
957

Richard M. Stallman's avatar
Richard M. Stallman committed
958
  /* We have to wait for the go-ahead before we can start */
Geoff Voelker's avatar
Geoff Voelker committed
959
  if (cp == NULL
Juanma Barranquero's avatar
Juanma Barranquero committed
960 961
      || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0
      || cp->fd < 0)
962 963
    return 1;

Richard M. Stallman's avatar
Richard M. Stallman committed
964 965
  for (;;)
    {
966 967
      int rc;

968
      if (cp->fd >= 0 && fd_info[cp->fd].flags & FILE_LISTEN)
969 970 971
	rc = _sys_wait_accept (cp->fd);
      else
	rc = _sys_read_ahead (cp->fd);
972

973 974 975 976 977
      /* 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;

978 979
      /* 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
980 981 982 983
      if (!SetEvent (cp->char_avail))
        {
	  DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n",
		     GetLastError (), cp->fd));
984 985 986 987 988
	  return 1;
	}

      if (rc == STATUS_READ_ERROR)
	return 1;
989

Richard M. Stallman's avatar
Richard M. Stallman committed
990
      /* If the read died, the child has died so let the thread die */
991
      if (rc == STATUS_READ_FAILED)
Richard M. Stallman's avatar
Richard M. Stallman committed
992
	break;
993

994 995 996 997 998
      /* 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
999 1000 1001 1002 1003 1004 1005
      /* 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;
        }
1006 1007
      /* delete_child sets status to STATUS_READ_ERROR when it wants
	 us to exit.  */
1008 1009
      if (cp->status == STATUS_READ_ERROR)
	break;
Richard M. Stallman's avatar
Richard M. Stallman committed
1010 1011 1012 1013
    }
  return 0;
}

Geoff Voelker's avatar
Geoff Voelker committed
1014 1015 1016 1017 1018
/* 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;

1019
static BOOL
1020
create_child (char *exe, char *cmdline, char *env, int is_gui_app,
1021
	      int * pPid, child_process *cp)
Richard M. Stallman's avatar
Richard M. Stallman committed
1022 1023 1024
{
  STARTUPINFO start;
  SECURITY_ATTRIBUTES sec_attrs;
1025
#if 0
Richard M. Stallman's avatar
Richard M. Stallman committed
1026
  SECURITY_DESCRIPTOR sec_desc;
1027
#endif
1028
  DWORD flags;
Geoff Voelker's avatar
Geoff Voelker committed
1029
  char dir[ MAXPATHLEN ];
1030

1031
  if (cp == NULL) emacs_abort ();
1032

Richard M. Stallman's avatar
Richard M. Stallman committed
1033 1034
  memset (&start, 0, sizeof (start));
  start.cb = sizeof (start);
1035

1036
#ifdef HAVE_NTGUI
1037
  if (NILP (Vw32_start_process_show_window) && !is_gui_app)
1038 1039 1040
    start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  else
    start.dwFlags = STARTF_USESTDHANDLES;
1041 1042 1043 1044 1045 1046 1047
  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 */

1048
#if 0
Richard M. Stallman's avatar
Richard M. Stallman committed
1049 1050
  /* Explicitly specify no security */
  if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
1051
    goto EH_Fail;
Richard M. Stallman's avatar
Richard M. Stallman committed
1052
  if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
1053
    goto EH_Fail;
1054
#endif
Richard M. Stallman's avatar
Richard M. Stallman committed
1055
  sec_attrs.nLength = sizeof (sec_attrs);
1056
  sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
Richard M. Stallman's avatar
Richard M. Stallman committed
1057
  sec_attrs.bInheritHandle = FALSE;
1058

Geoff Voelker's avatar
Geoff Voelker committed
1059 1060
  strcpy (dir, process_dir);
  unixtodos_filename (dir);
1061 1062 1063 1064 1065 1066

  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
1067
  if (!CreateProcess (exe, cmdline, &sec_attrs, NULL, TRUE,
1068
		      flags, env, dir, &start, &cp->procinfo))
1069 1070 1071 1072 1073 1074 1075 1076 1077
    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
1078

Richard M. Stallman's avatar
Richard M. Stallman committed
1079
  return TRUE;
Geoff Voelker's avatar
Geoff Voelker committed
1080

Richard M. Stallman's avatar
Richard M. Stallman committed
1081
 EH_Fail:
1082
  DebPrint (("create_child.CreateProcess failed: %ld\n", GetLastError ()););
Richard M. Stallman's avatar
Richard M. Stallman committed
1083 1084 1085 1086 1087 1088 1089 1090
  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.  */
1091
void
1092
register_child (pid_t pid, int fd)
Richard M. Stallman's avatar
Richard M. Stallman committed
1093 1094
{
  child_process *cp;
1095

1096
  cp = find_child_pid ((DWORD)pid);
Richard M. Stallman's avatar
Richard M. Stallman committed
1097 1098 1099 1100 1101
  if (cp == NULL)
    {
      DebPrint (("register_child unable to find pid %lu\n", pid));
      return;
    }
1102

Richard M. Stallman's avatar
Richard M. Stallman committed
1103 1104 1105
#ifdef FULL_DEBUG
  DebPrint (("register_child registered fd %d with pid %lu\n", fd, pid));
#endif
1106

Richard M. Stallman's avatar
Richard M. Stallman committed
1107 1108
  cp->fd = fd;

1109 1110 1111 1112 1113 1114
  /* 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
1115
    {
1116
      DebPrint (("register_child: fd_info[%d] apparently in use!\n", fd));
1117
      emacs_abort ();
Richard M. Stallman's avatar
Richard M. Stallman committed
1118
    }
1119 1120

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

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132