Imported Upstream version 4.0
[platform/upstream/make.git] / output.c
1 /* Output to stdout / stderr for GNU make
2 Copyright (C) 2013 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
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 /* 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.  */
59 #ifdef __VMS
60 # define va_copy(_d, _s) ((_d) = (_s))
61 #endif
62 #ifdef _MSC_VER
63 # define va_copy(_d, _s) ((_d) = (_s))
64 # define snprintf msc_vsnprintf
65 static int
66 msc_vsnprintf (char *str, size_t size, const char *format, va_list ap)
67 {
68   int len = -1;
69
70   if (size > 0)
71     len = _vsnprintf_s (str, size, _TRUNCATE, format, ap);
72   if (len == -1)
73     len = _vscprintf (format, ap);
74
75   return len;
76 }
77 #endif
78
79 /* Write a string to the current STDOUT or STDERR.  */
80 static void
81 _outputs (struct output *out, int is_err, const char *msg)
82 {
83   if (! out || ! out->syncout)
84     {
85       FILE *f = is_err ? stderr : stdout;
86       fputs (msg, f);
87       fflush (f);
88     }
89   else
90     {
91       int fd = is_err ? out->err : out->out;
92       int len = strlen (msg);
93       int r;
94
95       EINTRLOOP (r, lseek (fd, 0, SEEK_END));
96       while (1)
97         {
98           EINTRLOOP (r, write (fd, msg, len));
99           if (r == len || r <= 0)
100             break;
101           len -= r;
102           msg += r;
103         }
104     }
105 }
106 \f
107 /* Write a message indicating that we've just entered or
108    left (according to ENTERING) the current directory.  */
109
110 static int
111 log_working_directory (int entering)
112 {
113   static char *buf = NULL;
114   static unsigned int len = 0;
115   unsigned int need;
116   const char *fmt;
117   char *p;
118
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);
123
124   /* Use entire sentences to give the translators a fighting chance.  */
125   if (makelevel == 0)
126     if (starting_directory == 0)
127       if (entering)
128         fmt = _("%s: Entering an unknown directory\n");
129       else
130         fmt = _("%s: Leaving an unknown directory\n");
131     else
132       if (entering)
133         fmt = _("%s: Entering directory '%s'\n");
134       else
135         fmt = _("%s: Leaving directory '%s'\n");
136   else
137     if (starting_directory == 0)
138       if (entering)
139         fmt = _("%s[%u]: Entering an unknown directory\n");
140       else
141         fmt = _("%s[%u]: Leaving an unknown directory\n");
142     else
143       if (entering)
144         fmt = _("%s[%u]: Entering directory '%s'\n");
145       else
146         fmt = _("%s[%u]: Leaving directory '%s'\n");
147
148   need += strlen (fmt);
149
150   if (need > len)
151     {
152       buf = xrealloc (buf, need);
153       len = need;
154     }
155
156   p = buf;
157   if (print_data_base_flag)
158     {
159       *(p++) = '#';
160       *(p++) = ' ';
161     }
162
163   if (makelevel == 0)
164     if (starting_directory == 0)
165       sprintf (p, fmt , program);
166     else
167       sprintf (p, fmt, program, starting_directory);
168   else if (starting_directory == 0)
169     sprintf (p, fmt, program, makelevel);
170   else
171     sprintf (p, fmt, program, makelevel, starting_directory);
172
173   _outputs (NULL, 0, buf);
174
175   return 1;
176 }
177
178 /* Set a file descriptor to be in O_APPEND mode.
179    If it fails, just ignore it.  */
180
181 static void
182 set_append_mode (int fd)
183 {
184 #if defined(F_GETFL) && defined(F_SETFL) && defined(O_APPEND)
185   int flags = fcntl (fd, F_GETFL, 0);
186   if (flags >= 0)
187     fcntl (fd, F_SETFL, flags | O_APPEND);
188 #endif
189 }
190 \f
191
192 #ifndef NO_OUTPUT_SYNC
193
194 /* Semaphore for use in -j mode with output_sync. */
195 static sync_handle_t sync_handle = -1;
196
197 #define FD_NOT_EMPTY(_f) ((_f) != OUTPUT_NONE && lseek ((_f), 0, SEEK_END) > 0)
198
199 /* Set up the sync handle.  Disables output_sync on error.  */
200 static int
201 sync_init ()
202 {
203   int combined_output = 0;
204
205 #ifdef WINDOWS32
206   if ((!STREAM_OK (stdout) && !STREAM_OK (stderr))
207       || (sync_handle = create_mutex ()) == -1)
208     {
209       perror_with_name ("output-sync suppressed: ", "stderr");
210       output_sync = 0;
211     }
212   else
213     {
214       combined_output = same_stream (stdout, stderr);
215       prepare_mutex_handle_string (sync_handle);
216     }
217
218 #else
219   if (STREAM_OK (stdout))
220     {
221       struct stat stbuf_o, stbuf_e;
222
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);
228     }
229   else if (STREAM_OK (stderr))
230     sync_handle = fileno (stderr);
231   else
232     {
233       perror_with_name ("output-sync suppressed: ", "stderr");
234       output_sync = 0;
235     }
236 #endif
237
238   return combined_output;
239 }
240
241 /* Support routine for output_sync() */
242 static void
243 pump_from_tmp (int from, FILE *to)
244 {
245   static char buffer[8192];
246
247 #ifdef WINDOWS32
248   int prev_mode;
249
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);
253 #endif
254
255   if (lseek (from, 0, SEEK_SET) == -1)
256     perror ("lseek()");
257
258   while (1)
259     {
260       int len;
261       EINTRLOOP (len, read (from, buffer, sizeof (buffer)));
262       if (len < 0)
263         perror ("read()");
264       if (len <= 0)
265         break;
266       if (fwrite (buffer, len, 1, to) < 1)
267         perror ("fwrite()");
268     }
269
270 #ifdef WINDOWS32
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);
274 #endif
275 }
276
277 /* Obtain the lock for writing output.  */
278 static void *
279 acquire_semaphore (void)
280 {
281   static struct flock fl;
282
283   fl.l_type = F_WRLCK;
284   fl.l_whence = SEEK_SET;
285   fl.l_start = 0;
286   fl.l_len = 1;
287   if (fcntl (sync_handle, F_SETLKW, &fl) != -1)
288     return &fl;
289   perror ("fcntl()");
290   return NULL;
291 }
292
293 /* Release the lock for writing output.  */
294 static void
295 release_semaphore (void *sem)
296 {
297   struct flock *flp = (struct flock *)sem;
298   flp->l_type = F_UNLCK;
299   if (fcntl (sync_handle, F_SETLKW, flp) == -1)
300     perror ("fcntl()");
301 }
302
303 /* Returns a file descriptor to a temporary file.  The file is automatically
304    closed/deleted on exit.  Don't use a FILE* stream.  */
305 int
306 output_tmpfd ()
307 {
308   int fd = -1;
309   FILE *tfile = tmpfile ();
310
311   if (! tfile)
312     pfatal_with_name ("tmpfile");
313
314   /* Create a duplicate so we can close the stream.  */
315   fd = dup (fileno (tfile));
316   if (fd < 0)
317     pfatal_with_name ("dup");
318
319   fclose (tfile);
320
321   set_append_mode (fd);
322
323   return fd;
324 }
325
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.  */
330 static void
331 setup_tmpfile (struct output *out)
332 {
333   /* Is make's stdout going to the same place as stderr?  */
334   static int combined_output = -1;
335
336   if (combined_output < 0)
337     combined_output = sync_init ();
338
339   if (STREAM_OK (stdout))
340     {
341       int fd = output_tmpfd ();
342       if (fd < 0)
343         goto error;
344       CLOSE_ON_EXEC (fd);
345       out->out = fd;
346     }
347
348   if (STREAM_OK (stderr))
349     {
350       if (out->out != OUTPUT_NONE && combined_output)
351         out->err = out->out;
352       else
353         {
354           int fd = output_tmpfd ();
355           if (fd < 0)
356             goto error;
357           CLOSE_ON_EXEC (fd);
358           out->err = fd;
359         }
360     }
361
362   return;
363
364   /* If we failed to create a temp file, disable output sync going forward.  */
365  error:
366   output_close (out);
367   output_sync = 0;
368 }
369
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. */
374
375 void
376 output_dump (struct output *out)
377 {
378   int outfd_not_empty = FD_NOT_EMPTY (out->out);
379   int errfd_not_empty = FD_NOT_EMPTY (out->err);
380
381   if (outfd_not_empty || errfd_not_empty)
382     {
383       int traced = 0;
384
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 ();
389
390       /* Log the working directory for this dump.  */
391       if (print_directory_flag && output_sync != OUTPUT_SYNC_RECURSE)
392         traced = log_working_directory (1);
393
394       if (outfd_not_empty)
395         pump_from_tmp (out->out, stdout);
396       if (errfd_not_empty && out->err != out->out)
397         pump_from_tmp (out->err, stderr);
398
399       if (traced)
400         log_working_directory (0);
401
402       /* Exit the critical section.  */
403       if (sem)
404         release_semaphore (sem);
405
406       /* Truncate and reset the output, in case we use it again.  */
407       if (out->out != OUTPUT_NONE)
408         {
409           int e;
410           lseek (out->out, 0, SEEK_SET);
411           EINTRLOOP (e, ftruncate (out->out, 0));
412         }
413       if (out->err != OUTPUT_NONE && out->err != out->out)
414         {
415           int e;
416           lseek (out->err, 0, SEEK_SET);
417           EINTRLOOP (e, ftruncate (out->err, 0));
418         }
419     }
420 }
421 #endif /* NO_OUTPUT_SYNC */
422 \f
423
424 /* Provide support for temporary files.  */
425
426 #ifndef HAVE_STDLIB_H
427 # ifdef HAVE_MKSTEMP
428 int mkstemp (char *template);
429 # else
430 char *mktemp (char *template);
431 # endif
432 #endif
433
434 FILE *
435 output_tmpfile (char **name, const char *template)
436 {
437 #ifdef HAVE_FDOPEN
438   int fd;
439 #endif
440
441 #if defined HAVE_MKSTEMP || defined HAVE_MKTEMP
442 # define TEMPLATE_LEN   strlen (template)
443 #else
444 # define TEMPLATE_LEN   L_tmpnam
445 #endif
446   *name = xmalloc (TEMPLATE_LEN + 1);
447   strcpy (*name, template);
448
449 #if defined HAVE_MKSTEMP && defined HAVE_FDOPEN
450   /* It's safest to use mkstemp(), if we can.  */
451   fd = mkstemp (*name);
452   if (fd == -1)
453     return 0;
454   return fdopen (fd, "w");
455 #else
456 # ifdef HAVE_MKTEMP
457   (void) mktemp (*name);
458 # else
459   (void) tmpnam (*name);
460 # endif
461
462 # ifdef HAVE_FDOPEN
463   /* Can't use mkstemp(), but guard against a race condition.  */
464   fd = open (*name, O_CREAT|O_EXCL|O_WRONLY, 0600);
465   if (fd == -1)
466     return 0;
467   return fdopen (fd, "w");
468 # else
469   /* Not secure, but what can we do?  */
470   return fopen (*name, "w");
471 # endif
472 #endif
473 }
474 \f
475
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
479    gnulib directly.
480
481    This is called only through atexit(), which means die() has already been
482    invoked.  So, call exit() here directly.  Apparently that works...?
483 */
484
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.
497
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.
501
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.  */
505
506 static void
507 close_stdout (void)
508 {
509   int prev_fail = ferror (stdout);
510   int fclose_fail = fclose (stdout);
511
512   if (prev_fail || fclose_fail)
513     {
514       if (fclose_fail)
515         error (NILF, _("write error: %s"), strerror (errno));
516       else
517         error (NILF, _("write error"));
518       exit (EXIT_FAILURE);
519     }
520 }
521 \f
522
523 void
524 output_init (struct output *out)
525 {
526   if (out)
527     {
528       out->out = out->err = OUTPUT_NONE;
529       out->syncout = !!output_sync;
530       return;
531     }
532
533   /* Configure this instance of make.  Be sure stdout is line-buffered.  */
534
535 #ifdef HAVE_SETVBUF
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
543   setlinebuf (stdout);
544 #endif  /* setlinebuf missing.  */
545
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));
550
551 #ifdef HAVE_ATEXIT
552   if (STREAM_OK (stdout))
553     atexit (close_stdout);
554 #endif
555 }
556
557 void
558 output_close (struct output *out)
559 {
560   if (! out)
561     {
562       if (stdio_traced)
563         log_working_directory (0);
564       return;
565     }
566
567 #ifndef NO_OUTPUT_SYNC
568   output_dump (out);
569 #endif
570
571   if (out->out >= 0)
572     close (out->out);
573   if (out->err >= 0 && out->err != out->out)
574     close (out->err);
575
576   output_init (out);
577 }
578
579 /* We're about to generate output: be sure it's set up.  */
580 void
581 output_start ()
582 {
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);
588 #endif
589
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);
595 }
596
597 void
598 outputs (int is_err, const char *msg)
599 {
600   if (! msg || *msg == '\0')
601     return;
602
603   output_start ();
604
605   _outputs (output_context, is_err, msg);
606 }
607 \f
608
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.  */
613
614 static struct fmtstring
615   {
616     char *buffer;
617     unsigned int size;
618     unsigned int len;
619   } fmtbuf = { NULL, 0, 0 };
620
621 /* Concatenate a formatted string onto the format buffer.  */
622 static const char *
623 vfmtconcat (const char *fmt, va_list args)
624 {
625   va_list vcopy;
626   int tot;
627   int unused = fmtbuf.size - fmtbuf.len;
628
629   va_copy (vcopy, args);
630
631   tot = vsnprintf (&fmtbuf.buffer[fmtbuf.len], unused, fmt, args);
632   assert (tot >= 0);
633
634   if (tot >= unused)
635     {
636       fmtbuf.size += tot * 2;
637       fmtbuf.buffer = xrealloc (fmtbuf.buffer, fmtbuf.size);
638
639       unused = fmtbuf.size - fmtbuf.len;
640       tot = vsnprintf (&fmtbuf.buffer[fmtbuf.len], unused, fmt, vcopy);
641     }
642
643   va_end (vcopy);
644
645   fmtbuf.len += tot;
646
647   return fmtbuf.buffer;
648 }
649
650 static const char *
651 fmtconcat (const char *fmt, ...)
652 {
653   const char *p;
654   va_list args;
655
656   va_start (args, fmt);
657   p = vfmtconcat (fmt, args);
658   va_end (args);
659
660   return p;
661 }
662 \f
663 /* Print a message on stdout.  */
664
665 void
666 message (int prefix, const char *fmt, ...)
667 {
668   va_list args;
669
670   assert (fmt != NULL);
671
672   fmtbuf.len = 0;
673
674   if (prefix)
675     {
676       if (makelevel == 0)
677         fmtconcat ("%s: ", program);
678       else
679         fmtconcat ("%s[%u]: ", program, makelevel);
680     }
681
682   va_start (args, fmt);
683   vfmtconcat (fmt, args);
684   va_end (args);
685
686   fmtconcat ("\n");
687
688   outputs (0, fmtbuf.buffer);
689 }
690
691 /* Print an error message.  */
692
693 void
694 error (const gmk_floc *flocp, const char *fmt, ...)
695 {
696   va_list args;
697
698   assert (fmt != NULL);
699
700   fmtbuf.len = 0;
701
702   if (flocp && flocp->filenm)
703     fmtconcat ("%s:%lu: ", flocp->filenm, flocp->lineno);
704   else if (makelevel == 0)
705     fmtconcat ("%s: ", program);
706   else
707     fmtconcat ("%s[%u]: ", program, makelevel);
708
709   va_start (args, fmt);
710   vfmtconcat (fmt, args);
711   va_end (args);
712
713   fmtconcat ("\n");
714
715   outputs (1, fmtbuf.buffer);
716 }
717
718 /* Print an error message and exit.  */
719
720 void
721 fatal (const gmk_floc *flocp, const char *fmt, ...)
722 {
723   va_list args;
724
725   assert (fmt != NULL);
726
727   fmtbuf.len = 0;
728
729   if (flocp && flocp->filenm)
730     fmtconcat ("%s:%lu: *** ", flocp->filenm, flocp->lineno);
731   else if (makelevel == 0)
732     fmtconcat ("%s: *** ", program);
733   else
734     fmtconcat ("%s[%u]: *** ", program, makelevel);
735
736   va_start (args, fmt);
737   vfmtconcat (fmt, args);
738   va_end (args);
739
740   fmtconcat (_(".  Stop.\n"));
741   outputs (1, fmtbuf.buffer);
742
743   die (2);
744 }
745
746 /* Print an error message from errno.  */
747
748 void
749 perror_with_name (const char *str, const char *name)
750 {
751   error (NILF, _("%s%s: %s"), str, name, strerror (errno));
752 }
753
754 /* Print an error message from errno and exit.  */
755
756 void
757 pfatal_with_name (const char *name)
758 {
759   fatal (NILF, _("%s: %s"), name, strerror (errno));
760
761   /* NOTREACHED */
762 }