1 /* Output to stdout / stderr for GNU make
2 Copyright (C) 2013 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 /* I really want to move to gnulib. However, this is a big undertaking
56 especially for non-UNIX platforms: how to get bootstrapping to work, etc.
57 I don't want to take the time to do it right now. Use a hack to get a
58 useful version of vsnprintf() for Windows. */
60 # define va_copy(_d, _s) ((_d) = (_s))
63 # define va_copy(_d, _s) ((_d) = (_s))
64 # define snprintf msc_vsnprintf
66 msc_vsnprintf (char *str, size_t size, const char *format, va_list ap)
71 len = _vsnprintf_s (str, size, _TRUNCATE, format, ap);
73 len = _vscprintf (format, ap);
79 /* Write a string to the current STDOUT or STDERR. */
81 _outputs (struct output *out, int is_err, const char *msg)
83 if (! out || ! out->syncout)
85 FILE *f = is_err ? stderr : stdout;
91 int fd = is_err ? out->err : out->out;
92 int len = strlen (msg);
95 EINTRLOOP (r, lseek (fd, 0, SEEK_END));
98 EINTRLOOP (r, write (fd, msg, len));
99 if (r == len || r <= 0)
107 /* Write a message indicating that we've just entered or
108 left (according to ENTERING) the current directory. */
111 log_working_directory (int entering)
113 static char *buf = NULL;
114 static unsigned int len = 0;
119 /* Get enough space for the longest possible output. */
120 need = strlen (program) + INTEGER_LENGTH + 2 + 1;
121 if (starting_directory)
122 need += strlen (starting_directory);
124 /* Use entire sentences to give the translators a fighting chance. */
126 if (starting_directory == 0)
128 fmt = _("%s: Entering an unknown directory\n");
130 fmt = _("%s: Leaving an unknown directory\n");
133 fmt = _("%s: Entering directory '%s'\n");
135 fmt = _("%s: Leaving directory '%s'\n");
137 if (starting_directory == 0)
139 fmt = _("%s[%u]: Entering an unknown directory\n");
141 fmt = _("%s[%u]: Leaving an unknown directory\n");
144 fmt = _("%s[%u]: Entering directory '%s'\n");
146 fmt = _("%s[%u]: Leaving directory '%s'\n");
148 need += strlen (fmt);
152 buf = xrealloc (buf, need);
157 if (print_data_base_flag)
164 if (starting_directory == 0)
165 sprintf (p, fmt , program);
167 sprintf (p, fmt, program, starting_directory);
168 else if (starting_directory == 0)
169 sprintf (p, fmt, program, makelevel);
171 sprintf (p, fmt, program, makelevel, starting_directory);
173 _outputs (NULL, 0, buf);
178 /* Set a file descriptor to be in O_APPEND mode.
179 If it fails, just ignore it. */
182 set_append_mode (int fd)
184 #if defined(F_GETFL) && defined(F_SETFL) && defined(O_APPEND)
185 int flags = fcntl (fd, F_GETFL, 0);
187 fcntl (fd, F_SETFL, flags | O_APPEND);
192 #ifndef NO_OUTPUT_SYNC
194 /* Semaphore for use in -j mode with output_sync. */
195 static sync_handle_t sync_handle = -1;
197 #define FD_NOT_EMPTY(_f) ((_f) != OUTPUT_NONE && lseek ((_f), 0, SEEK_END) > 0)
199 /* Set up the sync handle. Disables output_sync on error. */
203 int combined_output = 0;
206 if ((!STREAM_OK (stdout) && !STREAM_OK (stderr))
207 || (sync_handle = create_mutex ()) == -1)
209 perror_with_name ("output-sync suppressed: ", "stderr");
214 combined_output = same_stream (stdout, stderr);
215 prepare_mutex_handle_string (sync_handle);
219 if (STREAM_OK (stdout))
221 struct stat stbuf_o, stbuf_e;
223 sync_handle = fileno (stdout);
224 combined_output = (fstat (fileno (stdout), &stbuf_o) == 0
225 && fstat (fileno (stderr), &stbuf_e) == 0
226 && stbuf_o.st_dev == stbuf_e.st_dev
227 && stbuf_o.st_ino == stbuf_e.st_ino);
229 else if (STREAM_OK (stderr))
230 sync_handle = fileno (stderr);
233 perror_with_name ("output-sync suppressed: ", "stderr");
238 return combined_output;
241 /* Support routine for output_sync() */
243 pump_from_tmp (int from, FILE *to)
245 static char buffer[8192];
250 /* "from" is opened by open_tmpfd, which does it in binary mode, so
251 we need the mode of "to" to match that. */
252 prev_mode = _setmode (fileno (to), _O_BINARY);
255 if (lseek (from, 0, SEEK_SET) == -1)
261 EINTRLOOP (len, read (from, buffer, sizeof (buffer)));
266 if (fwrite (buffer, len, 1, to) < 1)
271 /* Switch "to" back to its original mode, so that log messages by
272 Make have the same EOL format as without --output-sync. */
273 _setmode (fileno (to), prev_mode);
277 /* Obtain the lock for writing output. */
279 acquire_semaphore (void)
281 static struct flock fl;
284 fl.l_whence = SEEK_SET;
287 if (fcntl (sync_handle, F_SETLKW, &fl) != -1)
293 /* Release the lock for writing output. */
295 release_semaphore (void *sem)
297 struct flock *flp = (struct flock *)sem;
298 flp->l_type = F_UNLCK;
299 if (fcntl (sync_handle, F_SETLKW, flp) == -1)
303 /* Returns a file descriptor to a temporary file. The file is automatically
304 closed/deleted on exit. Don't use a FILE* stream. */
309 FILE *tfile = tmpfile ();
312 pfatal_with_name ("tmpfile");
314 /* Create a duplicate so we can close the stream. */
315 fd = dup (fileno (tfile));
317 pfatal_with_name ("dup");
321 set_append_mode (fd);
326 /* Adds file descriptors to the child structure to support output_sync; one
327 for stdout and one for stderr as long as they are open. If stdout and
328 stderr share a device they can share a temp file too.
329 Will reset output_sync on error. */
331 setup_tmpfile (struct output *out)
333 /* Is make's stdout going to the same place as stderr? */
334 static int combined_output = -1;
336 if (combined_output < 0)
337 combined_output = sync_init ();
339 if (STREAM_OK (stdout))
341 int fd = output_tmpfd ();
348 if (STREAM_OK (stderr))
350 if (out->out != OUTPUT_NONE && combined_output)
354 int fd = output_tmpfd ();
364 /* If we failed to create a temp file, disable output sync going forward. */
370 /* Synchronize the output of jobs in -j mode to keep the results of
371 each job together. This is done by holding the results in temp files,
372 one for stdout and potentially another for stderr, and only releasing
373 them to "real" stdout/stderr when a semaphore can be obtained. */
376 output_dump (struct output *out)
378 int outfd_not_empty = FD_NOT_EMPTY (out->out);
379 int errfd_not_empty = FD_NOT_EMPTY (out->err);
381 if (outfd_not_empty || errfd_not_empty)
385 /* Try to acquire the semaphore. If it fails, dump the output
386 unsynchronized; still better than silently discarding it.
387 We want to keep this lock for as little time as possible. */
388 void *sem = acquire_semaphore ();
390 /* Log the working directory for this dump. */
391 if (print_directory_flag && output_sync != OUTPUT_SYNC_RECURSE)
392 traced = log_working_directory (1);
395 pump_from_tmp (out->out, stdout);
396 if (errfd_not_empty && out->err != out->out)
397 pump_from_tmp (out->err, stderr);
400 log_working_directory (0);
402 /* Exit the critical section. */
404 release_semaphore (sem);
406 /* Truncate and reset the output, in case we use it again. */
407 if (out->out != OUTPUT_NONE)
410 lseek (out->out, 0, SEEK_SET);
411 EINTRLOOP (e, ftruncate (out->out, 0));
413 if (out->err != OUTPUT_NONE && out->err != out->out)
416 lseek (out->err, 0, SEEK_SET);
417 EINTRLOOP (e, ftruncate (out->err, 0));
421 #endif /* NO_OUTPUT_SYNC */
424 /* Provide support for temporary files. */
426 #ifndef HAVE_STDLIB_H
428 int mkstemp (char *template);
430 char *mktemp (char *template);
435 output_tmpfile (char **name, const char *template)
441 #if defined HAVE_MKSTEMP || defined HAVE_MKTEMP
442 # define TEMPLATE_LEN strlen (template)
444 # define TEMPLATE_LEN L_tmpnam
446 *name = xmalloc (TEMPLATE_LEN + 1);
447 strcpy (*name, template);
449 #if defined HAVE_MKSTEMP && defined HAVE_FDOPEN
450 /* It's safest to use mkstemp(), if we can. */
451 fd = mkstemp (*name);
454 return fdopen (fd, "w");
457 (void) mktemp (*name);
459 (void) tmpnam (*name);
463 /* Can't use mkstemp(), but guard against a race condition. */
464 fd = open (*name, O_CREAT|O_EXCL|O_WRONLY, 0600);
467 return fdopen (fd, "w");
469 /* Not secure, but what can we do? */
470 return fopen (*name, "w");
476 /* This code is stolen from gnulib.
477 If/when we abandon the requirement to work with K&R compilers, we can
478 remove this (and perhaps other parts of GNU make!) and migrate to using
481 This is called only through atexit(), which means die() has already been
482 invoked. So, call exit() here directly. Apparently that works...?
485 /* Close standard output, exiting with status 'exit_failure' on failure.
486 If a program writes *anything* to stdout, that program should close
487 stdout and make sure that it succeeds before exiting. Otherwise,
488 suppose that you go to the extreme of checking the return status
489 of every function that does an explicit write to stdout. The last
490 printf can succeed in writing to the internal stream buffer, and yet
491 the fclose(stdout) could still fail (due e.g., to a disk full error)
492 when it tries to write out that buffered data. Thus, you would be
493 left with an incomplete output file and the offending program would
494 exit successfully. Even calling fflush is not always sufficient,
495 since some file systems (NFS and CODA) buffer written/flushed data
496 until an actual close call.
498 Besides, it's wasteful to check the return value from every call
499 that writes to stdout -- just let the internal stream state record
500 the failure. That's what the ferror test is checking below.
502 It's important to detect such failures and exit nonzero because many
503 tools (most notably 'make' and other build-management systems) depend
504 on being able to detect failure in other tools via their exit status. */
509 int prev_fail = ferror (stdout);
510 int fclose_fail = fclose (stdout);
512 if (prev_fail || fclose_fail)
515 error (NILF, _("write error: %s"), strerror (errno));
517 error (NILF, _("write error"));
524 output_init (struct output *out)
528 out->out = out->err = OUTPUT_NONE;
529 out->syncout = !!output_sync;
533 /* Configure this instance of make. Be sure stdout is line-buffered. */
536 # ifdef SETVBUF_REVERSED
537 setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
538 # else /* setvbuf not reversed. */
539 /* Some buggy systems lose if we pass 0 instead of allocating ourselves. */
540 setvbuf (stdout, 0, _IOLBF, BUFSIZ);
541 # endif /* setvbuf reversed. */
542 #elif HAVE_SETLINEBUF
544 #endif /* setlinebuf missing. */
546 /* Force stdout/stderr into append mode. This ensures parallel jobs won't
547 lose output due to overlapping writes. */
548 set_append_mode (fileno (stdout));
549 set_append_mode (fileno (stderr));
552 if (STREAM_OK (stdout))
553 atexit (close_stdout);
558 output_close (struct output *out)
563 log_working_directory (0);
567 #ifndef NO_OUTPUT_SYNC
573 if (out->err >= 0 && out->err != out->out)
579 /* We're about to generate output: be sure it's set up. */
583 #ifndef NO_OUTPUT_SYNC
584 /* If we're syncing output make sure the temporary file is set up. */
585 if (output_context && output_context->syncout)
586 if (! OUTPUT_ISSET(output_context))
587 setup_tmpfile (output_context);
590 /* If we're not syncing this output per-line or per-target, make sure we emit
591 the "Entering..." message where appropriate. */
592 if (output_sync == OUTPUT_SYNC_NONE || output_sync == OUTPUT_SYNC_RECURSE)
593 if (! stdio_traced && print_directory_flag)
594 stdio_traced = log_working_directory (1);
598 outputs (int is_err, const char *msg)
600 if (! msg || *msg == '\0')
605 _outputs (output_context, is_err, msg);
609 /* Return formatted string buffers.
610 If we move to gnulib we can use vasnprintf() etc. to make this simpler.
611 Note these functions use a static buffer, so each call overwrites the
612 results of the previous call. */
614 static struct fmtstring
619 } fmtbuf = { NULL, 0, 0 };
621 /* Concatenate a formatted string onto the format buffer. */
623 vfmtconcat (const char *fmt, va_list args)
627 int unused = fmtbuf.size - fmtbuf.len;
629 va_copy (vcopy, args);
631 tot = vsnprintf (&fmtbuf.buffer[fmtbuf.len], unused, fmt, args);
636 fmtbuf.size += tot * 2;
637 fmtbuf.buffer = xrealloc (fmtbuf.buffer, fmtbuf.size);
639 unused = fmtbuf.size - fmtbuf.len;
640 tot = vsnprintf (&fmtbuf.buffer[fmtbuf.len], unused, fmt, vcopy);
647 return fmtbuf.buffer;
651 fmtconcat (const char *fmt, ...)
656 va_start (args, fmt);
657 p = vfmtconcat (fmt, args);
663 /* Print a message on stdout. */
666 message (int prefix, const char *fmt, ...)
670 assert (fmt != NULL);
677 fmtconcat ("%s: ", program);
679 fmtconcat ("%s[%u]: ", program, makelevel);
682 va_start (args, fmt);
683 vfmtconcat (fmt, args);
688 outputs (0, fmtbuf.buffer);
691 /* Print an error message. */
694 error (const gmk_floc *flocp, const char *fmt, ...)
698 assert (fmt != NULL);
702 if (flocp && flocp->filenm)
703 fmtconcat ("%s:%lu: ", flocp->filenm, flocp->lineno);
704 else if (makelevel == 0)
705 fmtconcat ("%s: ", program);
707 fmtconcat ("%s[%u]: ", program, makelevel);
709 va_start (args, fmt);
710 vfmtconcat (fmt, args);
715 outputs (1, fmtbuf.buffer);
718 /* Print an error message and exit. */
721 fatal (const gmk_floc *flocp, const char *fmt, ...)
725 assert (fmt != NULL);
729 if (flocp && flocp->filenm)
730 fmtconcat ("%s:%lu: *** ", flocp->filenm, flocp->lineno);
731 else if (makelevel == 0)
732 fmtconcat ("%s: *** ", program);
734 fmtconcat ("%s[%u]: *** ", program, makelevel);
736 va_start (args, fmt);
737 vfmtconcat (fmt, args);
740 fmtconcat (_(". Stop.\n"));
741 outputs (1, fmtbuf.buffer);
746 /* Print an error message from errno. */
749 perror_with_name (const char *str, const char *name)
751 error (NILF, _("%s%s: %s"), str, name, strerror (errno));
754 /* Print an error message from errno and exit. */
757 pfatal_with_name (const char *name)
759 fatal (NILF, _("%s: %s"), name, strerror (errno));