1 /* Copyright (C) 2008-2016 Free Software Foundation, Inc.
2 
3 This file is part of GCC.
4 
5 GCC is free software; you can redistribute it and/or modify it under
6 the terms of the GNU General Public License as published by the Free
7 Software Foundation; either version 3, or (at your option) any later
8 version.
9 
10 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13 for more details.
14 
15 You should have received a copy of the GNU General Public License
16 along with GCC; see the file COPYING3.  If not see
17 <http://www.gnu.org/licenses/>.  */
18 
19 #include "config.h"
20 #include "system.h"
21 #include "coretypes.h"
22 #include "target.h"
23 #include "gfortran.h"
24 #include "diagnostic.h"
25 
26 
27 #include "toplev.h"
28 
29 #include "../../libcpp/internal.h"
30 #include "cpp.h"
31 #include "incpath.h"
32 #include "cppbuiltin.h"
33 #include "mkdeps.h"
34 
35 #ifndef TARGET_SYSTEM_ROOT
36 # define TARGET_SYSTEM_ROOT NULL
37 #endif
38 
39 #ifndef TARGET_CPU_CPP_BUILTINS
40 # define TARGET_CPU_CPP_BUILTINS()
41 #endif
42 
43 #ifndef TARGET_OS_CPP_BUILTINS
44 # define TARGET_OS_CPP_BUILTINS()
45 #endif
46 
47 #ifndef TARGET_OBJFMT_CPP_BUILTINS
48 # define TARGET_OBJFMT_CPP_BUILTINS()
49 #endif
50 
51 
52 /* Holds switches parsed by gfc_cpp_handle_option (), but whose
53    handling is deferred to gfc_cpp_init ().  */
54 typedef struct
55 {
56     enum opt_code code;
57     const char *arg;
58 }
59 gfc_cpp_deferred_opt_t;
60 
61 
62 /* Defined and undefined macros being queued for output with -dU at
63    the next newline.  */
64 typedef struct gfc_cpp_macro_queue
65 {
66   struct gfc_cpp_macro_queue *next;	/* Next macro in the list.  */
67   char *macro;				/* The name of the macro if not
68 					   defined, the full definition if
69 					   defined.  */
70 } gfc_cpp_macro_queue;
71 static gfc_cpp_macro_queue *cpp_define_queue, *cpp_undefine_queue;
72 
73 struct gfc_cpp_option_data
74 {
75   /* Argument of -cpp, implied by SPEC;
76      if NULL, preprocessing disabled.  */
77   const char *temporary_filename;
78 
79   const char *output_filename;          /* -o <arg>  */
80   int preprocess_only;                  /* -E  */
81   int discard_comments;                 /* -C  */
82   int discard_comments_in_macro_exp;    /* -CC  */
83   int print_include_names;              /* -H  */
84   int no_line_commands;                 /* -P  */
85   char dump_macros;                     /* -d[DMNU]  */
86   int dump_includes;                    /* -dI  */
87   int working_directory;                /* -fworking-directory  */
88   int no_predefined;                    /* -undef */
89   int standard_include_paths;           /* -nostdinc */
90   int verbose;                          /* -v */
91   int deps;                             /* -M */
92   int deps_skip_system;                 /* -MM */
93   const char *deps_filename;            /* -M[M]D */
94   const char *deps_filename_user;       /* -MF <arg> */
95   int deps_missing_are_generated;       /* -MG */
96   int deps_phony;                       /* -MP */
97   int warn_date_time;                   /* -Wdate-time */
98 
99   const char *multilib;                 /* -imultilib <dir>  */
100   const char *prefix;                   /* -iprefix <dir>  */
101   const char *sysroot;                  /* -isysroot <dir>  */
102 
103   /* Options whose handling needs to be deferred until the
104      appropriate cpp-objects are created:
105       -A predicate=answer
106       -D <macro>[=<val>]
107       -U <macro>  */
108   gfc_cpp_deferred_opt_t *deferred_opt;
109   int deferred_opt_count;
110 }
111 gfc_cpp_option;
112 
113 /* Structures used with libcpp:  */
114 static cpp_options *cpp_option = NULL;
115 static cpp_reader *cpp_in = NULL;
116 
117 /* Encapsulates state used to convert a stream of cpp-tokens into
118    a text file.  */
119 static struct
120 {
121   FILE *outf;			/* Stream to write to.  */
122   const cpp_token *prev;	/* Previous token.  */
123   const cpp_token *source;	/* Source token for spacing.  */
124   int src_line;			/* Line number currently being written.  */
125   unsigned char printed;	/* Nonzero if something output at line.  */
126   bool first_time;		/* cb_file_change hasn't been called yet.  */
127 } print;
128 
129 /* General output routines.  */
130 static void scan_translation_unit (cpp_reader *);
131 static void scan_translation_unit_trad (cpp_reader *);
132 
133 /* Callback routines for the parser. Most of these are active only
134    in specific modes.  */
135 static void cb_file_change (cpp_reader *, const line_map_ordinary *);
136 static void cb_line_change (cpp_reader *, const cpp_token *, int);
137 static void cb_define (cpp_reader *, source_location, cpp_hashnode *);
138 static void cb_undef (cpp_reader *, source_location, cpp_hashnode *);
139 static void cb_def_pragma (cpp_reader *, source_location);
140 static void cb_include (cpp_reader *, source_location, const unsigned char *,
141 			const char *, int, const cpp_token **);
142 static void cb_ident (cpp_reader *, source_location, const cpp_string *);
143 static void cb_used_define (cpp_reader *, source_location, cpp_hashnode *);
144 static void cb_used_undef (cpp_reader *, source_location, cpp_hashnode *);
145 static bool cb_cpp_error (cpp_reader *, int, int, rich_location *,
146 			  const char *, va_list *)
147      ATTRIBUTE_GCC_DIAG(5,0);
148 void pp_dir_change (cpp_reader *, const char *);
149 
150 static int dump_macro (cpp_reader *, cpp_hashnode *, void *);
151 static void dump_queued_macros (cpp_reader *);
152 
153 
154 static void
cpp_define_builtins(cpp_reader * pfile)155 cpp_define_builtins (cpp_reader *pfile)
156 {
157   /* Initialize CPP built-ins; '1' corresponds to 'flag_hosted'
158      in C, defines __STDC_HOSTED__?!  */
159   cpp_init_builtins (pfile, 0);
160 
161   /* Initialize GFORTRAN specific builtins.
162      These are documented.  */
163   define_language_independent_builtin_macros (pfile);
164   cpp_define (pfile, "__GFORTRAN__=1");
165   cpp_define (pfile, "_LANGUAGE_FORTRAN=1");
166 
167   if (flag_openacc)
168     cpp_define (pfile, "_OPENACC=201306");
169 
170   if (flag_openmp)
171     cpp_define (pfile, "_OPENMP=201307");
172 
173   /* The defines below are necessary for the TARGET_* macros.
174 
175      FIXME:  Note that builtin_define_std() actually is a function
176      in c-cppbuiltin.c which uses flags undefined for Fortran.
177      Let's skip this for now. If needed, one needs to look into it
178      once more.  */
179 
180 # define builtin_define(TXT) cpp_define (pfile, TXT)
181 # define builtin_define_std(TXT)
182 # define builtin_assert(TXT) cpp_assert (pfile, TXT)
183 
184   /* FIXME: Pandora's Box
185     Using the macros below results in multiple breakages:
186      - mingw will fail to compile this file as dependent macros
187        assume to be used in c-cppbuiltin.c only. Further, they use
188        flags only valid/defined in C (same as noted above).
189        [config/i386/mingw32.h, config/i386/cygming.h]
190      - other platforms (not as popular) break similarly
191        [grep for 'builtin_define_with_int_value' in gcc/config/]
192 
193   TARGET_CPU_CPP_BUILTINS ();
194   TARGET_OS_CPP_BUILTINS ();
195   TARGET_OBJFMT_CPP_BUILTINS (); */
196 
197 #undef builtin_define
198 #undef builtin_define_std
199 #undef builtin_assert
200 }
201 
202 bool
gfc_cpp_enabled(void)203 gfc_cpp_enabled (void)
204 {
205   return gfc_cpp_option.temporary_filename != NULL;
206 }
207 
208 bool
gfc_cpp_preprocess_only(void)209 gfc_cpp_preprocess_only (void)
210 {
211   return gfc_cpp_option.preprocess_only;
212 }
213 
214 bool
gfc_cpp_makedep(void)215 gfc_cpp_makedep (void)
216 {
217   return gfc_cpp_option.deps;
218 }
219 
220 void
gfc_cpp_add_dep(const char * name,bool system)221 gfc_cpp_add_dep (const char *name, bool system)
222 {
223   if (!gfc_cpp_option.deps_skip_system || !system)
224     deps_add_dep (cpp_get_deps (cpp_in), name);
225 }
226 
227 void
gfc_cpp_add_target(const char * name)228 gfc_cpp_add_target (const char *name)
229 {
230   deps_add_target (cpp_get_deps (cpp_in), name, 0);
231 }
232 
233 
234 const char *
gfc_cpp_temporary_file(void)235 gfc_cpp_temporary_file (void)
236 {
237   return gfc_cpp_option.temporary_filename;
238 }
239 
240 void
gfc_cpp_init_options(unsigned int decoded_options_count,struct cl_decoded_option * decoded_options ATTRIBUTE_UNUSED)241 gfc_cpp_init_options (unsigned int decoded_options_count,
242 		      struct cl_decoded_option *decoded_options ATTRIBUTE_UNUSED)
243 {
244   /* Do not create any objects from libcpp here. If no
245      preprocessing is requested, this would be wasted
246      time and effort.
247 
248      See gfc_cpp_post_options() instead.  */
249 
250   gfc_cpp_option.temporary_filename = NULL;
251   gfc_cpp_option.output_filename = NULL;
252   gfc_cpp_option.preprocess_only = 0;
253   gfc_cpp_option.discard_comments = 1;
254   gfc_cpp_option.discard_comments_in_macro_exp = 1;
255   gfc_cpp_option.print_include_names = 0;
256   gfc_cpp_option.no_line_commands = 0;
257   gfc_cpp_option.dump_macros = '\0';
258   gfc_cpp_option.dump_includes = 0;
259   gfc_cpp_option.working_directory = -1;
260   gfc_cpp_option.no_predefined = 0;
261   gfc_cpp_option.standard_include_paths = 1;
262   gfc_cpp_option.verbose = 0;
263   gfc_cpp_option.warn_date_time = 0;
264   gfc_cpp_option.deps = 0;
265   gfc_cpp_option.deps_skip_system = 0;
266   gfc_cpp_option.deps_phony = 0;
267   gfc_cpp_option.deps_missing_are_generated = 0;
268   gfc_cpp_option.deps_filename = NULL;
269   gfc_cpp_option.deps_filename_user = NULL;
270 
271   gfc_cpp_option.multilib = NULL;
272   gfc_cpp_option.prefix = NULL;
273   gfc_cpp_option.sysroot = TARGET_SYSTEM_ROOT;
274 
275   gfc_cpp_option.deferred_opt = XNEWVEC (gfc_cpp_deferred_opt_t,
276 					 decoded_options_count);
277   gfc_cpp_option.deferred_opt_count = 0;
278 }
279 
280 int
gfc_cpp_handle_option(size_t scode,const char * arg,int value ATTRIBUTE_UNUSED)281 gfc_cpp_handle_option (size_t scode, const char *arg, int value ATTRIBUTE_UNUSED)
282 {
283   int result = 1;
284   enum opt_code code = (enum opt_code) scode;
285 
286   switch (code)
287   {
288     default:
289       result = 0;
290       break;
291 
292     case OPT_cpp_:
293       gfc_cpp_option.temporary_filename = arg;
294       break;
295 
296     case OPT_nocpp:
297       gfc_cpp_option.temporary_filename = 0L;
298       break;
299 
300     case OPT_d:
301       for ( ; *arg; ++arg)
302         switch (*arg)
303 	{
304 	  case 'D':
305 	  case 'M':
306 	  case 'N':
307 	  case 'U':
308 	    gfc_cpp_option.dump_macros = *arg;
309 	    break;
310 
311 	  case 'I':
312 	    gfc_cpp_option.dump_includes = 1;
313 	    break;
314 	}
315       break;
316 
317     case OPT_fworking_directory:
318       gfc_cpp_option.working_directory = value;
319       break;
320 
321     case OPT_idirafter:
322       gfc_cpp_add_include_path_after (xstrdup(arg), true);
323       break;
324 
325     case OPT_imultilib:
326       gfc_cpp_option.multilib = arg;
327       break;
328 
329     case OPT_iprefix:
330       gfc_cpp_option.prefix = arg;
331       break;
332 
333     case OPT_isysroot:
334       gfc_cpp_option.sysroot = arg;
335       break;
336 
337     case OPT_iquote:
338     case OPT_isystem:
339       gfc_cpp_add_include_path (xstrdup(arg), true);
340       break;
341 
342     case OPT_nostdinc:
343       gfc_cpp_option.standard_include_paths = value;
344       break;
345 
346     case OPT_o:
347       if (!gfc_cpp_option.output_filename)
348 	gfc_cpp_option.output_filename = arg;
349       else
350 	gfc_fatal_error ("output filename specified twice");
351       break;
352 
353     case OPT_undef:
354       gfc_cpp_option.no_predefined = value;
355       break;
356 
357     case OPT_v:
358       gfc_cpp_option.verbose = value;
359       break;
360 
361     case OPT_Wdate_time:
362       gfc_cpp_option.warn_date_time = value;
363       break;
364 
365     case OPT_A:
366     case OPT_D:
367     case OPT_U:
368       gfc_cpp_option.deferred_opt[gfc_cpp_option.deferred_opt_count].code = code;
369       gfc_cpp_option.deferred_opt[gfc_cpp_option.deferred_opt_count].arg = arg;
370       gfc_cpp_option.deferred_opt_count++;
371       break;
372 
373     case OPT_C:
374       gfc_cpp_option.discard_comments = 0;
375       break;
376 
377     case OPT_CC:
378       gfc_cpp_option.discard_comments = 0;
379       gfc_cpp_option.discard_comments_in_macro_exp = 0;
380       break;
381 
382     case OPT_E:
383       gfc_cpp_option.preprocess_only = 1;
384       break;
385 
386     case OPT_H:
387       gfc_cpp_option.print_include_names = 1;
388       break;
389 
390     case OPT_MM:
391       gfc_cpp_option.deps_skip_system = 1;
392       /* fall through */
393 
394     case OPT_M:
395       gfc_cpp_option.deps = 1;
396       break;
397 
398     case OPT_MMD:
399       gfc_cpp_option.deps_skip_system = 1;
400       /* fall through */
401 
402     case OPT_MD:
403       gfc_cpp_option.deps = 1;
404       gfc_cpp_option.deps_filename = arg;
405       break;
406 
407     case OPT_MF:
408       /* If specified multiple times, last one wins.  */
409       gfc_cpp_option.deps_filename_user = arg;
410       break;
411 
412     case OPT_MG:
413       gfc_cpp_option.deps_missing_are_generated = 1;
414       break;
415 
416     case OPT_MP:
417       gfc_cpp_option.deps_phony = 1;
418       break;
419 
420     case OPT_MQ:
421     case OPT_MT:
422       gfc_cpp_option.deferred_opt[gfc_cpp_option.deferred_opt_count].code = code;
423       gfc_cpp_option.deferred_opt[gfc_cpp_option.deferred_opt_count].arg = arg;
424       gfc_cpp_option.deferred_opt_count++;
425       break;
426 
427     case OPT_P:
428       gfc_cpp_option.no_line_commands = 1;
429       break;
430   }
431 
432   return result;
433 }
434 
435 
436 void
gfc_cpp_post_options(void)437 gfc_cpp_post_options (void)
438 {
439   /* Any preprocessing-related option without '-cpp' is considered
440      an error.  */
441   if (!gfc_cpp_enabled ()
442       && (gfc_cpp_preprocess_only ()
443 	  || gfc_cpp_makedep ()
444 	  || !gfc_cpp_option.discard_comments
445 	  || !gfc_cpp_option.discard_comments_in_macro_exp
446 	  || gfc_cpp_option.print_include_names
447 	  || gfc_cpp_option.no_line_commands
448 	  || gfc_cpp_option.dump_macros
449 	  || gfc_cpp_option.dump_includes))
450     gfc_fatal_error ("To enable preprocessing, use %<-cpp%>");
451 
452   if (!gfc_cpp_enabled ())
453     return;
454 
455   cpp_in = cpp_create_reader (CLK_GNUC89, NULL, line_table);
456   gcc_assert (cpp_in);
457 
458   /* The cpp_options-structure defines far more flags than those set here.
459      If any other is implemented, see c-opt.c (sanitize_cpp_opts) for
460      inter-option dependencies that may need to be enforced.  */
461   cpp_option = cpp_get_options (cpp_in);
462   gcc_assert (cpp_option);
463 
464   /* TODO: allow non-traditional modes, e.g. by -cpp-std=...?  */
465   cpp_option->traditional = 1;
466   cpp_option->cplusplus_comments = 0;
467 
468   cpp_option->cpp_pedantic = pedantic;
469 
470   cpp_option->dollars_in_ident = flag_dollar_ok;
471   cpp_option->discard_comments = gfc_cpp_option.discard_comments;
472   cpp_option->discard_comments_in_macro_exp = gfc_cpp_option.discard_comments_in_macro_exp;
473   cpp_option->print_include_names = gfc_cpp_option.print_include_names;
474   cpp_option->preprocessed = gfc_option.flag_preprocessed;
475   cpp_option->warn_date_time = gfc_cpp_option.warn_date_time;
476 
477   if (gfc_cpp_makedep ())
478     {
479       cpp_option->deps.style = DEPS_USER;
480       cpp_option->deps.phony_targets = gfc_cpp_option.deps_phony;
481       cpp_option->deps.missing_files = gfc_cpp_option.deps_missing_are_generated;
482 
483       /* -MF <arg> overrides -M[M]D.  */
484       if (gfc_cpp_option.deps_filename_user)
485 	gfc_cpp_option.deps_filename = gfc_cpp_option.deps_filename_user;
486   }
487 
488   if (gfc_cpp_option.working_directory == -1)
489     gfc_cpp_option.working_directory = (debug_info_level != DINFO_LEVEL_NONE);
490 
491   cpp_post_options (cpp_in);
492 
493   gfc_cpp_register_include_paths ();
494 }
495 
496 
497 void
gfc_cpp_init_0(void)498 gfc_cpp_init_0 (void)
499 {
500   struct cpp_callbacks *cb;
501 
502   cb = cpp_get_callbacks (cpp_in);
503   cb->file_change = cb_file_change;
504   cb->line_change = cb_line_change;
505   cb->ident = cb_ident;
506   cb->def_pragma = cb_def_pragma;
507   cb->error = cb_cpp_error;
508 
509   if (gfc_cpp_option.dump_includes)
510     cb->include = cb_include;
511 
512   if ((gfc_cpp_option.dump_macros == 'D')
513       || (gfc_cpp_option.dump_macros == 'N'))
514     {
515       cb->define = cb_define;
516       cb->undef  = cb_undef;
517     }
518 
519   if (gfc_cpp_option.dump_macros == 'U')
520     {
521       cb->before_define = dump_queued_macros;
522       cb->used_define = cb_used_define;
523       cb->used_undef = cb_used_undef;
524     }
525 
526   /* Initialize the print structure.  Setting print.src_line to -1 here is
527      a trick to guarantee that the first token of the file will cause
528      a linemarker to be output by maybe_print_line.  */
529   print.src_line = -1;
530   print.printed = 0;
531   print.prev = 0;
532   print.first_time = 1;
533 
534   if (gfc_cpp_preprocess_only ())
535     {
536       if (gfc_cpp_option.output_filename)
537 	{
538 	  /* This needs cheating: with "-E -o <file>", the user wants the
539 	     preprocessed output in <file>. However, if nothing is done
540 	     about it <file> is also used for assembler output. Hence, it
541 	     is necessary to redirect assembler output (actually nothing
542 	     as -E implies -fsyntax-only) to another file, otherwise the
543 	     output from preprocessing is lost.  */
544 	  asm_file_name = gfc_cpp_option.temporary_filename;
545 
546 	  print.outf = fopen (gfc_cpp_option.output_filename, "w");
547 	  if (print.outf == NULL)
548 	    gfc_fatal_error ("opening output file %qs: %s",
549 			     gfc_cpp_option.output_filename,
550 			     xstrerror (errno));
551 	}
552       else
553 	print.outf = stdout;
554     }
555   else
556     {
557       print.outf = fopen (gfc_cpp_option.temporary_filename, "w");
558       if (print.outf == NULL)
559 	gfc_fatal_error ("opening output file %qs: %s",
560 			 gfc_cpp_option.temporary_filename, xstrerror (errno));
561     }
562 
563   gcc_assert(cpp_in);
564   if (!cpp_read_main_file (cpp_in, gfc_source_file))
565     errorcount++;
566 }
567 
568 void
gfc_cpp_init(void)569 gfc_cpp_init (void)
570 {
571   int i;
572 
573   if (gfc_option.flag_preprocessed)
574     return;
575 
576   cpp_change_file (cpp_in, LC_RENAME, _("<built-in>"));
577   if (!gfc_cpp_option.no_predefined)
578     {
579       /* Make sure all of the builtins about to be declared have
580 	BUILTINS_LOCATION has their source_location.  */
581       source_location builtins_loc = BUILTINS_LOCATION;
582       cpp_force_token_locations (cpp_in, &builtins_loc);
583 
584       cpp_define_builtins (cpp_in);
585 
586       cpp_stop_forcing_token_locations (cpp_in);
587     }
588 
589   /* Handle deferred options from command-line.  */
590   cpp_change_file (cpp_in, LC_RENAME, _("<command-line>"));
591 
592   for (i = 0; i < gfc_cpp_option.deferred_opt_count; i++)
593     {
594       gfc_cpp_deferred_opt_t *opt = &gfc_cpp_option.deferred_opt[i];
595 
596       if (opt->code == OPT_D)
597 	cpp_define (cpp_in, opt->arg);
598       else if (opt->code == OPT_U)
599 	cpp_undef (cpp_in, opt->arg);
600       else if (opt->code == OPT_A)
601 	{
602 	  if (opt->arg[0] == '-')
603 	    cpp_unassert (cpp_in, opt->arg + 1);
604 	  else
605 	    cpp_assert (cpp_in, opt->arg);
606 	}
607       else if (opt->code == OPT_MT || opt->code == OPT_MQ)
608 	deps_add_target (cpp_get_deps (cpp_in),
609 			 opt->arg, opt->code == OPT_MQ);
610     }
611 
612   if (gfc_cpp_option.working_directory
613       && gfc_cpp_option.preprocess_only && !gfc_cpp_option.no_line_commands)
614     pp_dir_change (cpp_in, get_src_pwd ());
615 }
616 
617 bool
gfc_cpp_preprocess(const char * source_file)618 gfc_cpp_preprocess (const char *source_file)
619 {
620   if (!gfc_cpp_enabled ())
621     return false;
622 
623   cpp_change_file (cpp_in, LC_RENAME, source_file);
624 
625   if (cpp_option->traditional)
626     scan_translation_unit_trad (cpp_in);
627   else
628     scan_translation_unit (cpp_in);
629 
630   /* -dM command line option.  */
631   if (gfc_cpp_preprocess_only () &&
632       gfc_cpp_option.dump_macros == 'M')
633     {
634       putc ('\n', print.outf);
635       cpp_forall_identifiers (cpp_in, dump_macro, NULL);
636     }
637 
638   putc ('\n', print.outf);
639 
640   if (!gfc_cpp_preprocess_only ()
641       || (gfc_cpp_preprocess_only () && gfc_cpp_option.output_filename))
642     fclose (print.outf);
643 
644   return true;
645 }
646 
647 void
gfc_cpp_done(void)648 gfc_cpp_done (void)
649 {
650   if (!gfc_cpp_enabled ())
651     return;
652 
653   gcc_assert (cpp_in);
654 
655   if (gfc_cpp_makedep ())
656     {
657       if (gfc_cpp_option.deps_filename)
658 	{
659 	  FILE *f = fopen (gfc_cpp_option.deps_filename, "w");
660 	  if (f)
661 	    {
662 	      cpp_finish (cpp_in, f);
663 	      fclose (f);
664 	    }
665 	  else
666 	    gfc_fatal_error ("opening output file %qs: %s",
667 			     gfc_cpp_option.deps_filename,
668 			     xstrerror (errno));
669 	}
670       else
671 	cpp_finish (cpp_in, stdout);
672     }
673 
674   cpp_undef_all (cpp_in);
675   cpp_clear_file_cache (cpp_in);
676 }
677 
678 /* PATH must be malloc-ed and NULL-terminated.  */
679 void
gfc_cpp_add_include_path(char * path,bool user_supplied)680 gfc_cpp_add_include_path (char *path, bool user_supplied)
681 {
682   /* CHAIN sets cpp_dir->sysp which differs from 0 if PATH is a system
683      include path. Fortran does not define any system include paths.  */
684   int cxx_aware = 0;
685 
686   add_path (path, BRACKET, cxx_aware, user_supplied);
687 }
688 
689 void
gfc_cpp_add_include_path_after(char * path,bool user_supplied)690 gfc_cpp_add_include_path_after (char *path, bool user_supplied)
691 {
692   int cxx_aware = 0;
693   add_path (path, AFTER, cxx_aware, user_supplied);
694 }
695 
696 void
gfc_cpp_register_include_paths(void)697 gfc_cpp_register_include_paths (void)
698 {
699   int cxx_stdinc = 0;
700   register_include_chains (cpp_in, gfc_cpp_option.sysroot,
701 			   gfc_cpp_option.prefix, gfc_cpp_option.multilib,
702 			   gfc_cpp_option.standard_include_paths, cxx_stdinc,
703 			   gfc_cpp_option.verbose);
704 }
705 
706 
707 
708 static void scan_translation_unit_trad (cpp_reader *);
709 static void account_for_newlines (const unsigned char *, size_t);
710 static int dump_macro (cpp_reader *, cpp_hashnode *, void *);
711 
712 static void print_line (source_location, const char *);
713 static void maybe_print_line (source_location);
714 
715 
716 /* Writes out the preprocessed file, handling spacing and paste
717    avoidance issues.  */
718 static void
scan_translation_unit(cpp_reader * pfile)719 scan_translation_unit (cpp_reader *pfile)
720 {
721   bool avoid_paste = false;
722 
723   print.source = NULL;
724   for (;;)
725     {
726       const cpp_token *token = cpp_get_token (pfile);
727 
728       if (token->type == CPP_PADDING)
729 	{
730 	  avoid_paste = true;
731 	  if (print.source == NULL
732 	      || (!(print.source->flags & PREV_WHITE)
733 		  && token->val.source == NULL))
734 	    print.source = token->val.source;
735 	  continue;
736 	}
737 
738       if (token->type == CPP_EOF)
739 	break;
740 
741       /* Subtle logic to output a space if and only if necessary.  */
742       if (avoid_paste)
743 	{
744 	  if (print.source == NULL)
745 	    print.source = token;
746 	  if (print.source->flags & PREV_WHITE
747 	      || (print.prev
748 		  && cpp_avoid_paste (pfile, print.prev, token))
749 	      || (print.prev == NULL && token->type == CPP_HASH))
750 	    putc (' ', print.outf);
751 	}
752       else if (token->flags & PREV_WHITE)
753 	putc (' ', print.outf);
754 
755       avoid_paste = false;
756       print.source = NULL;
757       print.prev = token;
758       cpp_output_token (token, print.outf);
759 
760       if (token->type == CPP_COMMENT)
761 	account_for_newlines (token->val.str.text, token->val.str.len);
762     }
763 }
764 
765 /* Adjust print.src_line for newlines embedded in output.  */
766 static void
account_for_newlines(const unsigned char * str,size_t len)767 account_for_newlines (const unsigned char *str, size_t len)
768 {
769   while (len--)
770     if (*str++ == '\n')
771       print.src_line++;
772 }
773 
774 /* Writes out a traditionally preprocessed file.  */
775 static void
scan_translation_unit_trad(cpp_reader * pfile)776 scan_translation_unit_trad (cpp_reader *pfile)
777 {
778   while (_cpp_read_logical_line_trad (pfile))
779     {
780       size_t len = pfile->out.cur - pfile->out.base;
781       maybe_print_line (pfile->out.first_line);
782       fwrite (pfile->out.base, 1, len, print.outf);
783       print.printed = 1;
784       if (!CPP_OPTION (pfile, discard_comments))
785 	account_for_newlines (pfile->out.base, len);
786     }
787 }
788 
789 /* If the token read on logical line LINE needs to be output on a
790    different line to the current one, output the required newlines or
791    a line marker.  */
792 static void
maybe_print_line(source_location src_loc)793 maybe_print_line (source_location src_loc)
794 {
795   const line_map_ordinary *map
796     = linemap_check_ordinary (linemap_lookup (line_table, src_loc));
797   int src_line = SOURCE_LINE (map, src_loc);
798 
799   /* End the previous line of text.  */
800   if (print.printed)
801     {
802       putc ('\n', print.outf);
803       print.src_line++;
804       print.printed = 0;
805     }
806 
807   if (src_line >= print.src_line && src_line < print.src_line + 8)
808     {
809       while (src_line > print.src_line)
810 	{
811 	  putc ('\n', print.outf);
812 	  print.src_line++;
813 	}
814     }
815   else
816     print_line (src_loc, "");
817 }
818 
819 /* Output a line marker for logical line LINE.  Special flags are "1"
820    or "2" indicating entering or leaving a file.  */
821 static void
print_line(source_location src_loc,const char * special_flags)822 print_line (source_location src_loc, const char *special_flags)
823 {
824   /* End any previous line of text.  */
825   if (print.printed)
826     putc ('\n', print.outf);
827   print.printed = 0;
828 
829   if (!gfc_cpp_option.no_line_commands)
830     {
831       expanded_location loc;
832       size_t to_file_len;
833       unsigned char *to_file_quoted;
834       unsigned char *p;
835       int sysp;
836 
837       loc = expand_location (src_loc);
838       to_file_len = strlen (loc.file);
839       to_file_quoted = (unsigned char *) alloca (to_file_len * 4 + 1);
840 
841       print.src_line = loc.line;
842 
843       /* cpp_quote_string does not nul-terminate, so we have to do it
844 	 ourselves.  */
845       p = cpp_quote_string (to_file_quoted,
846 			    (const unsigned char *) loc.file, to_file_len);
847       *p = '\0';
848       fprintf (print.outf, "# %u \"%s\"%s",
849 	       print.src_line == 0 ? 1 : print.src_line,
850 	       to_file_quoted, special_flags);
851 
852       sysp = in_system_header_at (src_loc);
853       if (sysp == 2)
854 	fputs (" 3 4", print.outf);
855       else if (sysp == 1)
856 	fputs (" 3", print.outf);
857 
858       putc ('\n', print.outf);
859     }
860 }
861 
862 static void
cb_file_change(cpp_reader * ARG_UNUSED (pfile),const line_map_ordinary * map)863 cb_file_change (cpp_reader * ARG_UNUSED (pfile), const line_map_ordinary *map)
864 {
865   const char *flags = "";
866 
867   if (gfc_cpp_option.no_line_commands)
868     return;
869 
870   if (!map)
871     return;
872 
873       if (print.first_time)
874 	{
875 	  /* Avoid printing foo.i when the main file is foo.c.  */
876 	  if (!cpp_get_options (cpp_in)->preprocessed)
877 	    print_line (map->start_location, flags);
878 	  print.first_time = 0;
879 	}
880       else
881 	{
882 	  /* Bring current file to correct line when entering a new file.  */
883 	  if (map->reason == LC_ENTER)
884 	    {
885 	      const line_map_ordinary *from = INCLUDED_FROM (line_table, map);
886 	      maybe_print_line (LAST_SOURCE_LINE_LOCATION (from));
887 	    }
888 	  if (map->reason == LC_ENTER)
889 	    flags = " 1";
890 	  else if (map->reason == LC_LEAVE)
891 	    flags = " 2";
892 	  print_line (map->start_location, flags);
893 	}
894 
895 }
896 
897 /* Called when a line of output is started.  TOKEN is the first token
898    of the line, and at end of file will be CPP_EOF.  */
899 static void
cb_line_change(cpp_reader * pfile,const cpp_token * token,int parsing_args)900 cb_line_change (cpp_reader *pfile, const cpp_token *token,
901 		int parsing_args)
902 {
903   source_location src_loc = token->src_loc;
904 
905   if (token->type == CPP_EOF || parsing_args)
906     return;
907 
908   maybe_print_line (src_loc);
909   print.prev = 0;
910   print.source = 0;
911 
912   /* Supply enough spaces to put this token in its original column,
913      one space per column greater than 2, since scan_translation_unit
914      will provide a space if PREV_WHITE.  Don't bother trying to
915      reconstruct tabs; we can't get it right in general, and nothing
916      ought to care.  Some things do care; the fault lies with them.  */
917   if (!CPP_OPTION (pfile, traditional))
918     {
919       const line_map_ordinary *map
920 	= linemap_check_ordinary (linemap_lookup (line_table, src_loc));
921       int spaces = SOURCE_COLUMN (map, src_loc) - 2;
922       print.printed = 1;
923 
924       while (-- spaces >= 0)
925 	putc (' ', print.outf);
926     }
927 }
928 
929 static void
cb_ident(cpp_reader * pfile ATTRIBUTE_UNUSED,source_location line,const cpp_string * str)930 cb_ident (cpp_reader *pfile ATTRIBUTE_UNUSED, source_location line,
931 	  const cpp_string *str)
932 {
933   maybe_print_line (line);
934   fprintf (print.outf, "#ident %s\n", str->text);
935   print.src_line++;
936 }
937 
938 static void
cb_define(cpp_reader * pfile ATTRIBUTE_UNUSED,source_location line,cpp_hashnode * node ATTRIBUTE_UNUSED)939 cb_define (cpp_reader *pfile ATTRIBUTE_UNUSED, source_location line,
940            cpp_hashnode *node ATTRIBUTE_UNUSED)
941 {
942   maybe_print_line (line);
943   fputs ("#define ", print.outf);
944 
945   /* 'D' is whole definition; 'N' is name only.  */
946   if (gfc_cpp_option.dump_macros == 'D')
947     fputs ((const char *) cpp_macro_definition (pfile, node),
948 	   print.outf);
949   else
950     fputs ((const char *) NODE_NAME (node), print.outf);
951 
952   putc ('\n', print.outf);
953   if (LOCATION_LINE (line) != 0)
954     print.src_line++;
955 }
956 
957 static void
cb_undef(cpp_reader * pfile ATTRIBUTE_UNUSED,source_location line,cpp_hashnode * node)958 cb_undef (cpp_reader *pfile ATTRIBUTE_UNUSED, source_location line,
959 	  cpp_hashnode *node)
960 {
961   maybe_print_line (line);
962   fprintf (print.outf, "#undef %s\n", NODE_NAME (node));
963   print.src_line++;
964 }
965 
966 static void
cb_include(cpp_reader * pfile ATTRIBUTE_UNUSED,source_location line,const unsigned char * dir,const char * header,int angle_brackets,const cpp_token ** comments)967 cb_include (cpp_reader *pfile ATTRIBUTE_UNUSED, source_location line,
968 	    const unsigned char *dir, const char *header, int angle_brackets,
969 	    const cpp_token **comments)
970 {
971   maybe_print_line (line);
972   if (angle_brackets)
973     fprintf (print.outf, "#%s <%s>", dir, header);
974   else
975     fprintf (print.outf, "#%s \"%s\"", dir, header);
976 
977   if (comments != NULL)
978     {
979       while (*comments != NULL)
980 	{
981 	  if ((*comments)->flags & PREV_WHITE)
982 	    putc (' ', print.outf);
983 	  cpp_output_token (*comments, print.outf);
984 	  ++comments;
985 	}
986     }
987 
988   putc ('\n', print.outf);
989   print.src_line++;
990 }
991 
992 /* Dump out the hash table.  */
993 static int
dump_macro(cpp_reader * pfile,cpp_hashnode * node,void * v ATTRIBUTE_UNUSED)994 dump_macro (cpp_reader *pfile, cpp_hashnode *node, void *v ATTRIBUTE_UNUSED)
995 {
996   if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
997     {
998       fputs ("#define ", print.outf);
999       fputs ((const char *) cpp_macro_definition (pfile, node),
1000 	     print.outf);
1001       putc ('\n', print.outf);
1002       print.src_line++;
1003     }
1004 
1005   return 1;
1006 }
1007 
1008 static void
cb_used_define(cpp_reader * pfile,source_location line ATTRIBUTE_UNUSED,cpp_hashnode * node)1009 cb_used_define (cpp_reader *pfile, source_location line ATTRIBUTE_UNUSED,
1010 		cpp_hashnode *node)
1011 {
1012   gfc_cpp_macro_queue *q;
1013   q = XNEW (gfc_cpp_macro_queue);
1014   q->macro = xstrdup ((const char *) cpp_macro_definition (pfile, node));
1015   q->next = cpp_define_queue;
1016   cpp_define_queue = q;
1017 }
1018 
1019 /* Callback from cpp_error for PFILE to print diagnostics from the
1020    preprocessor.  The diagnostic is of type LEVEL, with REASON set
1021    to the reason code if LEVEL is represents a warning, at location
1022    RICHLOC; MSG is the translated message and AP the arguments.
1023    Returns true if a diagnostic was emitted, false otherwise.  */
1024 
1025 static bool
cb_cpp_error(cpp_reader * pfile ATTRIBUTE_UNUSED,int level,int reason,rich_location * richloc,const char * msg,va_list * ap)1026 cb_cpp_error (cpp_reader *pfile ATTRIBUTE_UNUSED, int level, int reason,
1027 	      rich_location *richloc,
1028 	      const char *msg, va_list *ap)
1029 {
1030   diagnostic_info diagnostic;
1031   diagnostic_t dlevel;
1032   bool save_warn_system_headers = global_dc->dc_warn_system_headers;
1033   bool ret;
1034 
1035   switch (level)
1036     {
1037     case CPP_DL_WARNING_SYSHDR:
1038       global_dc->dc_warn_system_headers = 1;
1039       /* Fall through.  */
1040     case CPP_DL_WARNING:
1041       dlevel = DK_WARNING;
1042       break;
1043     case CPP_DL_PEDWARN:
1044       dlevel = DK_PEDWARN;
1045       break;
1046     case CPP_DL_ERROR:
1047       dlevel = DK_ERROR;
1048       break;
1049     case CPP_DL_ICE:
1050       dlevel = DK_ICE;
1051       break;
1052     case CPP_DL_NOTE:
1053       dlevel = DK_NOTE;
1054       break;
1055     case CPP_DL_FATAL:
1056       dlevel = DK_FATAL;
1057       break;
1058     default:
1059       gcc_unreachable ();
1060     }
1061   diagnostic_set_info_translated (&diagnostic, msg, ap,
1062 				  richloc, dlevel);
1063   if (reason == CPP_W_WARNING_DIRECTIVE)
1064     diagnostic_override_option_index (&diagnostic, OPT_Wcpp);
1065   ret = report_diagnostic (&diagnostic);
1066   if (level == CPP_DL_WARNING_SYSHDR)
1067     global_dc->dc_warn_system_headers = save_warn_system_headers;
1068   return ret;
1069 }
1070 
1071 /* Callback called when -fworking-director and -E to emit working
1072    directory in cpp output file.  */
1073 
1074 void
pp_dir_change(cpp_reader * pfile ATTRIBUTE_UNUSED,const char * dir)1075 pp_dir_change (cpp_reader *pfile ATTRIBUTE_UNUSED, const char *dir)
1076 {
1077   size_t to_file_len = strlen (dir);
1078   unsigned char *to_file_quoted =
1079      (unsigned char *) alloca (to_file_len * 4 + 1);
1080   unsigned char *p;
1081 
1082   /* cpp_quote_string does not nul-terminate, so we have to do it ourselves.  */
1083   p = cpp_quote_string (to_file_quoted, (const unsigned char *) dir, to_file_len);
1084   *p = '\0';
1085   fprintf (print.outf, "# 1 \"%s//\"\n", to_file_quoted);
1086 }
1087 
1088 /* Copy a #pragma directive to the preprocessed output.  */
1089 static void
cb_def_pragma(cpp_reader * pfile,source_location line)1090 cb_def_pragma (cpp_reader *pfile, source_location line)
1091 {
1092   maybe_print_line (line);
1093   fputs ("#pragma ", print.outf);
1094   cpp_output_line (pfile, print.outf);
1095   print.src_line++;
1096 }
1097 
1098 static void
cb_used_undef(cpp_reader * pfile ATTRIBUTE_UNUSED,source_location line ATTRIBUTE_UNUSED,cpp_hashnode * node)1099 cb_used_undef (cpp_reader *pfile ATTRIBUTE_UNUSED,
1100 	       source_location line ATTRIBUTE_UNUSED,
1101 	       cpp_hashnode *node)
1102 {
1103   gfc_cpp_macro_queue *q;
1104   q = XNEW (gfc_cpp_macro_queue);
1105   q->macro = xstrdup ((const char *) NODE_NAME (node));
1106   q->next = cpp_undefine_queue;
1107   cpp_undefine_queue = q;
1108 }
1109 
1110 static void
dump_queued_macros(cpp_reader * pfile ATTRIBUTE_UNUSED)1111 dump_queued_macros (cpp_reader *pfile ATTRIBUTE_UNUSED)
1112 {
1113   gfc_cpp_macro_queue *q;
1114 
1115   /* End the previous line of text.  */
1116   if (print.printed)
1117     {
1118       putc ('\n', print.outf);
1119       print.src_line++;
1120       print.printed = 0;
1121     }
1122 
1123   for (q = cpp_define_queue; q;)
1124     {
1125       gfc_cpp_macro_queue *oq;
1126       fputs ("#define ", print.outf);
1127       fputs (q->macro, print.outf);
1128       putc ('\n', print.outf);
1129       print.src_line++;
1130       oq = q;
1131       q = q->next;
1132       free (oq->macro);
1133       free (oq);
1134     }
1135   cpp_define_queue = NULL;
1136   for (q = cpp_undefine_queue; q;)
1137     {
1138       gfc_cpp_macro_queue *oq;
1139       fprintf (print.outf, "#undef %s\n", q->macro);
1140       print.src_line++;
1141       oq = q;
1142       q = q->next;
1143       free (oq->macro);
1144       free (oq);
1145     }
1146   cpp_undefine_queue = NULL;
1147 }
1148