Debian Codegraph @

proc.c

raw
1 /**************************************************************************
2 * This program is Copyright (C) 1986-2002 by Jonathan Payne. JOVE is *
3 * provided by Jonathan and Jovehacks without charge and without *
4 * warranty. You may copy, modify, and/or distribute JOVE, provided that *
5 * this notice is included in all the source files and documentation. *
6 **************************************************************************/
7
8 #include "jove.h"
9
10 #include "jctype.h"
11 #include "fp.h"
12 #include "re.h"
13 #include "disp.h"
14 #include "ask.h"
15 #include "delete.h"
16 #include "extend.h"
17 #include "fmt.h"
18 #include "insert.h"
19 #ifdef IPROCS
20 # include "iproc.h"
21 #endif
22 #include "marks.h"
23 #include "misc.h"
24 #include "move.h"
25 #include "proc.h"
26 #include "wind.h"
27
28 #include <signal.h>
29
30 #include <sys/stat.h> /* for S_IWRITE and S_IREAD */
31
32 #ifdef POSIX_SIGS
33 # define SIGINTMASK_DECL sigset_t sigintmask;
34 # define SIGINTMASK_INIT() { sigemptyset(&sigintmask); sigaddset(&sigintmask, SIGINT); }
35 # define SIGINT_BLOCK() sigprocmask(SIG_BLOCK, &sigintmask, (sigset_t *)NULL)
36 # define SIGINT_UNBLOCK() sigprocmask(SIG_UNBLOCK, &sigintmask, (sigset_t *)NULL)
37 #else /* !POSIX_SIGS */
38 # ifdef USE_SIGSET
39 # define SIGINT_BLOCK() sighold(SIGINT)
40 # define SIGINT_UNBLOCK() sigrelse(SIGINT)
41 # else /* !USE_SIGSET */
42 # ifdef BSD_SIGS
43 # define SIGINT_BLOCK() sigsetmask(sigmask(SIGINT))
44 # define SIGINT_UNBLOCK() sigsetmask(0)
45 # endif /* BSD_SIGS */
46 # endif /* !USE_SIGSET */
47 #endif /* !POSIX_SIGS */
48
49 /* This disgusting RE search string parses output from the GREP
50 * family, from the pdp11 compiler, pcc, and lint. Jay (HACK)
51 * Fenlasen changed this to work for the lint errors.
52 */
53 char ErrFmtStr[256] = "^\\{\"\\|\\}\\([^:\"( \t]*\\)\\{\"\\, line \\|:\\|(\\} *\\([0-9][0-9]*\\)[:)]\
54 \\|:: *\\([^(]*\\)(\\([0-9]*\\))$\
55 \\|( \\([^(]*\\)(\\([0-9]*\\)) ),"; /* VAR: format string for parse errors */
56
57 #ifdef SPELL
58 char SpellCmdFmt[FILESIZE] = SPELL; /* VAR: command to use for spell check */
59 #endif
60
61 struct error {
62 Buffer *er_buf; /* Buffer error is in */
63 LinePtr er_mess, /* Actual error message */
64 er_text; /* Actual error */
65 int er_char; /* char pos of error */
66 struct error *er_prev, /* List of errors */
67 *er_next;
68 };
69
70 private struct error *cur_error = NULL,
71 *errorlist = NULL;
72
73 /* Eliminate any error records that contain dangling references to Lines.
74 * We only eliminate error structs when either referent is recycled.
75 * If it deleted, we keep it (dormant) in case it will be pasted back
76 * into the same buffer.
77 */
78 void
79 ChkErrorLines(void)
80 {
81 struct error
82 *e,
83 *prev = NULL;
84
85 for (e = errorlist; e != NULL; ) {
86 struct error *next = e->er_next;
87
88 if (e->er_mess->l_dline == NULL_DADDR
89 || e->er_text->l_dline == NULL_DADDR)
90 {
91 /* dangling reference: delete */
92 if (prev == NULL)
93 errorlist = next;
94 else
95 prev->er_next = next;
96 if (next != NULL)
97 next->er_prev = prev;
98 if (cur_error == e)
99 cur_error = next;
100 free(e);
101 } else {
102 prev = e;
103 }
104 e = next;
105 }
106 }
107
108 /* Add an error to the end of the list of errors. This is used for
109 * parse-{C,LINT}-errors and for the spell-buffer command
110 */
111 private struct error *
112 AddError(struct error *laste, LinePtr errline,
113 Buffer *buf, LinePtr line, int charpos)
114 {
115 struct error *new = (struct error *) emalloc(sizeof *new);
116
117 new->er_prev = laste;
118 if (laste == NULL) {
119 /* first time: free up old errors */
120 if (errorlist != NULL)
121 ErrFree();
122 cur_error = errorlist = new;
123 } else {
124 laste->er_next = new;
125 }
126 new->er_next = NULL;
127 new->er_buf = buf;
128 new->er_text = line;
129 new->er_char = charpos;
130 new->er_mess = errline;
131
132 return new;
133 }
134
135 void
136 get_FL_info(char *fname, char *lineno)
137 {
138 putmatch(1, fname, (size_t)FILESIZE);
139 putmatch(2, lineno, (size_t)FILESIZE);
140
141 /* if error had lineno before fname, switch the two */
142 if (!jisdigit(lineno[0]) && jisdigit(fname[0])) {
143 putmatch(1, lineno, (size_t)FILESIZE);
144 putmatch(2, fname, (size_t)FILESIZE);
145 }
146 }
147
148 /* Free up all the errors */
149
150 void
151 ErrFree(void)
152 {
153 cur_error = NULL;
154 while (errorlist != NULL) {
155 struct error *nel = errorlist->er_next;
156
157 free(errorlist);
158 errorlist = nel;
159 }
160 }
161
162 /* Parse errors of the form specified in ErrFmtStr in the current
163 * buffer. Do a show error of the first error. This is neat because this
164 * will work for any kind of output that prints a file name and a line
165 * number on the same line.
166 */
167 void
168 ErrParse(void)
169 {
170 struct RE_block re_blk;
171 Bufpos *bp;
172 char fname[FILESIZE],
173 lineno[FILESIZE];
174 long lnum,
175 last_lnum = -1;
176 struct error *ep = NULL;
177 Buffer *buf,
178 *lastb = NULL;
179 LinePtr err_line = NULL; /* avoid uninitialized complaint from gcc -W */
180
181 ErrFree(); /* This is important! */
182 ToFirst();
183 perr_buf = curbuf;
184 REcompile(ErrFmtStr, YES, &re_blk);
185 /* Find a line with a number on it. */
186 while ((bp = docompiled(FORWARD, &re_blk)) != NULL) {
187 SetDot(bp);
188 get_FL_info(fname, lineno);
189 buf = do_find((Window *)NULL, fname, YES, YES);
190 (void) chr_to_long(lineno, 10, NO, &lnum);
191 if (buf != lastb) {
192 lastb = buf;
193 last_lnum = 1; /* new file */
194 err_line = buf->b_first;
195 } else if (lnum == last_lnum) /* one error per line is nicer */
196 continue;
197 err_line = next_line(err_line, lnum - last_lnum);
198 ep = AddError(ep, curline, buf, err_line, 0);
199 last_lnum = lnum;
200 }
201 if (cur_error != NULL)
202 ShowErr();
203 }
204
205 private void
206 NeedErrors(void)
207 {
208 if (cur_error == NULL) {
209 complain("No errors!");
210 /* NOTREACHED */
211 }
212 }
213
214 private jbool
215 ErrorHasReferents(void)
216 {
217 return inlist(cur_error->er_buf->b_first, cur_error->er_text) &&
218 inlist(perr_buf->b_first, cur_error->er_mess);
219 }
220
221 /* Go the the next error, if there is one. Put the error buffer in
222 * one window and the buffer with the error in another window.
223 * It checks to make sure that the error actually exists.
224 */
225 private void
226 ToError(jbool forward)
227 {
228 struct error
229 *e = cur_error;
230 int num = arg_value();
231
232 NeedErrors();
233 if ((forward? e->er_next : e->er_prev) == NULL) {
234 s_mess("You're at the %s error.", forward ? "last" : "first");
235 } else {
236 while (--num >= 0 || !ErrorHasReferents()) {
237 e = forward ? e->er_next : e->er_prev;
238 if (e == NULL)
239 break;
240
241 cur_error = e;
242 }
243 ShowErr();
244 }
245 }
246
247 void
248 NextError(void)
249 {
250 ToError(YES);
251 }
252
253 void
254 PrevError(void)
255 {
256 ToError(NO);
257 }
258
259 int EWSize = 20; /* VAR: percentage of screen to make the error window */
260
261 private void
262 set_wsize(int wsize)
263 {
264 wsize = (LI * wsize) / 100;
265 if (wsize >= 1 && !one_windp())
266 WindSize(curwind, wsize - (curwind->w_height - 1));
267 }
268
269 /* Show the current error, i.e. put the line containing the error message
270 * in one window, and the buffer containing the actual error in another
271 * window.
272 */
273 void
274 ShowErr(void)
275 {
276 Window *err_wind,
277 *buf_wind;
278
279 NeedErrors();
280 if (!ErrorHasReferents()) {
281 rbell();
282 return;
283 }
284 err_wind = windbp(perr_buf);
285 buf_wind = windbp(cur_error->er_buf);
286
287 if (err_wind == NULL) {
288 if (buf_wind != NULL) {
289 SetWind(buf_wind);
290 pop_wind(perr_buf->b_name, NO, -1);
291 err_wind = curwind;
292 } else {
293 pop_wind(perr_buf->b_name, NO, -1);
294 err_wind = curwind;
295 pop_wind(cur_error->er_buf->b_name, NO, -1);
296 buf_wind = curwind;
297 }
298 } else if (buf_wind == NULL) {
299 SetWind(err_wind);
300 pop_wind(cur_error->er_buf->b_name, NO, -1);
301 buf_wind = curwind;
302 }
303
304 /* Put the current error message at the top of its Window */
305 SetWind(err_wind);
306 SetLine(cur_error->er_mess);
307 SetTop(curwind, (curwind->w_line = cur_error->er_mess));
308 set_wsize(EWSize);
309
310 /* now go to the the line with the error in the other window */
311 SetWind(buf_wind);
312 DotTo(cur_error->er_text, cur_error->er_char);
313 }
314
315 char ShcomBuf[LBSIZE];
316
317 /* Make a buffer name given the command `command', i.e. "fgrep -n foo *.c"
318 * will return the buffer name "fgrep".
319 */
320 char *
321 MakeName(char *command)
322 {
323 static char
324 bnm[FILESIZE];
325 char *cp = bnm,
326 c;
327 const char
328 *bp;
329
330 do {
331 c = *command++;
332 } while (jiswhite(c));
333 *cp++ = '['; /* avoid potential clash with script or program names */
334 while (cp < &bnm[sizeof(bnm) - 1] && c != '\0' && !jiswhite(c)) {
335 *cp++ = c;
336 c = *command++;
337 }
338 *cp = '\0';
339 if ((bp = jbasename(&bnm[1])) != &bnm[1]) {
340 /* bp overlaps bnm, cannot use strcpy */
341 cp = &bnm[1];
342 do ; while ((*cp++ = *bp++) != '\0');
343 cp--; /* make sure cp points at '\0' */
344 }
345 if (cp > &bnm[1] && cp < &bnm[sizeof(bnm)-1]) {
346 *cp++ = ']';
347 *cp = '\0';
348 }
349 return bnm;
350 }
351
352 #ifdef SUBSHELL /* the body is the rest of this file */
353
354 /* Run make, first writing all the modified buffers (if the WtOnMk flag is
355 * on), parse the errors, and go the first error.
356 */
357 jbool WtOnMk = YES; /* VAR: write files on compile-it command */
358 jbool WrapProcessLines = NO; /* VAR: wrap process lines at CO-1 chars */
359
360 private void
361 DoShell(char *, char *),
362 com_finish(wait_status_t, char *);
363
364 private char make_cmd[LBSIZE] = "make";
365
366 void
367 MakeErrors(void)
368 {
369 Window *old = curwind;
370
371 if (WtOnMk)
372 put_bufs(NO);
373
374 /* When we're not doing make or cc (i.e., the last command
375 * was probably a grep or something) and the user just types
376 * ^X ^E, he probably (possibly, hopefully, usually (in my
377 * case)) doesn't want to do the grep again but rather wants
378 * to do a make again; so we ring the bell and insert the
379 * default command and let the person decide.
380 */
381 if (is_an_arg()
382 || !(sindex("make", make_cmd) || sindex("cc", make_cmd)))
383 {
384 if (!is_an_arg())
385 rbell();
386 /* insert the default for the user (Kludge: only if Inputp is free) */
387 if (Inputp == NULL)
388 Inputp = make_cmd;
389 jamstr(make_cmd, ask(make_cmd, "Compilation command: "));
390 }
391 com_finish(UnixToBuf(UTB_DISP|UTB_CLOBBER|UTB_ERRWIN|UTB_SH,
392 MakeName(make_cmd), (char *)NULL, make_cmd), make_cmd);
393
394 ErrParse();
395
396 if (!cur_error)
397 SetWind(old);
398 }
399
400 # ifdef SPELL
401
402 private void
403 SpelParse(const char *bname)
404 {
405 Buffer *buftospel,
406 *wordsb;
407 char wordspel[100];
408 Bufpos *bp;
409 struct error *ep = NULL;
410
411 ErrFree(); /* This is important! */
412
413 buftospel = curbuf;
414 wordsb = buf_exists(bname);
415 if (wordsb == NULL) {
416 complain("Buffer %s is gone!", bname);
417 /* NOTREACHED */
418 }
419 perr_buf = wordsb; /* This is important (buffer containing
420 error messages) */
421 SetBuf(wordsb);
422 ToFirst();
423 f_mess("Finding misspelled words ... ");
424 while (!lastp(curline)) {
425 swritef(wordspel, sizeof(wordspel), "\\<%s\\>", linebuf);
426 SetBuf(buftospel);
427 ToFirst();
428 while ((bp = dosearch(wordspel, FORWARD, NO)) != NULL) {
429 SetDot(bp);
430 ep = AddError(ep, wordsb->b_dot, buftospel,
431 curline, curchar);
432 }
433 SetBuf(wordsb);
434 line_move(FORWARD, 1, NO);
435 }
436 add_mess("Done.");
437
438 /* undo buffer switches that ought not to be reflected in current window */
439 SetBuf(curwind->w_bufp);
440
441 ShowErr();
442 }
443
444 void
445 SpelBuffer(void)
446 {
447 static const char Spell[] = "Spell";
448 const char *cp;
449 char com[100];
450 Buffer *savebp = curbuf;
451
452 if (curbuf->b_fname == NULL) {
453 complain("no file name");
454 /* NOTREACHED */
455 }
456 if ((cp = strchr(SpellCmdFmt, '%')) == NULL ||
457 cp[1] != 's' || strchr(cp+2, '%') != NULL) {
458 complain("spell-command-format needs one %%s with no other format characters");
459 /* NOTREACHED */
460 }
461 if (IsModified(curbuf))
462 SaveFile();
463 swritef(com, sizeof(com), SpellCmdFmt, curbuf->b_fname);
464 (void) UnixToBuf(UTB_DISP|UTB_CLOBBER|UTB_ERRWIN|UTB_SH,
465 Spell, (char *)NULL, com);
466 message("[Delete the irrelevant words and then type ^X ^C]");
467 ToFirst();
468 Recur();
469 if (!valid_bp(savebp)) {
470 complain("Buffer gone!");
471 /* NOTREACHED */
472 }
473 SetBuf(savebp);
474 SpelParse(Spell);
475 }
476
477 void
478 SpelWords(void)
479 {
480 Buffer *wordsb = curbuf;
481 const char *buftospel = ask_buf((Buffer *)NULL, ALLOW_OLD | ALLOW_INDEX);
482
483 SetBuf(do_select(curwind, buftospel));
484 SpelParse(wordsb->b_name);
485 }
486
487 # endif /* SPELL */
488
489 void
490 ShToBuf(void)
491 {
492 char bnm[128],
493 cmd[LBSIZE];
494
495 jamstr(bnm, ask((char *)NULL, "Buffer: "));
496 jamstr(cmd, ask(ShcomBuf, "Command: "));
497 DoShell(bnm, cmd);
498 }
499
500 void
501 ShellCom(void)
502 {
503 jamstr(ShcomBuf, ask(ShcomBuf, ProcFmt));
504 DoShell(MakeName(ShcomBuf), ShcomBuf);
505 }
506
507 void
508 ShNoBuf(void)
509 {
510 jamstr(ShcomBuf, ask(ShcomBuf, ProcFmt));
511 com_finish(UnixToBuf(UTB_SH|UTB_FILEARG, (char *)NULL, (char *)NULL,
512 ShcomBuf), ShcomBuf);
513 }
514
515 void
516 Shtypeout(void)
517 {
518 wait_status_t status;
519
520 jamstr(ShcomBuf, ask(ShcomBuf, ProcFmt));
521 status = UnixToBuf(UTB_DISP|UTB_SH|UTB_FILEARG, (char *)NULL, (char *)NULL,
522 ShcomBuf);
523 #ifdef MSDOS_PROCS
524 if (status < 0)
525 Typeout("[%s: not executed %d]", ShcomBuf, status);
526 else if (status > 0)
527 Typeout("[%s: exited with %d]", ShcomBuf, status);
528 else if (!is_an_arg())
529 Typeout("[%s: completed successfully]", ShcomBuf);
530 #else /* !MSDOS_PROCS */
531 if (WIFSIGNALED(status))
532 Typeout("[%s: terminated by signal %d]", ShcomBuf, WTERMSIG(status));
533 else if (WIFEXITED(status) && WEXITSTATUS(status)!=0)
534 Typeout("[%s: exited with %d]", ShcomBuf, WEXITSTATUS(status));
535 else if (!is_an_arg())
536 Typeout("[%s: completed successfully]", ShcomBuf);
537 #endif /* !MSDOS_PROCS */
538 TOstop();
539 }
540
541 /* Run the shell command into `bnm'. Empty the buffer except when we
542 * give a numeric argument, in which case it inserts the output at the
543 * current position in the buffer.
544 */
545 private void
546 DoShell(char *bnm, char *command)
547 {
548 Window *savewp = curwind;
549
550 com_finish(UnixToBuf(
551 (is_an_arg()
552 ? UTB_DISP|UTB_SH|UTB_FILEARG
553 : UTB_DISP|UTB_CLOBBER|UTB_SH|UTB_FILEARG),
554 bnm, (char *)NULL, command), command);
555 SetWind(savewp);
556 }
557
558 private void
559 com_finish(wait_status_t status, char *cmd)
560 {
561 #ifdef MSDOS_PROCS
562 if (status < 0)
563 s_mess("[%s: not executed %d]", cmd, status);
564 else if (status > 0)
565 s_mess("[%s: exited with %d]", cmd, status);
566 else
567 s_mess("[%s: completed successfully]", cmd);
568 #else /* !MSDOS_PROCS */
569 if (WIFSIGNALED(status))
570 s_mess("[%s: terminated by signal %d]", cmd, WTERMSIG(status));
571 else if (WIFEXITED(status) && WEXITSTATUS(status)!=0)
572 s_mess("[%s: exited with %d]", cmd, WEXITSTATUS(status));
573 else
574 s_mess("[%s: completed successfully]", cmd);
575 #endif /* !MSDOS_PROCS */
576 }
577
578 #ifndef MSDOS_PROCS
579
580 /* pid of any outstanding non-iproc process.
581 * Note: since there is only room for one pid, there can be no more than
582 * one running non-iproc process.
583 */
584 pid_t ChildPid;
585
586 void
587 dowait(wait_status_t *status) /* may be NULL */
588 {
589 # ifdef IPROCS
590 while (DeadPid != ChildPid) {
591 wait_status_t w;
592 pid_t rpid = wait(&w);
593
594 if (rpid == -1) {
595 if (errno == ECHILD) {
596 /* fudge what we hope is a bland value */
597 byte_zero(&DeadStatus, sizeof(wait_status_t));
598 break;
599 }
600 } else {
601 kill_off(rpid, w);
602 }
603 }
604 DeadPid = 0;
605 if (status != NULL)
606 *status = DeadStatus;
607 # else
608 wait_status_t w;
609
610 for (;;) {
611 pid_t rpid = wait(&w);
612
613 if (rpid == -1) {
614 if (errno == ECHILD) {
615 /* fudge what we hope is a bland value */
616 byte_zero(&w, sizeof(wait_status_t));
617 break;
618 }
619 } else if (rpid == ChildPid) {
620 break;
621 }
622 }
623 if (status != NULL)
624 *status = w;
625 # endif
626 ChildPid = 0;
627 }
628
629 #endif /* !MSDOS_PROCS */
630
631 /* Environment management for subshells */
632 private Env proc_env;
633 private char PEnvExpBuf[LBSIZE];
634 private char PEnvUnsetBuf[LBSIZE];
635
636 void
637 ProcEnvExport(void)
638 {
639 jamstr(PEnvExpBuf, ask(PEnvExpBuf, ProcFmt));
640 jputenv(&proc_env, PEnvExpBuf);
641 }
642
643 void
644 ProcEnvShow(void)
645 {
646 const char **p;
647 TOstart("subshell environment");
648 for (p = jenvdata(&proc_env); *p; p++) {
649 Typeout("%s", *p);
650 }
651 TOstop();
652 }
653
654 void
655 ProcEnvUnset(void)
656 {
657 jamstr(PEnvUnsetBuf, ask(PEnvUnsetBuf, ProcFmt));
658 junsetenv(&proc_env, PEnvUnsetBuf);
659 }
660
661 /* Run the command cmd. Output to the buffer named bnm (if not
662 * NULL), first erasing bnm (if UTB_DISP and UTB_CLOBBER), and
663 * redisplay (if UTB_DISP). Leaves bnm as the current buffer and
664 * leaves any windows it creates lying around. It's up to the
665 * caller to fix everything up after we're done. (Usually there's
666 * nothing to fix up.)
667 *
668 * If bnm is non-NULL, the process output goes to that buffer.
669 * Furthermore, if UTB_DISP, the buffer is displayed in a window.
670 * If not UTB_DISP, the buffer is not given a window (of course it
671 * might already have one). If UTB_DISP and UTB_CLOBBER, the buffer
672 * is emptied initially. If UTB_DISP and UTB_ERRWIN, that window's
673 * size is as specified by the variable error-window-size.
674 *
675 * If bnm is NULL, the process output does not go to a buffer. In this
676 * case, if UTB_DISP, it is displayed using Typeout; if not UTB_DISP,
677 * the output is discarded.
678 *
679 * Only if UTB_DISP and bnm is non-NULL are UTB_ERRWIN and
680 * UTB_CLOBBER meaningful.
681 */
682 wait_status_t
683 UnixToBuf(int flags, /* bunch of booleans: see UTB_* in proc.h */
684 const char *bnm, /* buffer name (NULL means none) */
685 const char *InFName, /* name of file for process stdin (NULL means none) */
686 const char *cmd) /* command to run */
687 {
688 #ifndef MSDOS_PROCS
689 int p[2];
690 wait_status_t status;
691 SIGHANDLERTYPE old_int;
692 char bfn[FILESIZE]; /* buffer file name */
693 char bln[10]; /* buffer line number (big enough for any line number) */
694 char bc[6]; /* buffer column (big enough for any column) */
695 #else /* MSDOS_PROCS */
696 char cmdbuf[129];
697 int status = 0;
698 char pipename[FILESIZE];
699 #endif /* MSDOS_PROCS */
700 jbool eof;
701 char *argv[9]; /* worst case: /bin/sh sh -cf "echo $1" $1 $1 $2 $3 NULL */
702 char **ap = argv;
703 File *fp;
704 #ifdef SIGINTMASK_DECL
705 SIGINTMASK_DECL
706
707 SIGINTMASK_INIT();
708 #endif
709
710 jdbg("UnixToBuf flags 0x%x \"%s\"\n", flags, cmd);
711 SlowCmd += 1;;
712 if (flags & UTB_SH) {
713 *ap++ = Shell;
714 *ap++ = (char *)jbasename(Shell); /* lose const (but it's safe) */
715 *ap++ = ShFlags;
716 *ap++ = (char *)cmd; /* lose const (but it's safe) */
717 #ifdef MSDOS_PROCS
718 /* Kludge alert!
719 * UNIX-like DOS shells and command.com-like DOS shells
720 * seem to differ seem to differ on two points:
721 * - UNIX-like shells use "-" to start flags whereas
722 * command.com-like shells use "/".
723 * - UNIX-like shells seem to require that the argument to
724 * $SHELL -c be quoted to cause it to be taken as a single argument.
725 * command.com-like shells seem to automatically use the rest
726 * of the arguments. This is not an issue under real UNIX
727 * since arguments are passed already broken down.
728 *
729 * E.g., your shell comand: echo foo
730 * jove runs: command /c echo foo OK
731 * jove runs: sh -c echo foo Oops! sh just runs "echo"
732 * jove runs: sh -c "echo foo" Ah, now I get it.
733 *
734 * We use the first character of ShFlags to distinguish
735 * which kind of shell we are dealing with!
736 */
737 if (ShFlags[0] == '-') {
738 swritef(cmdbuf, sizeof(cmdbuf), "\"%s\"", cmd);
739 ap[-1] = cmdbuf;
740 /* ??? can we usefully jam in a copy or two of current filename? */
741 }
742 #else /* !MSDOS_PROCS */
743 /* Two copies of the file name are passed to the shell:
744 * The Cshell uses the first as a definition of $1.
745 * Most versions of the Bourne shell use the second as a
746 * definition of $1. (Unfortunately, these same versions
747 * of the Bourne shell take the first as their own name
748 * for error reporting.)
749 */
750 if ((flags & UTB_FILEARG) && curbuf->b_fname != NULL) {
751 strcpy(bfn, pr_name(curbuf->b_fname, NO));
752 *ap++ = bfn;
753 *ap++ = bfn;
754 {
755 int ln = 1; /* origin 1 */
756 LinePtr lp;
757
758 for (lp = curbuf->b_first; lp != curline; lp = lp->l_next)
759 ln++;
760 swritef(bln, sizeof(bln), "%d", ln);
761 *ap++ = bln;
762 }
763 swritef(bc, sizeof(bc), "%d", curchar + 1); /* origin 1 */
764 *ap++ = bc;
765 }
766 #endif /* !MSDOS_PROCS */
767 } else {
768 *ap++ = (char *)cmd; /* lose const (but it's safe) */
769 *ap++ = (char *)jbasename(cmd); /* lose const (but it's safe) */
770 }
771 *ap++ = NULL;
772
773 if (access(argv[0], J_X_OK) != 0) {
774 complain("[Couldn't access %s: %s]", argv[0], strerror(errno));
775 /* NOTREACHED */
776 }
777 if (flags & UTB_DISP) {
778 if (bnm != NULL) {
779 if (flags & UTB_CLOBBER) {
780 isprocbuf(bnm);
781 pop_wind(bnm, YES, B_PROCESS);
782 } else {
783 pop_wind(bnm, NO, B_FILE);
784 }
785 set_wsize(flags & UTB_ERRWIN? EWSize : 0);
786 message("Starting up...");
787 redisplay();
788 } else {
789 TOstart(argv[0]);
790 Typeout("Starting up...");
791 TOstart(argv[0]); /* overwrite "Starting up..." */
792 }
793 }
794 /* Now I will attempt to describe how I deal with signals during
795 * the execution of the shell command. My desire was to be able
796 * to interrupt the shell command AS SOON AS the window pops up.
797 * So, if we have SIGINT_BLOCK (i.e., a modern signal mechanism)
798 * I hold SIGINT, meaning if we interrupt now, we will eventually
799 * see the interrupt, but not before we are ready for it. We
800 * fork, the child releases the interrupt, it then sees the
801 * interrupt, and so exits. Meanwhile the parent ignores the
802 * signal, so if there was a pending one, it's now lost.
803 *
804 * Without SIGINT_BLOCK, the best behavior you can expect is that
805 * when you type ^] too soon after the window pops up, it may
806 * be ignored. The behavior BEFORE was that it would interrupt
807 * JOVE and then you would have to continue JOVE and wait a
808 * little while longer before trying again. Now that is fixed,
809 * in that you just have to type it twice.
810 */
811
812 #ifndef MSDOS_PROCS
813 dopipe(p);
814
815 # ifdef SIGINT_BLOCK
816 SIGINT_BLOCK();
817 # else
818 old_int = setsighandler(SIGINT, SIG_IGN),
819 # endif
820
821 # ifdef USE_VFORK
822 /*
823 * There are several other forks in Jove, but for
824 * machines lacking MMUs, where vfork might be
825 * significantly more performant, it is nice to have
826 * SUBSHELL capability using pipes (MSDOS_PROCS use a
827 * temporary file for subshell output and spawn).
828 * moraes Note from 2020 4.17: vfork has not been tested in a
829 * long time, it is quite possible/likely that it does
830 * not even work (I think that nothing between here
831 * and the exec damages parent state, but using vfork
832 * is a deal with the devil)
833 */
834 ChildPid = vfork();
835 # else
836 ChildPid = fork();
837 # endif
838
839 if (ChildPid == -1) {
840 int fork_errno = errno;
841
842 pipeclose(p);
843 # ifdef SIGINT_UNBLOCK
844 SIGINT_UNBLOCK();
845 # else
846 (void) setsighandler(SIGINT, old_int),
847 # endif
848 complain("[Fork failed: %s]", strerror(fork_errno));
849 /* NOTREACHED */
850 }
851 if (ChildPid == 0) {
852 const char *a; /* action name (for error message) */
853 (void) setsighandler(SIGINT, SIG_DFL);
854 # ifdef SIGINT_UNBLOCK
855 SIGINT_UNBLOCK();
856 # endif
857 if (!((a = "close 0", close(0)) == 0
858 && (a = "open", open(InFName==NULL? "/dev/null" : InFName, O_RDONLY | O_BINARY)) == 0
859 && (a = "close 1", close(1)) == 0
860 && (a = "dup 1", dup(p[1])) == 1
861 && (a = "close 2", close(2)) == 0
862 && (a = "dup 2", dup(p[1])) == 2))
863 {
864 raw_complain("% in setup for child failed: %s", a, strerror(errno));
865 _exit(1);
866 }
867
868 pipeclose(p);
869 jcloseall();
870 execve(argv[0], &argv[1], (char **) jenvdata(&proc_env));
871 raw_complain("Execl failed: %s", strerror(errno));
872 _exit(1);
873 }
874 # ifdef SIGINT_BLOCK
875 old_int = setsighandler(SIGINT, SIG_IGN); /* got to do this eventually */
876 # endif
877 (void) close(p[1]);
878 fp = fd_open(argv[1], F_READ, p[0], iobuff, LBSIZE);
879 #else /* MSDOS_PROCS*/
880 {
881 int oldi = dup(0),
882 oldo = dup(1),
883 olde = dup(2);
884 jbool InFailure = NO;
885 int ph, pinh, saverrno = 0;
886 const char *op = "";
887
888 PathCat(pipename, sizeof(pipename), TmpDir, "jpXXXXXX");
889 ph = MakeTemp(pipename, "filter buffer");
890 jdbg("created temp \"%s\" ph %d\n", pipename, ph);
891 if (InFName == NULL) {
892 char nullname[FILESIZE];
893 PathCat(nullname, sizeof(nullname), TmpDir, "jnXXXXXX");
894 pinh = MakeTemp(nullname, "filter null file");
895 (void) unlink(nullname);
896 } else {
897 pinh = open(InFName, O_RDONLY | O_BINARY);
898 if (pinh < 0) {
899 saverrno = errno;
900 op = InFName;
901 jdbg("error opening \"%s\": %d %s\n", InFName, errno);
902 InFailure = YES;
903 }
904 }
905 if (!InFailure && (dup2(ph, 1) < 0 || dup2(ph, 2) < 0)) {
906 saverrno = errno;
907 op = "dup2 temp";
908 jdbg("%s file fd failed: %d %s\n", op, errno,
909 strerror(errno));
910 InFailure = YES;
911 }
912 (void) close(ph);
913 if (!InFailure && dup2(pinh, 0) < 0) {
914 saverrno = errno;
915 op = "dup2 input";
916 jdbg("%s file fd failed: %d %s\n", op, errno,
917 strerror(errno));
918 InFailure = YES;
919 }
920 (void) close(pinh);
921
922 jdbg("InFailure %d InFName \"%s\"\n", InFailure,
923 InFName == NULL ? "(NULL)" : InFName);
924 if (!InFailure) {
925 if (jdebug) {
926 int vk = 0;
927 while (argv[vk]) {
928 jdprintf("%d: \"%s\"\n", vk, argv[vk]);
929 vk++;
930 }
931 }
932 status = spawnve(0, argv[0], &argv[1],
933 (char *const *)jenvdata(&proc_env));
934 if (status < 0) {
935 saverrno = errno;
936 }
937 }
938 jdbg("restoring fds 0 1 2 from %d %d %d\n", oldi, oldo, olde);
939 (void) dup2(oldi, 0);
940 (void) dup2(oldo, 1);
941 (void) dup2(olde, 2);
942 (void) close(oldi);
943 (void) close(oldo);
944 (void) close(olde);
945
946 if (InFailure) {
947 complain("[filter %s failed %s %d]", op, strerror(saverrno), saverrno);
948 /* NOTREACHED */
949 }
950 if (status < 0)
951 s_mess("[Spawn failed, status %d: %s %d]", status, strerror(saverrno), saverrno);
952 jdbg("opening \"%s\" from \"%s\"\n", pipename, argv[1]);
953 ph = open(pipename, O_RDONLY | O_BINARY | O_CLOEXEC);
954 if (ph < 0) {
955 complain("[cannot reopen pipe %s: %s]", pipename, strerror(errno));
956 /* NOTREACHED */
957 }
958 fp = fd_open(argv[1], F_READ, ph, iobuff, LBSIZE);
959 }
960
961 #endif /* MSDOS_PROCS */
962
963 do {
964 int wrap_col = WrapProcessLines ? CO-1 : LBSIZE;
965 #ifdef UNIX
966 InSlowRead = YES;
967 #endif
968 eof = f_gets(fp, genbuf, (size_t)LBSIZE);
969 #ifdef UNIX
970 InSlowRead = NO;
971 #endif
972 if (bnm != NULL) {
973 ins_str_wrap(genbuf, YES, wrap_col);
974 if (!eof)
975 LineInsert(1);
976 if ((flags & UTB_DISP) && fp->f_cnt <= 0) {
977 message("Chugging along...");
978 redisplay();
979 }
980 } else if (flags & UTB_DISP)
981 Typeout("%s", genbuf);
982 } while (!eof);
983 if (flags & UTB_DISP)
984 DrawMesg(NO);
985 close_file(fp);
986 #ifndef MSDOS_PROCS
987 dowait(&status);
988 # ifdef SIGINT_UNBLOCK
989 SIGINT_UNBLOCK();
990 # endif
991 (void) setsighandler(SIGINT, old_int);
992 #else /* MSDOS_PROCS */
993 unlink(pipename);
994 getCWD();
995 jdbg("removing %s\n", pipename);
996 # ifdef WINRESIZE
997 ResizePending = YES; /* In case subproc did a MODE command or something */
998 # endif
999 #endif /* MSDOS_PROCS */
1000 SlowCmd -= 1;;
1001 jdbg("returning %d\n", status);
1002 return status;
1003 }
1004
1005 /* Send the current region to CMD and insert the output from the
1006 * command into OUT_BUF.
1007 */
1008 private void
1009 RegToUnix(Buffer *outbuf, char *cmd, jbool wrap)
1010 {
1011 Mark *m = CurMark();
1012 static char tname[FILESIZE];
1013 Window *save_wind = curwind;
1014 volatile wait_status_t
1015 status;
1016 volatile jbool err = NO;
1017 jbool old_wrap = WrapProcessLines;
1018 File *volatile fp;
1019 jmp_buf sav_jmp;
1020
1021 PathCat(tname, sizeof(tname), TmpDir, "jfXXXXXX");
1022
1023 /* safe version of mktemp */
1024 close(MakeTemp(tname, "filter region"));
1025
1026 fp = open_file(tname, iobuff, F_WRITE, YES);
1027 push_env(sav_jmp);
1028 if (setjmp(mainjmp) == 0) {
1029 WrapProcessLines = wrap;
1030 putreg(fp, m->m_line, m->m_char, curline, curchar, YES);
1031 DelReg();
1032 f_close(fp);
1033 status = UnixToBuf(UTB_SH|UTB_FILEARG, outbuf->b_name, tname, cmd);
1034 } else {
1035 f_close(fp);
1036 err = YES;
1037 }
1038 pop_env(sav_jmp);
1039 WrapProcessLines = old_wrap;
1040
1041 (void) unlink(tname);
1042 SetWind(save_wind);
1043 if (!err)
1044 com_finish(status, cmd);
1045 }
1046
1047 void
1048 FilterRegion(void)
1049 {
1050 static char FltComBuf[LBSIZE];
1051
1052 jamstr(FltComBuf, ask(FltComBuf, ": %f (through command) "));
1053 RegToUnix(curbuf, FltComBuf, NO);
1054 this_cmd = UNDOABLECMD;
1055 }
1056
1057 void
1058 isprocbuf(const char *bnm)
1059 {
1060 Buffer *bp;
1061
1062 if ((bp = buf_exists(bnm)) != NULL && bp->b_type != B_PROCESS)
1063 confirm("Over-write buffer %s? ", bnm);
1064 }
1065
1066 #endif /* SUBSHELL */