Debian Codegraph @

libcpp/mkdeps.cc

raw
1 /* Dependency generator for Makefile fragments.
2 Copyright (C) 2000-2025 Free Software Foundation, Inc.
3 Contributed by Zack Weinberg, Mar 2000
4
5 This program is free software; you can redistribute it and/or modify it
6 under the terms of the GNU General Public License as published by the
7 Free Software Foundation; either version 3, or (at your option) any
8 later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; see the file COPYING3. If not see
17 <http://www.gnu.org/licenses/>.
18
19 In other words, you are welcome to use, share and improve this program.
20 You are forbidden to forbid anyone else to use, share and improve
21 what you give them. Help stamp out software-hoarding! */
22
23 #include "config.h"
24 #include "system.h"
25 #include "mkdeps.h"
26 #include "internal.h"
27
28 /* Not set up to just include std::vector et al, here's a simple
29 implementation. */
30
31 /* Keep this structure local to this file, so clients don't find it
32 easy to start making assumptions. */
33 class mkdeps
34 {
35 public:
36 /* T has trivial cctor & dtor. */
37 template <typename T>
38 class vec
39 {
40 private:
41 T *ary;
42 unsigned num;
43 unsigned alloc;
44
45 public:
46 vec ()
47 : ary (NULL), num (0), alloc (0)
48 {}
49 ~vec ()
50 {
51 XDELETEVEC (ary);
52 }
53
54 public:
55 unsigned size () const
56 {
57 return num;
58 }
59 const T &operator[] (unsigned ix) const
60 {
61 return ary[ix];
62 }
63 T &operator[] (unsigned ix)
64 {
65 return ary[ix];
66 }
67 void push (const T &elt)
68 {
69 if (num == alloc)
70 {
71 alloc = alloc ? alloc * 2 : 16;
72 ary = XRESIZEVEC (T, ary, alloc);
73 }
74 ary[num++] = elt;
75 }
76 };
77 struct velt
78 {
79 const char *str;
80 size_t len;
81 };
82
83 mkdeps ()
84 : primary_output (NULL), module_name (NULL), cmi_name (NULL),
85 is_header_unit (false), is_exported (false), quote_lwm (0),
86 first_phony_dep (1)
87 {
88 }
89 ~mkdeps ()
90 {
91 unsigned int i;
92
93 for (i = targets.size (); i--;)
94 free (const_cast <char *> (targets[i]));
95 free (const_cast <char *> (primary_output));
96 for (i = fdeps_targets.size (); i--;)
97 free (const_cast <char *> (fdeps_targets[i]));
98 for (i = deps.size (); i--;)
99 free (const_cast <char *> (deps[i]));
100 for (i = vpath.size (); i--;)
101 XDELETEVEC (vpath[i].str);
102 for (i = modules.size (); i--;)
103 XDELETEVEC (modules[i]);
104 XDELETEVEC (module_name);
105 free (const_cast <char *> (cmi_name));
106 }
107
108 public:
109 vec<const char *> targets;
110 vec<const char *> deps;
111 const char * primary_output;
112 vec<const char *> fdeps_targets;
113 vec<velt> vpath;
114 vec<const char *> modules;
115
116 public:
117 const char *module_name;
118 const char *cmi_name;
119 bool is_header_unit;
120 bool is_exported;
121 unsigned short quote_lwm;
122 unsigned int first_phony_dep;
123 };
124
125 /* Apply Make quoting to STR, TRAIL. Note that it's not possible to
126 quote all such characters - e.g. \n, %, *, ?, [, \ (in some
127 contexts), and ~ are not properly handled. It isn't possible to
128 get this right in any current version of Make. (??? Still true?
129 Old comment referred to 3.76.1.) */
130
131 static const char *
132 munge (const char *str, const char *trail = nullptr)
133 {
134 static unsigned alloc;
135 static char *buf;
136 unsigned dst = 0;
137
138 for (; str; str = trail, trail = nullptr)
139 {
140 unsigned slashes = 0;
141 char c;
142 for (const char *probe = str; (c = *probe++);)
143 {
144 if (alloc < dst + 4 + slashes)
145 {
146 alloc = alloc * 2 + 32;
147 buf = XRESIZEVEC (char, buf, alloc);
148 }
149
150 switch (c)
151 {
152 case '\\':
153 slashes++;
154 break;
155
156 case '$':
157 buf[dst++] = '$';
158 goto def;
159
160 case ' ':
161 case '\t':
162 /* GNU make uses a weird quoting scheme for white space.
163 A space or tab preceded by 2N+1 backslashes
164 represents N backslashes followed by space; a space
165 or tab preceded by 2N backslashes represents N
166 backslashes at the end of a file name; and
167 backslashes in other contexts should not be
168 doubled. */
169 while (slashes--)
170 buf[dst++] = '\\';
171 /* FALLTHROUGH */
172
173 case '#':
174 buf[dst++] = '\\';
175 /* FALLTHROUGH */
176
177 default:
178 def:
179 slashes = 0;
180 break;
181 }
182
183 buf[dst++] = c;
184 }
185 }
186
187 buf[dst] = 0;
188 return buf;
189 }
190
191 /* If T begins with any of the partial pathnames listed in d->vpathv,
192 then advance T to point beyond that pathname. */
193 static const char *
194 apply_vpath (class mkdeps *d, const char *t)
195 {
196 if (unsigned len = d->vpath.size ())
197 for (unsigned i = len; i--;)
198 {
199 if (!filename_ncmp (d->vpath[i].str, t, d->vpath[i].len))
200 {
201 const char *p = t + d->vpath[i].len;
202 if (!IS_DIR_SEPARATOR (*p))
203 goto not_this_one;
204
205 /* Do not simplify $(vpath)/../whatever. ??? Might not
206 be necessary. */
207 if (p[1] == '.' && p[2] == '.' && IS_DIR_SEPARATOR (p[3]))
208 goto not_this_one;
209
210 /* found a match */
211 t = t + d->vpath[i].len + 1;
212 break;
213 }
214 not_this_one:;
215 }
216
217 /* Remove leading ./ in any case. */
218 while (t[0] == '.' && IS_DIR_SEPARATOR (t[1]))
219 {
220 t += 2;
221 /* If we removed a leading ./, then also remove any /s after the
222 first. */
223 while (IS_DIR_SEPARATOR (t[0]))
224 ++t;
225 }
226
227 return t;
228 }
229
230 /* Public routines. */
231
232 class mkdeps *
233 deps_init (void)
234 {
235 return new mkdeps ();
236 }
237
238 void
239 deps_free (class mkdeps *d)
240 {
241 delete d;
242 }
243
244 /* Adds a target T. We make a copy, so it need not be a permanent
245 string. QUOTE is true if the string should be quoted. */
246 void
247 deps_add_target (class mkdeps *d, const char *t, int quote)
248 {
249 t = xstrdup (apply_vpath (d, t));
250
251 if (!quote)
252 {
253 /* Sometimes unquoted items are added after quoted ones.
254 Swap out the lowest quoted. */
255 if (d->quote_lwm != d->targets.size ())
256 {
257 const char *lowest = d->targets[d->quote_lwm];
258 d->targets[d->quote_lwm] = t;
259 t = lowest;
260 }
261 d->quote_lwm++;
262 }
263
264 d->targets.push (t);
265 }
266
267 /* Sets the default target if none has been given already. An empty
268 string as the default target in interpreted as stdin. The string
269 is quoted for MAKE. */
270 void
271 deps_add_default_target (class mkdeps *d, const char *tgt)
272 {
273 /* Only if we have no targets. */
274 if (d->targets.size ())
275 return;
276
277 if (tgt[0] == '\0')
278 d->targets.push (xstrdup ("-"));
279 else
280 {
281 #ifndef TARGET_OBJECT_SUFFIX
282 # define TARGET_OBJECT_SUFFIX ".o"
283 #endif
284 const char *start = lbasename (tgt);
285 char *o = (char *) alloca (strlen (start)
286 + strlen (TARGET_OBJECT_SUFFIX) + 1);
287 char *suffix;
288
289 strcpy (o, start);
290
291 suffix = strrchr (o, '.');
292 if (!suffix)
293 suffix = o + strlen (o);
294 strcpy (suffix, TARGET_OBJECT_SUFFIX);
295
296 deps_add_target (d, o, 1);
297 }
298 }
299
300 /* Adds a target O. We make a copy, so it need not be a permanent
301 string.
302
303 This is the target associated with the rule that (in a C++ modules build)
304 compiles the source that is being scanned for dynamic dependencies. It is
305 used to associate the structured dependency information with that rule as
306 needed. */
307 void
308 fdeps_add_target (struct mkdeps *d, const char *o, bool is_primary)
309 {
310 o = apply_vpath (d, o);
311 if (is_primary)
312 {
313 if (d->primary_output)
314 d->fdeps_targets.push (d->primary_output);
315 d->primary_output = xstrdup (o);
316 } else
317 d->fdeps_targets.push (xstrdup (o));
318 }
319
320 void
321 deps_add_dep (class mkdeps *d, const char *t)
322 {
323 if (*t)
324 {
325 t = apply_vpath (d, t);
326
327 d->deps.push (xstrdup (t));
328 }
329 /* When called first with "", remember we should
330 emit for -MP all dependencies rather than just
331 second and following dependency. See PR105412. */
332 else if (d->deps.size () == 0)
333 d->first_phony_dep = 0;
334 }
335
336 void
337 deps_add_vpath (class mkdeps *d, const char *vpath)
338 {
339 const char *elem, *p;
340
341 for (elem = vpath; *elem; elem = p)
342 {
343 for (p = elem; *p && *p != ':'; p++)
344 continue;
345 mkdeps::velt elt;
346 elt.len = p - elem;
347 char *str = XNEWVEC (char, elt.len + 1);
348 elt.str = str;
349 memcpy (str, elem, elt.len);
350 str[elt.len] = '\0';
351 if (*p == ':')
352 p++;
353
354 d->vpath.push (elt);
355 }
356 }
357
358 /* Add a new module target (there can only be one). M is the module
359 name. */
360
361 void
362 deps_add_module_target (struct mkdeps *d, const char *m,
363 const char *cmi, bool is_header_unit, bool is_exported)
364 {
365 gcc_assert (!d->module_name);
366
367 d->module_name = xstrdup (m);
368 d->is_header_unit = is_header_unit;
369 d->is_exported = is_exported;
370 d->cmi_name = xstrdup (cmi);
371 }
372
373 /* Add a new module dependency. M is the module name. */
374
375 void
376 deps_add_module_dep (struct mkdeps *d, const char *m)
377 {
378 d->modules.push (xstrdup (m));
379 }
380
381 /* Write NAME, with a leading space to FP, a Makefile. Advance COL as
382 appropriate, wrap at COLMAX, returning new column number. Iff
383 QUOTE apply quoting. Append TRAIL. */
384
385 static unsigned
386 make_write_name (const char *name, FILE *fp, unsigned col, unsigned colmax,
387 bool quote = true, const char *trail = NULL)
388 {
389 if (quote)
390 name = munge (name, trail);
391 unsigned size = strlen (name);
392
393 if (col)
394 {
395 if (colmax && col + size> colmax)
396 {
397 fputs (" \\\n", fp);
398 col = 0;
399 }
400 col++;
401 fputs (" ", fp);
402 }
403
404 col += size;
405 fputs (name, fp);
406
407 return col;
408 }
409
410 /* Write all the names in VEC via make_write_name. */
411
412 static unsigned
413 make_write_vec (const mkdeps::vec<const char *> &vec, FILE *fp,
414 unsigned col, unsigned colmax, unsigned quote_lwm = 0,
415 const char *trail = NULL)
416 {
417 for (unsigned ix = 0; ix != vec.size (); ix++)
418 col = make_write_name (vec[ix], fp, col, colmax, ix >= quote_lwm, trail);
419 return col;
420 }
421
422 /* Write the dependencies to a Makefile. */
423
424 static void
425 make_write (const cpp_reader *pfile, FILE *fp, unsigned int colmax)
426 {
427 const mkdeps *d = pfile->deps;
428
429 unsigned column = 0;
430 if (colmax && colmax < 34)
431 colmax = 34;
432
433 /* Write out C++ modules information if no other `-fdeps-format=`
434 option is given. */
435 cpp_fdeps_format fdeps_format = CPP_OPTION (pfile, deps.fdeps_format);
436 bool write_make_modules_deps = (fdeps_format == FDEPS_FMT_NONE
437 && CPP_OPTION (pfile, deps.modules));
438
439 if (d->deps.size ())
440 {
441 column = make_write_vec (d->targets, fp, 0, colmax, d->quote_lwm);
442 if (write_make_modules_deps && d->cmi_name)
443 column = make_write_name (d->cmi_name, fp, column, colmax);
444 fputs (":", fp);
445 column++;
446 make_write_vec (d->deps, fp, column, colmax);
447 fputs ("\n", fp);
448 if (CPP_OPTION (pfile, deps.phony_targets))
449 for (unsigned i = d->first_phony_dep; i < d->deps.size (); i++)
450 fprintf (fp, "%s:\n", munge (d->deps[i]));
451 }
452
453 if (!write_make_modules_deps)
454 return;
455
456 if (d->modules.size ())
457 {
458 column = make_write_vec (d->targets, fp, 0, colmax, d->quote_lwm);
459 if (d->cmi_name)
460 column = make_write_name (d->cmi_name, fp, column, colmax);
461 fputs (":", fp);
462 column++;
463 column = make_write_vec (d->modules, fp, column, colmax, 0, ".c++-module");
464 fputs ("\n", fp);
465 }
466
467 if (d->module_name)
468 {
469 if (d->cmi_name)
470 {
471 /* module-name : cmi-name */
472 column = make_write_name (d->module_name, fp, 0, colmax,
473 true, ".c++-module");
474 const char *module_basename = nullptr;
475 if (d->is_header_unit)
476 {
477 /* Also emit a target for the include name, so for #include
478 <iostream> you'd make iostream.c++-header-unit, regardless of
479 what actual directory iostream lives in. We reconstruct the
480 include name by skipping the directory where we found it. */
481 auto *dir = _cpp_get_file_dir (pfile->main_file);
482 gcc_assert (!strncmp (d->module_name, dir->name, dir->len));
483 module_basename = (d->module_name + dir->len + 1);
484 column = make_write_name (module_basename, fp, column, colmax,
485 true, ".c++-header-unit");
486 }
487 fputs (":", fp);
488 column++;
489 column = make_write_name (d->cmi_name, fp, column, colmax);
490 fputs ("\n", fp);
491
492 column = fprintf (fp, ".PHONY:");
493 column = make_write_name (d->module_name, fp, column, colmax,
494 true, ".c++-module");
495 if (module_basename)
496 column = make_write_name (module_basename, fp, column, colmax,
497 true, ".c++-header-unit");
498 fputs ("\n", fp);
499 }
500
501 if (d->cmi_name && !d->is_header_unit)
502 {
503 /* An order-only dependency.
504 cmi-name :| first-target
505 We can probably drop this this in favour of Make-4.3's grouped
506 targets '&:' */
507 column = make_write_name (d->cmi_name, fp, 0, colmax);
508 fputs (":|", fp);
509 column++;
510 column = make_write_name (d->targets[0], fp, column, colmax);
511 fputs ("\n", fp);
512 }
513 }
514
515 if (d->modules.size ())
516 {
517 column = fprintf (fp, "CXX_IMPORTS +=");
518 make_write_vec (d->modules, fp, column, colmax, 0, ".c++-module");
519 fputs ("\n", fp);
520 }
521 }
522
523 /* Write out dependencies according to the selected format (which is
524 only Make at the moment). */
525 /* Really we should be opening fp here. */
526
527 void
528 deps_write (const cpp_reader *pfile, FILE *fp, unsigned int colmax)
529 {
530 make_write (pfile, fp, colmax);
531 }
532
533 /* Write out a a filepath for P1689R5 output. */
534
535 static void
536 p1689r5_write_filepath (const char *name, FILE *fp)
537 {
538 if (cpp_valid_utf8_p (name, strlen (name)))
539 {
540 fputc ('"', fp);
541 for (const char* c = name; *c; c++)
542 {
543 // Escape control characters.
544 if (ISCNTRL (*c))
545 fprintf (fp, "\\u%04x", *c);
546 // JSON escape characters.
547 else if (*c == '"' || *c == '\\')
548 {
549 fputc ('\\', fp);
550 fputc (*c, fp);
551 }
552 // Everything else.
553 else
554 fputc (*c, fp);
555 }
556 fputc ('"', fp);
557 }
558 else
559 {
560 // TODO: print an error
561 }
562 }
563
564 /* Write a JSON array from a `vec` for P1689R5 output.
565
566 In P1689R5, all array values are filepaths. */
567
568 static void
569 p1689r5_write_vec (const mkdeps::vec<const char *> &vec, FILE *fp)
570 {
571 for (unsigned ix = 0; ix != vec.size (); ix++)
572 {
573 p1689r5_write_filepath (vec[ix], fp);
574 if (ix < vec.size () - 1)
575 fputc (',', fp);
576 fputc ('\n', fp);
577 }
578 }
579
580 /* Write out the P1689R5 format using the module dependency tracking
581 information gathered while scanning and/or compiling.
582
583 Ideally this (and the above `p1689r5_` functions) would use `gcc/json.h`,
584 but since this is `libcpp`, we cannot use `gcc/` code.
585
586 TODO: move `json.h` to libiberty. */
587
588 void
589 deps_write_p1689r5 (const struct mkdeps *d, FILE *fp)
590 {
591 fputs ("{\n", fp);
592
593 fputs ("\"rules\": [\n", fp);
594 fputs ("{\n", fp);
595
596 if (d->primary_output)
597 {
598 fputs ("\"primary-output\": ", fp);
599 p1689r5_write_filepath (d->primary_output, fp);
600 fputs (",\n", fp);
601 }
602
603 if (d->fdeps_targets.size ())
604 {
605 fputs ("\"outputs\": [\n", fp);
606 p1689r5_write_vec (d->fdeps_targets, fp);
607 fputs ("],\n", fp);
608 }
609
610 if (d->module_name)
611 {
612 fputs ("\"provides\": [\n", fp);
613 fputs ("{\n", fp);
614
615 fputs ("\"logical-name\": ", fp);
616 p1689r5_write_filepath (d->module_name, fp);
617 fputs (",\n", fp);
618
619 fprintf (fp, "\"is-interface\": %s\n", d->is_exported ? "true" : "false");
620
621 // TODO: header-unit information
622
623 fputs ("}\n", fp);
624 fputs ("],\n", fp);
625 }
626
627 fputs ("\"requires\": [\n", fp);
628 for (size_t i = 0; i < d->modules.size (); i++)
629 {
630 if (i != 0)
631 fputs (",\n", fp);
632 fputs ("{\n", fp);
633
634 fputs ("\"logical-name\": ", fp);
635 p1689r5_write_filepath (d->modules[i], fp);
636 fputs ("\n", fp);
637
638 // TODO: header-unit information
639
640 fputs ("}\n", fp);
641 }
642 fputs ("]\n", fp);
643
644 fputs ("}\n", fp);
645
646 fputs ("],\n", fp);
647
648 fputs ("\"version\": 0,\n", fp);
649 fputs ("\"revision\": 0\n", fp);
650
651 fputs ("}\n", fp);
652 }
653
654 /* Write out a deps buffer to a file, in a form that can be read back
655 with deps_restore. Returns nonzero on error, in which case the
656 error number will be in errno. */
657
658 int
659 deps_save (class mkdeps *deps, FILE *f)
660 {
661 unsigned int i;
662 size_t size;
663
664 /* The cppreader structure contains makefile dependences. Write out this
665 structure. */
666
667 /* The number of dependences. */
668 size = deps->deps.size ();
669 if (fwrite (&size, sizeof (size), 1, f) != 1)
670 return -1;
671
672 /* The length of each dependence followed by the string. */
673 for (i = 0; i < deps->deps.size (); i++)
674 {
675 size = strlen (deps->deps[i]);
676 if (fwrite (&size, sizeof (size), 1, f) != 1)
677 return -1;
678 if (fwrite (deps->deps[i], size, 1, f) != 1)
679 return -1;
680 }
681
682 return 0;
683 }
684
685 /* Read back dependency information written with deps_save into
686 the deps sizefer. The third argument may be NULL, in which case
687 the dependency information is just skipped, or it may be a filename,
688 in which case that filename is skipped. */
689
690 int
691 deps_restore (class mkdeps *deps, FILE *fd, const char *self)
692 {
693 size_t size;
694 char *buf = NULL;
695 size_t buf_size = 0;
696
697 /* Number of dependences. */
698 if (fread (&size, sizeof (size), 1, fd) != 1)
699 return -1;
700
701 /* The length of each dependence string, followed by the string. */
702 for (unsigned i = size; i--;)
703 {
704 /* Read in # bytes in string. */
705 if (fread (&size, sizeof (size), 1, fd) != 1)
706 return -1;
707
708 if (size >= buf_size)
709 {
710 buf_size = size + 512;
711 buf = XRESIZEVEC (char, buf, buf_size);
712 }
713 if (fread (buf, 1, size, fd) != size)
714 {
715 XDELETEVEC (buf);
716 return -1;
717 }
718 buf[size] = 0;
719
720 /* Generate makefile dependencies from .pch if -nopch-deps. */
721 if (self != NULL && filename_cmp (buf, self) != 0)
722 deps_add_dep (deps, buf);
723 }
724
725 XDELETEVEC (buf);
726 return 0;
727 }