1 /* Output to stdout / stderr for GNU make
2 Copyright (C) 2013-2016 Free Software Foundation, Inc.
3 This file is part of GNU Make.
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
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.
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/>. */
20 /* GNU make no longer supports pre-ANSI89 environments. */
33 # include <sys/file.h>
39 # include "sub_proc.h"
40 #endif /* WINDOWS32 */
42 struct output *output_context = NULL;
43 unsigned int stdio_traced = 0;
45 #define OUTPUT_NONE (-1)
47 #define OUTPUT_ISSET(_out) ((_out)->out >= 0 || (_out)->err >= 0)
50 # define STREAM_OK(_s) ((fcntl (fileno (_s), F_GETFD) != -1) || (errno != EBADF))
52 # define STREAM_OK(_s) 1
55 /* Write a string to the current STDOUT or STDERR. */
57 _outputs (struct output *out, int is_err, const char *msg)
59 if (! out || ! out->syncout)
61 FILE *f = is_err ? stderr : stdout;
67 int fd = is_err ? out->err : out->out;
68 int len = strlen (msg);
71 EINTRLOOP (r, lseek (fd, 0, SEEK_END));
74 EINTRLOOP (r, write (fd, msg, len));
75 if (r == len || r <= 0)
83 /* Write a message indicating that we've just entered or
84 left (according to ENTERING) the current directory. */
87 log_working_directory (int entering)
89 static char *buf = NULL;
90 static unsigned int len = 0;
95 /* Get enough space for the longest possible output. */
96 need = strlen (program) + INTSTR_LENGTH + 2 + 1;
97 if (starting_directory)
98 need += strlen (starting_directory);
100 /* Use entire sentences to give the translators a fighting chance. */
102 if (starting_directory == 0)
104 fmt = _("%s: Entering an unknown directory\n");
106 fmt = _("%s: Leaving an unknown directory\n");
109 fmt = _("%s: Entering directory '%s'\n");
111 fmt = _("%s: Leaving directory '%s'\n");
113 if (starting_directory == 0)
115 fmt = _("%s[%u]: Entering an unknown directory\n");
117 fmt = _("%s[%u]: Leaving an unknown directory\n");
120 fmt = _("%s[%u]: Entering directory '%s'\n");
122 fmt = _("%s[%u]: Leaving directory '%s'\n");
124 need += strlen (fmt);
128 buf = xrealloc (buf, need);
133 if (print_data_base_flag)
140 if (starting_directory == 0)
141 sprintf (p, fmt , program);
143 sprintf (p, fmt, program, starting_directory);
144 else if (starting_directory == 0)
145 sprintf (p, fmt, program, makelevel);
147 sprintf (p, fmt, program, makelevel, starting_directory);
149 _outputs (NULL, 0, buf);
154 /* Set a file descriptor to be in O_APPEND mode.
155 If it fails, just ignore it. */
158 set_append_mode (int fd)
160 #if defined(F_GETFL) && defined(F_SETFL) && defined(O_APPEND)
161 int flags = fcntl (fd, F_GETFL, 0);
163 fcntl (fd, F_SETFL, flags | O_APPEND);
168 #ifndef NO_OUTPUT_SYNC
170 /* Semaphore for use in -j mode with output_sync. */
171 static sync_handle_t sync_handle = -1;
173 #define FD_NOT_EMPTY(_f) ((_f) != OUTPUT_NONE && lseek ((_f), 0, SEEK_END) > 0)
175 /* Set up the sync handle. Disables output_sync on error. */
179 int combined_output = 0;
182 if ((!STREAM_OK (stdout) && !STREAM_OK (stderr))
183 || (sync_handle = create_mutex ()) == -1)
185 perror_with_name ("output-sync suppressed: ", "stderr");
190 combined_output = same_stream (stdout, stderr);
191 prepare_mutex_handle_string (sync_handle);
195 if (STREAM_OK (stdout))
197 struct stat stbuf_o, stbuf_e;
199 sync_handle = fileno (stdout);
200 combined_output = (fstat (fileno (stdout), &stbuf_o) == 0
201 && fstat (fileno (stderr), &stbuf_e) == 0
202 && stbuf_o.st_dev == stbuf_e.st_dev
203 && stbuf_o.st_ino == stbuf_e.st_ino);
205 else if (STREAM_OK (stderr))
206 sync_handle = fileno (stderr);
209 perror_with_name ("output-sync suppressed: ", "stderr");
214 return combined_output;
217 /* Support routine for output_sync() */
219 pump_from_tmp (int from, FILE *to)
221 static char buffer[8192];
226 /* "from" is opened by open_tmpfd, which does it in binary mode, so
227 we need the mode of "to" to match that. */
228 prev_mode = _setmode (fileno (to), _O_BINARY);
231 if (lseek (from, 0, SEEK_SET) == -1)
237 EINTRLOOP (len, read (from, buffer, sizeof (buffer)));
242 if (fwrite (buffer, len, 1, to) < 1)
251 /* Switch "to" back to its original mode, so that log messages by
252 Make have the same EOL format as without --output-sync. */
253 _setmode (fileno (to), prev_mode);
257 /* Obtain the lock for writing output. */
259 acquire_semaphore (void)
261 static struct flock fl;
264 fl.l_whence = SEEK_SET;
267 if (fcntl (sync_handle, F_SETLKW, &fl) != -1)
273 /* Release the lock for writing output. */
275 release_semaphore (void *sem)
277 struct flock *flp = (struct flock *)sem;
278 flp->l_type = F_UNLCK;
279 if (fcntl (sync_handle, F_SETLKW, flp) == -1)
283 /* Returns a file descriptor to a temporary file. The file is automatically
284 closed/deleted on exit. Don't use a FILE* stream. */
289 FILE *tfile = tmpfile ();
292 pfatal_with_name ("tmpfile");
294 /* Create a duplicate so we can close the stream. */
295 fd = dup (fileno (tfile));
297 pfatal_with_name ("dup");
301 set_append_mode (fd);
306 /* Adds file descriptors to the child structure to support output_sync; one
307 for stdout and one for stderr as long as they are open. If stdout and
308 stderr share a device they can share a temp file too.
309 Will reset output_sync on error. */
311 setup_tmpfile (struct output *out)
313 /* Is make's stdout going to the same place as stderr? */
314 static int combined_output = -1;
316 if (combined_output < 0)
317 combined_output = sync_init ();
319 if (STREAM_OK (stdout))
321 int fd = output_tmpfd ();
328 if (STREAM_OK (stderr))
330 if (out->out != OUTPUT_NONE && combined_output)
334 int fd = output_tmpfd ();
344 /* If we failed to create a temp file, disable output sync going forward. */
347 output_sync = OUTPUT_SYNC_NONE;
350 /* Synchronize the output of jobs in -j mode to keep the results of
351 each job together. This is done by holding the results in temp files,
352 one for stdout and potentially another for stderr, and only releasing
353 them to "real" stdout/stderr when a semaphore can be obtained. */
356 output_dump (struct output *out)
358 int outfd_not_empty = FD_NOT_EMPTY (out->out);
359 int errfd_not_empty = FD_NOT_EMPTY (out->err);
361 if (outfd_not_empty || errfd_not_empty)
365 /* Try to acquire the semaphore. If it fails, dump the output
366 unsynchronized; still better than silently discarding it.
367 We want to keep this lock for as little time as possible. */
368 void *sem = acquire_semaphore ();
370 /* Log the working directory for this dump. */
371 if (print_directory_flag && output_sync != OUTPUT_SYNC_RECURSE)
372 traced = log_working_directory (1);
375 pump_from_tmp (out->out, stdout);
376 if (errfd_not_empty && out->err != out->out)
377 pump_from_tmp (out->err, stderr);
380 log_working_directory (0);
382 /* Exit the critical section. */
384 release_semaphore (sem);
386 /* Truncate and reset the output, in case we use it again. */
387 if (out->out != OUTPUT_NONE)
390 lseek (out->out, 0, SEEK_SET);
391 EINTRLOOP (e, ftruncate (out->out, 0));
393 if (out->err != OUTPUT_NONE && out->err != out->out)
396 lseek (out->err, 0, SEEK_SET);
397 EINTRLOOP (e, ftruncate (out->err, 0));
401 #endif /* NO_OUTPUT_SYNC */
404 /* Provide support for temporary files. */
406 #ifndef HAVE_STDLIB_H
408 int mkstemp (char *template);
410 char *mktemp (char *template);
415 output_tmpfile (char **name, const char *template)
421 #if defined HAVE_MKSTEMP || defined HAVE_MKTEMP
422 # define TEMPLATE_LEN strlen (template)
424 # define TEMPLATE_LEN L_tmpnam
426 *name = xmalloc (TEMPLATE_LEN + 1);
427 strcpy (*name, template);
429 #if defined HAVE_MKSTEMP && defined HAVE_FDOPEN
430 /* It's safest to use mkstemp(), if we can. */
431 fd = mkstemp (*name);
434 return fdopen (fd, "w");
437 (void) mktemp (*name);
439 (void) tmpnam (*name);
443 /* Can't use mkstemp(), but guard against a race condition. */
444 EINTRLOOP (fd, open (*name, O_CREAT|O_EXCL|O_WRONLY, 0600));
447 return fdopen (fd, "w");
449 /* Not secure, but what can we do? */
450 return fopen (*name, "w");
456 /* This code is stolen from gnulib.
457 If/when we abandon the requirement to work with K&R compilers, we can
458 remove this (and perhaps other parts of GNU make!) and migrate to using
461 This is called only through atexit(), which means die() has already been
462 invoked. So, call exit() here directly. Apparently that works...?
465 /* Close standard output, exiting with status 'exit_failure' on failure.
466 If a program writes *anything* to stdout, that program should close
467 stdout and make sure that it succeeds before exiting. Otherwise,
468 suppose that you go to the extreme of checking the return status
469 of every function that does an explicit write to stdout. The last
470 printf can succeed in writing to the internal stream buffer, and yet
471 the fclose(stdout) could still fail (due e.g., to a disk full error)
472 when it tries to write out that buffered data. Thus, you would be
473 left with an incomplete output file and the offending program would
474 exit successfully. Even calling fflush is not always sufficient,
475 since some file systems (NFS and CODA) buffer written/flushed data
476 until an actual close call.
478 Besides, it's wasteful to check the return value from every call
479 that writes to stdout -- just let the internal stream state record
480 the failure. That's what the ferror test is checking below.
482 It's important to detect such failures and exit nonzero because many
483 tools (most notably 'make' and other build-management systems) depend
484 on being able to detect failure in other tools via their exit status. */
489 int prev_fail = ferror (stdout);
490 int fclose_fail = fclose (stdout);
492 if (prev_fail || fclose_fail)
495 perror_with_name (_("write error: stdout"), "");
497 O (error, NILF, _("write error: stdout"));
504 output_init (struct output *out)
508 out->out = out->err = OUTPUT_NONE;
509 out->syncout = !!output_sync;
513 /* Configure this instance of make. Be sure stdout is line-buffered. */
516 # ifdef SETVBUF_REVERSED
517 setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
518 # else /* setvbuf not reversed. */
519 /* Some buggy systems lose if we pass 0 instead of allocating ourselves. */
520 setvbuf (stdout, 0, _IOLBF, BUFSIZ);
521 # endif /* setvbuf reversed. */
522 #elif HAVE_SETLINEBUF
524 #endif /* setlinebuf missing. */
526 /* Force stdout/stderr into append mode. This ensures parallel jobs won't
527 lose output due to overlapping writes. */
528 set_append_mode (fileno (stdout));
529 set_append_mode (fileno (stderr));
532 if (STREAM_OK (stdout))
533 atexit (close_stdout);
538 output_close (struct output *out)
543 log_working_directory (0);
547 #ifndef NO_OUTPUT_SYNC
553 if (out->err >= 0 && out->err != out->out)
559 /* We're about to generate output: be sure it's set up. */
563 #ifndef NO_OUTPUT_SYNC
564 /* If we're syncing output make sure the temporary file is set up. */
565 if (output_context && output_context->syncout)
566 if (! OUTPUT_ISSET(output_context))
567 setup_tmpfile (output_context);
570 /* If we're not syncing this output per-line or per-target, make sure we emit
571 the "Entering..." message where appropriate. */
572 if (output_sync == OUTPUT_SYNC_NONE || output_sync == OUTPUT_SYNC_RECURSE)
573 if (! stdio_traced && print_directory_flag)
574 stdio_traced = log_working_directory (1);
578 outputs (int is_err, const char *msg)
580 if (! msg || *msg == '\0')
585 _outputs (output_context, is_err, msg);
589 static struct fmtstring
593 } fmtbuf = { NULL, 0 };
596 get_buffer (size_t need)
598 /* Make sure we have room. NEED includes space for \0. */
599 if (need > fmtbuf.size)
601 fmtbuf.size += need * 2;
602 fmtbuf.buffer = xrealloc (fmtbuf.buffer, fmtbuf.size);
605 fmtbuf.buffer[need-1] = '\0';
607 return fmtbuf.buffer;
610 /* Print a message on stdout. */
613 message (int prefix, size_t len, const char *fmt, ...)
618 len += strlen (fmt) + strlen (program) + INTSTR_LENGTH + 4 + 1 + 1;
619 p = get_buffer (len);
624 sprintf (p, "%s: ", program);
626 sprintf (p, "%s[%u]: ", program, makelevel);
630 va_start (args, fmt);
631 vsprintf (p, fmt, args);
636 assert (fmtbuf.buffer[len-1] == '\0');
637 outputs (0, fmtbuf.buffer);
640 /* Print an error message. */
643 error (const floc *flocp, size_t len, const char *fmt, ...)
648 len += (strlen (fmt) + strlen (program)
649 + (flocp && flocp->filenm ? strlen (flocp->filenm) : 0)
650 + INTSTR_LENGTH + 4 + 1 + 1);
651 p = get_buffer (len);
653 if (flocp && flocp->filenm)
654 sprintf (p, "%s:%lu: ", flocp->filenm, flocp->lineno + flocp->offset);
655 else if (makelevel == 0)
656 sprintf (p, "%s: ", program);
658 sprintf (p, "%s[%u]: ", program, makelevel);
661 va_start (args, fmt);
662 vsprintf (p, fmt, args);
667 assert (fmtbuf.buffer[len-1] == '\0');
668 outputs (1, fmtbuf.buffer);
671 /* Print an error message and exit. */
674 fatal (const floc *flocp, size_t len, const char *fmt, ...)
677 const char *stop = _(". Stop.\n");
680 len += (strlen (fmt) + strlen (program)
681 + (flocp && flocp->filenm ? strlen (flocp->filenm) : 0)
682 + INTSTR_LENGTH + 8 + strlen (stop) + 1);
683 p = get_buffer (len);
685 if (flocp && flocp->filenm)
686 sprintf (p, "%s:%lu: *** ", flocp->filenm, flocp->lineno + flocp->offset);
687 else if (makelevel == 0)
688 sprintf (p, "%s: *** ", program);
690 sprintf (p, "%s[%u]: *** ", program, makelevel);
693 va_start (args, fmt);
694 vsprintf (p, fmt, args);
699 assert (fmtbuf.buffer[len-1] == '\0');
700 outputs (1, fmtbuf.buffer);
705 /* Print an error message from errno. */
708 perror_with_name (const char *str, const char *name)
710 const char *err = strerror (errno);
711 OSSS (error, NILF, _("%s%s: %s"), str, name, err);
714 /* Print an error message from errno and exit. */
717 pfatal_with_name (const char *name)
719 const char *err = strerror (errno);
720 OSS (fatal, NILF, _("%s: %s"), name, err);