1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "tools/gn/header_checker.h"
10 #include "base/files/file_util.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/strings/string_util.h"
13 #include "base/threading/sequenced_worker_pool.h"
14 #include "tools/gn/build_settings.h"
15 #include "tools/gn/builder.h"
16 #include "tools/gn/c_include_iterator.h"
17 #include "tools/gn/config.h"
18 #include "tools/gn/err.h"
19 #include "tools/gn/filesystem_utils.h"
20 #include "tools/gn/scheduler.h"
21 #include "tools/gn/source_file_type.h"
22 #include "tools/gn/target.h"
23 #include "tools/gn/trace.h"
27 struct PublicGeneratedPair
{
28 PublicGeneratedPair() : is_public(false), is_generated(false) {}
33 // If the given file is in the "gen" folder, trims this so it treats the gen
34 // directory as the source root:
35 // //out/Debug/gen/foo/bar.h -> //foo/bar.h
36 // If the file isn't in the generated root, returns the input unchanged.
37 SourceFile
RemoveRootGenDirFromFile(const Target
* target
,
38 const SourceFile
& file
) {
39 const SourceDir
& gen
= target
->settings()->toolchain_gen_dir();
40 if (!gen
.is_null() && StartsWithASCII(file
.value(), gen
.value(), true))
41 return SourceFile("//" + file
.value().substr(gen
.value().size()));
45 // This class makes InputFiles on the stack as it reads files to check. When
46 // we throw an error, the Err indicates a locatin which has a pointer to
47 // an InputFile that must persist as long as the Err does.
49 // To make this work, this function creates a clone of the InputFile managed
50 // by the InputFileManager so the error can refer to something that
51 // persists. This means that the current file contents will live as long as
52 // the program, but this is OK since we're erroring out anyway.
53 LocationRange
CreatePersistentRange(const InputFile
& input_file
,
54 const LocationRange
& range
) {
55 InputFile
* clone_input_file
;
56 std::vector
<Token
>* tokens
; // Don't care about this.
57 scoped_ptr
<ParseNode
>* parse_root
; // Don't care about this.
59 g_scheduler
->input_file_manager()->AddDynamicInput(
60 input_file
.name(), &clone_input_file
, &tokens
, &parse_root
);
61 clone_input_file
->SetContents(input_file
.contents());
63 return LocationRange(Location(clone_input_file
,
64 range
.begin().line_number(),
65 range
.begin().char_offset(),
66 -1 /* TODO(scottmg) */),
67 Location(clone_input_file
,
68 range
.end().line_number(),
69 range
.end().char_offset(),
70 -1 /* TODO(scottmg) */));
73 // Given a reverse dependency chain where the target chain[0]'s includes are
74 // being used by chain[end] and not all deps are public, returns the string
75 // describing the error.
76 std::string
GetDependencyChainPublicError(
77 const HeaderChecker::Chain
& chain
) {
78 std::string ret
= "The target:\n " +
79 chain
[chain
.size() - 1].target
->label().GetUserVisibleName(false) +
80 "\nis including a file from the target:\n " +
81 chain
[0].target
->label().GetUserVisibleName(false) +
84 // Invalid chains should always be 0 (no chain) or more than two
85 // (intermediate private dependencies). 1 and 2 are impossible because a
86 // target can always include headers from itself and its direct dependents.
87 DCHECK(chain
.size() != 1 && chain
.size() != 2);
89 ret
+= "There is no dependency chain between these targets.";
91 // Indirect dependency chain, print the chain.
92 ret
+= "\nIt's usually best to depend directly on the destination target.\n"
93 "In some cases, the destination target is considered a subcomponent\n"
94 "of an intermediate target. In this case, the intermediate target\n"
95 "should depend publicly on the destination to forward the ability\n"
96 "to include headers.\n"
98 "Dependency chain (there may also be others):\n";
100 for (int i
= static_cast<int>(chain
.size()) - 1; i
>= 0; i
--) {
101 ret
.append(" " + chain
[i
].target
->label().GetUserVisibleName(false));
103 // Identify private dependencies so the user can see where in the
104 // dependency chain things went bad. Don't list this for the first link
105 // in the chain since direct dependencies are OK, and listing that as
106 // "private" may make people feel like they need to fix it.
107 if (i
== static_cast<int>(chain
.size()) - 1 || chain
[i
- 1].is_public
)
110 ret
.append(" --[private]-->");
118 // Returns true if the two targets have the same label not counting the
120 bool TargetLabelsMatchExceptToolchain(const Target
* a
, const Target
* b
) {
121 return a
->label().dir() == b
->label().dir() &&
122 a
->label().name() == b
->label().name();
127 HeaderChecker::HeaderChecker(const BuildSettings
* build_settings
,
128 const std::vector
<const Target
*>& targets
)
129 : main_loop_(base::MessageLoop::current()),
130 build_settings_(build_settings
) {
131 for (const auto& target
: targets
)
132 AddTargetToFileMap(target
, &file_map_
);
135 HeaderChecker::~HeaderChecker() {
138 bool HeaderChecker::Run(const std::vector
<const Target
*>& to_check
,
140 std::vector
<Err
>* errors
) {
141 FileMap files_to_check
;
142 for (const auto& check
: to_check
)
143 AddTargetToFileMap(check
, &files_to_check
);
144 RunCheckOverFiles(files_to_check
, force_check
);
152 void HeaderChecker::RunCheckOverFiles(const FileMap
& files
, bool force_check
) {
156 scoped_refptr
<base::SequencedWorkerPool
> pool(
157 new base::SequencedWorkerPool(16, "HeaderChecker"));
158 for (const auto& file
: files
) {
159 // Only check C-like source files (RC files also have includes).
160 SourceFileType type
= GetSourceFileType(file
.first
);
161 if (type
!= SOURCE_CC
&& type
!= SOURCE_H
&& type
!= SOURCE_C
&&
162 type
!= SOURCE_M
&& type
!= SOURCE_MM
&& type
!= SOURCE_RC
)
165 // If any target marks it as generated, don't check it.
166 bool is_generated
= false;
167 for (const auto& vect_i
: file
.second
)
168 is_generated
|= vect_i
.is_generated
;
172 for (const auto& vect_i
: file
.second
) {
173 if (vect_i
.target
->check_includes()) {
174 pool
->PostWorkerTaskWithShutdownBehavior(
176 base::Bind(&HeaderChecker::DoWork
, this, vect_i
.target
, file
.first
),
177 base::SequencedWorkerPool::BLOCK_SHUTDOWN
);
182 // After this call we're single-threaded again.
186 void HeaderChecker::DoWork(const Target
* target
, const SourceFile
& file
) {
188 if (!CheckFile(target
, file
, &err
)) {
189 base::AutoLock
lock(lock_
);
190 errors_
.push_back(err
);
195 void HeaderChecker::AddTargetToFileMap(const Target
* target
, FileMap
* dest
) {
196 // Files in the sources have this public bit by default.
197 bool default_public
= target
->all_headers_public();
199 std::map
<SourceFile
, PublicGeneratedPair
> files_to_public
;
201 // First collect the normal files, they get the default visibility. Always
202 // trim the root gen dir if it exists. This will only exist on outputs of an
203 // action, but those are often then wired into the sources of a compiled
204 // target to actually compile generated code. If you depend on the compiled
205 // target, it should be enough to be able to include the header.
206 for (const auto& source
: target
->sources()) {
207 SourceFile file
= RemoveRootGenDirFromFile(target
, source
);
208 files_to_public
[file
].is_public
= default_public
;
211 // Add in the public files, forcing them to public. This may overwrite some
212 // entries, and it may add new ones.
213 if (default_public
) // List only used when default is not public.
214 DCHECK(target
->public_headers().empty());
215 for (const auto& source
: target
->public_headers()) {
216 SourceFile file
= RemoveRootGenDirFromFile(target
, source
);
217 files_to_public
[file
].is_public
= true;
220 // Add in outputs from actions. These are treated as public (since if other
221 // targets can't use them, then there wouldn't be any point in outputting).
222 std::vector
<SourceFile
> outputs
;
223 target
->action_values().GetOutputsAsSourceFiles(target
, &outputs
);
224 for (const auto& output
: outputs
) {
225 // For generated files in the "gen" directory, add the filename to the
226 // map assuming "gen" is the source root. This means that when files include
227 // the generated header relative to there (the recommended practice), we'll
229 SourceFile output_file
= RemoveRootGenDirFromFile(target
, output
);
230 PublicGeneratedPair
* pair
= &files_to_public
[output_file
];
231 pair
->is_public
= true;
232 pair
->is_generated
= true;
235 // Add the merged list to the master list of all files.
236 for (const auto& cur
: files_to_public
) {
237 (*dest
)[cur
.first
].push_back(TargetInfo(
238 target
, cur
.second
.is_public
, cur
.second
.is_generated
));
242 bool HeaderChecker::IsFileInOuputDir(const SourceFile
& file
) const {
243 const std::string
& build_dir
= build_settings_
->build_dir().value();
244 return file
.value().compare(0, build_dir
.size(), build_dir
) == 0;
247 // This current assumes all include paths are relative to the source root
248 // which is generally the case for Chromium.
250 // A future enhancement would be to search the include path for the target
251 // containing the source file containing this include and find the file to
252 // handle the cases where people do weird things with the paths.
253 SourceFile
HeaderChecker::SourceFileForInclude(
254 const base::StringPiece
& input
) const {
255 std::string
str("//");
256 input
.AppendToString(&str
);
257 return SourceFile(str
);
260 bool HeaderChecker::CheckFile(const Target
* from_target
,
261 const SourceFile
& file
,
263 ScopedTrace
trace(TraceItem::TRACE_CHECK_HEADER
, file
.value());
265 // Sometimes you have generated source files included as sources in another
266 // target. These won't exist at checking time. Since we require all generated
267 // files to be somewhere in the output tree, we can just check the name to
268 // see if they should be skipped.
269 if (IsFileInOuputDir(file
))
272 base::FilePath path
= build_settings_
->GetFullPath(file
);
273 std::string contents
;
274 if (!base::ReadFileToString(path
, &contents
)) {
275 *err
= Err(from_target
->defined_from(), "Source file not found.",
276 "The target:\n " + from_target
->label().GetUserVisibleName(false) +
277 "\nhas a source file:\n " + file
.value() +
278 "\nwhich was not found.");
282 InputFile
input_file(file
);
283 input_file
.SetContents(contents
);
285 CIncludeIterator
iter(&input_file
);
286 base::StringPiece current_include
;
288 while (iter
.GetNextIncludeString(¤t_include
, &range
)) {
289 SourceFile include
= SourceFileForInclude(current_include
);
290 if (!CheckInclude(from_target
, input_file
, include
, range
, err
))
297 // If the file exists:
298 // - It must be in one or more dependencies of the given target.
299 // - Those dependencies must have visibility from the source file.
300 // - The header must be in the public section of those dependeices.
301 // - Those dependencies must either have no direct dependent configs with
302 // flags that affect the compiler, or those direct dependent configs apply
303 // to the "from_target" (it's one "hop" away). This ensures that if the
304 // include file needs needs compiler settings to compile it, that those
305 // settings are applied to the file including it.
306 bool HeaderChecker::CheckInclude(const Target
* from_target
,
307 const InputFile
& source_file
,
308 const SourceFile
& include_file
,
309 const LocationRange
& range
,
311 // Assume if the file isn't declared in our sources that we don't need to
312 // check it. It would be nice if we could give an error if this happens, but
313 // our include finder is too primitive and returns all includes, even if
314 // they're in a #if not executed in the current build. In that case, it's
315 // not unusual for the buildfiles to not specify that header at all.
316 FileMap::const_iterator found
= file_map_
.find(include_file
);
317 if (found
== file_map_
.end())
320 const TargetVector
& targets
= found
->second
;
321 Chain chain
; // Prevent reallocating in the loop.
323 // For all targets containing this file, we require that at least one be
324 // a direct or public dependency of the current target, and that the header
325 // is public within the target.
327 // If there is more than one target containing this header, we may encounter
328 // some error cases before finding a good one. This error stores the previous
329 // one encountered, which we may or may not throw away.
332 bool found_dependency
= false;
333 for (size_t i
= 0; i
< targets
.size(); i
++) {
334 // We always allow source files in a target to include headers also in that
336 const Target
* to_target
= targets
[i
].target
;
337 if (to_target
== from_target
)
340 // Additionally, allow a target to include files from that same target
341 // in other toolchains. This is a bit of a hack to account for the fact that
342 // the include finder doesn't understand the preprocessor.
344 // If a source file conditionally depends on a platform-specific include in
345 // the same target, and there is a cross-compile such that GN sees
346 // definitions of the target both with and without that include, it would
347 // give an error that the target needs to depend on itself in the other
348 // toolchain (where the platform-specific header is defined as a source).
349 if (TargetLabelsMatchExceptToolchain(to_target
, from_target
))
352 bool is_permitted_chain
= false;
353 if (IsDependencyOf(to_target
, from_target
, &chain
, &is_permitted_chain
)) {
354 DCHECK(chain
.size() >= 2);
355 DCHECK(chain
[0].target
== to_target
);
356 DCHECK(chain
[chain
.size() - 1].target
== from_target
);
358 found_dependency
= true;
360 if (targets
[i
].is_public
&& is_permitted_chain
) {
361 // This one is OK, we're done.
366 // Diagnose the error.
367 if (!targets
[i
].is_public
) {
368 // Danger: must call CreatePersistentRange to put in Err.
370 CreatePersistentRange(source_file
, range
),
371 "Including a private header.",
372 "This file is private to the target " +
373 targets
[i
].target
->label().GetUserVisibleName(false));
374 } else if (!is_permitted_chain
) {
376 CreatePersistentRange(source_file
, range
),
377 "Can't include this header from here.",
378 GetDependencyChainPublicError(chain
));
383 to_target
->allow_circular_includes_from().find(from_target
->label()) !=
384 to_target
->allow_circular_includes_from().end()) {
385 // Not a dependency, but this include is whitelisted from the destination.
386 found_dependency
= true;
392 if (!found_dependency
) {
393 DCHECK(!last_error
.has_error());
394 *err
= MakeUnreachableError(source_file
, range
, from_target
, targets
);
397 if (last_error
.has_error()) {
398 // Found at least one dependency chain above, but it had an error.
403 // One thing we didn't check for is targets that expose their dependents
404 // headers in their own public headers.
406 // Say we have A -> B -> C. If C has public_configs, everybody getting headers
407 // from C should get the configs also or things could be out-of-sync. Above,
408 // we check for A including C's headers directly, but A could also include a
409 // header from B that in turn includes a header from C.
411 // There are two ways to solve this:
412 // - If a public header in B includes C, force B to publicly depend on C.
413 // This is possible to check, but might be super annoying because most
414 // targets (especially large leaf-node targets) don't declare
415 // public/private headers and you'll get lots of false positives.
417 // - Save the includes found in each file and actually compute the graph of
418 // includes to detect when A implicitly includes C's header. This will not
419 // have the annoying false positive problem, but is complex to write.
424 bool HeaderChecker::IsDependencyOf(const Target
* search_for
,
425 const Target
* search_from
,
427 bool* is_permitted
) const {
428 if (search_for
== search_from
) {
429 // A target is always visible from itself.
430 *is_permitted
= true;
434 // Find the shortest public dependency chain.
435 if (IsDependencyOf(search_for
, search_from
, true, chain
)) {
436 *is_permitted
= true;
440 // If not, try to find any dependency chain at all.
441 if (IsDependencyOf(search_for
, search_from
, false, chain
)) {
442 *is_permitted
= false;
446 *is_permitted
= false;
450 bool HeaderChecker::IsDependencyOf(const Target
* search_for
,
451 const Target
* search_from
,
452 bool require_permitted
,
453 Chain
* chain
) const {
454 // This method conducts a breadth-first search through the dependency graph
455 // to find a shortest chain from search_from to search_for.
457 // work_queue maintains a queue of targets which need to be considered as
458 // part of this chain, in the order they were first traversed.
460 // Each time a new transitive dependency of search_from is discovered for
461 // the first time, it is added to work_queue and a "breadcrumb" is added,
462 // indicating which target it was reached from when first discovered.
464 // Once this search finds search_for, the breadcrumbs are used to reconstruct
465 // a shortest dependency chain (in reverse order) from search_from to
468 std::map
<const Target
*, ChainLink
> breadcrumbs
;
469 std::queue
<ChainLink
> work_queue
;
470 work_queue
.push(ChainLink(search_from
, true));
472 bool first_time
= true;
473 while (!work_queue
.empty()) {
474 ChainLink cur_link
= work_queue
.front();
475 const Target
* target
= cur_link
.target
;
478 if (target
== search_for
) {
479 // Found it! Reconstruct the chain.
481 while (target
!= search_from
) {
482 chain
->push_back(cur_link
);
483 cur_link
= breadcrumbs
[target
];
484 target
= cur_link
.target
;
486 chain
->push_back(ChainLink(search_from
, true));
490 // Always consider public dependencies as possibilities.
491 for (const auto& dep
: target
->public_deps()) {
492 if (breadcrumbs
.insert(std::make_pair(dep
.ptr
, cur_link
)).second
)
493 work_queue
.push(ChainLink(dep
.ptr
, true));
496 if (first_time
|| !require_permitted
) {
497 // Consider all dependencies since all target paths are allowed, so add
498 // in private ones. Also do this the first time through the loop, since
499 // a target can include headers from its direct deps regardless of
500 // public/private-ness.
502 for (const auto& dep
: target
->private_deps()) {
503 if (breadcrumbs
.insert(std::make_pair(dep
.ptr
, cur_link
)).second
)
504 work_queue
.push(ChainLink(dep
.ptr
, false));
512 Err
HeaderChecker::MakeUnreachableError(
513 const InputFile
& source_file
,
514 const LocationRange
& range
,
515 const Target
* from_target
,
516 const TargetVector
& targets
) {
517 // Normally the toolchains will all match, but when cross-compiling, we can
518 // get targets with more than one toolchain in the list of possibilities.
519 std::vector
<const Target
*> targets_with_matching_toolchains
;
520 std::vector
<const Target
*> targets_with_other_toolchains
;
521 for (const TargetInfo
& candidate
: targets
) {
522 if (candidate
.target
->toolchain() == from_target
->toolchain())
523 targets_with_matching_toolchains
.push_back(candidate
.target
);
525 targets_with_other_toolchains
.push_back(candidate
.target
);
528 // It's common when cross-compiling to have a target with the same file in
529 // more than one toolchain. We could output all of them, but this is
530 // generally confusing to people (most end-users won't understand toolchains
533 // So delete any candidates in other toolchains that also appear in the same
534 // toolchain as the from_target.
535 for (int other_index
= 0;
536 other_index
< static_cast<int>(targets_with_other_toolchains
.size());
538 for (const Target
* cur_matching
: targets_with_matching_toolchains
) {
539 if (TargetLabelsMatchExceptToolchain(
540 cur_matching
, targets_with_other_toolchains
[other_index
])) {
541 // Found a duplicate, erase it.
542 targets_with_other_toolchains
.erase(
543 targets_with_other_toolchains
.begin() + other_index
);
550 // Only display toolchains on labels if they don't all match.
551 bool include_toolchain
= !targets_with_other_toolchains
.empty();
553 std::string msg
= "It is not in any dependency of\n " +
554 from_target
->label().GetUserVisibleName(include_toolchain
);
555 msg
+= "\nThe include file is in the target(s):\n";
556 for (const auto& target
: targets_with_matching_toolchains
)
557 msg
+= " " + target
->label().GetUserVisibleName(include_toolchain
) + "\n";
558 for (const auto& target
: targets_with_other_toolchains
)
559 msg
+= " " + target
->label().GetUserVisibleName(include_toolchain
) + "\n";
560 if (targets_with_other_toolchains
.size() +
561 targets_with_matching_toolchains
.size() > 1)
562 msg
+= "at least one of ";
563 msg
+= "which should somehow be reachable.";
565 // Danger: must call CreatePersistentRange to put in Err.
566 return Err(CreatePersistentRange(source_file
, range
),
567 "Include not allowed.", msg
);