65182c4b837d995bb92e64972f2fcd954380e66f
[platform/upstream/make.git] / output.c
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.
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 "job.h"
19
20 /* GNU make no longer supports pre-ANSI89 environments.  */
21
22 #include <assert.h>
23 #include <stdio.h>
24 #include <stdarg.h>
25
26 #ifdef HAVE_UNISTD_H
27 # include <unistd.h>
28 #endif
29
30 #ifdef HAVE_FCNTL_H
31 # include <fcntl.h>
32 #else
33 # include <sys/file.h>
34 #endif
35
36 #ifdef WINDOWS32
37 # include <windows.h>
38 # include <io.h>
39 # include "sub_proc.h"
40 #endif /* WINDOWS32 */
41
42 struct output *output_context = NULL;
43 unsigned int stdio_traced = 0;
44
45 #define OUTPUT_NONE (-1)
46
47 #define OUTPUT_ISSET(_out) ((_out)->out >= 0 || (_out)->err >= 0)
48
49 #ifdef HAVE_FCNTL_H
50 # define STREAM_OK(_s) ((fcntl (fileno (_s), F_GETFD) != -1) || (errno != EBADF))
51 #else
52 # define STREAM_OK(_s) 1
53 #endif
54
55 /* Write a string to the current STDOUT or STDERR.  */
56 static void
57 _outputs (struct output *out, int is_err, const char *msg)
58 {
59   if (! out || ! out->syncout)
60     {
61       FILE *f = is_err ? stderr : stdout;
62       fputs (msg, f);
63       fflush (f);
64     }
65   else
66     {
67       int fd = is_err ? out->err : out->out;
68       int len = strlen (msg);
69       int r;
70
71       EINTRLOOP (r, lseek (fd, 0, SEEK_END));
72       while (1)
73         {
74           EINTRLOOP (r, write (fd, msg, len));
75           if (r == len || r <= 0)
76             break;
77           len -= r;
78           msg += r;
79         }
80     }
81 }
82 \f
83 /* Write a message indicating that we've just entered or
84    left (according to ENTERING) the current directory.  */
85
86 static int
87 log_working_directory (int entering)
88 {
89   static char *buf = NULL;
90   static unsigned int len = 0;
91   unsigned int need;
92   const char *fmt;
93   char *p;
94
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);
99
100   /* Use entire sentences to give the translators a fighting chance.  */
101   if (makelevel == 0)
102     if (starting_directory == 0)
103       if (entering)
104         fmt = _("%s: Entering an unknown directory\n");
105       else
106         fmt = _("%s: Leaving an unknown directory\n");
107     else
108       if (entering)
109         fmt = _("%s: Entering directory '%s'\n");
110       else
111         fmt = _("%s: Leaving directory '%s'\n");
112   else
113     if (starting_directory == 0)
114       if (entering)
115         fmt = _("%s[%u]: Entering an unknown directory\n");
116       else
117         fmt = _("%s[%u]: Leaving an unknown directory\n");
118     else
119       if (entering)
120         fmt = _("%s[%u]: Entering directory '%s'\n");
121       else
122         fmt = _("%s[%u]: Leaving directory '%s'\n");
123
124   need += strlen (fmt);
125
126   if (need > len)
127     {
128       buf = xrealloc (buf, need);
129       len = need;
130     }
131
132   p = buf;
133   if (print_data_base_flag)
134     {
135       *(p++) = '#';
136       *(p++) = ' ';
137     }
138
139   if (makelevel == 0)
140     if (starting_directory == 0)
141       sprintf (p, fmt , program);
142     else
143       sprintf (p, fmt, program, starting_directory);
144   else if (starting_directory == 0)
145     sprintf (p, fmt, program, makelevel);
146   else
147     sprintf (p, fmt, program, makelevel, starting_directory);
148
149   _outputs (NULL, 0, buf);
150
151   return 1;
152 }
153
154 /* Set a file descriptor to be in O_APPEND mode.
155    If it fails, just ignore it.  */
156
157 static void
158 set_append_mode (int fd)
159 {
160 #if defined(F_GETFL) && defined(F_SETFL) && defined(O_APPEND)
161   int flags = fcntl (fd, F_GETFL, 0);
162   if (flags >= 0)
163     fcntl (fd, F_SETFL, flags | O_APPEND);
164 #endif
165 }
166 \f
167
168 #ifndef NO_OUTPUT_SYNC
169
170 /* Semaphore for use in -j mode with output_sync. */
171 static sync_handle_t sync_handle = -1;
172
173 #define FD_NOT_EMPTY(_f) ((_f) != OUTPUT_NONE && lseek ((_f), 0, SEEK_END) > 0)
174
175 /* Set up the sync handle.  Disables output_sync on error.  */
176 static int
177 sync_init (void)
178 {
179   int combined_output = 0;
180
181 #ifdef WINDOWS32
182   if ((!STREAM_OK (stdout) && !STREAM_OK (stderr))
183       || (sync_handle = create_mutex ()) == -1)
184     {
185       perror_with_name ("output-sync suppressed: ", "stderr");
186       output_sync = 0;
187     }
188   else
189     {
190       combined_output = same_stream (stdout, stderr);
191       prepare_mutex_handle_string (sync_handle);
192     }
193
194 #else
195   if (STREAM_OK (stdout))
196     {
197       struct stat stbuf_o, stbuf_e;
198
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);
204     }
205   else if (STREAM_OK (stderr))
206     sync_handle = fileno (stderr);
207   else
208     {
209       perror_with_name ("output-sync suppressed: ", "stderr");
210       output_sync = 0;
211     }
212 #endif
213
214   return combined_output;
215 }
216
217 /* Support routine for output_sync() */
218 static void
219 pump_from_tmp (int from, FILE *to)
220 {
221   static char buffer[8192];
222
223 #ifdef WINDOWS32
224   int prev_mode;
225
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);
229 #endif
230
231   if (lseek (from, 0, SEEK_SET) == -1)
232     perror ("lseek()");
233
234   while (1)
235     {
236       int len;
237       EINTRLOOP (len, read (from, buffer, sizeof (buffer)));
238       if (len < 0)
239         perror ("read()");
240       if (len <= 0)
241         break;
242       if (fwrite (buffer, len, 1, to) < 1)
243         {
244           perror ("fwrite()");
245           break;
246         }
247       fflush (to);
248     }
249
250 #ifdef WINDOWS32
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);
254 #endif
255 }
256
257 /* Obtain the lock for writing output.  */
258 static void *
259 acquire_semaphore (void)
260 {
261   static struct flock fl;
262
263   fl.l_type = F_WRLCK;
264   fl.l_whence = SEEK_SET;
265   fl.l_start = 0;
266   fl.l_len = 1;
267   if (fcntl (sync_handle, F_SETLKW, &fl) != -1)
268     return &fl;
269   perror ("fcntl()");
270   return NULL;
271 }
272
273 /* Release the lock for writing output.  */
274 static void
275 release_semaphore (void *sem)
276 {
277   struct flock *flp = (struct flock *)sem;
278   flp->l_type = F_UNLCK;
279   if (fcntl (sync_handle, F_SETLKW, flp) == -1)
280     perror ("fcntl()");
281 }
282
283 /* Returns a file descriptor to a temporary file.  The file is automatically
284    closed/deleted on exit.  Don't use a FILE* stream.  */
285 int
286 output_tmpfd (void)
287 {
288   int fd = -1;
289   FILE *tfile = tmpfile ();
290
291   if (! tfile)
292     pfatal_with_name ("tmpfile");
293
294   /* Create a duplicate so we can close the stream.  */
295   fd = dup (fileno (tfile));
296   if (fd < 0)
297     pfatal_with_name ("dup");
298
299   fclose (tfile);
300
301   set_append_mode (fd);
302
303   return fd;
304 }
305
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.  */
310 static void
311 setup_tmpfile (struct output *out)
312 {
313   /* Is make's stdout going to the same place as stderr?  */
314   static int combined_output = -1;
315
316   if (combined_output < 0)
317     combined_output = sync_init ();
318
319   if (STREAM_OK (stdout))
320     {
321       int fd = output_tmpfd ();
322       if (fd < 0)
323         goto error;
324       CLOSE_ON_EXEC (fd);
325       out->out = fd;
326     }
327
328   if (STREAM_OK (stderr))
329     {
330       if (out->out != OUTPUT_NONE && combined_output)
331         out->err = out->out;
332       else
333         {
334           int fd = output_tmpfd ();
335           if (fd < 0)
336             goto error;
337           CLOSE_ON_EXEC (fd);
338           out->err = fd;
339         }
340     }
341
342   return;
343
344   /* If we failed to create a temp file, disable output sync going forward.  */
345  error:
346   output_close (out);
347   output_sync = OUTPUT_SYNC_NONE;
348 }
349
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. */
354
355 void
356 output_dump (struct output *out)
357 {
358   int outfd_not_empty = FD_NOT_EMPTY (out->out);
359   int errfd_not_empty = FD_NOT_EMPTY (out->err);
360
361   if (outfd_not_empty || errfd_not_empty)
362     {
363       int traced = 0;
364
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 ();
369
370       /* Log the working directory for this dump.  */
371       if (print_directory_flag && output_sync != OUTPUT_SYNC_RECURSE)
372         traced = log_working_directory (1);
373
374       if (outfd_not_empty)
375         pump_from_tmp (out->out, stdout);
376       if (errfd_not_empty && out->err != out->out)
377         pump_from_tmp (out->err, stderr);
378
379       if (traced)
380         log_working_directory (0);
381
382       /* Exit the critical section.  */
383       if (sem)
384         release_semaphore (sem);
385
386       /* Truncate and reset the output, in case we use it again.  */
387       if (out->out != OUTPUT_NONE)
388         {
389           int e;
390           lseek (out->out, 0, SEEK_SET);
391           EINTRLOOP (e, ftruncate (out->out, 0));
392         }
393       if (out->err != OUTPUT_NONE && out->err != out->out)
394         {
395           int e;
396           lseek (out->err, 0, SEEK_SET);
397           EINTRLOOP (e, ftruncate (out->err, 0));
398         }
399     }
400 }
401 #endif /* NO_OUTPUT_SYNC */
402 \f
403
404 /* Provide support for temporary files.  */
405
406 #ifndef HAVE_STDLIB_H
407 # ifdef HAVE_MKSTEMP
408 int mkstemp (char *template);
409 # else
410 char *mktemp (char *template);
411 # endif
412 #endif
413
414 FILE *
415 output_tmpfile (char **name, const char *template)
416 {
417 #ifdef HAVE_FDOPEN
418   int fd;
419 #endif
420
421 #if defined HAVE_MKSTEMP || defined HAVE_MKTEMP
422 # define TEMPLATE_LEN   strlen (template)
423 #else
424 # define TEMPLATE_LEN   L_tmpnam
425 #endif
426   *name = xmalloc (TEMPLATE_LEN + 1);
427   strcpy (*name, template);
428
429 #if defined HAVE_MKSTEMP && defined HAVE_FDOPEN
430   /* It's safest to use mkstemp(), if we can.  */
431   fd = mkstemp (*name);
432   if (fd == -1)
433     return 0;
434   return fdopen (fd, "w");
435 #else
436 # ifdef HAVE_MKTEMP
437   (void) mktemp (*name);
438 # else
439   (void) tmpnam (*name);
440 # endif
441
442 # ifdef HAVE_FDOPEN
443   /* Can't use mkstemp(), but guard against a race condition.  */
444   EINTRLOOP (fd, open (*name, O_CREAT|O_EXCL|O_WRONLY, 0600));
445   if (fd == -1)
446     return 0;
447   return fdopen (fd, "w");
448 # else
449   /* Not secure, but what can we do?  */
450   return fopen (*name, "w");
451 # endif
452 #endif
453 }
454 \f
455
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
459    gnulib directly.
460
461    This is called only through atexit(), which means die() has already been
462    invoked.  So, call exit() here directly.  Apparently that works...?
463 */
464
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.
477
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.
481
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.  */
485
486 static void
487 close_stdout (void)
488 {
489   int prev_fail = ferror (stdout);
490   int fclose_fail = fclose (stdout);
491
492   if (prev_fail || fclose_fail)
493     {
494       if (fclose_fail)
495         perror_with_name (_("write error: stdout"), "");
496       else
497         O (error, NILF, _("write error: stdout"));
498       exit (MAKE_TROUBLE);
499     }
500 }
501 \f
502
503 void
504 output_init (struct output *out)
505 {
506   if (out)
507     {
508       out->out = out->err = OUTPUT_NONE;
509       out->syncout = !!output_sync;
510       return;
511     }
512
513   /* Configure this instance of make.  Be sure stdout is line-buffered.  */
514
515 #ifdef HAVE_SETVBUF
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
523   setlinebuf (stdout);
524 #endif  /* setlinebuf missing.  */
525
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));
530
531 #ifdef HAVE_ATEXIT
532   if (STREAM_OK (stdout))
533     atexit (close_stdout);
534 #endif
535 }
536
537 void
538 output_close (struct output *out)
539 {
540   if (! out)
541     {
542       if (stdio_traced)
543         log_working_directory (0);
544       return;
545     }
546
547 #ifndef NO_OUTPUT_SYNC
548   output_dump (out);
549 #endif
550
551   if (out->out >= 0)
552     close (out->out);
553   if (out->err >= 0 && out->err != out->out)
554     close (out->err);
555
556   output_init (out);
557 }
558
559 /* We're about to generate output: be sure it's set up.  */
560 void
561 output_start (void)
562 {
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);
568 #endif
569
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);
575 }
576
577 void
578 outputs (int is_err, const char *msg)
579 {
580   if (! msg || *msg == '\0')
581     return;
582
583   output_start ();
584
585   _outputs (output_context, is_err, msg);
586 }
587 \f
588
589 static struct fmtstring
590   {
591     char *buffer;
592     size_t size;
593   } fmtbuf = { NULL, 0 };
594
595 static char *
596 get_buffer (size_t need)
597 {
598   /* Make sure we have room.  NEED includes space for \0.  */
599   if (need > fmtbuf.size)
600     {
601       fmtbuf.size += need * 2;
602       fmtbuf.buffer = xrealloc (fmtbuf.buffer, fmtbuf.size);
603     }
604
605   fmtbuf.buffer[need-1] = '\0';
606
607   return fmtbuf.buffer;
608 }
609
610 /* Print a message on stdout.  */
611
612 void
613 message (int prefix, size_t len, const char *fmt, ...)
614 {
615   va_list args;
616   char *p;
617
618   len += strlen (fmt) + strlen (program) + INTSTR_LENGTH + 4 + 1 + 1;
619   p = get_buffer (len);
620
621   if (prefix)
622     {
623       if (makelevel == 0)
624         sprintf (p, "%s: ", program);
625       else
626         sprintf (p, "%s[%u]: ", program, makelevel);
627       p += strlen (p);
628     }
629
630   va_start (args, fmt);
631   vsprintf (p, fmt, args);
632   va_end (args);
633
634   strcat (p, "\n");
635
636   assert (fmtbuf.buffer[len-1] == '\0');
637   outputs (0, fmtbuf.buffer);
638 }
639
640 /* Print an error message.  */
641
642 void
643 error (const floc *flocp, size_t len, const char *fmt, ...)
644 {
645   va_list args;
646   char *p;
647
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);
652
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);
657   else
658     sprintf (p, "%s[%u]: ", program, makelevel);
659   p += strlen (p);
660
661   va_start (args, fmt);
662   vsprintf (p, fmt, args);
663   va_end (args);
664
665   strcat (p, "\n");
666
667   assert (fmtbuf.buffer[len-1] == '\0');
668   outputs (1, fmtbuf.buffer);
669 }
670
671 /* Print an error message and exit.  */
672
673 void
674 fatal (const floc *flocp, size_t len, const char *fmt, ...)
675 {
676   va_list args;
677   const char *stop = _(".  Stop.\n");
678   char *p;
679
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);
684
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);
689   else
690     sprintf (p, "%s[%u]: *** ", program, makelevel);
691   p += strlen (p);
692
693   va_start (args, fmt);
694   vsprintf (p, fmt, args);
695   va_end (args);
696
697   strcat (p, stop);
698
699   assert (fmtbuf.buffer[len-1] == '\0');
700   outputs (1, fmtbuf.buffer);
701
702   die (MAKE_FAILURE);
703 }
704
705 /* Print an error message from errno.  */
706
707 void
708 perror_with_name (const char *str, const char *name)
709 {
710   const char *err = strerror (errno);
711   OSSS (error, NILF, _("%s%s: %s"), str, name, err);
712 }
713
714 /* Print an error message from errno and exit.  */
715
716 void
717 pfatal_with_name (const char *name)
718 {
719   const char *err = strerror (errno);
720   OSS (fatal, NILF, _("%s: %s"), name, err);
721
722   /* NOTREACHED */
723 }