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.
5 #include "tools/gn/ninja_binary_target_writer.h"
9 #include "base/strings/string_util.h"
10 #include "tools/gn/config_values_extractors.h"
11 #include "tools/gn/err.h"
12 #include "tools/gn/escape.h"
13 #include "tools/gn/string_utils.h"
17 // Returns the proper escape options for writing compiler and linker flags.
18 EscapeOptions GetFlagOptions() {
20 opts.mode = ESCAPE_NINJA;
22 // Some flag strings are actually multiple flags that expect to be just
23 // added to the command line. We assume that quoting is done by the
24 // buildfiles if it wants such things quoted.
25 opts.inhibit_quoting = true;
32 options.mode = ESCAPE_SHELL;
35 void operator()(const std::string& s, std::ostream& out) const {
37 EscapeStringToStream(out, s, options);
40 EscapeOptions options;
43 struct IncludeWriter {
44 IncludeWriter(PathOutput& path_output,
47 path_output_(path_output),
48 old_inhibit_quoting_(path_output.inhibit_quoting()) {
49 // Inhibit quoting since we'll put quotes around the whole thing ourselves.
50 // Since we're writing in NINJA escaping mode, this won't actually do
51 // anything, but I think we may need to change to shell-and-then-ninja
52 // escaping for this in the future.
53 path_output_.set_inhibit_quoting(true);
56 path_output_.set_inhibit_quoting(old_inhibit_quoting_);
59 void operator()(const SourceDir& d, std::ostream& out) const {
61 // It's important not to include the trailing slash on directories or on
62 // Windows it will be a backslash and the compiler might think we're
63 // escaping the quote!
64 path_output_.WriteDir(out, d, PathOutput::DIR_NO_LAST_SLASH);
68 const NinjaHelper& helper;
69 PathOutput& path_output_;
70 bool old_inhibit_quoting_; // So we can put the PathOutput back.
73 Toolchain::ToolType GetToolTypeForTarget(const Target* target) {
74 switch (target->output_type()) {
75 case Target::STATIC_LIBRARY:
76 return Toolchain::TYPE_ALINK;
77 case Target::SHARED_LIBRARY:
78 return Toolchain::TYPE_SOLINK;
79 case Target::EXECUTABLE:
80 return Toolchain::TYPE_LINK;
82 return Toolchain::TYPE_NONE;
88 NinjaBinaryTargetWriter::NinjaBinaryTargetWriter(const Target* target,
89 const Toolchain* toolchain,
91 : NinjaTargetWriter(target, toolchain, out),
92 tool_type_(GetToolTypeForTarget(target)){
95 NinjaBinaryTargetWriter::~NinjaBinaryTargetWriter() {
98 void NinjaBinaryTargetWriter::Run() {
101 std::vector<OutputFile> obj_files;
102 WriteSources(&obj_files);
104 if (target_->output_type() == Target::SOURCE_SET)
105 WriteSourceSetStamp(obj_files);
107 WriteLinkerStuff(obj_files);
110 void NinjaBinaryTargetWriter::WriteCompilerVars() {
113 RecursiveTargetConfigToStream<std::string>(target_, &ConfigValues::defines,
114 DefineWriter(), out_);
117 // Include directories.
118 out_ << "includes =";
119 RecursiveTargetConfigToStream<SourceDir>(target_, &ConfigValues::include_dirs,
120 IncludeWriter(path_output_, helper_),
125 // C flags and friends.
126 EscapeOptions flag_escape_options = GetFlagOptions();
127 #define WRITE_FLAGS(name) \
128 out_ << #name " ="; \
129 RecursiveTargetConfigStringsToStream(target_, &ConfigValues::name, \
130 flag_escape_options, out_); \
134 WRITE_FLAGS(cflags_c)
135 WRITE_FLAGS(cflags_cc)
136 WRITE_FLAGS(cflags_objc)
137 WRITE_FLAGS(cflags_objcc)
144 void NinjaBinaryTargetWriter::WriteSources(
145 std::vector<OutputFile>* object_files) {
146 const Target::FileList& sources = target_->sources();
147 object_files->reserve(sources.size());
149 std::string implicit_deps = GetSourcesImplicitDeps();
151 for (size_t i = 0; i < sources.size(); i++) {
152 const SourceFile& input_file = sources[i];
154 SourceFileType input_file_type = GetSourceFileType(input_file,
155 settings_->target_os());
156 if (input_file_type == SOURCE_UNKNOWN)
157 continue; // Skip unknown file types.
158 std::string command =
159 helper_.GetRuleForSourceType(settings_, input_file_type);
161 continue; // Skip files not needing compilation.
163 OutputFile output_file = helper_.GetOutputFileForSource(
164 target_, input_file, input_file_type);
165 object_files->push_back(output_file);
168 path_output_.WriteFile(out_, output_file);
169 out_ << ": " << command << " ";
170 path_output_.WriteFile(out_, input_file);
171 out_ << implicit_deps << std::endl;
176 void NinjaBinaryTargetWriter::WriteLinkerStuff(
177 const std::vector<OutputFile>& object_files) {
178 // Manifest file on Windows.
179 // TODO(brettw) this seems not to be necessary for static libs, skip in
181 OutputFile windows_manifest;
182 if (settings_->IsWin()) {
183 windows_manifest.value().assign(helper_.GetTargetOutputDir(target_));
184 windows_manifest.value().append(target_->label().name());
185 windows_manifest.value().append(".intermediate.manifest");
186 out_ << "manifests = ";
187 path_output_.WriteFile(out_, windows_manifest);
193 // Append manifest flag on Windows to reference our file.
194 // HACK ERASEME BRETTW FIXME
195 if (settings_->IsWin()) {
196 out_ << " /MANIFEST /ManifestFile:";
197 path_output_.WriteFile(out_, windows_manifest);
201 // Libraries to link.
203 if (settings_->IsMac()) {
204 // TODO(brettw) fix this.
205 out_ << " -framework AppKit -framework ApplicationServices -framework Carbon -framework CoreFoundation -framework Foundation -framework IOKit -framework Security";
209 // The external output file is the one that other libs depend on.
210 OutputFile external_output_file = helper_.GetTargetOutputFile(target_);
212 // The internal output file is the "main thing" we think we're making. In
213 // the case of shared libraries, this is the shared library and the external
214 // output file is the import library. In other cases, the internal one and
215 // the external one are the same.
216 OutputFile internal_output_file;
217 if (target_->output_type() == Target::SHARED_LIBRARY) {
218 if (settings_->IsWin()) {
219 internal_output_file = OutputFile(target_->label().name() + ".dll");
221 internal_output_file = external_output_file;
224 internal_output_file = external_output_file;
227 // In Python see "self.ninja.build(output, command, input,"
228 WriteLinkCommand(external_output_file, internal_output_file, object_files);
230 if (target_->output_type() == Target::SHARED_LIBRARY) {
231 // The shared object name doesn't include a path.
232 out_ << " soname = ";
233 out_ << FindFilename(&internal_output_file.value());
237 path_output_.WriteFile(out_, internal_output_file);
240 if (settings_->IsWin()) {
242 path_output_.WriteFile(out_, internal_output_file);
246 if (settings_->IsWin()) {
247 out_ << " implibflag = /IMPLIB:";
248 path_output_.WriteFile(out_, external_output_file);
252 // TODO(brettw) postbuild steps.
253 if (settings_->IsMac())
254 out_ << " postbuilds = $ && (export BUILT_PRODUCTS_DIR=/Users/brettw/prj/src/out/gn; export CONFIGURATION=Debug; export DYLIB_INSTALL_NAME_BASE=@rpath; export EXECUTABLE_NAME=libbase.dylib; export EXECUTABLE_PATH=libbase.dylib; export FULL_PRODUCT_NAME=libbase.dylib; export LD_DYLIB_INSTALL_NAME=@rpath/libbase.dylib; export MACH_O_TYPE=mh_dylib; export PRODUCT_NAME=base; export PRODUCT_TYPE=com.apple.product-type.library.dynamic; export SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.7.sdk; export SRCROOT=/Users/brettw/prj/src/out/gn/../../base; export SOURCE_ROOT=\"$${SRCROOT}\"; export TARGET_BUILD_DIR=/Users/brettw/prj/src/out/gn; export TEMP_DIR=\"$${TMPDIR}\"; (cd ../../base && ../build/mac/strip_from_xcode); G=$$?; ((exit $$G) || rm -rf libbase.dylib) && exit $$G)";
260 void NinjaBinaryTargetWriter::WriteLinkerFlags() {
263 // First the ldflags from the target and its config.
264 EscapeOptions flag_options = GetFlagOptions();
265 RecursiveTargetConfigStringsToStream(target_, &ConfigValues::ldflags,
268 const Toolchain::Tool& tool = toolchain_->GetTool(tool_type_);
270 // Followed by library search paths that have been recursively pushed
271 // through the dependency tree.
272 const OrderedSet<SourceDir> all_lib_dirs = target_->all_lib_dirs();
273 if (!all_lib_dirs.empty()) {
274 // Since we're passing these on the command line to the linker and not
275 // to Ninja, we need to do shell escaping.
276 PathOutput lib_path_output(path_output_.current_dir(), ESCAPE_NINJA_SHELL,
278 for (size_t i = 0; i < all_lib_dirs.size(); i++) {
279 out_ << " " << tool.lib_dir_prefix;
280 lib_path_output.WriteDir(out_, all_lib_dirs[i],
281 PathOutput::DIR_NO_LAST_SLASH);
285 // Followed by libraries that have been recursively pushed through the
287 EscapeOptions lib_escape_opts;
288 lib_escape_opts.mode = ESCAPE_NINJA_SHELL;
289 const OrderedSet<std::string> all_libs = target_->all_libs();
290 for (size_t i = 0; i < all_libs.size(); i++) {
291 out_ << " " << tool.lib_prefix;
292 EscapeStringToStream(out_, all_libs[i], lib_escape_opts);
297 void NinjaBinaryTargetWriter::WriteLinkCommand(
298 const OutputFile& external_output_file,
299 const OutputFile& internal_output_file,
300 const std::vector<OutputFile>& object_files) {
302 path_output_.WriteFile(out_, internal_output_file);
303 if (external_output_file != internal_output_file) {
305 path_output_.WriteFile(out_, external_output_file);
308 << helper_.GetRulePrefix(target_->settings())
309 << Toolchain::ToolTypeToName(tool_type_);
311 std::set<OutputFile> extra_object_files;
312 std::vector<const Target*> linkable_deps;
313 std::vector<const Target*> non_linkable_deps;
314 GetDeps(&extra_object_files, &linkable_deps, &non_linkable_deps);
317 for (size_t i = 0; i < object_files.size(); i++) {
319 path_output_.WriteFile(out_, object_files[i]);
321 for (std::set<OutputFile>::iterator i = extra_object_files.begin();
322 i != extra_object_files.end(); ++i) {
324 path_output_.WriteFile(out_, *i);
328 for (size_t i = 0; i < linkable_deps.size(); i++) {
330 path_output_.WriteFile(out_, helper_.GetTargetOutputFile(linkable_deps[i]));
333 // Append data dependencies as implicit dependencies.
334 WriteImplicitDependencies(non_linkable_deps);
339 void NinjaBinaryTargetWriter::WriteSourceSetStamp(
340 const std::vector<OutputFile>& object_files) {
341 // The stamp rule for source sets is generally not used, since targets that
342 // depend on this will reference the object files directly. However, writing
343 // this rule allows the user to type the name of the target and get a build
344 // which can be convenient for development.
346 path_output_.WriteFile(out_, helper_.GetTargetOutputFile(target_));
348 << helper_.GetRulePrefix(target_->settings())
351 std::set<OutputFile> extra_object_files;
352 std::vector<const Target*> linkable_deps;
353 std::vector<const Target*> non_linkable_deps;
354 GetDeps(&extra_object_files, &linkable_deps, &non_linkable_deps);
356 // The classifier should never put extra object files in a source set:
357 // any source sets that we depend on should appear in our non-linkable
359 DCHECK(extra_object_files.empty());
361 for (size_t i = 0; i < object_files.size(); i++) {
363 path_output_.WriteFile(out_, object_files[i]);
366 // Append data dependencies as implicit dependencies.
367 WriteImplicitDependencies(non_linkable_deps);
372 void NinjaBinaryTargetWriter::GetDeps(
373 std::set<OutputFile>* extra_object_files,
374 std::vector<const Target*>* linkable_deps,
375 std::vector<const Target*>* non_linkable_deps) const {
376 const LabelTargetVector& deps = target_->deps();
377 const std::set<const Target*>& inherited = target_->inherited_libraries();
380 for (size_t i = 0; i < deps.size(); i++) {
381 if (inherited.find(deps[i].ptr) != inherited.end())
382 continue; // Don't add dupes.
383 ClassifyDependency(deps[i].ptr, extra_object_files,
384 linkable_deps, non_linkable_deps);
387 // Inherited libraries.
388 for (std::set<const Target*>::const_iterator i = inherited.begin();
389 i != inherited.end(); ++i) {
390 ClassifyDependency(*i, extra_object_files,
391 linkable_deps, non_linkable_deps);
395 const LabelTargetVector& datadeps = target_->datadeps();
396 for (size_t i = 0; i < datadeps.size(); i++)
397 non_linkable_deps->push_back(datadeps[i].ptr);
400 void NinjaBinaryTargetWriter::ClassifyDependency(
402 std::set<OutputFile>* extra_object_files,
403 std::vector<const Target*>* linkable_deps,
404 std::vector<const Target*>* non_linkable_deps) const {
405 // Only these types of outputs have libraries linked into them. Child deps of
406 // static libraries get pushed up the dependency tree until one of these is
407 // reached, and source sets don't link at all.
409 (target_->output_type() == Target::EXECUTABLE ||
410 target_->output_type() == Target::SHARED_LIBRARY);
412 if (dep->output_type() == Target::SOURCE_SET) {
413 if (target_->output_type() == Target::SOURCE_SET) {
414 // When a source set depends on another source set, add it as a data
415 // dependency so if the user says "ninja second_source_set" it will
416 // also compile the first (what you would expect) even though we'll
417 // never do anything with the first one's files.
418 non_linkable_deps->push_back(dep);
420 // Linking in a source set, copy its object files.
421 for (size_t i = 0; i < dep->sources().size(); i++) {
422 SourceFileType input_file_type = GetSourceFileType(
423 dep->sources()[i], dep->settings()->target_os());
424 if (input_file_type != SOURCE_UNKNOWN &&
425 input_file_type != SOURCE_H) {
426 // Note we need to specify the target as the source_set target
427 // itself, since this is used to prefix the object file name.
428 extra_object_files->insert(helper_.GetOutputFileForSource(
429 dep, dep->sources()[i], input_file_type));
433 } else if (can_link_libs && dep->IsLinkable()) {
434 linkable_deps->push_back(dep);
436 non_linkable_deps->push_back(dep);
440 void NinjaBinaryTargetWriter::WriteImplicitDependencies(
441 const std::vector<const Target*>& non_linkable_deps) {
442 const std::vector<SourceFile>& data = target_->data();
443 if (!non_linkable_deps.empty() || !data.empty()) {
446 // Non-linkable targets.
447 for (size_t i = 0; i < non_linkable_deps.size(); i++) {
449 path_output_.WriteFile(out_,
450 helper_.GetTargetOutputFile(non_linkable_deps[i]));
454 const std::vector<SourceFile>& data = target_->data();
455 for (size_t i = 0; i < data.size(); i++) {
457 path_output_.WriteFile(out_, data[i]);