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

3
Copyright (C) 1992, 1995, 1999-2014 Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
4

5 6
This file is part of GNU Emacs.

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

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
18
along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
19

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

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

37
/* must include CRT headers *before* config.h */
Pavel Janík's avatar
Pavel Janík committed
38 39
#include <config.h>

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

Richard M. Stallman's avatar
Richard M. Stallman committed
46
#include <windows.h>
47 48 49
#if defined(__GNUC__) && !defined(__MINGW64__)
/* This definition is missing from mingw.org headers, but not MinGW64
   headers. */
50
extern BOOL WINAPI IsValidLocale (LCID, DWORD);
51
#endif
Richard M. Stallman's avatar
Richard M. Stallman committed
52

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

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

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

Geoff Voelker's avatar
Geoff Voelker committed
75
Lisp_Object Qhigh, Qlow;
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
/* Improve on the CRT 'signal' implementation so that we could record
85
   the SIGCHLD handler and fake interval timers.  */
86
signal_handler
87
sys_signal (int sig, signal_handler handler)
Richard M. Stallman's avatar
Richard M. Stallman committed
88 89
{
  signal_handler old;
90

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

116 117 118 119
/* Emulate sigaction. */
int
sigaction (int sig, const struct sigaction *act, struct sigaction *oact)
{
120 121 122 123 124 125 126
  signal_handler old = SIG_DFL;
  int retval = 0;

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

128
  if (old == SIG_ERR)
129 130
    {
      errno = EINVAL;
131
      retval = -1;
132 133 134 135 136 137 138
    }
  if (oact)
    {
      oact->sa_handler = old;
      oact->sa_flags = 0;
      oact->sa_mask = empty_mask;
    }
139
  return retval;
140 141
}

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

238 239
pid_t
getpgrp (void)
240
{
241
  return getpid ();
242 243
}

244
pid_t
245
tcgetpgrp (int fd)
246 247 248 249 250 251 252 253 254 255
{
  return getpid ();
}

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

256 257 258 259 260 261
pid_t
setsid (void)
{
  return getpid ();
}

262 263 264 265 266 267 268 269 270
/* 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 {
271 272 273
  volatile ULONGLONG expire;
  volatile ULONGLONG reload;
  volatile int terminate;
274 275 276 277 278
  int type;
  HANDLE caller_thread;
  HANDLE timer_thread;
};

279
static ULONGLONG ticks_now;
280
static struct itimer_data real_itimer, prof_itimer;
281
static ULONGLONG clocks_min;
282 283 284
/* If non-zero, itimers are disabled.  Used during shutdown, when we
   delete the critical sections used by the timer threads.  */
static int disable_itimers;
285 286 287

static CRITICAL_SECTION crit_real, crit_prof;

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

static GetThreadTimes_Proc s_pfn_Get_Thread_Times;

298 299 300
#define MAX_SINGLE_SLEEP    30
#define TIMER_TICKS_PER_SEC 1000

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

  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 =
331 332
	    temp_creation.QuadPart / tscale + temp_kernel.QuadPart / tscale
	    + temp_user.QuadPart / tscale;
333 334 335 336 337
	}
      else
	DebPrint (("GetThreadTimes failed with error code %lu\n",
		   GetLastError ()));
    }
338

339 340 341 342 343 344 345 346 347 348
  if (use_system_time)
    {
      FILETIME current_ftime;
      ULARGE_INTEGER temp;

      GetSystemTimeAsFileTime (&current_ftime);

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

349
      retval = temp.QuadPart / tscale;
350 351 352 353 354 355
    }

  return retval;
}

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

  while (1)
    {
      DWORD sleep_time;
      signal_handler handler;
370
      ULONGLONG now, expire, reload;
371 372 373 374 375 376 377 378 379

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

380
      if (expire == 0)
381 382 383 384 385 386
	{
	  /* We are idle.  */
	  Sleep (max_sleep);
	  continue;
	}

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

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

	  if (result == (DWORD)-1)
443 444
	    return 2;

445
	  handler (sig);
446
	  ResumeThread (th);
447 448 449 450 451
	}

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

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

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

533 534 535 536
  /* We are going to delete the critical sections, so timers cannot
     work after this.  */
  disable_itimers = 1;

537 538 539 540 541 542 543 544 545
  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
546
  /* GetThreadTimes is not available on all versions of Windows, so
547 548 549 550 551 552 553 554
     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");

555 556 557 558 559 560 561 562
  /* 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);
563 564

  disable_itimers = 0;
565 566 567 568 569
}

static int
start_timer_thread (int which)
{
570
  DWORD exit_code, tid;
571
  HANDLE th;
572 573 574 575 576 577 578 579
  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;

580 581 582 583 584 585 586 587 588 589 590 591
  /* 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;
    }

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

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

623 624 625
  return 0;
}

626 627 628 629 630 631
/* 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)
{
632 633 634
  volatile ULONGLONG *t_expire;
  volatile ULONGLONG *t_reload;
  ULONGLONG expire, reload;
635 636
  __int64 usecs;
  CRITICAL_SECTION *crit;
637
  struct itimer_data *itimer;
638

639 640 641
  if (disable_itimers)
    return -1;

642 643 644 645 646 647 648 649 650 651 652 653
  if (!value)
    {
      errno = EFAULT;
      return -1;
    }

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

654 655 656 657
  itimer = (which == ITIMER_REAL) ? &real_itimer : &prof_itimer;

  ticks_now = w32_get_timer_time ((which == ITIMER_REAL)
				  ? NULL
658
				  : GetCurrentThread ());
659 660 661

  t_expire = &itimer->expire;
  t_reload = &itimer->reload;
662 663 664 665 666 667 668 669 670 671
  crit = (which == ITIMER_REAL) ? &crit_real : &crit_prof;

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

  if (expire)
    expire -= ticks_now;

672 673 674
  value->it_value.tv_sec    = expire / TIMER_TICKS_PER_SEC;
  usecs =
    (expire % TIMER_TICKS_PER_SEC) * (__int64)1000000 / TIMER_TICKS_PER_SEC;
675
  value->it_value.tv_usec   = usecs;
676 677 678
  value->it_interval.tv_sec = reload / TIMER_TICKS_PER_SEC;
  usecs =
    (reload % TIMER_TICKS_PER_SEC) * (__int64)1000000 / TIMER_TICKS_PER_SEC;
679 680 681 682 683 684 685 686
  value->it_interval.tv_usec= usecs;

  return 0;
}

int
setitimer(int which, struct itimerval *value, struct itimerval *ovalue)
{
687 688
  volatile ULONGLONG *t_expire, *t_reload;
  ULONGLONG expire, reload, expire_old, reload_old;
689 690
  __int64 usecs;
  CRITICAL_SECTION *crit;
691
  struct itimerval tem, *ptem;
692

693 694 695
  if (disable_itimers)
    return -1;

696 697 698 699 700
  /* 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)
    {
701
      ULONGLONG t1, t2;
702

703 704
      for (t1 = w32_get_timer_time (NULL);
	   (t2 = w32_get_timer_time (NULL)) == t1; )
705 706 707 708 709
	;
      clocks_min = t2 - t1;
    }

  if (ovalue)
710
    ptem = ovalue;
711
  else
712
    ptem = &tem;
713

714 715
  if (getitimer (which, ptem)) /* also sets ticks_now */
    return -1;		       /* errno already set */
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734

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

735
  reload = value->it_interval.tv_sec * TIMER_TICKS_PER_SEC;
736 737 738

  usecs = value->it_interval.tv_usec;
  if (value->it_interval.tv_sec == 0
739
      && usecs && usecs * TIMER_TICKS_PER_SEC < clocks_min * 1000000)
740 741 742
    reload = clocks_min;
  else
    {
743
      usecs *= TIMER_TICKS_PER_SEC;
744 745 746
      reload += usecs / 1000000;
    }

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

  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;

783 784 785 786
  if (setitimer (ITIMER_REAL, &new_values, &old_values) < 0)
    return 0;
  return old_values.it_value.tv_sec;
#else
787
  return seconds;
788
#endif
789 790
}

791 792 793 794 795 796 797
/* 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 ];

798
static DWORD WINAPI reader_thread (void *arg);
799

Richard M. Stallman's avatar
Richard M. Stallman committed
800
/* Find an unused process slot.  */
801
child_process *
Richard M. Stallman's avatar
Richard M. Stallman committed
802 803 804
new_child (void)
{
  child_process *cp;
805
  DWORD id;
806

807
  for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
808
    if (!CHILD_ACTIVE (cp) && cp->procinfo.hProcess == NULL)
Paul Eggert's avatar
Paul Eggert committed
809
      goto Initialize;
810 811
  if (child_proc_count == MAX_CHILDREN)
    {
812
      int i = 0;
813
      child_process *dead_cp = NULL;
814

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

Paul Eggert's avatar
Paul Eggert committed
856
 Initialize:
857 858 859 860 861 862
  /* 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);
863
  memset (cp, 0, sizeof (*cp));
864 865 866 867 868 869 870 871 872 873 874 875
  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)
        {
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
	  /* 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);
895 896 897 898 899 900 901 902
	  if (cp->thrd)
	    return cp;
	}
    }
  delete_child (cp);
  return NULL;
}

903
void
904 905 906 907 908 909 910
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)
911
      emacs_abort ();
912

913
  if (!CHILD_ACTIVE (cp) && cp->procinfo.hProcess == NULL)
914 915 916 917 918 919 920 921 922 923 924 925
    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);
926
#if 0
Paul Eggert's avatar
Paul Eggert committed
927
          /* We used to forcibly terminate the thread here, but it
928 929 930
             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.  */
931 932 933 934 935 936
	  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);
	    }
937
#endif
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
	}
      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--)
957 958
	if (CHILD_ACTIVE (&child_procs[i])
	    || child_procs[i].procinfo.hProcess != NULL)
959 960 961 962 963 964 965
	  {
	    child_proc_count = i + 1;
	    break;
	  }
    }
  if (i < 0)
    child_proc_count = 0;
Richard M. Stallman's avatar
Richard M. Stallman committed
966 967 968 969 970 971 972
}

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

974
  for (cp = child_procs + (child_proc_count-1); cp >= child_procs; cp--)
975 976
    if ((CHILD_ACTIVE (cp) || cp->procinfo.hProcess != NULL)
	&& pid == cp->pid)
Richard M. Stallman's avatar
Richard M. Stallman committed
977 978 979 980
      return cp;
  return NULL;
}

981 982 983 984 985 986 987 988 989 990 991 992
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
993

994 995
/* 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
996
   reading one char.  When the read completes, char_avail is signaled
997
   to wake up the select emulator and the thread blocks itself again. */
998
static DWORD WINAPI
Richard M. Stallman's avatar
Richard M. Stallman committed
999 1000 1001
reader_thread (void *arg)
{
  child_process *cp;
1002

Richard M. Stallman's avatar
Richard M. Stallman committed
1003 1004
  /* Our identity */
  cp = (child_process *)arg;
1005

Richard M. Stallman's avatar
Richard M. Stallman committed
1006
  /* We have to wait for the go-ahead before we can start */
Geoff Voelker's avatar
Geoff Voelker committed
1007
  if (cp == NULL
Juanma Barranquero's avatar
Juanma Barranquero committed
1008 1009
      || WaitForSingleObject (cp->char_consumed, INFINITE) != WAIT_OBJECT_0
      || cp->fd < 0)
1010 1011
    return 1;

Richard M. Stallman's avatar
Richard M. Stallman committed
1012 1013
  for (;;)
    {
1014 1015
      int rc;

1016
      if (cp->fd >= 0 && fd_info[cp->fd].flags & FILE_LISTEN)
1017 1018 1019
	rc = _sys_wait_accept (cp->fd);
      else
	rc = _sys_read_ahead (cp->fd);
1020

1021 1022 1023 1024 1025
      /* 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;

1026 1027
      /* 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
1028 1029
      if (!SetEvent (cp->char_avail))
        {
1030 1031 1032
	  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));
1033 1034 1035 1036 1037
	  return 1;
	}

      if (rc == STATUS_READ_ERROR)
	return 1;
1038

Richard M. Stallman's avatar
Richard M. Stallman committed
1039
      /* If the read died, the child has died so let the thread die */
1040
      if (rc == STATUS_READ_FAILED)
Richard M. Stallman's avatar
Richard M. Stallman committed
1041
	break;
1042

1043 1044 1045 1046 1047
      /* 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
1048 1049 1050 1051 1052 1053 1054
      /* 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;
        }
1055 1056
      /* delete_child sets status to STATUS_READ_ERROR when it wants
	 us to exit.  */
1057 1058
      if (cp->status == STATUS_READ_ERROR)
	break;
Richard M. Stallman's avatar
Richard M. Stallman committed
1059 1060 1061 1062
    }
  return 0;
}

1063 1064 1065 1066
/* 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
1067 1068
static char * process_dir;

1069
static BOOL
1070
create_child (char *exe, char *cmdline, char *env, int is_gui_app,
1071
	      pid_t * pPid, child_process *cp)
Richard M. Stallman's avatar
Richard M. Stallman committed
1072 1073 1074
{
  STARTUPINFO start;
  SECURITY_ATTRIBUTES sec_attrs;
1075
#if 0
Richard M. Stallman's avatar
Richard M. Stallman committed
1076
  SECURITY_DESCRIPTOR sec_desc;
1077
#endif
1078
  DWORD flags;
1079 1080
  char dir[ MAX_PATH ];
  char *p;
1081

1082
  if (cp == NULL) emacs_abort ();
1083

Richard M. Stallman's avatar
Richard M. Stallman committed
1084 1085
  memset (&start, 0, sizeof (start));
  start.cb = sizeof (start);
1086

1087
#ifdef HAVE_NTGUI
1088
  if (NILP (Vw32_start_process_show_window) && !is_gui_app)
1089 1090 1091
    start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  else
    start.dwFlags = STARTF_USESTDHANDLES;
1092 1093 1094 1095 1096 1097 1098
  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 */

1099
#if 0
Richard M. Stallman's avatar
Richard M. Stallman committed
1100 1101
  /* Explicitly specify no security */
  if (!InitializeSecurityDescriptor (&sec_desc, SECURITY_DESCRIPTOR_REVISION))
1102
    goto EH_Fail;
Richard M. Stallman's avatar
Richard M. Stallman committed
1103
  if (!SetSecurityDescriptorDacl (&sec_desc, TRUE, NULL, FALSE))
1104
    goto EH_Fail;
1105
#endif
Richard M. Stallman's avatar
Richard M. Stallman committed
1106
  sec_attrs.nLength = sizeof (sec_attrs);
1107
  sec_attrs.lpSecurityDescriptor = NULL /* &sec_desc */;
Richard M. Stallman's avatar
Richard M. Stallman committed
1108
  sec_attrs.bInheritHandle = FALSE;
1109

1110 1111 1112 1113 1114 1115 1116 1117
  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 = '\\';
1118 1119 1120 1121 1122 1123

  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;
1124 1125
  if (!CreateProcessA (exe, cmdline, &sec_attrs, NULL, TRUE,
		       flags, env, dir, &start, &cp->procinfo))
1126 1127 1128 1129 1130 1131 1132 1133