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