1//===-- MakeSupport.cpp
2//--------------------------------------------------*-===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Basic/MakeSupport.h"
11#include "llvm/ADT/SmallString.h"
12#include "llvm/Support/Path.h"
13#include "llvm/Support/raw_ostream.h"
14
15void clang::quoteMakeTarget(StringRef Target, SmallVectorImpl<char> &Res) {
16 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
17 switch (Target[i]) {
18 case ' ':
19 case '\t':
20 // Escape the preceding backslashes
21 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
22 Res.push_back(Elt: '\\');
23
24 // Escape the space/tab
25 Res.push_back(Elt: '\\');
26 break;
27 case '$':
28 Res.push_back(Elt: '$');
29 break;
30 case '#':
31 Res.push_back(Elt: '\\');
32 break;
33 default:
34 break;
35 }
36
37 Res.push_back(Elt: Target[i]);
38 }
39}
40
41/// Print the filename, with escaping or quoting that accommodates the three
42/// most likely tools that use dependency files: GNU Make, BSD Make, and
43/// NMake/Jom.
44///
45/// BSD Make is the simplest case: It does no escaping at all. This means
46/// characters that are normally delimiters, i.e. space and # (the comment
47/// character) simply aren't supported in filenames.
48///
49/// GNU Make does allow space and # in filenames, but to avoid being treated
50/// as a delimiter or comment, these must be escaped with a backslash. Because
51/// backslash is itself the escape character, if a backslash appears in a
52/// filename, it should be escaped as well. (As a special case, $ is escaped
53/// as $$, which is the normal Make way to handle the $ character.)
54/// For compatibility with BSD Make and historical practice, if GNU Make
55/// un-escapes characters in a filename but doesn't find a match, it will
56/// retry with the unmodified original string.
57///
58/// GCC tries to accommodate both Make formats by escaping any space or #
59/// characters in the original filename, but not escaping backslashes. The
60/// apparent intent is so that filenames with backslashes will be handled
61/// correctly by BSD Make, and by GNU Make in its fallback mode of using the
62/// unmodified original string; filenames with # or space characters aren't
63/// supported by BSD Make at all, but will be handled correctly by GNU Make
64/// due to the escaping.
65///
66/// A corner case that GCC gets only partly right is when the original filename
67/// has a backslash immediately followed by space or #. GNU Make would expect
68/// this backslash to be escaped; however GCC escapes the original backslash
69/// only when followed by space, not #. It will therefore take a dependency
70/// from a directive such as
71/// #include "a\ b\#c.h"
72/// and emit it as
73/// a\\\ b\\#c.h
74/// which GNU Make will interpret as
75/// a\ b\
76/// followed by a comment. Failing to find this file, it will fall back to the
77/// original string, which probably doesn't exist either; in any case it won't
78/// find
79/// a\ b\#c.h
80/// which is the actual filename specified by the include directive.
81///
82/// Clang does what GCC does, rather than what GNU Make expects.
83///
84/// NMake/Jom has a different set of scary characters, but wraps filespecs in
85/// double-quotes to avoid misinterpreting them; see
86/// https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx for NMake info,
87/// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
88/// for Windows file-naming info.
89static void printFilename(llvm::raw_ostream &OS, llvm::StringRef Filename,
90 clang::DependencyOutputFormat OutputFormat) {
91 // Convert filename to platform native path
92 llvm::SmallString<256> NativePath;
93 llvm::sys::path::native(path: Filename, result&: NativePath);
94
95 if (OutputFormat == clang::DependencyOutputFormat::NMake) {
96 // Add quotes if needed. These are the characters listed as "special" to
97 // NMake, that are legal in a Windows filespec, and that could cause
98 // misinterpretation of the dependency string.
99 if (NativePath.find_first_of(Chars: " #${}^!") != llvm::StringRef::npos)
100 OS << '\"' << NativePath << '\"';
101 else
102 OS << NativePath;
103 return;
104 }
105 assert(OutputFormat == clang::DependencyOutputFormat::Make);
106 for (unsigned i = 0, e = NativePath.size(); i != e; ++i) {
107 if (NativePath[i] == '#') // Handle '#' the broken gcc way.
108 OS << '\\';
109 else if (NativePath[i] == ' ') { // Handle space correctly.
110 OS << '\\';
111 unsigned j = i;
112 while (j > 0 && NativePath[--j] == '\\')
113 OS << '\\';
114 } else if (NativePath[i] == '$') // $ is escaped by $$.
115 OS << '$';
116 OS << NativePath[i];
117 }
118}
119
120void clang::printMakeDependencyFile(llvm::raw_ostream &OS,
121 llvm::ArrayRef<std::string> Targets,
122 llvm::ArrayRef<std::string> Files,
123 DependencyOutputFormat Format,
124 bool PhonyTargets,
125 unsigned InputFileIndex) {
126 // Write out the dependency targets, trying to avoid overly long
127 // lines when possible. We try our best to emit exactly the same
128 // dependency file as GCC>=10, assuming the included files are the
129 // same.
130 const unsigned MaxColumns = 75;
131 unsigned Columns = 0;
132
133 for (StringRef Target : Targets) {
134 unsigned N = Target.size();
135 if (Columns == 0) {
136 Columns += N;
137 } else if (Columns + N + 2 > MaxColumns) {
138 Columns = N + 2;
139 OS << " \\\n ";
140 } else {
141 Columns += N + 1;
142 OS << ' ';
143 }
144 // Targets already quoted as needed.
145 OS << Target;
146 }
147
148 OS << ':';
149 Columns += 1;
150
151 // Now add each dependency in the order it was seen, but avoiding
152 // duplicates.
153 for (StringRef File : Files) {
154 if (File == "<stdin>")
155 continue;
156 // Start a new line if this would exceed the column limit. Make
157 // sure to leave space for a trailing " \" in case we need to
158 // break the line on the next iteration.
159 unsigned N = File.size();
160 if (Columns + (N + 1) + 2 > MaxColumns) {
161 OS << " \\\n ";
162 Columns = 2;
163 }
164 OS << ' ';
165 printFilename(OS, Filename: File, OutputFormat: Format);
166 Columns += N + 1;
167 }
168 OS << '\n';
169
170 // Create phony targets if requested.
171 if (PhonyTargets && !Files.empty()) {
172 unsigned Index = 0;
173 for (auto I = Files.begin(), E = Files.end(); I != E; ++I) {
174 if (Index++ == InputFileIndex)
175 continue;
176 printFilename(OS, Filename: *I, OutputFormat: Format);
177 OS << ":\n";
178 }
179 }
180}
181