-
Notifications
You must be signed in to change notification settings - Fork 181
/
child.c
1469 lines (1339 loc) · 36.7 KB
/
child.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// child.c (part of mintty)
// Copyright 2008-11 Andy Koppe, 2015-2022 Thomas Wolff
// Licensed under the terms of the GNU General Public License v3 or later.
#include "child.h"
#include "term.h"
#include "charset.h"
#include "winpriv.h" /* win_prefix_title, win_update_now */
#include "appinfo.h" /* APPNAME, VERSION */
#include <pwd.h>
#include <fcntl.h>
#include <utmp.h>
#include <dirent.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#ifdef __CYGWIN__
#include <sys/cygwin.h> // cygwin_internal
#endif
#if CYGWIN_VERSION_API_MINOR >= 93
#include <pty.h>
#else
int forkpty(int *, char *, struct termios *, struct winsize *);
#endif
#include <winbase.h>
#if CYGWIN_VERSION_DLL_MAJOR < 1007
#include <winnls.h>
#include <wincon.h>
#include <wingdi.h>
#include <winuser.h>
#endif
// exit code to use for failure of `exec` (changed from 255, see #745)
// http://www.tldp.org/LDP/abs/html/exitcodes.html
#define mexit 126
string child_dir = null;
bool logging = false;
static pid_t pid;
static bool killed;
static int win_fd;
static int pty_fd = -1;
static int log_fd = -1;
#if CYGWIN_VERSION_API_MINOR >= 74
static struct winsize prev_winsize = {0, 0, 0, 0};
#else
static struct winsize prev_winsize;
#endif
#if CYGWIN_VERSION_API_MINOR >= 66
#include <langinfo.h>
#endif
#define dont_debug_dir
#ifdef debug_dir
#define trace_dir(d) show_info(d)
#else
#define trace_dir(d)
#endif
static void
childerror(char * action, bool from_fork, int errno_code, int code)
{
#if CYGWIN_VERSION_API_MINOR >= 66
bool utf8 = strcmp(nl_langinfo(CODESET), "UTF-8") == 0;
char * oldloc;
#else
char * oldloc = (char *)cs_get_locale();
bool utf8 = strstr(oldloc, ".65001");
#endif
if (utf8)
oldloc = null;
else {
oldloc = strdup(cs_get_locale());
cs_set_locale("C.UTF-8");
}
char s[33];
bool colour_code = code && !errno_code;
sprintf(s, "\r\n\033[30;%dm\033[K", from_fork ? 41 : colour_code ? code : 43);
term_write(s, strlen(s));
term_write(action, strlen(action));
if (errno_code) {
char * err = strerror(errno_code);
if (from_fork && errno_code == ENOENT)
err = _("There are no available terminals");
term_write(": ", 2);
term_write(err, strlen(err));
}
if (code && !colour_code) {
sprintf(s, " (%d)", code);
term_write(s, strlen(s));
}
term_write(".\033[0m\r\n", 7);
if (oldloc) {
cs_set_locale(oldloc);
free(oldloc);
}
}
static void
sigexit(int sig)
{
if (pid)
kill(-pid, SIGHUP);
signal(sig, SIG_DFL);
report_pos();
kill(getpid(), sig);
}
static void
open_logfile(bool toggling)
{
// Open log file if any
if (*cfg.log) {
// use cygwin conversion function to escape unencoded characters
// and thus avoid the locale trick (2.2.3)
if (0 == wcscmp(cfg.log, W("-"))) {
log_fd = fileno(stdout);
logging = true;
}
else {
char * log;
if (*cfg.log == '~' && cfg.log[1] == '/') {
// substitute '~' -> home
char * path = cs__wcstombs(&cfg.log[2]);
log = asform("%s/%s", home, path);
free(path);
}
else
log = path_win_w_to_posix(cfg.log);
#ifdef debug_logfilename
printf("<%ls> -> <%s>\n", cfg.log, log);
#endif
char * format = strchr(log, '%');
if (format && * ++ format == 'd' && !strchr(format, '%')) {
char * logf = newn(char, strlen(log) + 20);
sprintf(logf, log, getpid());
free(log);
log = logf;
}
else if (format) {
struct timeval now;
gettimeofday(& now, 0);
char * logf = newn(char, MAX_PATH + 1);
strftime(logf, MAX_PATH, log, localtime (& now.tv_sec));
free(log);
log = logf;
}
log_fd = open(log, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (log_fd < 0) {
// report message and filename:
wchar * wpath = path_posix_to_win_w(log);
char * upath = cs__wcstoutf(wpath);
#ifdef debug_logfilename
printf(" -> <%ls> -> <%s>\n", wpath, upath);
#endif
char * msg = _("Error: Could not open log file");
if (toggling) {
char * err = strerror(errno);
char * errmsg = newn(char, strlen(msg) + strlen(err) + strlen(upath) + 4);
sprintf(errmsg, "%s: %s\n%s", msg, err, upath);
win_show_warning(errmsg);
free(errmsg);
}
else {
childerror(msg, false, errno, 0);
childerror(upath, false, 0, 0);
}
free(upath);
free(wpath);
}
else
logging = true;
free(log);
}
}
}
void
toggle_logging()
{
if (logging)
logging = false;
else if (log_fd >= 0)
logging = true;
else
open_logfile(true);
}
void
child_update_charset(void)
{
#ifdef IUTF8
if (pty_fd >= 0) {
// Terminal line settings
struct termios attr;
tcgetattr(pty_fd, &attr);
bool utf8 = strcmp(nl_langinfo(CODESET), "UTF-8") == 0;
if (utf8)
attr.c_iflag |= IUTF8;
else
attr.c_iflag &= ~IUTF8;
tcsetattr(pty_fd, TCSANOW, &attr);
}
#endif
}
/*
Trim environment from variables set by launchers, other terminals,
or other shells, in order to avoid confusing behaviour or invalid
information (e.g. LINES, COLUMNS).
*/
static void
trim_environment(void)
{
void trimenv(string e) {
if (e[strlen(e) - 1] == '_') {
#if CYGWIN_VERSION_API_MINOR >= 74
for (int ei = 0; environ[ei]; ei++) {
if (strncmp(e, environ[ei], strlen(e)) == 0) {
char * ee = strchr(environ[ei], '=');
if (ee) {
char * ev = strndup(environ[ei], ee - environ[ei]);
//printf("%s @%d - unsetenv %s: %s\n", e, ei, ev, environ[ei]);
unsetenv(ev);
free(ev);
// recheck current position after deletion
--ei;
}
}
}
#endif
}
else
unsetenv(e);
}
// clear startup information from desktop launchers
trimenv("WINDOWID");
trimenv("GIO_LAUNCHED_");
trimenv("DESKTOP_STARTUP_ID");
// clear optional terminal configuration indications
trimenv("LINES");
trimenv("COLUMNS");
trimenv("TERMCAP");
trimenv("COLORFGBG");
trimenv("COLORTERM");
trimenv("DEFAULT_COLORS");
trimenv("WCWIDTH_CJK_LEGACY");
// clear identification from other terminals
trimenv("ITERM2_");
trimenv("MC_");
trimenv("PUTTY");
trimenv("RXVT_");
trimenv("URXVT_");
trimenv("VTE_");
trimenv("XTERM_");
trimenv("TERM_");
// clear indications from terminal multiplexers
trimenv("STY");
trimenv("WINDOW");
trimenv("TMUX");
trimenv("TMUX_PANE");
trimenv("BYOBU_");
}
static bool
ispathprefix(string pref, string path)
{
if (*pref == '/')
pref++;
if (*path == '/')
path++;
int len = strlen(pref);
if (0 == strncmp(pref, path, len)) {
path += len;
if (!*path || *path == '/')
return true;
}
return false;
}
void
child_create(char *argv[], struct winsize *winp)
{
trace_dir(asform("child_create: %s", getcwd(malloc(MAX_PATH), MAX_PATH)));
trim_environment();
prev_winsize = *winp;
// xterm and urxvt ignore SIGHUP, so let's do the same.
signal(SIGHUP, SIG_IGN);
signal(SIGINT, sigexit);
signal(SIGTERM, sigexit);
signal(SIGQUIT, sigexit);
// support OSC 7 directory cloning if cloning WSL window while in rootfs
if (support_wsl && wslname) {
// this is done once in a new window, so don't care about memory leaks
char * rootfs = path_win_w_to_posix(wsl_basepath);
char * cwd = getcwd(malloc(MAX_PATH), MAX_PATH);
if (ispathprefix(rootfs, cwd)) {
char * dist = cs__wcstombs(wslname);
char * wslsubdir = cwd + strlen(rootfs);
char * wsldir = asform("//wsl$/%s%s", dist, wslsubdir);
chdir(wsldir);
}
}
// Create the child process and pseudo terminal.
pid = forkpty(&pty_fd, 0, 0, winp);
if (pid < 0) {
bool rebase_prompt = (errno == EAGAIN);
//ENOENT There are no available terminals.
//EAGAIN Cannot allocate sufficient memory to allocate a task structure.
//EAGAIN Not possible to create a new process; RLIMIT_NPROC limit.
//ENOMEM Memory is tight.
childerror(_("Error: Could not fork child process"), true, errno, pid);
if (rebase_prompt)
childerror(_("DLL rebasing may be required; see 'rebaseall / rebase --help'"), false, 0, 0);
pid = 0;
term_hide_cursor();
}
else if (!pid) { // Child process.
#if CYGWIN_VERSION_DLL_MAJOR < 1007
// Some native console programs require a console to be attached to the
// process, otherwise they pop one up themselves, which is rather annoying.
// Cygwin's exec function from 1.5 onwards automatically allocates a console
// on an invisible window station if necessary. Unfortunately that trick no
// longer works on Windows 7, which is why Cygwin 1.7 contains a new hack
// for creating the invisible console.
// On Cygwin versions before 1.5 and on Cygwin 1.5 running on Windows 7,
// we need to create the invisible console ourselves. The hack here is not
// as clever as Cygwin's, with the console briefly flashing up on startup,
// but it'll do.
#if CYGWIN_VERSION_DLL_MAJOR == 1005
DWORD win_version = GetVersion();
win_version = ((win_version & 0xff) << 8) | ((win_version >> 8) & 0xff);
if (win_version >= 0x0601) // Windows 7 is NT 6.1.
#endif
if (AllocConsole()) {
HMODULE kernel = GetModuleHandleA("kernel32");
HWND (WINAPI *pGetConsoleWindow)(void) =
(void *)GetProcAddress(kernel, "GetConsoleWindow");
ShowWindowAsync(pGetConsoleWindow(), SW_HIDE);
}
#endif
// Reset signals
signal(SIGHUP, SIG_DFL);
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
signal(SIGCHLD, SIG_DFL);
// Mimick login's behavior by disabling the job control signals
signal(SIGTSTP, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
setenv("TERM", cfg.term, true);
// unreliable info about terminal application (#881)
setenv("TERM_PROGRAM", APPNAME, true);
setenv("TERM_PROGRAM_VERSION", VERSION, true);
// If option Locale is used, set locale variables?
// https://github.com/mintty/mintty/issues/116#issuecomment-108888265
// Variables are now set in update_locale() which sets one of
// LC_ALL or LC_CTYPE depending on previous setting of
// LC_ALL or LC_CTYPE or LANG, stripping @cjk modifiers for WSL.
if (cfg.old_locale) {
//string lang = cs_lang();
string lang = cs_lang() ? cs_get_locale() : 0;
if (lang) {
unsetenv("LC_ALL");
unsetenv("LC_COLLATE");
unsetenv("LC_CTYPE");
unsetenv("LC_MONETARY");
unsetenv("LC_NUMERIC");
unsetenv("LC_TIME");
unsetenv("LC_MESSAGES");
setenv("LANG", lang, true);
}
}
// Terminal line settings
struct termios attr;
tcgetattr(0, &attr);
attr.c_cc[VERASE] = cfg.backspace_sends_bs ? CTRL('H') : CDEL;
attr.c_iflag |= IXANY | IMAXBEL;
#ifdef IUTF8
bool utf8 = strcmp(nl_langinfo(CODESET), "UTF-8") == 0;
if (utf8)
attr.c_iflag |= IUTF8;
else
attr.c_iflag &= ~IUTF8;
#endif
attr.c_lflag |= ECHOE | ECHOK | ECHOCTL | ECHOKE;
tcsetattr(0, TCSANOW, &attr);
// Invoke command
execvp(cmd, argv);
// If we get here, exec failed.
fprintf(stderr, "\033]701;C.UTF-8\007");
fprintf(stderr, "\033[30;41m\033[K");
//__ %1$s: client command (e.g. shell) to be run; %2$s: error message
fprintf(stderr, _("Failed to run '%s': %s"), cmd, strerror(errno));
fprintf(stderr, "\r\n");
fflush(stderr);
#if CYGWIN_VERSION_DLL_MAJOR < 1005
// Before Cygwin 1.5, the message above doesn't appear if we exit
// immediately. So have a little nap first.
usleep(200000);
#endif
exit(mexit);
}
else { // Parent process.
if (report_child_pid) {
printf("%d\n", pid);
fflush(stdout);
}
if (report_child_tty) {
printf("%s\n", ptsname(pty_fd));
fflush(stdout);
}
#ifdef __midipix__
// This corrupts CR in cygwin
struct termios attr;
tcgetattr(pty_fd, &attr);
cfmakeraw(&attr);
tcsetattr(pty_fd, TCSANOW, &attr);
#endif
fcntl(pty_fd, F_SETFL, O_NONBLOCK);
//child_update_charset(); // could do it here or as above
if (cfg.create_utmp) {
char *dev = ptsname(pty_fd);
if (dev) {
struct utmp ut;
memset(&ut, 0, sizeof ut);
if (!strncmp(dev, "/dev/", 5))
dev += 5;
strlcpy(ut.ut_line, dev, sizeof ut.ut_line);
if (dev[1] == 't' && dev[2] == 'y')
dev += 3;
else if (!strncmp(dev, "pts/", 4))
dev += 4;
//strncpy(ut.ut_id, dev, sizeof ut.ut_id);
for (uint i = 0; i < sizeof ut.ut_id && *dev; i++)
ut.ut_id[i] = *dev++;
ut.ut_type = USER_PROCESS;
ut.ut_pid = pid;
ut.ut_time = time(0);
strlcpy(ut.ut_user, getlogin() ?: "?", sizeof ut.ut_user);
gethostname(ut.ut_host, sizeof ut.ut_host);
login(&ut);
}
}
}
win_fd = open("/dev/windows", O_RDONLY);
if (cfg.logging) {
// option Logging=yes => initially open log file if configured
open_logfile(false);
}
}
char *
child_tty(void)
{
return ptsname(pty_fd);
}
uchar *
child_termios_chars(void)
{
static struct termios attr;
tcgetattr(pty_fd, &attr);
return attr.c_cc;
}
#define patch_319
#ifdef debug_pty
static void
trace_line(char * tag, int n, const char * s, int len)
{
printf("%s %d", tag, n);
for (int i = 0; i < len; i++)
printf(" %02X", (uint)s[i]);
printf("\n");
}
#else
#define trace_line(tag, n, s, len)
#endif
void
child_proc(void)
{
if (term.no_scroll)
return;
for (;;) {
if (term.paste_buffer)
term_send_paste();
struct timeval timeout = {0, 100000}, *timeout_p = 0;
fd_set fds;
FD_ZERO(&fds);
FD_SET(win_fd, &fds);
if (pty_fd >= 0)
FD_SET(pty_fd, &fds);
#ifndef patch_319
else
#endif
if (pid) {
int status;
if (waitpid(pid, &status, WNOHANG) == pid) {
pid = 0;
// Decide whether we want to exit now or later
if (killed || cfg.hold == HOLD_NEVER)
exit_mintty();
else if (cfg.hold == HOLD_START) {
if (WIFSIGNALED(status) || WEXITSTATUS(status) != mexit)
exit_mintty();
}
else if (cfg.hold == HOLD_ERROR) {
if (WIFEXITED(status)) {
if (WEXITSTATUS(status) == 0)
exit_mintty();
}
else {
const int error_sigs =
1 << SIGILL | 1 << SIGTRAP | 1 << SIGABRT | 1 << SIGFPE |
1 << SIGBUS | 1 << SIGSEGV | 1 << SIGPIPE | 1 << SIGSYS;
if (!(error_sigs & 1 << WTERMSIG(status)))
exit_mintty();
}
}
char *s = 0;
bool err = true;
if (WIFEXITED(status)) {
int code = WEXITSTATUS(status);
if (code == 0)
err = false;
if ((code || cfg.exit_write) /*&& cfg.hold != HOLD_START*/)
//__ %1$s: client command (e.g. shell) terminated, %2$i: exit code
asprintf(&s, _("%s: Exit %i"), cmd, code);
}
else if (WIFSIGNALED(status))
asprintf(&s, "%s: %s", cmd, strsignal(WTERMSIG(status)));
if (!s && cfg.exit_write) {
//__ default inline notification if ExitWrite=yes
s = _("TERMINATED");
}
if (s) {
char * wsl_pre = "\0337\033[H\033[L";
char * wsl_post = "\0338\033[B";
if (err && support_wsl)
term_write(wsl_pre, strlen(wsl_pre));
childerror(s, false, 0, err ? 41 : 42);
if (err && support_wsl)
term_write(wsl_post, strlen(wsl_post));
}
if (cfg.exit_title && *cfg.exit_title)
win_prefix_title(cfg.exit_title);
}
#ifdef patch_319
if (pid != 0 && pty_fd < 0) // Pty gone, but process still there: keep checking
#else
else // Pty gone, but process still there: keep checking
#endif
timeout_p = &timeout;
}
if (select(win_fd + 1, &fds, 0, 0, timeout_p) > 0) {
if (pty_fd >= 0 && FD_ISSET(pty_fd, &fds)) {
// Pty devices on old Cygwin versions (pre 1005) deliver only 4 bytes
// at a time, and newer ones or MSYS2 deliver up to 256 at a time.
// so call read() repeatedly until we have a worthwhile haul.
// this avoids most partial updates, results in less flickering/tearing.
static char buf[4096];
uint len = 0;
#if CYGWIN_VERSION_API_MINOR >= 74
if (cfg.baud > 0) {
uint cps = cfg.baud / 10; // 1 start bit, 8 data bits, 1 stop bit
uint nspc = 2000000000 / cps;
static ulong prevtime = 0;
static ulong exceeded = 0;
static ulong granularity = 0;
struct timespec tim;
if (!granularity) {
clock_getres(CLOCK_MONOTONIC, &tim); // cygwin granularity: 539ns
granularity = tim.tv_nsec;
}
clock_gettime(CLOCK_MONOTONIC, &tim);
ulong now = tim.tv_sec * (long)1000000000 + tim.tv_nsec;
//printf("baud %d ns/char %d prev %ld now %ld delta\n", cfg.baud, nspc, prevtime, now);
if (now < prevtime + nspc) {
ulong delay = prevtime ? prevtime + nspc - now : 0;
if (delay < exceeded)
exceeded -= delay;
else {
tim.tv_sec = delay / 1000000000;
tim.tv_nsec = delay % 1000000000;
clock_nanosleep(CLOCK_MONOTONIC, 0, &tim, 0);
clock_gettime(CLOCK_MONOTONIC, &tim);
ulong then = tim.tv_sec * (long)1000000000 + tim.tv_nsec;
//printf("nsleep %ld -> %ld\n", delay, then - now);
if (then - now > delay)
exceeded = then - now - delay;
now = then;
}
}
prevtime = now;
int ret = read(pty_fd, buf, 1);
if (ret > 0)
len = ret;
}
else
#endif
do {
int ret = read(pty_fd, buf + len, sizeof buf - len);
trace_line("read", ret, buf + len, ret);
//if (kb_trace) printf("[%lu] read %d\n", mtime(), ret);
if (ret > 0)
len += ret;
else
break;
} while (len < sizeof buf);
if (len > 0) {
term_write(buf, len);
trace_line("twrt", len, buf, len);
// accelerate keyboard echo if (unechoed) keyboard input is pending
if (kb_input) {
kb_input = false;
if (cfg.display_speedup)
// undocumented safeguard in case something goes wrong here
win_update_now();
}
if (log_fd >= 0 && logging)
write(log_fd, buf, len);
}
else {
pty_fd = -1;
term_hide_cursor();
}
}
if (FD_ISSET(win_fd, &fds))
return;
}
}
}
void
child_kill(bool point_blank)
{
if (!pid ||
kill(-pid, point_blank ? SIGKILL : SIGHUP) < 0 ||
point_blank)
exit_mintty();
killed = true;
}
bool
child_is_alive(void)
{
return pid;
}
bool
child_is_parent(void)
{
if (!pid)
return false;
DIR * d = opendir("/proc");
if (!d)
return false;
bool res = false;
struct dirent * e;
while ((e = readdir(d))) {
char * pn = e->d_name;
if (isdigit((uchar)*pn) && strlen(pn) <= 6) {
char * fn = asform("/proc/%s/ppid", pn);
FILE * f = fopen(fn, "r");
free(fn);
if (!f)
continue;
pid_t ppid = 0;
fscanf(f, "%u", &ppid);
fclose(f);
if (ppid == pid) {
res = true;
break;
}
}
}
closedir(d);
return res;
}
static struct procinfo {
int pid;
int ppid;
int winpid;
char * cmdline;
} * ttyprocs = 0;
static uint nttyprocs = 0;
char *
procres(int pid, char * res)
{
char fbuf[99];
char * fn = asform("/proc/%d/%s", pid, res);
int fd = open(fn, O_BINARY | O_RDONLY);
free(fn);
if (fd < 0)
return 0;
int n = read(fd, fbuf, sizeof fbuf - 1);
close(fd);
for (int i = 0; i < n - 1; i++)
if (!fbuf[i])
fbuf[i] = ' ';
fbuf[n] = 0;
char * nl = strchr(fbuf, '\n');
if (nl)
*nl = 0;
return strdup(fbuf);
}
static int
procresi(int pid, char * res)
{
char * si = procres(pid, res);
int i = atoi(si);
free(si);
return i;
}
#ifndef HAS_LOCALES
#define wcwidth xcwidth
#else
#if CYGWIN_VERSION_API_MINOR < 74
#define wcwidth xcwidth
#endif
#endif
wchar *
grandchild_process_list(void)
{
if (!pid)
return 0;
DIR * d = opendir("/proc");
if (!d)
return 0;
char * tty = child_tty();
struct dirent * e;
while ((e = readdir(d))) {
char * pn = e->d_name;
int thispid = atoi(pn);
if (thispid && thispid != pid) {
char * ctty = procres(thispid, "ctty");
if (ctty) {
if (0 == strcmp(ctty, tty)) {
int ppid = procresi(thispid, "ppid");
int winpid = procresi(thispid, "winpid");
// not including the direct child (pid)
ttyprocs = renewn(ttyprocs, nttyprocs + 1);
ttyprocs[nttyprocs].pid = thispid;
ttyprocs[nttyprocs].ppid = ppid;
ttyprocs[nttyprocs].winpid = winpid;
char * cmd = procres(thispid, "cmdline");
ttyprocs[nttyprocs].cmdline = cmd;
nttyprocs++;
}
free(ctty);
}
}
}
closedir(d);
DWORD win_version = GetVersion();
win_version = ((win_version & 0xff) << 8) | ((win_version >> 8) & 0xff);
wchar * res = 0;
for (uint i = 0; i < nttyprocs; i++) {
char * proc = newn(char, 50 + strlen(ttyprocs[i].cmdline));
sprintf(proc, " %5u %5u %s", ttyprocs[i].winpid, ttyprocs[i].pid, ttyprocs[i].cmdline);
free(ttyprocs[i].cmdline);
wchar * procw = cs__mbstowcs(proc);
free(proc);
if (win_version >= 0x0601)
for (int i = 0; i < 13; i++)
if (procw[i] == ' ')
procw[i] = 0x2007; // FIGURE SPACE
int wid = min(wcslen(procw), 40);
for (int i = 13; i < wid; i++)
if (((cfg.charwidth % 10) ? xcwidth(procw[i]) : wcwidth(procw[i])) == 2)
wid--;
procw[wid] = 0;
if (win_version >= 0x0601) {
if (!res)
res = wcsdup(W("╎ WPID PID COMMAND\n")); // ┆┇┊┋╎╏
res = renewn(res, wcslen(res) + wcslen(procw) + 3);
wcscat(res, W("╎"));
}
else {
if (!res)
res = wcsdup(W("| WPID PID COMMAND\n")); // ┆┇┊┋╎╏
res = renewn(res, wcslen(res) + wcslen(procw) + 3);
wcscat(res, W("|"));
}
wcscat(res, procw);
wcscat(res, W("\n"));
free(procw);
}
if (ttyprocs) {
nttyprocs = 0;
free(ttyprocs);
ttyprocs = 0;
}
return res;
}
void
child_write(const char *buf, uint len)
{
if (pty_fd >= 0) {
#ifdef debug_pty
int n =
#endif
write(pty_fd, buf, len);
trace_line("cwrt", n, buf, len);
}
}
/*
Simulate a BREAK event.
*/
void
child_break()
{
int gid = tcgetpgrp(pty_fd);
if (gid > 1) {
struct termios attr;
tcgetattr(pty_fd, &attr);
if ((attr.c_iflag & (IGNBRK | BRKINT)) == BRKINT) {
kill(gid, SIGINT);
}
}
}
/*
Send an INTR char.
*/
void
child_intr()
{
char * c_cc = (char *)child_termios_chars();
child_write(&c_cc[VINTR], 1);
}
void
child_printf(const char *fmt, ...)
{
if (pty_fd >= 0) {
va_list va;
va_start(va, fmt);
char *s;
int len = vasprintf(&s, fmt, va);
va_end(va);
if (len >= 0) {
#ifdef debug_pty
int n =
#endif
write(pty_fd, s, len);
trace_line("tprt", n, s, len);
}
free(s);
}
}
void
child_send(const char *buf, uint len)
{
term_reset_screen();
if (term.echoing)
term_write(buf, len);
child_write(buf, len);
}
void
child_sendw(const wchar *ws, uint wlen)
{
char s[wlen * cs_cur_max];
int len = cs_wcntombn(s, ws, sizeof s, wlen);
if (len > 0)
child_send(s, len);
}
void
child_resize(struct winsize *winp)
{
if (pty_fd >= 0 && memcmp(&prev_winsize, winp, sizeof(struct winsize)) != 0) {
prev_winsize = *winp;
ioctl(pty_fd, TIOCSWINSZ, winp);
}
}
static int
foreground_pid()
{
int fg_pid = (pty_fd >= 0) ? tcgetpgrp(pty_fd) : 0;
if (fg_pid <= 0)
// fallback to child process
fg_pid = pid;
return fg_pid;
}
static char *
get_foreground_cwd()
{
// for WSL, do not check foreground process; hope start dir is good
if (support_wsl) {
char cwd[MAX_PATH];
if (getcwd(cwd, sizeof(cwd)))
return strdup(cwd);
else
return 0;
}
#if CYGWIN_VERSION_DLL_MAJOR >= 1005
int fg_pid = foreground_pid();
if (fg_pid > 0) {
char proc_cwd[32];
sprintf(proc_cwd, "/proc/%u/cwd", fg_pid);
return realpath(proc_cwd, 0);
}
#endif
return 0;
}
char *
foreground_cwd()
{
#ifdef consider_osc7
// if working dir is communicated interactively, use it
// - drop this generic handling here as it would also affect
// relative pathname resolution outside OSC 7 usage
if (child_dir && *child_dir)
return strdup(child_dir);
#endif
return get_foreground_cwd();
}
char *
foreground_prog()
{
#if CYGWIN_VERSION_DLL_MAJOR >= 1005
int fg_pid = foreground_pid();
if (fg_pid > 0) {