1 /* Asynchronous subprocess implementation for Win32
2 Copyright (C) 1985, 1986, 1987, 1988, 1992, 1993, 1994, 1995
3 Free Software Foundation, Inc.
4 Copyright (C) 1995 Sun Microsystems, Inc.
5 Copyright (C) 1995, 1996 Ben Wing.
7 This file is part of XEmacs.
9 XEmacs is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
14 XEmacs is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19 You should have received a copy of the GNU General Public License
20 along with XEmacs; see the file COPYING. If not, write to
21 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 Boston, MA 02111-1307, USA. */
24 /* Written by Kirill M. Katsnelson <kkm@kis.ru>, April 1998 */
42 /* Arbitrary size limit for code fragments passed to run_in_other_process */
43 #define FRAGMENT_CODE_SIZE 32
45 /* Bound by winnt.el */
46 Lisp_Object Qnt_quote_process_args;
48 /* Implementation-specific data. Pointed to by Lisp_Process->process_data */
49 struct nt_process_data
54 #define NT_DATA(p) ((struct nt_process_data*)((p)->process_data))
56 /*-----------------------------------------------------------------------*/
58 /*-----------------------------------------------------------------------*/
60 /* This one breaks process abstraction. Prototype is in console-msw.h,
61 used by select_process method in event-msw.c */
63 get_nt_process_handle (struct Lisp_Process *p)
65 return (NT_DATA (p)->h_process);
68 /*-----------------------------------------------------------------------*/
69 /* Running remote threads. See Microsoft Systems Journal 1994 Number 5 */
70 /* Jeffrey Richter, Load Your 32-bit DLL into Another Process's Address..*/
71 /*-----------------------------------------------------------------------*/
81 * Allocate SIZE bytes in H_PROCESS address space. Fill in PMC used
82 * further by other routines. Return nonzero if successful.
84 * The memory in other process is allocated by creating a suspended
85 * thread. Initial stack of that thread is used as the memory
86 * block. The thread entry point is the routine ExitThread in
87 * kernel32.dll, so the allocated memory is freed just by resuming the
88 * thread, which immediately terminates after that.
92 alloc_process_memory (HANDLE h_process, size_t size,
95 LPTHREAD_START_ROUTINE adr_ExitThread =
96 (LPTHREAD_START_ROUTINE)
97 GetProcAddress (GetModuleHandle ("kernel32"), "ExitThread");
100 MEMORY_BASIC_INFORMATION mbi;
102 pmc->h_process = h_process;
103 pmc->h_thread = CreateRemoteThread (h_process, NULL, size,
104 adr_ExitThread, NULL,
105 CREATE_SUSPENDED, &dw_unused);
106 if (pmc->h_thread == NULL)
109 /* Get context, for thread's stack pointer */
110 context.ContextFlags = CONTEXT_CONTROL;
111 if (!GetThreadContext (pmc->h_thread, &context))
114 /* Determine base address of the committed range */
115 if (sizeof(mbi) != VirtualQueryEx (h_process,
117 (LPDWORD)context.Esp - 1,
118 #elif defined (_ALPHA_)
119 (LPDWORD)context.IntSp - 1,
121 #error Unknown processor architecture
126 /* Change the page protection of the allocated memory to executable,
128 if (!VirtualProtectEx (h_process, mbi.BaseAddress, size,
129 PAGE_EXECUTE_READWRITE, &dw_unused))
132 pmc->address = mbi.BaseAddress;
136 ResumeThread (pmc->h_thread);
142 free_process_memory (process_memory* pmc)
144 ResumeThread (pmc->h_thread);
148 * Run ROUTINE in the context of process determined by H_PROCESS. The
149 * routine is passed the address of DATA as parameter. The ROUTINE must
150 * not be longer than ROUTINE_CODE_SIZE bytes. DATA_SIZE is the size of
153 * Note that the code must be positionally independent, and compiled
154 * without stack checks (they cause implicit calls into CRT so will
155 * fail). DATA should not refer any data in calling process, as both
156 * routine and its data are copied into remote process. Size of data
157 * and code together should not exceed one page (4K on x86 systems).
159 * Return the value returned by ROUTINE, or (DWORD)-1 if call failed.
162 run_in_other_process (HANDLE h_process,
163 LPTHREAD_START_ROUTINE routine,
164 LPVOID data, size_t data_size)
167 CONST size_t code_size = FRAGMENT_CODE_SIZE;
168 /* Need at most 3 extra bytes of memory, for data alignment */
169 size_t total_size = code_size + data_size + 3;
174 /* Allocate memory */
175 if (!alloc_process_memory (h_process, total_size, &pm))
179 if (!WriteProcessMemory (h_process, pm.address, (LPVOID)routine,
186 remote_data = (LPBYTE)pm.address + ((code_size + 4) & ~3);
187 if (!WriteProcessMemory (h_process, remote_data, data, data_size, NULL))
193 /* Execute the remote copy of code, passing it remote data */
194 h_thread = CreateRemoteThread (h_process, NULL, 0,
195 (LPTHREAD_START_ROUTINE) pm.address,
196 remote_data, 0, &dw_unused);
197 if (h_thread == NULL)
200 /* Wait till thread finishes */
201 WaitForSingleObject (h_thread, INFINITE);
203 /* Free remote memory */
204 free_process_memory (&pm);
206 /* Return thread's exit code */
209 GetExitCodeThread (h_thread, &exit_code);
210 CloseHandle (h_thread);
215 free_process_memory (&pm);
219 /*-----------------------------------------------------------------------*/
220 /* Sending signals */
221 /*-----------------------------------------------------------------------*/
224 * We handle the following signals:
226 * SIGKILL, SIGTERM, SIGQUIT, SIGHUP - These four translate to ExitProcess
227 * executed by the remote process
228 * SIGINT - The remote process is sent CTRL_BREAK_EVENT
230 * The MSVC5.0 compiler feels free to re-order functions within a
231 * compilation unit, so we have no way of finding out the size of the
232 * following functions. Therefore these functions must not be larger than
233 * FRAGMENT_CODE_SIZE.
241 void (WINAPI *adr_ExitProcess) (UINT);
245 sigkill_proc (sigkill_data* data)
247 (*data->adr_ExitProcess)(255);
252 * Sending break or control c
256 BOOL (WINAPI *adr_GenerateConsoleCtrlEvent) (DWORD, DWORD);
261 sigint_proc (sigint_data* data)
263 return (*data->adr_GenerateConsoleCtrlEvent) (data->event, 0);
271 BOOL (WINAPI *adr_SetConsoleCtrlHandler) (LPVOID, BOOL);
275 sig_enable_proc (sig_enable_data* data)
277 (*data->adr_SetConsoleCtrlHandler) (NULL, FALSE);
282 * Send signal SIGNO to process H_PROCESS.
283 * Return nonzero if successful.
286 /* This code assigns a return value of GetProcAddress to function pointers
287 of many different types. Instead of heavy obscure casts, we just disable
288 warnings about assignments to different function pointer types. */
289 #pragma warning (disable : 4113)
292 send_signal (HANDLE h_process, int signo)
294 HMODULE h_kernel = GetModuleHandle ("kernel32");
297 assert (h_kernel != NULL);
307 d.adr_ExitProcess = GetProcAddress (h_kernel, "ExitProcess");
308 assert (d.adr_ExitProcess);
309 retval = run_in_other_process (h_process, sigkill_proc,
316 d.adr_GenerateConsoleCtrlEvent =
317 GetProcAddress (h_kernel, "GenerateConsoleCtrlEvent");
318 assert (d.adr_GenerateConsoleCtrlEvent);
319 d.event = CTRL_C_EVENT;
320 retval = run_in_other_process (h_process, sigint_proc,
328 return (int)retval > 0 ? 1 : 0;
332 * Enable CTRL_C_EVENT handling in a new child process
335 enable_child_signals (HANDLE h_process)
337 HMODULE h_kernel = GetModuleHandle ("kernel32");
340 assert (h_kernel != NULL);
341 d.adr_SetConsoleCtrlHandler =
342 GetProcAddress (h_kernel, "SetConsoleCtrlHandler");
343 assert (d.adr_SetConsoleCtrlHandler);
344 run_in_other_process (h_process, sig_enable_proc,
348 #pragma warning (default : 4113)
351 * Signal error if SIGNO is not supported
354 validate_signal_number (int signo)
356 if (signo != SIGKILL && signo != SIGTERM
357 && signo != SIGQUIT && signo != SIGINT
359 signal_simple_error ("Signal number not supported", make_int (signo));
362 /*-----------------------------------------------------------------------*/
363 /* Process methods */
364 /*-----------------------------------------------------------------------*/
367 * Allocate and initialize Lisp_Process->process_data
371 nt_alloc_process_data (struct Lisp_Process *p)
373 p->process_data = xnew_and_zero (struct nt_process_data);
377 nt_finalize_process_data (struct Lisp_Process *p, int for_disksave)
379 assert (!for_disksave);
380 if (NT_DATA(p)->h_process)
381 CloseHandle (NT_DATA(p)->h_process);
385 * Initialize XEmacs process implementation once
388 nt_init_process (void)
390 /* Initialize winsock */
392 /* Request Winsock v1.1 Note the order: (minor=1, major=1) */
393 WSAStartup (MAKEWORD (1,1), &wsa_data);
397 * Fork off a subprocess. P is a pointer to newly created subprocess
398 * object. If this function signals, the caller is responsible for
399 * deleting (and finalizing) the process object.
401 * The method must return PID of the new process, a (positive??? ####) number
402 * which fits into Lisp_Int. No return value indicates an error, the method
403 * must signal an error instead.
406 /* #### This function completely ignores Vprocess_environment */
409 signal_cannot_launch (Lisp_Object image_file, DWORD err)
411 mswindows_set_errno (err);
412 signal_simple_error_2 ("Error starting", image_file, lisp_strerror (errno));
416 nt_create_process (struct Lisp_Process *p,
417 Lisp_Object *argv, int nargv,
418 Lisp_Object program, Lisp_Object cur_dir)
420 HANDLE hmyshove, hmyslurp, hprocin, hprocout;
422 BOOL do_io, windowed;
424 /* Find out whether the application is windowed or not */
426 /* SHGetFileInfo tends to return ERROR_FILE_NOT_FOUND on most
427 errors. This leads to bogus error message. */
429 char *p = strrchr ((char *)XSTRING_DATA (program), '.');
431 (stricmp (p, ".exe") == 0 ||
432 stricmp (p, ".com") == 0 ||
433 stricmp (p, ".bat") == 0 ||
434 stricmp (p, ".cmd") == 0))
436 image_type = SHGetFileInfo ((char *)XSTRING_DATA (program), 0,NULL,
441 char progname[MAX_PATH];
442 sprintf (progname, "%s.exe", (char *)XSTRING_DATA (program));
443 image_type = SHGetFileInfo (progname, 0, NULL, 0, SHGFI_EXETYPE);
446 signal_cannot_launch (program, (GetLastError () == ERROR_FILE_NOT_FOUND
447 ? ERROR_BAD_FORMAT : GetLastError ()));
448 windowed = HIWORD (image_type) != 0;
451 /* Decide whether to do I/O on process handles, or just mark the
452 process exited immediately upon successful launching. We do I/O if the
453 process is a console one, or if it is windowed but windowed_process_io
455 do_io = !windowed || windowed_process_io ;
459 /* Create two unidirectional named pipes */
461 SECURITY_ATTRIBUTES sa;
463 sa.nLength = sizeof(sa);
464 sa.bInheritHandle = TRUE;
465 sa.lpSecurityDescriptor = NULL;
467 CreatePipe (&hprocin, &hmyshove, &sa, 0);
468 CreatePipe (&hmyslurp, &hprocout, &sa, 0);
470 /* Stupid Win32 allows to create a pipe with *both* ends either
471 inheritable or not. We need process ends inheritable, and local
472 ends not inheritable. */
473 DuplicateHandle (GetCurrentProcess(), hmyshove, GetCurrentProcess(), &htmp,
474 0, FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS);
476 DuplicateHandle (GetCurrentProcess(), hmyslurp, GetCurrentProcess(), &htmp,
477 0, FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS);
481 /* Convert an argv vector into Win32 style command line by a call to
482 lisp function `nt-quote-process-args' which see (in winnt.el)*/
485 Lisp_Object args_or_ret = Qnil;
488 GCPRO1 (args_or_ret);
490 for (i = 0; i < nargv; ++i)
491 args_or_ret = Fcons (*argv++, args_or_ret);
492 args_or_ret = Fnreverse (args_or_ret);
493 args_or_ret = Fcons (program, args_or_ret);
495 args_or_ret = call1 (Qnt_quote_process_args, args_or_ret);
497 if (!STRINGP (args_or_ret))
498 /* Luser wrote his/her own clever version */
499 error ("Bogus return value from `nt-quote-process-args'");
501 command_line = alloca_array (char, (XSTRING_LENGTH (program)
502 + XSTRING_LENGTH (args_or_ret) + 2));
503 strcpy (command_line, XSTRING_DATA (program));
504 strcat (command_line, " ");
505 strcat (command_line, XSTRING_DATA (args_or_ret));
507 UNGCPRO; /* args_or_ret */
513 PROCESS_INFORMATION pi;
517 si.dwFlags = STARTF_USESHOWWINDOW;
518 si.wShowWindow = windowed ? SW_SHOWNORMAL : SW_HIDE;
521 si.hStdInput = hprocin;
522 si.hStdOutput = hprocout;
523 si.hStdError = hprocout;
524 si.dwFlags |= STARTF_USESTDHANDLES;
527 err = (CreateProcess (NULL, command_line, NULL, NULL, TRUE,
528 CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP
530 NULL, (char *) XSTRING_DATA (cur_dir), &si, &pi)
531 ? 0 : GetLastError ());
535 /* These just have been inherited; we do not need a copy */
536 CloseHandle (hprocin);
537 CloseHandle (hprocout);
540 /* Handle process creation failure */
545 CloseHandle (hmyshove);
546 CloseHandle (hmyslurp);
548 signal_cannot_launch (program, GetLastError ());
551 /* The process started successfully */
554 NT_DATA(p)->h_process = pi.hProcess;
555 init_process_io_handles (p, (void*)hmyslurp, (void*)hmyshove, 0);
559 /* Indicate as if the process has exited immediately. */
560 p->status_symbol = Qexit;
561 CloseHandle (pi.hProcess);
565 enable_child_signals (pi.hProcess);
567 ResumeThread (pi.hThread);
568 CloseHandle (pi.hThread);
570 /* Hack to support Windows 95 negative pids */
571 return ((int)pi.dwProcessId < 0
572 ? -(int)pi.dwProcessId : (int)pi.dwProcessId);
577 * This method is called to update status fields of the process
578 * structure. If the process has not existed, this method is expected
581 * The method is called only for real child processes.
585 nt_update_status_if_terminated (struct Lisp_Process* p)
588 if (GetExitCodeProcess (NT_DATA(p)->h_process, &exit_code)
589 && exit_code != STILL_ACTIVE)
593 /* The exit code can be a code returned by process, or an
594 NTSTATUS value. We cannot accurately handle the latter since
595 it is a full 32 bit integer */
596 if (exit_code & 0xC0000000)
598 p->status_symbol = Qsignal;
599 p->exit_code = exit_code & 0x1FFFFFFF;
603 p->status_symbol = Qexit;
604 p->exit_code = exit_code;
610 * Stuff the entire contents of LSTREAM to the process output pipe
613 /* #### If only this function could be somehow merged with
614 unix_send_process... */
617 nt_send_process (Lisp_Object proc, struct lstream* lstream)
619 struct Lisp_Process *p = XPROCESS (proc);
621 /* use a reasonable-sized buffer (somewhere around the size of the
622 stream buffer) so as to avoid inundating the stream with blocked
624 Bufbyte chunkbuf[512];
631 chunklen = Lstream_read (lstream, chunkbuf, 512);
633 break; /* perhaps should abort() if < 0?
634 This should never happen. */
636 /* Lstream_write() will never successfully write less than the
637 amount sent in. In the worst case, it just buffers the
639 writeret = Lstream_write (XLSTREAM (DATA_OUTSTREAM(p)), chunkbuf,
641 Lstream_flush (XLSTREAM (DATA_OUTSTREAM(p)));
644 p->status_symbol = Qexit;
645 p->exit_code = ERROR_BROKEN_PIPE;
649 deactivate_process (proc);
650 error ("Broken pipe error sending to process %s; closed it",
651 XSTRING_DATA (p->name));
656 while (Lstream_was_blocked_p (XLSTREAM (p->pipe_outstream)))
658 /* Buffer is full. Wait, accepting input; that may allow
659 the program to finish doing output and read more. */
660 Faccept_process_output (Qnil, Qzero, make_int (wait_ms));
661 Lstream_flush (XLSTREAM (p->pipe_outstream));
662 wait_ms = min (1000, 2 * wait_ms);
669 * Send a signal number SIGNO to PROCESS.
670 * CURRENT_GROUP means send to the process group that currently owns
671 * the terminal being used to communicate with PROCESS.
672 * This is used for various commands in shell mode.
673 * If NOMSG is zero, insert signal-announcements into process's buffers
676 * If we can, we try to signal PROCESS by sending control characters
677 * down the pty. This allows us to signal inferiors who have changed
678 * their uid, for which killpg would return an EPERM error.
680 * The method signals an error if the given SIGNO is not valid
684 nt_kill_child_process (Lisp_Object proc, int signo,
685 int current_group, int nomsg)
687 struct Lisp_Process *p = XPROCESS (proc);
689 /* Signal error if SIGNO cannot be sent */
690 validate_signal_number (signo);
693 if (!send_signal (NT_DATA(p)->h_process, signo))
694 error ("Cannot send signal to process");
698 * Kill any process in the system given its PID.
700 * Returns zero if a signal successfully sent, or
701 * negative number upon failure
704 nt_kill_process_by_pid (int pid, int signo)
709 /* Signal error if SIGNO cannot be sent */
710 validate_signal_number (signo);
712 /* Try to open the process with required privileges */
713 h_process = OpenProcess (PROCESS_CREATE_THREAD
714 | PROCESS_QUERY_INFORMATION
715 | PROCESS_VM_OPERATION
718 if (h_process == NULL)
721 send_result = send_signal (h_process, signo);
723 CloseHandle (h_process);
725 return send_result ? 0 : -1;
728 /*-----------------------------------------------------------------------*/
729 /* Sockets connections */
730 /*-----------------------------------------------------------------------*/
733 /* #### Hey MS, how long Winsock 2 for '95 will be in beta? */
735 #define SOCK_TIMER_ID 666
736 #define XM_SOCKREPLY (WM_USER + 666)
739 get_internet_address (Lisp_Object host, struct sockaddr_in *address,
742 char buf [MAXGETHOSTSTRUCT];
747 address->sin_family = AF_INET;
749 /* First check if HOST is already a numeric address */
751 unsigned long inaddr = inet_addr (XSTRING_DATA (host));
752 if (inaddr != INADDR_NONE)
754 address->sin_addr.s_addr = inaddr;
759 /* Create a window which will receive completion messages */
760 hwnd = CreateWindow ("STATIC", NULL, WS_OVERLAPPED, 0, 0, 1, 1,
761 NULL, NULL, NULL, NULL);
764 /* Post name resolution request */
765 hasync = WSAAsyncGetHostByName (hwnd, XM_SOCKREPLY, XSTRING_DATA (host),
770 /* Set a timer to poll for quit every 250 ms */
771 SetTimer (hwnd, SOCK_TIMER_ID, 250, NULL);
776 GetMessage (&msg, hwnd, 0, 0);
777 if (msg.message == XM_SOCKREPLY)
779 /* Ok, got an answer */
780 if (WSAGETASYNCERROR(msg.lParam) == NO_ERROR)
784 else if (msg.message == WM_TIMER && msg.wParam == SOCK_TIMER_ID)
788 WSACancelAsyncRequest (hasync);
789 KillTimer (hwnd, SOCK_TIMER_ID);
790 DestroyWindow (hwnd);
794 DispatchMessage (&msg);
798 KillTimer (hwnd, SOCK_TIMER_ID);
799 DestroyWindow (hwnd);
802 /* BUF starts with struct hostent */
803 struct hostent* he = (struct hostent*) buf;
804 address->sin_addr.s_addr = *(unsigned long*)he->h_addr_list[0];
810 nt_canonicalize_host_name (Lisp_Object host)
812 struct sockaddr_in address;
814 if (!get_internet_address (host, &address, ERROR_ME_NOT))
817 if (address.sin_family == AF_INET)
818 return build_string (inet_ntoa (address.sin_addr));
823 /* open a TCP network connection to a given HOST/SERVICE. Treated
824 exactly like a normal process when reading and writing. Only
825 differences are in status display and process deletion. A network
826 connection has no PID; you cannot signal it. All you can do is
827 deactivate and close it via delete-process */
830 nt_open_network_stream (Lisp_Object name, Lisp_Object host, Lisp_Object service,
831 Lisp_Object family, void** vinfd, void** voutfd)
833 struct sockaddr_in address;
840 if (!EQ (family, Qtcpip))
841 error ("Unsupported protocol family \"%s\"",
842 string_data (symbol_name (XSYMBOL (family))));
845 port = htons ((unsigned short) XINT (service));
848 struct servent *svc_info;
849 CHECK_STRING (service);
850 svc_info = getservbyname ((char *) XSTRING_DATA (service), "tcp");
852 error ("Unknown service \"%s\"", XSTRING_DATA (service));
853 port = svc_info->s_port;
856 get_internet_address (host, &address, ERROR_ME);
857 address.sin_port = port;
859 s = socket (address.sin_family, SOCK_STREAM, 0);
861 report_file_error ("error creating socket", list1 (name));
863 /* We don't want to be blocked on connect */
865 unsigned int nonblock = 1;
866 ioctlsocket (s, FIONBIO, &nonblock);
869 retval = connect (s, (struct sockaddr *) &address, sizeof (address));
870 if (retval != NO_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
873 /* Wait while connection is established */
886 /* Poll for quit every 250 ms */
888 tv.tv_usec = 250 * 1000;
892 nsel = select (0, NULL, &fdset, &fdset, &tv);
896 /* Check: was connection successful or not? */
898 nsel = select (0, NULL, NULL, &fdset, &tv);
906 /* We are connected at this point */
908 DuplicateHandle (GetCurrentProcess(), (HANDLE)s,
909 GetCurrentProcess(), (LPHANDLE)voutfd,
910 0, FALSE, DUPLICATE_SAME_ACCESS);
915 report_file_error ("connection failed", list2 (host, name));
920 /*-----------------------------------------------------------------------*/
922 /*-----------------------------------------------------------------------*/
925 process_type_create_nt (void)
927 PROCESS_HAS_METHOD (nt, alloc_process_data);
928 PROCESS_HAS_METHOD (nt, finalize_process_data);
929 PROCESS_HAS_METHOD (nt, init_process);
930 PROCESS_HAS_METHOD (nt, create_process);
931 PROCESS_HAS_METHOD (nt, update_status_if_terminated);
932 PROCESS_HAS_METHOD (nt, send_process);
933 PROCESS_HAS_METHOD (nt, kill_child_process);
934 PROCESS_HAS_METHOD (nt, kill_process_by_pid);
936 PROCESS_HAS_METHOD (nt, canonicalize_host_name);
937 PROCESS_HAS_METHOD (nt, open_network_stream);
938 #ifdef HAVE_MULTICAST
939 #error I won't do this until '95 has winsock2
940 PROCESS_HAS_METHOD (nt, open_multicast_group);
946 syms_of_process_nt (void)
948 defsymbol (&Qnt_quote_process_args, "nt-quote-process-args");
952 vars_of_process_nt (void)