Debian Codegraph @

src/output.c

raw symbols SCIP
1 /* Output to stdout / stderr for GNU make
2 Copyright (C) 2013-2020 Free Software Foundation, Inc.
3 This file is part of GNU Make.
4
5 GNU Make is free software; you can redistribute it and/or modify it under the
6 terms of the GNU General Public License as published by the Free Software
7 Foundation; either version 3 of the License, or (at your option) any later
8 version.
9
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License along with
15 this program. If not, see <http://www.gnu.org/licenses/>. */
16
17 #include "makeint.h"
18 #include "globals.h"
19 #include "os.h"
20 #include "output.h"
21
22 /* GNU make no longer supports pre-ANSI89 environments. */
23
24 #include <assert.h>
25 #include <stdio.h>
26 #include <stdarg.h>
27
28 #ifdef HAVE_UNISTD_H
29 # include <unistd.h>
30 #endif
31
32 #ifdef HAVE_FCNTL_H
33 # include <fcntl.h>
34 #else
35 # include <sys/file.h>
36 #endif
37
38 #ifdef WINDOWS32
39 # include <windows.h>
40 # include <io.h>
41 # include "sub_proc.h"
42 #endif /* WINDOWS32 */
43
44 struct output *output_context = NULL;
45 unsigned int stdio_traced = 0;
46
47 #define OUTPUT_NONE (-1)
48
49 #define OUTPUT_ISSET(_out) ((_out)->out >= 0 || (_out)->err >= 0)
50
51 #ifdef HAVE_FCNTL_H
52 # define STREAM_OK(_s) ((fcntl (fileno (_s), F_GETFD) != -1) || (errno != EBADF))
53 #else
54 # define STREAM_OK(_s) 1
55 #endif
56
57 /* Write a string to the current STDOUT or STDERR. */
58 static void
59 _outputs (struct output *out, int is_err, const char *msg)
60 {
61 if (! out || ! out->syncout)
62 {
63 FILE *f = is_err ? stderr : stdout;
64 fputs (msg, f);
65 fflush (f);
66 }
67 else
68 {
69 int fd = is_err ? out->err : out->out;
70 size_t len = strlen (msg);
71 int r;
72 EINTRLOOP (r, lseek (fd, 0, SEEK_END));
73 writebuf (fd, msg, len);
74 }
75 }
76
77 /* Write a message indicating that we've just entered or
78 left (according to ENTERING) the current directory. */
79
80 int
81 log_working_directory (int entering)
82 {
83 static char *buf = NULL;
84 static size_t len = 0;
85 size_t need;
86 const char *fmt;
87 char *p;
88
89 /* Get enough space for the longest possible output. */
90 need = strlen (program) + INTSTR_LENGTH + 2 + 1;
91 if (starting_directory)
92 need += strlen (starting_directory);
93
94 /* Use entire sentences to give the translators a fighting chance. */
95 if (makelevel == 0)
96 if (starting_directory == 0)
97 if (entering)
98 fmt = _("%s: Entering an unknown directory\n");
99 else
100 fmt = _("%s: Leaving an unknown directory\n");
101 else
102 if (entering)
103 fmt = _("%s: Entering directory '%s'\n");
104 else
105 fmt = _("%s: Leaving directory '%s'\n");
106 else
107 if (starting_directory == 0)
108 if (entering)
109 fmt = _("%s[%u]: Entering an unknown directory\n");
110 else
111 fmt = _("%s[%u]: Leaving an unknown directory\n");
112 else
113 if (entering)
114 fmt = _("%s[%u]: Entering directory '%s'\n");
115 else
116 fmt = _("%s[%u]: Leaving directory '%s'\n");
117
118 need += strlen (fmt);
119
120 if (need > len)
121 {
122 buf = xrealloc (buf, need);
123 len = need;
124 }
125
126 p = buf;
127 if (print_data_base_flag)
128 {
129 *(p++) = '#';
130 *(p++) = ' ';
131 }
132
133 if (makelevel == 0)
134 if (starting_directory == 0)
135 sprintf (p, fmt , program);
136 else
137 sprintf (p, fmt, program, starting_directory);
138 else if (starting_directory == 0)
139 sprintf (p, fmt, program, makelevel);
140 else
141 sprintf (p, fmt, program, makelevel, starting_directory);
142
143 _outputs (NULL, 0, buf);
144
145 return 1;
146 }
147
148 /* Set a file descriptor referring to a regular file
149 to be in O_APPEND mode. If it fails, just ignore it. */
150
151 static void
152 set_append_mode (int fd)
153 {
154 #if defined(F_GETFL) && defined(F_SETFL) && defined(O_APPEND)
155 struct stat stbuf;
156 int flags;
157 if (fstat (fd, &stbuf) != 0 || !S_ISREG (stbuf.st_mode))
158 return;
159 flags = fcntl (fd, F_GETFL, 0);
160 if (flags >= 0)
161 {
162 int r;
163 EINTRLOOP(r, fcntl (fd, F_SETFL, flags | O_APPEND));
164 }
165 #endif
166 }
167
168
169 #ifndef NO_OUTPUT_SYNC
170
171 /* Semaphore for use in -j mode with output_sync. */
172 static sync_handle_t sync_handle = -1;
173
174 #define FD_NOT_EMPTY(_f) ((_f) != OUTPUT_NONE && lseek ((_f), 0, SEEK_END) > 0)
175
176 /* Set up the sync handle. Disables output_sync on error. */
177 static int
178 sync_init (void)
179 {
180 int combined_output = 0;
181
182 #ifdef WINDOWS32
183 if ((!STREAM_OK (stdout) && !STREAM_OK (stderr))
184 || (sync_handle = create_mutex ()) == -1)
185 {
186 perror_with_name ("output-sync suppressed: ", "stderr");
187 output_sync = 0;
188 }
189 else
190 {
191 combined_output = same_stream (stdout, stderr);
192 prepare_mutex_handle_string (sync_handle);
193 }
194
195 #else
196 if (STREAM_OK (stdout))
197 {
198 struct stat stbuf_o, stbuf_e;
199
200 sync_handle = fileno (stdout);
201 combined_output = (fstat (fileno (stdout), &stbuf_o) == 0
202 && fstat (fileno (stderr), &stbuf_e) == 0
203 && stbuf_o.st_dev == stbuf_e.st_dev
204 && stbuf_o.st_ino == stbuf_e.st_ino);
205 }
206 else if (STREAM_OK (stderr))
207 sync_handle = fileno (stderr);
208 else
209 {
210 perror_with_name ("output-sync suppressed: ", "stderr");
211 output_sync = 0;
212 }
213 #endif
214
215 return combined_output;
216 }
217
218 /* Support routine for output_sync() */
219 static void
220 pump_from_tmp (int from, FILE *to)
221 {
222 static char buffer[8192];
223
224 #ifdef WINDOWS32
225 int prev_mode;
226
227 /* "from" is opened by open_tmpfd, which does it in binary mode, so
228 we need the mode of "to" to match that. */
229 prev_mode = _setmode (fileno (to), _O_BINARY);
230 #endif
231
232 if (lseek (from, 0, SEEK_SET) == -1)
233 perror ("lseek()");
234
235 while (1)
236 {
237 int len;
238 EINTRLOOP (len, read (from, buffer, sizeof (buffer)));
239 if (len < 0)
240 perror ("read()");
241 if (len <= 0)
242 break;
243 if (fwrite (buffer, len, 1, to) < 1)
244 {
245 perror ("fwrite()");
246 break;
247 }
248 fflush (to);
249 }
250
251 #ifdef WINDOWS32
252 /* Switch "to" back to its original mode, so that log messages by
253 Make have the same EOL format as without --output-sync. */
254 _setmode (fileno (to), prev_mode);
255 #endif
256 }
257
258 /* Obtain the lock for writing output. */
259 static void *
260 acquire_semaphore (void)
261 {
262 static struct flock fl;
263
264 fl.l_type = F_WRLCK;
265 fl.l_whence = SEEK_SET;
266 fl.l_start = 0;
267 fl.l_len = 1;
268 if (fcntl (sync_handle, F_SETLKW, &fl) != -1)
269 return &fl;
270 perror ("fcntl()");
271 return NULL;
272 }
273
274 /* Release the lock for writing output. */
275 static void
276 release_semaphore (void *sem)
277 {
278 struct flock *flp = (struct flock *)sem;
279 flp->l_type = F_UNLCK;
280 if (fcntl (sync_handle, F_SETLKW, flp) == -1)
281 perror ("fcntl()");
282 }
283
284 /* Returns a file descriptor to a temporary file. The file is automatically
285 closed/deleted on exit. Don't use a FILE* stream. */
286 int
287 output_tmpfd (void)
288 {
289 mode_t mask = umask (0077);
290 int fd = -1;
291 FILE *tfile = tmpfile ();
292
293 if (! tfile)
294 pfatal_with_name ("tmpfile");
295
296 /* Create a duplicate so we can close the stream. */
297 fd = dup (fileno (tfile));
298 if (fd < 0)
299 pfatal_with_name ("dup");
300
301 fclose (tfile);
302
303 set_append_mode (fd);
304
305 umask (mask);
306
307 return fd;
308 }
309
310 /* Adds file descriptors to the child structure to support output_sync; one
311 for stdout and one for stderr as long as they are open. If stdout and
312 stderr share a device they can share a temp file too.
313 Will reset output_sync on error. */
314 static void
315 setup_tmpfile (struct output *out)
316 {
317 /* Is make's stdout going to the same place as stderr? */
318 static int combined_output = -1;
319
320 if (combined_output < 0)
321 combined_output = sync_init ();
322
323 if (STREAM_OK (stdout))
324 {
325 int fd = output_tmpfd ();
326 if (fd < 0)
327 goto error;
328 fd_noinherit (fd);
329 out->out = fd;
330 }
331
332 if (STREAM_OK (stderr))
333 {
334 if (out->out != OUTPUT_NONE && combined_output)
335 out->err = out->out;
336 else
337 {
338 int fd = output_tmpfd ();
339 if (fd < 0)
340 goto error;
341 fd_noinherit (fd);
342 out->err = fd;
343 }
344 }
345
346 return;
347
348 /* If we failed to create a temp file, disable output sync going forward. */
349 error:
350 output_close (out);
351 output_sync = OUTPUT_SYNC_NONE;
352 }
353
354 /* Synchronize the output of jobs in -j mode to keep the results of
355 each job together. This is done by holding the results in temp files,
356 one for stdout and potentially another for stderr, and only releasing
357 them to "real" stdout/stderr when a semaphore can be obtained. */
358
359 void
360 output_dump (struct output *out)
361 {
362 int outfd_not_empty = FD_NOT_EMPTY (out->out);
363 int errfd_not_empty = FD_NOT_EMPTY (out->err);
364
365 if (outfd_not_empty || errfd_not_empty)
366 {
367 int traced = 0;
368
369 /* Try to acquire the semaphore. If it fails, dump the output
370 unsynchronized; still better than silently discarding it.
371 We want to keep this lock for as little time as possible. */
372 void *sem = acquire_semaphore ();
373
374 /* Log the working directory for this dump. */
375 if (print_directory && output_sync != OUTPUT_SYNC_RECURSE)
376 traced = log_working_directory (1);
377
378 if (outfd_not_empty)
379 pump_from_tmp (out->out, stdout);
380 if (errfd_not_empty && out->err != out->out)
381 pump_from_tmp (out->err, stderr);
382
383 if (traced)
384 log_working_directory (0);
385
386 /* Exit the critical section. */
387 if (sem)
388 release_semaphore (sem);
389
390 /* Truncate and reset the output, in case we use it again. */
391 if (out->out != OUTPUT_NONE)
392 {
393 int e;
394 lseek (out->out, 0, SEEK_SET);
395 EINTRLOOP (e, ftruncate (out->out, 0));
396 }
397 if (out->err != OUTPUT_NONE && out->err != out->out)
398 {
399 int e;
400 lseek (out->err, 0, SEEK_SET);
401 EINTRLOOP (e, ftruncate (out->err, 0));
402 }
403 }
404 }
405 #endif /* NO_OUTPUT_SYNC */
406
407
408 /* This code is stolen from gnulib.
409 If/when we abandon the requirement to work with K&R compilers, we can
410 remove this (and perhaps other parts of GNU make!) and migrate to using
411 gnulib directly.
412
413 This is called only through atexit(), which means die() has already been
414 invoked. So, call exit() here directly. Apparently that works...?
415 */
416
417 /* Close standard output, exiting with status 'exit_failure' on failure.
418 If a program writes *anything* to stdout, that program should close
419 stdout and make sure that it succeeds before exiting. Otherwise,
420 suppose that you go to the extreme of checking the return status
421 of every function that does an explicit write to stdout. The last
422 printf can succeed in writing to the internal stream buffer, and yet
423 the fclose(stdout) could still fail (due e.g., to a disk full error)
424 when it tries to write out that buffered data. Thus, you would be
425 left with an incomplete output file and the offending program would
426 exit successfully. Even calling fflush is not always sufficient,
427 since some file systems (NFS and CODA) buffer written/flushed data
428 until an actual close call.
429
430 Besides, it's wasteful to check the return value from every call
431 that writes to stdout -- just let the internal stream state record
432 the failure. That's what the ferror test is checking below.
433
434 It's important to detect such failures and exit nonzero because many
435 tools (most notably 'make' and other build-management systems) depend
436 on being able to detect failure in other tools via their exit status. */
437
438 static void
439 close_stdout (void)
440 {
441 int prev_fail = ferror (stdout);
442 int fclose_fail = fclose (stdout);
443
444 if (prev_fail || fclose_fail)
445 {
446 if (fclose_fail)
447 perror_with_name (_("write error: stdout"), "");
448 else
449 O (error, NILF, _("write error: stdout"));
450 exit (MAKE_TROUBLE);
451 }
452 }
453
454
455 void
456 output_init (struct output *out)
457 {
458 if (out)
459 {
460 out->out = out->err = OUTPUT_NONE;
461 out->syncout = !!output_sync;
462 return;
463 }
464
465 /* Configure this instance of make. Be sure stdout is line-buffered. */
466
467 #ifdef HAVE_SETVBUF
468 # ifdef SETVBUF_REVERSED
469 setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
470 # else /* setvbuf not reversed. */
471 /* Some buggy systems lose if we pass 0 instead of allocating ourselves. */
472 setvbuf (stdout, 0, _IOLBF, BUFSIZ);
473 # endif /* setvbuf reversed. */
474 #elif HAVE_SETLINEBUF
475 setlinebuf (stdout);
476 #endif /* setlinebuf missing. */
477
478 /* Force stdout/stderr into append mode. This ensures parallel jobs won't
479 lose output due to overlapping writes. */
480 set_append_mode (fileno (stdout));
481 set_append_mode (fileno (stderr));
482
483 #ifdef HAVE_ATEXIT
484 if (STREAM_OK (stdout))
485 atexit (close_stdout);
486 #endif
487 }
488
489 void
490 output_close (struct output *out)
491 {
492 if (! out)
493 {
494 if (stdio_traced)
495 log_working_directory (0);
496 return;
497 }
498
499 #ifndef NO_OUTPUT_SYNC
500 output_dump (out);
501 #endif
502
503 if (out->out >= 0)
504 close (out->out);
505 if (out->err >= 0 && out->err != out->out)
506 close (out->err);
507
508 output_init (out);
509 }
510
511 /* We're about to generate output: be sure it's set up. */
512 void
513 output_start (void)
514 {
515 #ifndef NO_OUTPUT_SYNC
516 /* If we're syncing output make sure the temporary file is set up. */
517 if (output_context && output_context->syncout)
518 if (! OUTPUT_ISSET(output_context))
519 setup_tmpfile (output_context);
520 #endif
521
522 /* If we're not syncing this output per-line or per-target, make sure we emit
523 the "Entering..." message where appropriate. */
524 if (output_sync == OUTPUT_SYNC_NONE || output_sync == OUTPUT_SYNC_RECURSE)
525 if (! stdio_traced && print_directory)
526 stdio_traced = log_working_directory (1);
527 }
528
529 void
530 outputs (int is_err, const char *msg)
531 {
532 if (! msg || *msg == '\0')
533 return;
534
535 output_start ();
536
537 _outputs (output_context, is_err, msg);
538 }
539
540
541 static struct fmtstring
542 {
543 char *buffer;
544 size_t size;
545 } fmtbuf = { NULL, 0 };
546
547 static char *
548 get_buffer (size_t need)
549 {
550 /* Make sure we have room. NEED includes space for \0. */
551 if (need > fmtbuf.size)
552 {
553 fmtbuf.size += need * 2;
554 fmtbuf.buffer = xrealloc (fmtbuf.buffer, fmtbuf.size);
555 }
556
557 fmtbuf.buffer[need-1] = '\0';
558
559 return fmtbuf.buffer;
560 }
561
562 /* Print a message on stdout. */
563
564 void
565 message (int prefix, size_t len, const char *fmt, ...)
566 {
567 va_list args;
568 char *p;
569
570 len += strlen (fmt) + strlen (program) + INTSTR_LENGTH + 4 + 1 + 1;
571 p = get_buffer (len);
572
573 if (prefix)
574 {
575 if (makelevel == 0)
576 sprintf (p, "%s: ", program);
577 else
578 sprintf (p, "%s[%u]: ", program, makelevel);
579 p += strlen (p);
580 }
581
582 va_start (args, fmt);
583 vsprintf (p, fmt, args);
584 va_end (args);
585
586 strcat (p, "\n");
587
588 assert (fmtbuf.buffer[len-1] == '\0');
589 outputs (0, fmtbuf.buffer);
590 }
591
592 /* Print an error message. */
593
594 void
595 error (const gmk_floc *flocp, size_t len, const char *fmt, ...)
596 {
597 va_list args;
598 char *p;
599
600 len += (strlen (fmt) + strlen (program)
601 + (flocp && flocp->filenm ? strlen (flocp->filenm) : 0)
602 + INTSTR_LENGTH + 4 + 1 + 1);
603 p = get_buffer (len);
604
605 if (flocp && flocp->filenm)
606 sprintf (p, "%s:%lu: ", flocp->filenm, flocp->lineno + flocp->offset);
607 else if (makelevel == 0)
608 sprintf (p, "%s: ", program);
609 else
610 sprintf (p, "%s[%u]: ", program, makelevel);
611 p += strlen (p);
612
613 va_start (args, fmt);
614 vsprintf (p, fmt, args);
615 va_end (args);
616
617 strcat (p, "\n");
618
619 assert (fmtbuf.buffer[len-1] == '\0');
620 outputs (1, fmtbuf.buffer);
621 }
622
623 /* Print an error message and exit. */
624
625 void
626 fatal (const gmk_floc *flocp, size_t len, const char *fmt, ...)
627 {
628 va_list args;
629 const char *stop = _(". Stop.\n");
630 char *p;
631
632 len += (strlen (fmt) + strlen (program)
633 + (flocp && flocp->filenm ? strlen (flocp->filenm) : 0)
634 + INTSTR_LENGTH + 8 + strlen (stop) + 1);
635 p = get_buffer (len);
636
637 if (flocp && flocp->filenm)
638 sprintf (p, "%s:%lu: *** ", flocp->filenm, flocp->lineno + flocp->offset);
639 else if (makelevel == 0)
640 sprintf (p, "%s: *** ", program);
641 else
642 sprintf (p, "%s[%u]: *** ", program, makelevel);
643 p += strlen (p);
644
645 va_start (args, fmt);
646 vsprintf (p, fmt, args);
647 va_end (args);
648
649 strcat (p, stop);
650
651 assert (fmtbuf.buffer[len-1] == '\0');
652 outputs (1, fmtbuf.buffer);
653
654 die (MAKE_FAILURE);
655 }
656
657 /* Print an error message from errno. */
658
659 void
660 perror_with_name (const char *str, const char *name)
661 {
662 const char *err = strerror (errno);
663 OSSS (error, NILF, _("%s%s: %s"), str, name, err);
664 }
665
666 /* Print an error message from errno and exit. */
667
668 void
669 pfatal_with_name (const char *name)
670 {
671 const char *err = strerror (errno);
672 OSS (fatal, NILF, _("%s: %s"), name, err);
673
674 /* NOTREACHED */
675 }
676
677 /* Print a message about out of memory (not using more heap) and exit.
678 Our goal here is to be sure we don't try to allocate more memory, which
679 means we don't want to use string translations or normal cleanup. */
680
681 void
682 out_of_memory ()
683 {
684 writebuf (FD_STDOUT, program, strlen (program));
685 writebuf (FD_STDOUT, STRING_SIZE_TUPLE (": *** virtual memory exhausted\n"));
686 exit (MAKE_FAILURE);
687 }