• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2013 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.
4 
5 #ifndef TOOLS_GN_TARGET_H_
6 #define TOOLS_GN_TARGET_H_
7 
8 #include <set>
9 #include <string>
10 #include <vector>
11 
12 #include "base/gtest_prod_util.h"
13 #include "base/logging.h"
14 #include "gn/action_values.h"
15 #include "gn/bundle_data.h"
16 #include "gn/config_values.h"
17 #include "gn/inherited_libraries.h"
18 #include "gn/item.h"
19 #include "gn/label_pattern.h"
20 #include "gn/label_ptr.h"
21 #include "gn/lib_file.h"
22 #include "gn/metadata.h"
23 #include "gn/output_file.h"
24 #include "gn/pointer_set.h"
25 #include "gn/rust_values.h"
26 #include "gn/source_file.h"
27 #include "gn/swift_values.h"
28 #include "gn/toolchain.h"
29 #include "gn/unique_vector.h"
30 
31 class DepsIteratorRange;
32 class Settings;
33 class Target;
34 class Toolchain;
35 
36 using TargetSet = PointerSet<const Target>;
37 
38 class Target : public Item {
39  public:
40   enum OutputType {
41     UNKNOWN,
42     GROUP,
43     EXECUTABLE,
44     SHARED_LIBRARY,
45     LOADABLE_MODULE,
46     STATIC_LIBRARY,
47     SOURCE_SET,
48     COPY_FILES,
49     ACTION,
50     ACTION_FOREACH,
51     BUNDLE_DATA,
52     CREATE_BUNDLE,
53     GENERATED_FILE,
54     RUST_LIBRARY,
55     RUST_PROC_MACRO,
56   };
57 
58   enum DepsIterationType {
59     DEPS_ALL,     // Iterates through all public, private, and data deps.
60     DEPS_LINKED,  // Iterates through all non-data dependencies.
61   };
62 
63   using FileList = std::vector<SourceFile>;
64   using StringVector = std::vector<std::string>;
65 
66   // We track the set of build files that may affect this target, please refer
67   // to Scope for how this is determined.
68   Target(const Settings* settings,
69          const Label& label,
70          const SourceFileSet& build_dependency_files = {});
71   ~Target() override;
72 
73   // Returns a string naming the output type.
74   static const char* GetStringForOutputType(OutputType type);
75 
76   // Item overrides.
77   Target* AsTarget() override;
78   const Target* AsTarget() const override;
79   bool OnResolved(Err* err) override;
80 
output_type()81   OutputType output_type() const { return output_type_; }
set_output_type(OutputType t)82   void set_output_type(OutputType t) { output_type_ = t; }
83 
84   // True for targets that compile source code (all types of libraries and
85   // executables).
86   bool IsBinary() const;
87 
88   // Can be linked into other targets.
89   bool IsLinkable() const;
90 
91   // True if the target links dependencies rather than propagated up the graph.
92   // This is also true of action and copy steps even though they don't link
93   // dependencies, because they also don't propagate libraries up.
94   bool IsFinal() const;
95 
96   // Set when the target should normally be treated as a data dependency. These
97   // do not need to be treated as inputs or hard dependencies for normal build
98   // steps, but have to be kept in the dependency tree to be properly
99   // propagated. Treating these as data only decreases superfluous rebuilds and
100   // increases parallelism.
101   bool IsDataOnly() const;
102 
103   // Will be the empty string to use the target label as the output name.
104   // See GetComputedOutputName().
output_name()105   const std::string& output_name() const { return output_name_; }
set_output_name(const std::string & name)106   void set_output_name(const std::string& name) { output_name_ = name; }
107 
108   // Returns the output name for this target, which is the output_name if
109   // specified, or the target label if not.
110   //
111   // Because this depends on the tool for this target, the toolchain must
112   // have been set before calling.
113   std::string GetComputedOutputName() const;
114 
output_prefix_override()115   bool output_prefix_override() const { return output_prefix_override_; }
set_output_prefix_override(bool prefix_override)116   void set_output_prefix_override(bool prefix_override) {
117     output_prefix_override_ = prefix_override;
118   }
119 
120   // Desired output directory for the final output. This will be used for
121   // the {{output_dir}} substitution in the tool if it is specified. If
122   // is_null, the tool default will be used.
output_dir()123   const SourceDir& output_dir() const { return output_dir_; }
set_output_dir(const SourceDir & dir)124   void set_output_dir(const SourceDir& dir) { output_dir_ = dir; }
125 
126   // The output extension is really a tri-state: unset (output_extension_set
127   // is false and the string is empty, meaning the default extension should be
128   // used), the output extension is set but empty (output should have no
129   // extension) and the output extension is set but nonempty (use the given
130   // extension).
output_extension()131   const std::string& output_extension() const { return output_extension_; }
set_output_extension(const std::string & extension)132   void set_output_extension(const std::string& extension) {
133     output_extension_ = extension;
134     output_extension_set_ = true;
135   }
output_extension_set()136   bool output_extension_set() const { return output_extension_set_; }
137 
sources()138   const FileList& sources() const { return sources_; }
sources()139   FileList& sources() { return sources_; }
140 
source_types_used()141   const SourceFileTypeSet& source_types_used() const {
142     return source_types_used_;
143   }
source_types_used()144   SourceFileTypeSet& source_types_used() { return source_types_used_; }
145 
146   // Set to true when all sources are public. This is the default. In this case
147   // the public headers list should be empty.
all_headers_public()148   bool all_headers_public() const { return all_headers_public_; }
set_all_headers_public(bool p)149   void set_all_headers_public(bool p) { all_headers_public_ = p; }
150 
151   // When all_headers_public is false, this is the list of public headers. It
152   // could be empty which would mean no headers are public.
public_headers()153   const FileList& public_headers() const { return public_headers_; }
public_headers()154   FileList& public_headers() { return public_headers_; }
155 
156   // Whether this target's includes should be checked by "gn check".
check_includes()157   bool check_includes() const { return check_includes_; }
set_check_includes(bool ci)158   void set_check_includes(bool ci) { check_includes_ = ci; }
159 
160   // Whether this static_library target should have code linked in.
complete_static_lib()161   bool complete_static_lib() const { return complete_static_lib_; }
set_complete_static_lib(bool complete)162   void set_complete_static_lib(bool complete) {
163     DCHECK_EQ(STATIC_LIBRARY, output_type_);
164     complete_static_lib_ = complete;
165   }
166 
167     // Whether this copy target is linkable.
copy_linkable_file()168     bool copy_linkable_file() const { return copy_linkable_file_; }
set_copy_linkable_file(bool linkable)169     void set_copy_linkable_file(bool linkable)
170     {
171         DCHECK_EQ(COPY_FILES, output_type_);
172         copy_linkable_file_ = linkable;
173     }
174 
175   // Metadata. Target takes ownership of the resulting scope.
176   const Metadata& metadata() const;
177   Metadata& metadata();
has_metadata()178   bool has_metadata() const { return metadata_.get(); }
179 
180   // Get metadata from this target and its dependencies. This is intended to
181   // be called after the target is resolved.
182   bool GetMetadata(const std::vector<std::string>& keys_to_extract,
183                    const std::vector<std::string>& keys_to_walk,
184                    const SourceDir& rebase_dir,
185                    bool deps_only,
186                    std::vector<Value>* result,
187                    TargetSet* targets_walked,
188                    Err* err) const;
189 
190   // GeneratedFile-related methods.
191   bool GenerateFile(Err* err) const;
192 
193   // Metadata collection methods for GeneratedFile targets.
194   struct GeneratedFile {
195     Value output_conversion_;
196     Value contents_;  // Value::NONE if metadata collection should occur.
197     SourceDir rebase_;
198     std::vector<std::string> data_keys_;
199     std::vector<std::string> walk_keys_;
200   };
201   const GeneratedFile& generated_file() const;
202   GeneratedFile& generated_file();
has_generated_file()203   bool has_generated_file() const { return generated_file_.get(); }
204 
contents()205   const Value& contents() const { return generated_file().contents_; }
set_contents(const Value & value)206   void set_contents(const Value& value) { generated_file().contents_ = value; }
output_conversion()207   const Value& output_conversion() const {
208     return generated_file().output_conversion_;
209   }
set_output_conversion(const Value & value)210   void set_output_conversion(const Value& value) {
211     generated_file().output_conversion_ = value;
212   }
213 
rebase()214   const SourceDir& rebase() const { return generated_file().rebase_; }
set_rebase(const SourceDir & value)215   void set_rebase(const SourceDir& value) { generated_file().rebase_ = value; }
data_keys()216   const std::vector<std::string>& data_keys() const {
217     return generated_file().data_keys_;
218   }
data_keys()219   std::vector<std::string>& data_keys() { return generated_file().data_keys_; }
walk_keys()220   const std::vector<std::string>& walk_keys() const {
221     return generated_file().walk_keys_;
222   }
walk_keys()223   std::vector<std::string>& walk_keys() { return generated_file().walk_keys_; }
224 
write_runtime_deps_output()225   OutputFile write_runtime_deps_output() const {
226     return write_runtime_deps_output_;
227   }
set_write_runtime_deps_output(const OutputFile & value)228   void set_write_runtime_deps_output(const OutputFile& value) {
229     write_runtime_deps_output_ = value;
230   }
231 
232   // Runtime dependencies. These are "file-like things" that can either be
233   // directories or files. They do not need to exist, these are just passed as
234   // runtime dependencies to external test systems as necessary.
data()235   const std::vector<std::string>& data() const { return data_; }
data()236   std::vector<std::string>& data() { return data_; }
237 
238   // Information about the bundle. Only valid for CREATE_BUNDLE target after
239   // they have been resolved.
240   const BundleData& bundle_data() const;
241   BundleData& bundle_data();
has_bundle_data()242   bool has_bundle_data() const { return bundle_data_.get(); }
243 
244   // Returns true if targets depending on this one should have an order
245   // dependency.
hard_dep()246   bool hard_dep() const {
247     return output_type_ == ACTION || output_type_ == ACTION_FOREACH ||
248            output_type_ == COPY_FILES || output_type_ == CREATE_BUNDLE ||
249            output_type_ == BUNDLE_DATA || output_type_ == GENERATED_FILE ||
250            builds_swift_module();
251   }
252 
253   // Returns the iterator range which can be used in range-based for loops
254   // to iterate over multiple types of deps in one loop:
255   //   for (const auto& pair : target->GetDeps(Target::DEPS_ALL)) ...
256   DepsIteratorRange GetDeps(DepsIterationType type) const;
257 
258   // Linked private dependencies.
private_deps()259   const LabelTargetVector& private_deps() const { return private_deps_; }
private_deps()260   LabelTargetVector& private_deps() { return private_deps_; }
261 
262   // Linked public dependencies.
public_deps()263   const LabelTargetVector& public_deps() const { return public_deps_; }
public_deps()264   LabelTargetVector& public_deps() { return public_deps_; }
265 
266   // Non-linked dependencies.
data_deps()267   const LabelTargetVector& data_deps() const { return data_deps_; }
data_deps()268   LabelTargetVector& data_deps() { return data_deps_; }
269 
270   // gen_deps only propagate the "should_generate" flag. These dependencies can
271   // have cycles so care should be taken if iterating over them recursively.
gen_deps()272   const LabelTargetVector& gen_deps() const { return gen_deps_; }
gen_deps()273   LabelTargetVector& gen_deps() { return gen_deps_; }
274 
275   // List of configs that this class inherits settings from. Once a target is
276   // resolved, this will also list all-dependent and public configs.
configs()277   const UniqueVector<LabelConfigPair>& configs() const { return configs_; }
configs()278   UniqueVector<LabelConfigPair>& configs() { return configs_; }
279 
280   // List of configs that all dependencies (direct and indirect) of this
281   // target get. These configs are not added to this target. Note that due
282   // to the way this is computed, there may be duplicates in this list.
all_dependent_configs()283   const UniqueVector<LabelConfigPair>& all_dependent_configs() const {
284     return all_dependent_configs_;
285   }
all_dependent_configs()286   UniqueVector<LabelConfigPair>& all_dependent_configs() {
287     return all_dependent_configs_;
288   }
289 
290   // List of configs that targets depending directly on this one get. These
291   // configs are also added to this target.
public_configs()292   const UniqueVector<LabelConfigPair>& public_configs() const {
293     return public_configs_;
294   }
public_configs()295   UniqueVector<LabelConfigPair>& public_configs() { return public_configs_; }
296 
297   // Dependencies that can include files from this target.
allow_circular_includes_from()298   const std::set<Label>& allow_circular_includes_from() const {
299     return allow_circular_includes_from_;
300   }
allow_circular_includes_from()301   std::set<Label>& allow_circular_includes_from() {
302     return allow_circular_includes_from_;
303   }
304 
inherited_libraries()305   const InheritedLibraries& inherited_libraries() const {
306     return inherited_libraries_;
307   }
308 
309   // This config represents the configuration set directly on this target.
310   ConfigValues& config_values();
311   const ConfigValues& config_values() const;
has_config_values()312   bool has_config_values() const { return config_values_.get(); }
313 
314   ActionValues& action_values();
315   const ActionValues& action_values() const;
has_action_values()316   bool has_action_values() const { return action_values_.get(); }
317 
318   SwiftValues& swift_values();
319   const SwiftValues& swift_values() const;
has_swift_values()320   bool has_swift_values() const { return swift_values_.get(); }
321 
322   // Return true if this targets builds a SwiftModule
builds_swift_module()323   bool builds_swift_module() const {
324     return IsBinary() && has_swift_values() &&
325            source_types_used().SwiftSourceUsed();
326   }
327 
328   RustValues& rust_values();
329   const RustValues& rust_values() const;
has_rust_values()330   bool has_rust_values() const { return rust_values_.get(); }
331 
332   // Transitive closure of libraries that are depended on by this target
rust_transitive_inherited_libs()333   const InheritedLibraries& rust_transitive_inherited_libs() const {
334     return rust_transitive_inherited_libs_;
335   }
rust_transitive_inheritable_libs()336   const InheritedLibraries& rust_transitive_inheritable_libs() const {
337     return rust_transitive_inheritable_libs_;
338   }
339 
all_lib_dirs()340   const UniqueVector<SourceDir>& all_lib_dirs() const { return all_lib_dirs_; }
all_libs()341   const UniqueVector<LibFile>& all_libs() const { return all_libs_; }
342 
all_framework_dirs()343   const UniqueVector<SourceDir>& all_framework_dirs() const {
344     return all_framework_dirs_;
345   }
all_frameworks()346   const UniqueVector<std::string>& all_frameworks() const {
347     return all_frameworks_;
348   }
all_weak_frameworks()349   const UniqueVector<std::string>& all_weak_frameworks() const {
350     return all_weak_frameworks_;
351   }
352 
recursive_hard_deps()353   const TargetSet& recursive_hard_deps() const { return recursive_hard_deps_; }
354 
friends()355   std::vector<LabelPattern>& friends() { return friends_; }
friends()356   const std::vector<LabelPattern>& friends() const { return friends_; }
357 
assert_no_deps()358   std::vector<LabelPattern>& assert_no_deps() { return assert_no_deps_; }
assert_no_deps()359   const std::vector<LabelPattern>& assert_no_deps() const {
360     return assert_no_deps_;
361   }
362 
363   // The toolchain is only known once this target is resolved (all if its
364   // dependencies are known). They will be null until then. Generally, this can
365   // only be used during target writing.
toolchain()366   const Toolchain* toolchain() const { return toolchain_; }
367 
368   // Sets the toolchain. The toolchain must include a tool for this target
369   // or the error will be set and the function will return false. Unusually,
370   // this function's "err" output is optional since this is commonly used
371   // frequently by unit tests which become needlessly verbose.
372   bool SetToolchain(const Toolchain* toolchain, Err* err = nullptr);
373 
374   // Once this target has been resolved, all outputs from the target will be
375   // listed here. This will include things listed in the "outputs" for an
376   // action or a copy step, and the output library or executable file(s) from
377   // binary targets.
378   //
379   // It will NOT include stamp files and object files.
computed_outputs()380   const std::vector<OutputFile>& computed_outputs() const {
381     return computed_outputs_;
382   }
383 
384   // Returns outputs from this target. The link output file is the one that
385   // other targets link to when they depend on this target. This will only be
386   // valid for libraries and will be empty for all other target types.
387   //
388   // The dependency output file is the file that should be used to express
389   // a dependency on this one. It could be the same as the link output file
390   // (this will be the case for static libraries). For shared libraries it
391   // could be the same or different than the link output file, depending on the
392   // system. For actions this will be the stamp file.
393   //
394   // These are only known once the target is resolved and will be empty before
395   // that. This is a cache of the files to prevent every target that depends on
396   // a given library from recomputing the same pattern.
link_output_file()397   const OutputFile& link_output_file() const { return link_output_file_; }
dependency_output_file()398   const OutputFile& dependency_output_file() const {
399     return dependency_output_file_;
400   }
401 
402   // The subset of computed_outputs that are considered runtime outputs.
runtime_outputs()403   const std::vector<OutputFile>& runtime_outputs() const {
404     return runtime_outputs_;
405   }
406 
407   // Computes and returns the outputs of this target expressed as SourceFiles.
408   //
409   // For binary target this depends on the tool for this target so the toolchain
410   // must have been loaded beforehand. This will happen asynchronously so
411   // calling this on a binary target before the build is complete will produce a
412   // race condition.
413   //
414   // To resolve this, the caller passes in whether the entire build is complete
415   // (this is used for the introspection commands which run after everything
416   // else).
417   //
418   // If the build is complete, the toolchain will be used for binary targets to
419   // compute the outputs. If the build is not complete, calling this function
420   // for binary targets will produce an error.
421   //
422   // The |loc_for_error| is used to blame a location for any errors produced. It
423   // can be empty if there is no range (like this is being called based on the
424   // command-line.
425   bool GetOutputsAsSourceFiles(const LocationRange& loc_for_error,
426                                bool build_complete,
427                                std::vector<SourceFile>* outputs,
428                                Err* err) const;
429 
430   // Computes the set of output files resulting from compiling the given source
431   // file.
432   //
433   // For binary targets, if the file can be compiled and the tool exists, fills
434   // the outputs in and writes the tool type to computed_tool_type. If the file
435   // is not compilable, returns false.
436   //
437   // For action_foreach and copy targets, applies the output pattern to the
438   // given file name to compute the outputs.
439   //
440   // For all other target types, just returns the target outputs because such
441   // targets conceptually process all of their inputs as one step.
442   //
443   // The function can succeed with a "NONE" tool type for object files which
444   // are just passed to the output. The output will always be overwritten, not
445   // appended to.
446   bool GetOutputFilesForSource(const SourceFile& source,
447                                const char** computed_tool_type,
448                                std::vector<OutputFile>* outputs) const;
449 
450  private:
451   FRIEND_TEST_ALL_PREFIXES(TargetTest, ResolvePrecompiledHeaders);
452 
453   // Pulls necessary information from dependencies to this one when all
454   // dependencies have been resolved.
455   void PullDependentTargetConfigs();
456   void PullDependentTargetLibsFrom(const Target* dep, bool is_public);
457   void PullDependentTargetLibs();
458   void PullRecursiveHardDeps();
459   void PullRecursiveBundleData();
460 
461   // Fills the link and dependency output files when a target is resolved.
462   bool FillOutputFiles(Err* err);
463 
464   // Checks precompiled headers from configs and makes sure the resulting
465   // values are in config_values_.
466   bool ResolvePrecompiledHeaders(Err* err);
467 
468   // Validates the given thing when a target is resolved.
469   bool CheckVisibility(Err* err) const;
470   bool CheckConfigVisibility(Err* err) const;
471   bool CheckTestonly(Err* err) const;
472   bool CheckAssertNoDeps(Err* err) const;
473   void CheckSourcesGenerated() const;
474   void CheckSourceGenerated(const SourceFile& source) const;
475   bool CheckSourceSetLanguages(Err* err) const;
476 
477   OutputType output_type_ = UNKNOWN;
478   std::string output_name_;
479   bool output_prefix_override_ = false;
480   SourceDir output_dir_;
481   std::string output_extension_;
482   bool output_extension_set_ = false;
483 
484   FileList sources_;
485   SourceFileTypeSet source_types_used_;
486   bool all_headers_public_ = true;
487   FileList public_headers_;
488   bool check_includes_ = true;
489   bool complete_static_lib_ = false;
490   bool copy_linkable_file_ = false;
491   std::vector<std::string> data_;
492   std::unique_ptr<BundleData> bundle_data_;
493   OutputFile write_runtime_deps_output_;
494 
495   LabelTargetVector private_deps_;
496   LabelTargetVector public_deps_;
497   LabelTargetVector data_deps_;
498   LabelTargetVector gen_deps_;
499 
500   // See getters for more info.
501   UniqueVector<LabelConfigPair> configs_;
502   UniqueVector<LabelConfigPair> all_dependent_configs_;
503   UniqueVector<LabelConfigPair> public_configs_;
504 
505   std::set<Label> allow_circular_includes_from_;
506 
507   // Static libraries, shared libraries, and source sets from transitive deps
508   // that need to be linked.
509   InheritedLibraries inherited_libraries_;
510 
511   // These libs and dirs are inherited from statically linked deps and all
512   // configs applying to this target.
513   UniqueVector<SourceDir> all_lib_dirs_;
514   UniqueVector<LibFile> all_libs_;
515 
516   // These frameworks and dirs are inherited from statically linked deps and
517   // all configs applying to this target.
518   UniqueVector<SourceDir> all_framework_dirs_;
519   UniqueVector<std::string> all_frameworks_;
520   UniqueVector<std::string> all_weak_frameworks_;
521 
522   // All hard deps from this target and all dependencies. Filled in when this
523   // target is marked resolved. This will not include the current target.
524   TargetSet recursive_hard_deps_;
525 
526   std::vector<LabelPattern> friends_;
527   std::vector<LabelPattern> assert_no_deps_;
528 
529   // Used for all binary targets, and for inputs in regular targets. The
530   // precompiled header values in this struct will be resolved to the ones to
531   // use for this target, if precompiled headers are used.
532   std::unique_ptr<ConfigValues> config_values_;
533 
534   // Used for action[_foreach] targets.
535   std::unique_ptr<ActionValues> action_values_;
536 
537   // Used for Rust targets.
538   std::unique_ptr<RustValues> rust_values_;
539 
540   // Used by all targets, only useful to generate Rust targets though. These
541   // present 2 different views of the public flags:
542   //
543   // Lists all transitive libraries, and for each one the public bit says if
544   // there is a public chain such that this target can make direct use of the
545   // lib. For each library marked public: "I have access to these targets."
546   InheritedLibraries rust_transitive_inherited_libs_;
547   // Lists all transitive libraries, and for each one the public bit says if a
548   // target depending on this target would inherit the libraries as public too.
549   // For each library marked public: "If you depend on me, you get access to
550   // these targets."
551   InheritedLibraries rust_transitive_inheritable_libs_;
552 
553   // User for Swift targets.
554   std::unique_ptr<SwiftValues> swift_values_;
555 
556   // Toolchain used by this target. Null until target is resolved.
557   const Toolchain* toolchain_ = nullptr;
558 
559   // Output files. Empty until the target is resolved.
560   std::vector<OutputFile> computed_outputs_;
561   OutputFile link_output_file_;
562   OutputFile dependency_output_file_;
563   std::vector<OutputFile> runtime_outputs_;
564 
565   std::unique_ptr<Metadata> metadata_;
566 
567   // GeneratedFile as metadata collection values.
568   std::unique_ptr<GeneratedFile> generated_file_;
569 
570   Target(const Target&) = delete;
571   Target& operator=(const Target&) = delete;
572 };
573 
574 extern const char kExecution_Help[];
575 
576 #endif  // TOOLS_GN_TARGET_H_
577