1 /****************************************************************************
3 * GNAT RUN-TIME COMPONENTS *
7 * C Implementation File *
9 * Copyright (C) 2008-2023, AdaCore *
11 * GNAT is free software; you can redistribute it and/or modify it under *
12 * terms of the GNU General Public License as published by the Free Soft- *
13 * ware Foundation; either version 3, or (at your option) any later ver- *
14 * sion. GNAT is distributed in the hope that it will be useful, but WITH- *
15 * OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *
16 * or FITNESS FOR A PARTICULAR PURPOSE. *
18 * As a special exception under Section 7 of GPL version 3, you are granted *
19 * additional permissions described in the GCC Runtime Library Exception, *
20 * version 3.1, as published by the Free Software Foundation. *
22 * You should have received a copy of the GNU General Public License and *
23 * a copy of the GCC Runtime Library Exception along with this program; *
24 * see the files COPYING3 and COPYING.RUNTIME respectively. If not, see *
25 * <http://www.gnu.org/licenses/>. *
27 * GNAT was originally developed by the GNAT team at New York University. *
28 * Extensive contributions were provided by Ada Core Technologies Inc. *
30 ****************************************************************************/
32 #define ATTRIBUTE_UNUSED __attribute__((unused))
34 /* First all usupported platforms. Add stubs for exported routines. */
36 #if defined (VMS) || defined (__vxworks) || defined (__Lynx__) \
37 || defined (__ANDROID__) || defined (__PikeOS__) || defined(__DJGPP__)
46 __gnat_tty_name (void* t ATTRIBUTE_UNUSED
)
52 __gnat_interrupt_pid (int pid ATTRIBUTE_UNUSED
)
58 __gnat_interrupt_process (void* desc ATTRIBUTE_UNUSED
)
64 __gnat_setup_communication (void** desc ATTRIBUTE_UNUSED
)
70 __gnat_setup_parent_communication (void *d ATTRIBUTE_UNUSED
,
71 int *i ATTRIBUTE_UNUSED
,
72 int *o ATTRIBUTE_UNUSED
,
73 int *e ATTRIBUTE_UNUSED
,
74 int *p ATTRIBUTE_UNUSED
)
79 __gnat_setup_child_communication (void *d ATTRIBUTE_UNUSED
,
80 char **n ATTRIBUTE_UNUSED
,
81 int u ATTRIBUTE_UNUSED
)
87 __gnat_terminate_process (void *desc ATTRIBUTE_UNUSED
)
93 __gnat_terminate_pid (int pid ATTRIBUTE_UNUSED
)
99 __gnat_tty_fd (void* t ATTRIBUTE_UNUSED
)
105 __gnat_tty_supported (void)
111 __gnat_tty_waitpid (void *desc ATTRIBUTE_UNUSED
, int blocking
)
117 __gnat_close_tty (void* t ATTRIBUTE_UNUSED
)
122 __gnat_free_process (void** process ATTRIBUTE_UNUSED
)
127 __gnat_reset_tty (void* t ATTRIBUTE_UNUSED
)
132 __gnat_send_header (void* d ATTRIBUTE_UNUSED
,
133 char h
[5] ATTRIBUTE_UNUSED
,
134 int s ATTRIBUTE_UNUSED
,
135 int *r ATTRIBUTE_UNUSED
)
140 __gnat_setup_winsize (void *desc ATTRIBUTE_UNUSED
,
141 int rows ATTRIBUTE_UNUSED
,
142 int columns ATTRIBUTE_UNUSED
)
146 /* For Windows platforms. */
148 #elif defined(_WIN32)
154 #define WIN32_LEAN_AND_MEAN
156 #include <winternl.h>
159 #define MAXPATHLEN 1024
161 #define NILP(x) ((x) == 0)
163 #define report_file_error(x, y) fprintf (stderr, "Error: %s\n", x);
164 #define INTEGERP(x) 1
168 int pid
; /* Number of this process */
169 PROCESS_INFORMATION procinfo
;
170 HANDLE w_infd
, w_outfd
;
171 HANDLE w_forkin
, w_forkout
;
175 /* Control whether create_child cause the process to inherit GNAT Studio'
176 error mode setting. The default is 1, to minimize the possibility of
177 subprocesses blocking when accessing unmounted drives. */
178 static int Vw32_start_process_inherit_error_mode
= 1;
180 /* Control whether spawnve quotes arguments as necessary to ensure
181 correct parsing by child process. Because not all uses of spawnve
182 are careful about constructing argv arrays, we make this behavior
183 conditional (off by default, since a similar operation is already done
184 in g-expect.adb by calling Normalize_Argument). */
185 static int Vw32_quote_process_args
= 0;
187 static DWORD
AbsoluteSeek(HANDLE
, DWORD
);
188 static VOID
ReadBytes(HANDLE
, LPVOID
, DWORD
);
190 #define XFER_BUFFER_SIZE 2048
192 /* This tell if the executable we're about to launch uses a GUI interface. */
193 /* if we can't determine it, we will return true */
195 is_gui_app (char *exe
)
199 DWORD CoffHeaderOffset
;
200 DWORD MoreDosHeader
[16];
206 IMAGE_DOS_HEADER image_dos_header
;
207 IMAGE_FILE_HEADER image_file_header
;
208 IMAGE_OPTIONAL_HEADER image_optional_header
;
211 * Open the reference file.
219 file
= malloc ((nlen
+ 1) * sizeof (char));
220 memcpy (file
, &exe
[1], nlen
);
224 hImage
= CreateFile(file
,
229 FILE_ATTRIBUTE_NORMAL
,
236 if (INVALID_HANDLE_VALUE
== hImage
)
238 report_file_error ("Could not open exe: ", Qnil
);
239 report_file_error (exe
, Qnil
);
240 report_file_error ("\n", Qnil
);
241 CloseHandle (hImage
);
246 * Read the MS-DOS image header.
248 ReadBytes(hImage
, &image_dos_header
, sizeof(IMAGE_DOS_HEADER
));
250 if (IMAGE_DOS_SIGNATURE
!= image_dos_header
.e_magic
)
252 report_file_error("Sorry, I do not understand this file.\n", Qnil
);
253 CloseHandle (hImage
);
258 * Read more MS-DOS header. */
259 ReadBytes(hImage
, MoreDosHeader
, sizeof(MoreDosHeader
));
261 * Get actual COFF header.
263 CoffHeaderOffset
= AbsoluteSeek(hImage
, image_dos_header
.e_lfanew
) +
265 if (CoffHeaderOffset
== (DWORD
) -1) {
266 CloseHandle (hImage
);
270 ReadBytes (hImage
, &ntSignature
, sizeof(ULONG
));
272 if (IMAGE_NT_SIGNATURE
!= ntSignature
)
274 report_file_error ("Missing NT signature. Unknown file type.\n", Qnil
);
275 CloseHandle (hImage
);
279 ReadBytes(hImage
, &image_file_header
, IMAGE_SIZEOF_FILE_HEADER
);
282 * Read optional header.
285 &image_optional_header
,
286 IMAGE_SIZEOF_NT_OPTIONAL_HEADER
);
288 CloseHandle (hImage
);
290 switch (image_optional_header
.Subsystem
)
292 case IMAGE_SUBSYSTEM_UNKNOWN
:
295 case IMAGE_SUBSYSTEM_NATIVE
:
298 case IMAGE_SUBSYSTEM_WINDOWS_GUI
:
301 case IMAGE_SUBSYSTEM_WINDOWS_CUI
:
304 case IMAGE_SUBSYSTEM_OS2_CUI
:
307 case IMAGE_SUBSYSTEM_POSIX_CUI
:
311 /* Unknown, return GUI app to be preservative: if yes, it will be
312 correctly launched, if no, it will be launched, and a console will
313 be also displayed, which is not a big deal */
320 AbsoluteSeek (HANDLE hFile
, DWORD offset
)
324 newOffset
= SetFilePointer (hFile
, offset
, NULL
, FILE_BEGIN
);
326 if (newOffset
== 0xFFFFFFFF)
333 ReadBytes (HANDLE hFile
, LPVOID buffer
, DWORD size
)
337 if (!ReadFile(hFile
, buffer
, size
, &bytes
, NULL
))
342 else if (size
!= bytes
)
349 nt_spawnve (char *exe ATTRIBUTE_UNUSED
, char **argv
, char *env
,
350 struct TTY_Process
*process
)
353 SECURITY_ATTRIBUTES sec_attrs
;
354 SECURITY_DESCRIPTOR sec_desc
;
358 char *cmdline
, *parg
, **targ
;
360 char escape_char
= 0;
363 /* we have to do some conjuring here to put argv and envp into the
364 form CreateProcess wants... argv needs to be a space separated/null
365 terminated list of parameters, and envp is a null
366 separated/double-null terminated list of parameters.
368 Additionally, zero-length args and args containing whitespace or
369 quote chars need to be wrapped in double quotes - for this to work,
370 embedded quotes need to be escaped as well. The aim is to ensure
371 the child process reconstructs the argv array we start with
372 exactly, so we treat quotes at the beginning and end of arguments
375 Note that using backslash to escape embedded quotes requires
376 additional special handling if an embedded quote is already
377 preceded by backslash, or if an arg requiring quoting ends with
378 backslash. In such cases, the run of escape characters needs to be
379 doubled. For consistency, we apply this special handling as long
380 as the escape character is not quote.
382 Since we have no idea how large argv and envp are likely to be we
383 figure out list lengths on the fly and allocate them. */
385 if (!NILP (Vw32_quote_process_args
))
388 /* Override escape char by binding w32-quote-process-args to
389 desired character, or use t for auto-selection. */
390 if (INTEGERP (Vw32_quote_process_args
))
391 escape_char
= XINT (Vw32_quote_process_args
);
403 int escape_char_run
= 0;
411 /* allow for embedded quotes to be escaped */
414 /* handle the case where the embedded quote is already escaped */
415 if (escape_char_run
> 0)
417 /* To preserve the arg exactly, we need to double the
418 preceding escape characters (plus adding one to
419 escape the quote character itself). */
420 arglen
+= escape_char_run
;
423 else if (*p
== ' ' || *p
== '\t')
428 if (*p
== escape_char
&& escape_char
!= '"')
436 /* handle the case where the arg ends with an escape char - we
437 must not let the enclosing quote be escaped. */
438 if (escape_char_run
> 0)
439 arglen
+= escape_char_run
;
441 arglen
+= strlen (*targ
) + 1;
445 is_gui
= is_gui_app (argv
[0]);
449 /* could not determine application type. Try launching with "cmd /c" */
455 cmdline
= (char*)malloc (arglen
+ 1);
459 if (use_cmd
== TRUE
) {
460 strcpy (parg
, "cmd /c ");
475 if (*p
== ' ' || *p
== '\t' || *p
== '"')
480 int escape_char_run
= 0;
488 /* double preceding escape chars if any */
489 while (escape_char_run
> 0)
491 *parg
++ = escape_char
;
494 /* escape all quote chars, even at beginning or end */
495 *parg
++ = escape_char
;
499 if (*p
== escape_char
&& escape_char
!= '"')
504 /* double escape chars before enclosing quote */
505 while (escape_char_run
> 0)
507 *parg
++ = escape_char
;
514 strcpy (parg
, *targ
);
515 parg
+= strlen (*targ
);
522 memset (&start
, 0, sizeof (start
));
523 start
.cb
= sizeof (start
);
525 if (process
->usePipe
== TRUE
) {
526 start
.dwFlags
= STARTF_USESTDHANDLES
;
527 start
.hStdInput
= process
->w_forkin
;
528 start
.hStdOutput
= process
->w_forkout
;
529 /* child's stderr is always redirected to outfd */
530 start
.hStdError
= process
->w_forkout
;
532 start
.dwFlags
= STARTF_USESTDHANDLES
;
533 /* We only need to redirect stderr/stdout here. Stdin will be forced to
534 the spawned process console by explaunch */
535 start
.hStdInput
= NULL
;
536 start
.hStdOutput
= process
->w_forkout
;
537 start
.hStdError
= process
->w_forkout
;
540 /* Explicitly specify no security */
541 if (!InitializeSecurityDescriptor (&sec_desc
, SECURITY_DESCRIPTOR_REVISION
))
543 if (!SetSecurityDescriptorDacl (&sec_desc
, TRUE
, NULL
, FALSE
))
545 sec_attrs
.nLength
= sizeof (sec_attrs
);
546 sec_attrs
.lpSecurityDescriptor
= &sec_desc
;
547 sec_attrs
.bInheritHandle
= FALSE
;
549 /* creating a new console allow easier close. Do not use
550 CREATE_NEW_PROCESS_GROUP as this results in disabling Ctrl+C */
551 flags
= CREATE_NEW_CONSOLE
;
552 if (NILP (Vw32_start_process_inherit_error_mode
))
553 flags
|= CREATE_DEFAULT_ERROR_MODE
;
555 /* if app is not a gui application, hide the console */
556 if (is_gui
== FALSE
) {
557 start
.dwFlags
|= STARTF_USESHOWWINDOW
;
558 start
.wShowWindow
= SW_HIDE
;
561 /* Set initial directory to null character to use current directory */
562 if (!CreateProcess (NULL
, cmdline
, &sec_attrs
, NULL
, TRUE
,
563 flags
, env
, NULL
, &start
, &process
->procinfo
))
566 pid
= (int) (intptr_t) process
->procinfo
.hProcess
;
575 /*************************
576 ** __gnat_send_header ()
577 *************************/
579 #define EXP_SLAVE_CREATE 'c'
580 #define EXP_SLAVE_KEY 'k'
581 #define EXP_SLAVE_MOUSE 'm'
582 #define EXP_SLAVE_WRITE 'w'
583 #define EXP_SLAVE_KILL 'x'
585 #define EXP_KILL_TERMINATE 0x1
586 #define EXP_KILL_CTRL_C 0x2
587 #define EXP_KILL_CTRL_BREAK 0x4
590 __gnat_send_header (struct TTY_Process
* p
, char header
[5], int size
, int *ret
)
592 if (p
->usePipe
== FALSE
) {
593 header
[0] = EXP_SLAVE_WRITE
;
594 header
[1] = size
& 0xff;
595 header
[2] = (size
& 0xff00) >> 8;
596 header
[3] = (size
& 0xff0000) >> 16;
597 header
[4] = (size
& 0xff000000) >> 24;
604 /**********************************
605 ** __gnat_setup_communication ()
606 **********************************/
609 __gnat_setup_communication (struct TTY_Process
** process_out
) /* output param */
611 struct TTY_Process
* process
;
613 process
= (struct TTY_Process
*)malloc (sizeof (struct TTY_Process
));
614 ZeroMemory (process
, sizeof (struct TTY_Process
));
615 *process_out
= process
;
620 #define EXP_PIPE_BASENAME "\\\\.\\pipe\\ExpectPipe"
623 __gnat_setup_child_communication
624 (struct TTY_Process
* process
,
629 SECURITY_ATTRIBUTES sec_attrs
;
630 char slavePath
[MAX_PATH
];
634 char pipeNameIn
[100];
635 HANDLE hSlaveInDrv
= NULL
; /* Handle to communicate with slave driver */
637 /* Set inheritance for the pipe handles */
638 sec_attrs
.nLength
= sizeof (SECURITY_ATTRIBUTES
);
639 sec_attrs
.bInheritHandle
= TRUE
;
640 sec_attrs
.lpSecurityDescriptor
= NULL
;
643 /* Create in and out pipes */
644 if (!CreatePipe (&process
->w_forkin
, &process
->w_infd
, &sec_attrs
, 0))
645 report_file_error ("Creation of child's IN handle", Qnil
);
646 if (!CreatePipe (&process
->w_outfd
, &process
->w_forkout
, &sec_attrs
, 0))
647 report_file_error ("Creation of child's OUT handle", Qnil
);
649 /* Do not inherit the parent's side of the pipes */
650 SetHandleInformation (&process
->w_infd
, HANDLE_FLAG_INHERIT
, 0);
651 SetHandleInformation (&process
->w_outfd
, HANDLE_FLAG_INHERIT
, 0);
653 /* use native argv */
655 process
->usePipe
= TRUE
;
658 static int pipeNameId
= 0;
660 process
->w_infd
= NULL
;
662 /* We create a named pipe for Input, as we handle input by sending special
663 commands to the explaunch process, that uses it to feed the actual input
665 sprintf(pipeNameIn
, "%sIn%08lx_%08x", EXP_PIPE_BASENAME
,
666 GetCurrentProcessId(), pipeNameId
);
669 hSlaveInDrv
= CreateNamedPipe(pipeNameIn
,
670 PIPE_ACCESS_OUTBOUND
,
671 PIPE_TYPE_BYTE
| PIPE_WAIT
, 1, 8192, 8192,
673 if (hSlaveInDrv
== NULL
) goto end
;
675 if (!CreatePipe (&process
->w_outfd
, &process
->w_forkout
, &sec_attrs
, 0))
676 report_file_error ("Creation of child's OUT handle", Qnil
);
678 if (SearchPath (NULL
, "explaunch.exe", NULL
,
679 MAX_PATH
, slavePath
, NULL
) == 0) goto end
;
681 for (argc
=0; argv
[argc
] != NULL
; argc
++) ;
682 nargv
= (char **) malloc (sizeof (char*) * (argc
+ 3));
683 nargv
[0] = slavePath
;
684 nargv
[1] = pipeNameIn
;
686 for (i
= 0; i
<= argc
; i
++) nargv
[i
+ 2] = argv
[i
];
687 process
->usePipe
= FALSE
;
690 /* Spawn the child. */
691 cpid
= nt_spawnve (nargv
[0], nargv
, NULL
, process
);
693 /* close the duplicated handles passed to the child */
694 CloseHandle (process
->w_forkout
);
696 if (process
->usePipe
== TRUE
) {
697 CloseHandle (process
->w_forkin
);
700 UCHAR buf
[8]; /* enough space for child status info */
706 * Wait for connection with the slave driver
708 bRet
= ConnectNamedPipe(hSlaveInDrv
, NULL
);
710 dwRet
= GetLastError();
711 if (dwRet
== ERROR_PIPE_CONNECTED
) {
718 process
->w_infd
= hSlaveInDrv
;
721 * wait for slave driver to initialize before allowing user to send to it
723 bRet
= ReadFile(process
->w_outfd
, buf
, 8, &count
, NULL
);
728 dwRet
= buf
[0] | (buf
[1] << 8) | (buf
[2] << 16) | (buf
[3] << 24);
733 cpid
= buf
[4] | (buf
[5] << 8) | (buf
[6] << 16) | (buf
[7] << 24);
738 /* An error occurred while trying to spawn the process. */
739 report_file_error ("Spawning child process", Qnil
);
743 if (hSlaveInDrv
!= NULL
)
744 CloseHandle (hSlaveInDrv
);
749 __gnat_setup_parent_communication
750 (struct TTY_Process
* process
,
756 *in
= _open_osfhandle ((intptr_t) process
->w_infd
, 0);
757 *out
= _open_osfhandle ((intptr_t) process
->w_outfd
, 0);
758 /* child's stderr is always redirected to outfd */
763 typedef struct _child_process
766 PROCESS_INFORMATION
*procinfo
;
769 /* The major and minor versions of NT. */
770 static int w32_major_version
;
771 static int w32_minor_version
;
773 /* Distinguish between Windows NT and Windows 95. */
774 static enum {OS_UNKNOWN
, OS_WIN95
, OS_NT
} os_subtype
= OS_UNKNOWN
;
776 /* Cache information describing the NT system for later use. */
778 cache_system_info (void)
791 /* Cache the version of the operating system. */
792 version
.data
= GetVersion ();
793 w32_major_version
= version
.info
.major
;
794 w32_minor_version
= version
.info
.minor
;
796 if (version
.info
.platform
& 0x8000)
797 os_subtype
= OS_WIN95
;
802 static WINBOOL CALLBACK
803 find_child_console (HWND hwnd
, LPARAM param
)
805 child_process
*cp
= (child_process
*) param
;
808 (void) GetWindowThreadProcessId (hwnd
, &process_id
);
809 if (process_id
== cp
->procinfo
->dwProcessId
)
811 char window_class
[32];
813 GetClassName (hwnd
, window_class
, sizeof (window_class
));
814 if (strcmp (window_class
,
815 (os_subtype
== OS_WIN95
)
817 : "ConsoleWindowClass") == 0)
828 __gnat_interrupt_pid (int pid
)
830 volatile child_process cp
;
833 cp
.procinfo
= (LPPROCESS_INFORMATION
) malloc (sizeof (PROCESS_INFORMATION
));
834 cp
.procinfo
->dwProcessId
= pid
;
836 if (os_subtype
== OS_UNKNOWN
)
837 cache_system_info ();
839 /* Try to locate console window for process. */
840 EnumWindows ((WNDENUMPROC
) find_child_console
, (LPARAM
) &cp
);
844 BYTE control_scan_code
= (BYTE
) MapVirtualKey (VK_CONTROL
, 0);
845 /* Retrieve Ctrl-C scancode */
846 BYTE vk_break_code
= 'C';
847 BYTE break_scan_code
= (BYTE
) MapVirtualKey (vk_break_code
, 0);
848 HWND foreground_window
;
850 foreground_window
= GetForegroundWindow ();
851 if (foreground_window
)
853 /* NT 5.0, and apparently also Windows 98, will not allow
854 a Window to be set to foreground directly without the
855 user's involvement. The workaround is to attach
856 ourselves to the thread that owns the foreground
857 window, since that is the only thread that can set the
858 foreground window. */
859 DWORD foreground_thread
, child_thread
;
862 GetWindowThreadProcessId (foreground_window
, NULL
);
863 if (foreground_thread
== GetCurrentThreadId ()
864 || !AttachThreadInput (GetCurrentThreadId (),
865 foreground_thread
, TRUE
))
866 foreground_thread
= 0;
868 child_thread
= GetWindowThreadProcessId (cp
.hwnd
, NULL
);
869 if (child_thread
== GetCurrentThreadId ()
870 || !AttachThreadInput (GetCurrentThreadId (),
874 /* Set the foreground window to the child. */
875 if (SetForegroundWindow (cp
.hwnd
))
877 /* Generate keystrokes as if user had typed Ctrl-Break or
879 keybd_event (VK_CONTROL
, control_scan_code
, 0, 0);
880 keybd_event (vk_break_code
, break_scan_code
,
881 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
), 0);
882 keybd_event (vk_break_code
, break_scan_code
,
883 (vk_break_code
== 'C' ? 0 : KEYEVENTF_EXTENDEDKEY
)
884 | KEYEVENTF_KEYUP
, 0);
885 keybd_event (VK_CONTROL
, control_scan_code
, KEYEVENTF_KEYUP
, 0);
887 /* Sleep for a bit to give time for the main frame to respond
888 to focus change events. */
891 SetForegroundWindow (foreground_window
);
893 /* Detach from the foreground and child threads now that
894 the foreground switching is over. */
895 if (foreground_thread
)
896 AttachThreadInput (GetCurrentThreadId (), foreground_thread
, FALSE
);
898 AttachThreadInput (GetCurrentThreadId (), child_thread
, FALSE
);
901 /* Ctrl-Break is NT equivalent of SIGINT. */
902 else if (!GenerateConsoleCtrlEvent
903 (CTRL_BREAK_EVENT
, cp
.procinfo
->dwProcessId
))
914 __gnat_interrupt_process (struct TTY_Process
* p
)
920 if (p
->usePipe
== TRUE
) {
923 buf
[0] = EXP_SLAVE_KILL
;
924 buf
[1] = EXP_KILL_CTRL_C
;
925 bret
= WriteFile (p
->w_infd
, buf
, 2, &written
, NULL
);
929 return __gnat_interrupt_pid (p
->procinfo
.dwProcessId
);
934 /* kill a process, as this implementation use CreateProcess on Win32 we need
935 to use Win32 TerminateProcess API */
937 __gnat_terminate_process (struct TTY_Process
* p
)
943 if (p
->usePipe
== TRUE
) {
946 buf
[0] = EXP_SLAVE_KILL
;
947 buf
[1] = EXP_KILL_TERMINATE
;
948 bret
= WriteFile (p
->w_infd
, buf
, 2, &written
, NULL
);
952 if (!TerminateProcess (p
->procinfo
.hProcess
, 1))
965 static WINBOOL CALLBACK
966 find_process_handle (HWND hwnd
, LPARAM param
)
968 pid_struct
*ps
= (pid_struct
*) param
;
971 (void) GetWindowThreadProcessId (hwnd
, &process_id
);
972 if (process_id
== ps
->dwProcessId
)
982 __gnat_terminate_pid (int pid
)
986 ps
.dwProcessId
= pid
;
988 EnumWindows ((WNDENUMPROC
) find_process_handle
, (LPARAM
) &ps
);
992 if (!TerminateProcess (ps
.hwnd
, 1))
1001 /* wait for process pid to terminate and return the process status. This
1002 implementation is different from the adaint.c one for Windows as it uses
1003 the Win32 API instead of the C one. */
1006 __gnat_tty_waitpid (struct TTY_Process
* p
, int blocking
)
1009 HANDLE hprocess
= p
->procinfo
.hProcess
;
1012 /* Wait is needed on Windows only in blocking mode. */
1013 WaitForSingleObject (hprocess
, 0);
1016 GetExitCodeProcess (hprocess
, &exitcode
);
1018 if (exitcode
== STILL_ACTIVE
) {
1019 /* If process is still active return -1. */
1022 /* Process is dead, so handle to process and main thread can be closed. */
1023 CloseHandle (p
->procinfo
.hThread
);
1024 CloseHandle (hprocess
);
1027 /* No need to close the handles: they were closed on the ada side */
1028 return (int) exitcode
;
1031 /********************************
1032 ** __gnat_free_process ()
1033 ********************************/
1036 __gnat_free_process (struct TTY_Process
** process
)
1045 int tty_fd
; /* descriptor for the tty */
1046 char tty_name
[24]; /* Name of TTY device */
1050 __gnat_tty_supported (void)
1055 /* Return the tty name associated with p */
1058 __gnat_tty_name (TTY_Handle
* t
)
1064 __gnat_tty_fd (TTY_Handle
* t
)
1070 __gnat_new_tty (void)
1072 return (TTY_Handle
*)0;
1076 __gnat_reset_tty (TTY_Handle
* t ATTRIBUTE_UNUSED
)
1081 __gnat_close_tty (TTY_Handle
* t
)
1087 __gnat_setup_winsize (void *desc ATTRIBUTE_UNUSED
,
1088 int rows ATTRIBUTE_UNUSED
, int columns ATTRIBUTE_UNUSED
)
1092 #else /* defined(_WIN32, implementatin for all UNIXes */
1094 /* First defined some macro to identify easily some systems */
1095 #if defined (__FreeBSD__) \
1096 || defined (__OpenBSD__) \
1097 || defined (__NetBSD__) \
1098 || defined (__DragonFly__)
1102 /* Include every system header we need */
1107 #include <sys/ioctl.h>
1108 #include <termios.h>
1111 #include <sys/stat.h>
1112 #include <sys/types.h>
1113 #include <sys/wait.h>
1115 #if defined (__sun__)
1116 # include <sys/stropts.h>
1118 #if defined (BSD) || defined (__sun__)
1119 # include <sys/signal.h>
1121 #if defined (__hpux__)
1122 # include <sys/stropts.h>
1125 #define CDISABLE _POSIX_VDISABLE
1127 /* POSIX does not specify how to open the master side of a terminal.Several
1128 methods are available (system specific):
1129 1- using a cloning device (USE_CLONE_DEVICE)
1130 2- getpt (USE_GETPT)
1131 3- openpty (USE_OPENPTY)
1133 When using the cloning device method, the macro USE_CLONE_DEVICE should
1134 contains a full path to the adequate device.
1136 When a new system is about to be supported, one of the previous macro should
1137 be set otherwise allocate_pty_desc will return an error
1140 /* Configurable part */
1141 #if defined (__APPLE__) || defined (BSD)
1143 #elif defined (__linux__)
1145 #elif defined (__sun__)
1146 #define USE_CLONE_DEVICE "/dev/ptmx"
1147 #elif defined (_AIX)
1148 #define USE_CLONE_DEVICE "/dev/ptc"
1149 #elif defined (__hpux__)
1150 /* On HP-UX we use the streamed version. Using the non streamed version is not
1151 recommanded (through "/dev/ptym/clone"). Indeed it seems that there are
1152 issues to detect process terminations. */
1153 #define USE_CLONE_DEVICE "/dev/ptmx"
1156 /* structure that holds information about the terminal used and the process
1157 connected on the slave side */
1158 typedef struct pty_desc_struct
{
1159 int master_fd
; /* fd of the master side if the terminal */
1160 int slave_fd
; /* fd of the slave side */
1161 char slave_name
[32]; /* filename of the slave side */
1162 int child_pid
; /* PID of the child process connected to the slave side
1166 /* allocate_pty_desc - allocate a pseudo terminal
1169 * out desc returned pointer to a pty_desc structure containing information
1170 * about the opened pseudo terminal
1175 * If the function is successful we should have at least the master side fd
1176 * and the slave side filename. On some system, the slave side will also be
1177 * opened. If this is not the case the slave side will be open once we are in
1178 * the child process (note that opening the slave side at this stage will
1182 extern char* ptsname (int);
1185 allocate_pty_desc (pty_desc
**desc
) {
1191 char *slave_name
= NULL
;
1194 master_fd
= getpt ();
1195 #elif defined (USE_OPENPTY)
1196 status
= openpty (&master_fd
, &slave_fd
, NULL
, NULL
, NULL
);
1197 #elif defined (USE_CLONE_DEVICE)
1198 master_fd
= open (USE_CLONE_DEVICE
, O_RDWR
| O_NONBLOCK
, 0);
1200 printf ("[error]: terminal support is not configured\n");
1204 /* at this stage we should have the master side fd and status should be 0 */
1205 if (status
!= 0 || master_fd
< 0)
1207 /* If this is not the case close all opened files and return -1 */
1208 printf ("[error]: cannot allocate master side of the pty\n");
1209 if (master_fd
>= 0) close (master_fd
);
1210 if (slave_fd
>= 0) close (slave_fd
);
1215 /* retrieve the file name of the slave side if necessary */
1216 if (slave_name
== NULL
) slave_name
= (char *) ptsname (master_fd
);
1218 /* Now we should have slave file name */
1219 if (slave_name
== NULL
)
1221 /* If not the case close any opened file and return - 1 */
1222 printf ("[error]: cannot allocate slave side of the pty\n");
1223 if (master_fd
>= 0) close (master_fd
);
1224 if (slave_fd
>= 0) close (slave_fd
);
1229 #if !defined(__rtems__)
1230 /* grant access to the slave side */
1231 grantpt (master_fd
);
1232 /* unlock the terminal */
1233 unlockpt (master_fd
);
1236 /* set desc and return 0 */
1237 result
= malloc (sizeof (pty_desc
));
1238 result
->master_fd
= master_fd
;
1239 result
->slave_fd
= slave_fd
;
1240 /* the string returned by ptsname or _getpty is a static allocated string. So
1241 we should make a copy */
1242 strncpy (result
->slave_name
, slave_name
, sizeof (result
->slave_name
) - 1);
1243 result
->slave_name
[sizeof (result
->slave_name
) - 1] = '\0';
1244 result
->child_pid
= -1;
1249 /* some utility macro that make the code of child_setup_tty easier to read */
1250 #define __enable(a, b) ((a) |= (b))
1251 #define __disable(a, b) ((a) &= ~(b))
1253 /* some properties do not exist on all systems. Set their value to 0 in that
1270 /* child_setup_tty - set terminal properties
1273 * file descriptor of the slave side of the terminal
1276 * 0 if success, any other value if failed.
1282 child_setup_tty (int fd
)
1287 /* Ensure that s is filled with 0.
1289 Note that we avoid using bzero for a few reasons:
1290 - On HP-UX and Sun system, there is a bzero function but with
1291 a different signature, thus making the use of bzero more
1292 complicated on these platforms (we used to define a bzero
1293 macro that rewrote calls to bzero into calls to memset);
1294 - bzero is deprecated (marked as LEGACY in POSIX.1-2001). */
1295 memset (&s
, 0, sizeof (s
));
1297 /* Get the current terminal settings */
1298 status
= tcgetattr (fd
, &s
);
1299 if (status
!= 0) return -1;
1301 /* Adjust input modes */
1302 __disable (s
.c_iflag
, IUCLC
); /* don't transform to lower case */
1303 __disable (s
.c_iflag
, ISTRIP
); /* don't delete 8th bit */
1305 /* Adjust output modes */
1306 __enable (s
.c_oflag
, OPOST
); /* enable postprocessing */
1307 __disable (s
.c_oflag
, ONLCR
); /* don't map LF to CR-LF */
1308 __disable (s
.c_oflag
, NLDLY
|CRDLY
|TABDLY
|BSDLY
|VTDLY
|FFDLY
);
1309 /* disable delays */
1310 __disable (s
.c_oflag
, OLCUC
); /* don't transform to upper case */
1312 /* Adjust control modes */
1313 s
.c_cflag
= (s
.c_cflag
& ~CSIZE
) | CS8
; /* Don't strip 8th bit */
1315 /* Adjust local modes */
1316 __disable (s
.c_lflag
, ECHO
); /* disable echo */
1317 __enable (s
.c_lflag
, ISIG
); /* enable signals */
1318 __enable (s
.c_lflag
, ICANON
); /* erase/kill/eof processing */
1320 /* Adjust control characters */
1321 /* IMPORTANT: we need to ensure that Ctrl-C will trigger an interrupt signal
1322 otherwise send_signal_via_characters will fail */
1323 s
.c_cc
[VEOF
] = 04; /* insure that EOF is Control-D */
1324 s
.c_cc
[VERASE
] = CDISABLE
; /* disable erase processing */
1325 s
.c_cc
[VKILL
] = CDISABLE
; /* disable kill processing */
1326 s
.c_cc
[VQUIT
] = 28; /* Control-\ */
1327 s
.c_cc
[VINTR
] = 03; /* Control-C */
1328 s
.c_cc
[VEOL
] = CDISABLE
;
1329 s
.c_cc
[VSUSP
] = 26; /* Control-Z */
1331 /* push our changes */
1332 status
= tcsetattr (fd
, TCSADRAIN
, &s
);
1336 /* __gnat_setup_communication - interface to the external world. Should be
1337 * called before forking. On Unixes this function only call allocate_pty_desc.
1338 * The Windows implementation (in different part of this file) is very
1342 * out desc returned pointer to a pty_desc structure
1344 * 0 if success, -1 otherwise
1346 int __gnat_setup_communication (pty_desc
** desc
) {
1347 return allocate_pty_desc (desc
);
1350 /* __gnat_setup_parent_communication - interface to the external world. Should
1351 * be called after forking in the parent process
1356 out err_fd fds corresponding to the parent side of the
1358 in pid_out child process pid
1363 __gnat_setup_parent_communication
1365 int* in_fd
, /* input */
1366 int* out_fd
, /* output */
1367 int* err_fd
, /* error */
1371 *in_fd
= desc
->master_fd
;
1372 *out_fd
= desc
->master_fd
;
1373 *err_fd
= desc
->master_fd
;
1374 desc
->child_pid
= *pid_out
;
1377 /* __gnat_setup_winsize - Sets up the size of the terminal
1378 * This lets the process know the size of the terminal
1381 void __gnat_setup_winsize (pty_desc
*desc
, int rows
, int columns
) {
1384 s
.ws_row
= (unsigned short)rows
;
1385 s
.ws_col
= (unsigned short)columns
;
1388 ioctl (desc
->master_fd
, TIOCSWINSZ
, &s
);
1390 if (desc
->child_pid
> 0) {
1391 /* Let the process know about the change in size */
1392 kill (desc
->child_pid
, SIGWINCH
);
1398 /* __gnat_setup_child_communication - interface to external world. Should be
1399 * called after forking in the child process. On Unixes, this function
1400 * first adjust the line setting, set standard output, input and error and
1401 * then spawn the program.
1404 * desc a pty_desc structure containing the pty parameters
1405 * new_argv argv of the program to be spawned
1407 * this function should not return
1410 __gnat_setup_child_communication
1413 int Use_Pipes ATTRIBUTE_UNUSED
)
1416 int pid
= getpid ();
1420 /* open the slave side of the terminal if necessary */
1421 if (desc
->slave_fd
== -1)
1423 /* On AIX, if the slave process is not opened with O_NDELAY or O_NONBLOCK
1424 then we might have some processes hanging on I/O system calls. Not sure
1425 we can do that for all platforms so do it only on AIX for the moment.
1426 On AIX O_NONBLOCK and O_NDELAY have slightly different meanings. When
1427 reading on the slave fd, in case there is no data available, if O_NDELAY
1428 is set then 0 is returned. If O_NON_BLOCK is -1 is returned. It seems
1429 that interactive programs such as GDB prefer the O_NDELAY behavior.
1430 We chose O_NONBLOCK because it allows us to make the distinction
1431 between a true EOF and an EOF returned because there is no data
1432 available to be read. */
1433 desc
->slave_fd
= open (desc
->slave_name
, O_RDWR
| O_NONBLOCK
, 0);
1435 desc
->slave_fd
= open (desc
->slave_name
, O_RDWR
, 0);
1438 #if defined (__sun__) || defined (__hpux__)
1439 /* On systems such as Solaris we are using stream. We need to push the right
1440 "modules" in order to get the expected terminal behaviors. Otherwise
1441 functionalities such as termios are not available. */
1442 ioctl (desc
->slave_fd
, I_PUSH
, "ptem");
1443 ioctl (desc
->slave_fd
, I_PUSH
, "ldterm");
1444 ioctl (desc
->slave_fd
, I_PUSH
, "ttcompat");
1448 /* make the tty the controlling terminal */
1449 if ((status
= ioctl (desc
->slave_fd
, TIOCSCTTY
, 0)) == -1)
1453 /* adjust tty settings */
1454 child_setup_tty (desc
->slave_fd
);
1455 __gnat_setup_winsize (desc
, 24, 80); /* To prevent errors in some shells */
1457 /* stdin, stdout and stderr should be now our tty */
1458 dup2 (desc
->slave_fd
, 0);
1459 dup2 (desc
->slave_fd
, 1);
1460 dup2 (desc
->slave_fd
, 2);
1461 if (desc
->slave_fd
> 2) close (desc
->slave_fd
);
1463 /* adjust process group settings */
1464 /* ignore failures of the following two commands as the context might not
1465 * allow making those changes. */
1469 /* launch the program */
1470 execvp (new_argv
[0], new_argv
);
1475 /* send_signal_via_characters - Send a characters that will trigger a signal
1476 * in the child process.
1479 * desc a pty_desc structure containing terminal information
1480 * int a signal number
1485 send_signal_via_characters
1490 char ctrl_backslash
= 28;
1493 switch (signal_number
)
1496 write (desc
->master_fd
, &ctrl_c
, 1); return;
1498 write (desc
->master_fd
, &ctrl_backslash
, 1); return;
1500 write (desc
->master_fd
, &ctrl_Z
, 1); return;
1504 /* __gnat_interrupt_process - interrupt the child process
1507 * desc a pty_desc structure
1510 __gnat_interrupt_process (pty_desc
*desc
)
1512 send_signal_via_characters (desc
, SIGINT
);
1516 /* __gnat_interrupt_pid - interrupt a process group
1519 * pid pid of the process to interrupt
1522 __gnat_interrupt_pid (int pid
)
1524 kill (-pid
, SIGINT
);
1528 /* __gnat_terminate_process - kill a child process
1531 * desc pty_desc structure
1533 int __gnat_terminate_process (pty_desc
*desc
)
1535 return kill (desc
->child_pid
, SIGKILL
);
1538 /* __gnat_terminate_pid - kill a process
1541 * pid unix process id
1544 __gnat_terminate_pid (int pid
)
1546 return kill (pid
, SIGKILL
);
1549 /* __gnat_tty_waitpid - wait for the child process to die
1552 * desc pty_desc structure
1554 * exit status of the child process
1557 __gnat_tty_waitpid (pty_desc
*desc
, int blocking
)
1567 waitpid (desc
->child_pid
, &status
, options
);
1568 if WIFEXITED (status
) {
1569 status
= WEXITSTATUS (status
);
1574 /* __gnat_tty_supported - Are tty supported ?
1577 * always 1 on Unix systems
1580 __gnat_tty_supported (void)
1585 /* __gnat_free_process - free a pty_desc structure
1588 * in out desc: a pty desc structure
1591 __gnat_free_process (pty_desc
** desc
)
1597 /* __gnat_send_header - dummy function. this interface is only used on Windows */
1599 __gnat_send_header (pty_desc
* desc ATTRIBUTE_UNUSED
,
1600 char header
[5] ATTRIBUTE_UNUSED
,
1601 int size ATTRIBUTE_UNUSED
,
1602 int *ret ATTRIBUTE_UNUSED
)
1607 /* __gnat_reset_tty - reset line setting
1610 * desc: a pty_desc structure
1613 __gnat_reset_tty (pty_desc
* desc
)
1615 child_setup_tty (desc
->master_fd
);
1618 /* __gnat_new_tty - allocate a new terminal
1621 * a pty_desc structure
1624 __gnat_new_tty (void)
1627 pty_desc
* desc
= NULL
;
1628 if ((status
= allocate_pty_desc (&desc
)))
1629 child_setup_tty (desc
->master_fd
);
1633 /* __gnat_close_tty - close a terminal
1636 * desc a pty_desc strucure
1638 void __gnat_close_tty (pty_desc
* desc
)
1640 if (desc
->master_fd
>= 0) { close (desc
->master_fd
); desc
->master_fd
= -1; }
1641 if (desc
->slave_fd
>= 0) { close (desc
->slave_fd
); desc
->slave_fd
= -1; }
1644 /* __gnat_tty_name - return slave side device name
1647 * desc a pty_desc strucure
1652 __gnat_tty_name (pty_desc
* desc
)
1654 return desc
->slave_name
;
1657 /* __gnat_tty_name - return master side fd
1660 * desc a pty_desc strucure
1665 __gnat_tty_fd (pty_desc
* desc
)
1667 return desc
->master_fd
;