1 // Copyright 2016 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 #include "gn/analyzer.h"
6
7 #include <algorithm>
8 #include <iterator>
9 #include <memory>
10 #include <set>
11 #include <vector>
12
13 #include "base/json/json_reader.h"
14 #include "base/json/json_writer.h"
15 #include "base/strings/string_util.h"
16 #include "base/values.h"
17 #include "gn/builder.h"
18 #include "gn/config.h"
19 #include "gn/config_values_extractors.h"
20 #include "gn/deps_iterator.h"
21 #include "gn/err.h"
22 #include "gn/filesystem_utils.h"
23 #include "gn/loader.h"
24 #include "gn/location.h"
25 #include "gn/pool.h"
26 #include "gn/source_file.h"
27 #include "gn/target.h"
28
29 namespace {
30
31 struct Inputs {
32 std::vector<SourceFile> source_vec;
33 std::vector<Label> compile_vec;
34 std::vector<Label> test_vec;
35 bool compile_included_all = false;
36 std::set<const SourceFile*> source_files;
37 std::set<Label> compile_labels;
38 std::set<Label> test_labels;
39 };
40
41 struct Outputs {
42 std::string status;
43 std::string error;
44 bool compile_includes_all = false;
45 std::set<Label> compile_labels;
46 std::set<Label> test_labels;
47 std::set<Label> invalid_labels;
48 };
49
LabelsFor(const TargetSet & targets)50 std::set<Label> LabelsFor(const TargetSet& targets) {
51 std::set<Label> labels;
52 for (auto* target : targets)
53 labels.insert(target->label());
54 return labels;
55 }
56
Intersect(const TargetSet & l,const TargetSet & r)57 TargetSet Intersect(const TargetSet& l, const TargetSet& r) {
58 return l.intersection_with(r);
59 }
60
GetStringVector(const base::DictionaryValue & dict,const std::string & key,Err * err)61 std::vector<std::string> GetStringVector(const base::DictionaryValue& dict,
62 const std::string& key,
63 Err* err) {
64 std::vector<std::string> strings;
65 const base::ListValue* lst;
66 bool ret = dict.GetList(key, &lst);
67 if (!ret) {
68 *err = Err(Location(), "Input does not have a key named \"" + key +
69 "\" with a list value.");
70 return strings;
71 }
72
73 for (size_t i = 0; i < lst->GetSize(); i++) {
74 std::string s;
75 ret = lst->GetString(i, &s);
76 if (!ret) {
77 *err = Err(Location(), "Item " + std::to_string(i) + " of \"" + key +
78 "\" is not a string.");
79 strings.clear();
80 return strings;
81 }
82 strings.push_back(std::move(s));
83 }
84 *err = Err();
85 return strings;
86 }
87
WriteString(base::DictionaryValue & dict,const std::string & key,const std::string & value)88 void WriteString(base::DictionaryValue& dict,
89 const std::string& key,
90 const std::string& value) {
91 dict.SetKey(key, base::Value(value));
92 };
93
WriteLabels(const Label & default_toolchain,base::DictionaryValue & dict,const std::string & key,const std::set<Label> & labels)94 void WriteLabels(const Label& default_toolchain,
95 base::DictionaryValue& dict,
96 const std::string& key,
97 const std::set<Label>& labels) {
98 std::vector<std::string> strings;
99 auto value = std::make_unique<base::ListValue>();
100 for (const auto& l : labels)
101 strings.push_back(l.GetUserVisibleName(default_toolchain));
102 std::sort(strings.begin(), strings.end());
103 value->AppendStrings(strings);
104 dict.SetWithoutPathExpansion(key, std::move(value));
105 }
106
AbsoluteOrSourceAbsoluteStringToLabel(const Label & default_toolchain,const std::string & s,Err * err)107 Label AbsoluteOrSourceAbsoluteStringToLabel(const Label& default_toolchain,
108 const std::string& s,
109 Err* err) {
110 if (!IsPathSourceAbsolute(s) && !IsPathAbsolute(s)) {
111 *err = Err(Location(),
112 "\"" + s + "\" is not a source-absolute or absolute path.");
113 return Label();
114 }
115 return Label::Resolve(SourceDir("//"), std::string_view(), default_toolchain,
116 Value(nullptr, s), err);
117 }
118
JSONToInputs(const Label & default_toolchain,const std::string input,Inputs * inputs)119 Err JSONToInputs(const Label& default_toolchain,
120 const std::string input,
121 Inputs* inputs) {
122 int error_code_out;
123 std::string error_msg_out;
124 int error_line_out;
125 int error_column_out;
126 std::unique_ptr<base::Value> value = base::JSONReader::ReadAndReturnError(
127 input, base::JSONParserOptions::JSON_PARSE_RFC, &error_code_out,
128 &error_msg_out, &error_line_out, &error_column_out);
129 if (!value)
130 return Err(Location(), "Input is not valid JSON:" + error_msg_out);
131
132 const base::DictionaryValue* dict;
133 if (!value->GetAsDictionary(&dict))
134 return Err(Location(), "Input is not a dictionary.");
135
136 Err err;
137
138 const char kFilesKey[] = "files";
139 {
140 std::vector<std::string> files = GetStringVector(*dict, kFilesKey, &err);
141 if (err.has_error())
142 return err;
143 for (auto& s : files) {
144 if (!IsPathSourceAbsolute(s) && !IsPathAbsolute(s)) {
145 return Err(Location(),
146 "\"" + s + "\" is not a source-absolute or absolute path.");
147 }
148 inputs->source_vec.emplace_back(std::move(s));
149 }
150 }
151
152 inputs->compile_included_all = false;
153 const char kAdditonalCompileTargetsKey[] = "additional_compile_targets";
154 if (dict->HasKey(kAdditonalCompileTargetsKey)) {
155 std::vector<std::string> additional_compile_targets =
156 GetStringVector(*dict, kAdditonalCompileTargetsKey, &err);
157 if (err.has_error())
158 return err;
159
160 for (auto& s : additional_compile_targets) {
161 if (s == "all") {
162 inputs->compile_included_all = true;
163 } else {
164 inputs->compile_vec.push_back(
165 AbsoluteOrSourceAbsoluteStringToLabel(default_toolchain, s, &err));
166 if (err.has_error())
167 return err;
168 }
169 }
170 }
171
172 const char kTestTargetsKey[] = "test_targets";
173 {
174 std::vector<std::string> test_targets =
175 GetStringVector(*dict, kTestTargetsKey, &err);
176 if (err.has_error())
177 return err;
178 for (auto& s : test_targets) {
179 inputs->test_vec.push_back(
180 AbsoluteOrSourceAbsoluteStringToLabel(default_toolchain, s, &err));
181 if (err.has_error())
182 return err;
183 }
184 }
185
186 for (const auto& kv : dict->DictItems()) {
187 if (kv.first == kFilesKey || kv.first == kAdditonalCompileTargetsKey ||
188 kv.first == kTestTargetsKey) {
189 continue;
190 }
191 return Err(Location(), "Unknown analyze input key \"" + kv.first + "\".");
192 }
193
194 for (auto& s : inputs->source_vec)
195 inputs->source_files.insert(&s);
196 for (auto& l : inputs->compile_vec)
197 inputs->compile_labels.insert(l);
198 for (auto& l : inputs->test_vec)
199 inputs->test_labels.insert(l);
200 return Err();
201 }
202
OutputsToJSON(const Outputs & outputs,const Label & default_toolchain,Err * err)203 std::string OutputsToJSON(const Outputs& outputs,
204 const Label& default_toolchain,
205 Err* err) {
206 std::string output;
207 auto value = std::make_unique<base::DictionaryValue>();
208
209 if (outputs.error.size()) {
210 WriteString(*value, "error", outputs.error);
211 WriteLabels(default_toolchain, *value, "invalid_targets",
212 outputs.invalid_labels);
213 } else {
214 WriteString(*value, "status", outputs.status);
215 if (outputs.compile_includes_all) {
216 auto compile_targets = std::make_unique<base::ListValue>();
217 compile_targets->AppendString("all");
218 value->SetWithoutPathExpansion("compile_targets",
219 std::move(compile_targets));
220 } else {
221 WriteLabels(default_toolchain, *value, "compile_targets",
222 outputs.compile_labels);
223 }
224 WriteLabels(default_toolchain, *value, "test_targets", outputs.test_labels);
225 }
226
227 if (!base::JSONWriter::Write(*value.get(), &output))
228 *err = Err(Location(), "Failed to marshal JSON value for output");
229 return output;
230 }
231
232 } // namespace
233
Analyzer(const Builder & builder,const SourceFile & build_config_file,const SourceFile & dot_file,const SourceFileSet & build_args_dependency_files)234 Analyzer::Analyzer(const Builder& builder,
235 const SourceFile& build_config_file,
236 const SourceFile& dot_file,
237 const SourceFileSet& build_args_dependency_files)
238 : all_items_(builder.GetAllResolvedItems()),
239 default_toolchain_(builder.loader()->GetDefaultToolchain()),
240 build_config_file_(build_config_file),
241 dot_file_(dot_file),
242 build_args_dependency_files_(build_args_dependency_files) {
243 for (const auto* item : all_items_) {
244 labels_to_items_[item->label()] = item;
245
246 // Fill dep_map_.
247 if (item->AsTarget()) {
248 for (const auto& dep_target_pair :
249 item->AsTarget()->GetDeps(Target::DEPS_ALL))
250 dep_map_.insert(std::make_pair(dep_target_pair.ptr, item));
251
252 for (const auto& dep_config_pair : item->AsTarget()->configs())
253 dep_map_.insert(std::make_pair(dep_config_pair.ptr, item));
254
255 dep_map_.insert(std::make_pair(item->AsTarget()->toolchain(), item));
256
257 if (item->AsTarget()->output_type() == Target::ACTION ||
258 item->AsTarget()->output_type() == Target::ACTION_FOREACH) {
259 const LabelPtrPair<Pool>& pool =
260 item->AsTarget()->action_values().pool();
261 if (pool.ptr)
262 dep_map_.insert(std::make_pair(pool.ptr, item));
263 }
264 } else if (item->AsConfig()) {
265 for (const auto& dep_config_pair : item->AsConfig()->configs())
266 dep_map_.insert(std::make_pair(dep_config_pair.ptr, item));
267 } else if (item->AsToolchain()) {
268 for (const auto& dep_pair : item->AsToolchain()->deps())
269 dep_map_.insert(std::make_pair(dep_pair.ptr, item));
270 } else {
271 DCHECK(item->AsPool());
272 }
273 }
274 }
275
276 Analyzer::~Analyzer() = default;
277
Analyze(const std::string & input,Err * err) const278 std::string Analyzer::Analyze(const std::string& input, Err* err) const {
279 Inputs inputs;
280 Outputs outputs;
281
282 Err local_err = JSONToInputs(default_toolchain_, input, &inputs);
283 if (local_err.has_error()) {
284 outputs.error = local_err.message();
285 return OutputsToJSON(outputs, default_toolchain_, err);
286 }
287
288 std::set<Label> invalid_labels;
289 for (const auto& label : InvalidLabels(inputs.compile_labels))
290 invalid_labels.insert(label);
291 for (const auto& label : InvalidLabels(inputs.test_labels))
292 invalid_labels.insert(label);
293 if (!invalid_labels.empty()) {
294 outputs.error = "Invalid targets";
295 outputs.invalid_labels = invalid_labels;
296 return OutputsToJSON(outputs, default_toolchain_, err);
297 }
298
299 if (WereMainGNFilesModified(inputs.source_files)) {
300 outputs.status = "Found dependency (all)";
301 if (inputs.compile_included_all) {
302 outputs.compile_includes_all = true;
303 } else {
304 outputs.compile_labels.insert(inputs.compile_labels.begin(),
305 inputs.compile_labels.end());
306 outputs.compile_labels.insert(inputs.test_labels.begin(),
307 inputs.test_labels.end());
308 }
309 outputs.test_labels = inputs.test_labels;
310 return OutputsToJSON(outputs, default_toolchain_, err);
311 }
312
313 std::set<const Item*> affected_items =
314 GetAllAffectedItems(inputs.source_files);
315 TargetSet affected_targets;
316 for (const Item* affected_item : affected_items) {
317 if (affected_item->AsTarget())
318 affected_targets.insert(affected_item->AsTarget());
319 }
320
321 if (affected_targets.empty()) {
322 outputs.status = "No dependency";
323 return OutputsToJSON(outputs, default_toolchain_, err);
324 }
325
326 TargetSet root_targets;
327 for (const auto* item : all_items_) {
328 if (item->AsTarget() && dep_map_.find(item) == dep_map_.end())
329 root_targets.insert(item->AsTarget());
330 }
331
332 TargetSet compile_targets = TargetsFor(inputs.compile_labels);
333 if (inputs.compile_included_all) {
334 for (auto* root_target : root_targets)
335 compile_targets.insert(root_target);
336 }
337 TargetSet filtered_targets = Filter(compile_targets);
338 outputs.compile_labels =
339 LabelsFor(Intersect(filtered_targets, affected_targets));
340
341 // If every target is affected, simply compile All instead of listing all
342 // the targets to make the output easier to read.
343 if (inputs.compile_included_all &&
344 outputs.compile_labels.size() == filtered_targets.size())
345 outputs.compile_includes_all = true;
346
347 TargetSet test_targets = TargetsFor(inputs.test_labels);
348 outputs.test_labels = LabelsFor(Intersect(test_targets, affected_targets));
349
350 if (outputs.compile_labels.empty() && outputs.test_labels.empty())
351 outputs.status = "No dependency";
352 else
353 outputs.status = "Found dependency";
354 return OutputsToJSON(outputs, default_toolchain_, err);
355 }
356
GetAllAffectedItems(const std::set<const SourceFile * > & source_files) const357 std::set<const Item*> Analyzer::GetAllAffectedItems(
358 const std::set<const SourceFile*>& source_files) const {
359 std::set<const Item*> directly_affected_items;
360 for (auto* source_file : source_files)
361 AddItemsDirectlyReferringToFile(source_file, &directly_affected_items);
362
363 std::set<const Item*> all_affected_items;
364 for (auto* affected_item : directly_affected_items)
365 AddAllItemsReferringToItem(affected_item, &all_affected_items);
366
367 return all_affected_items;
368 }
369
InvalidLabels(const std::set<Label> & labels) const370 std::set<Label> Analyzer::InvalidLabels(const std::set<Label>& labels) const {
371 std::set<Label> invalid_labels;
372 for (const Label& label : labels) {
373 if (labels_to_items_.find(label) == labels_to_items_.end())
374 invalid_labels.insert(label);
375 }
376 return invalid_labels;
377 }
378
TargetsFor(const std::set<Label> & labels) const379 TargetSet Analyzer::TargetsFor(const std::set<Label>& labels) const {
380 TargetSet targets;
381 for (const auto& label : labels) {
382 auto it = labels_to_items_.find(label);
383 if (it != labels_to_items_.end()) {
384 DCHECK(it->second->AsTarget());
385 targets.insert(it->second->AsTarget());
386 }
387 }
388 return targets;
389 }
390
Filter(const TargetSet & targets) const391 TargetSet Analyzer::Filter(const TargetSet& targets) const {
392 TargetSet seen;
393 TargetSet filtered;
394 for (const auto* target : targets)
395 FilterTarget(target, &seen, &filtered);
396 return filtered;
397 }
398
FilterTarget(const Target * target,TargetSet * seen,TargetSet * filtered) const399 void Analyzer::FilterTarget(const Target* target,
400 TargetSet* seen,
401 TargetSet* filtered) const {
402 if (seen->add(target)) {
403 if (target->output_type() != Target::GROUP) {
404 filtered->insert(target);
405 } else {
406 for (const auto& pair : target->GetDeps(Target::DEPS_ALL))
407 FilterTarget(pair.ptr, seen, filtered);
408 }
409 }
410 }
411
ItemRefersToFile(const Item * item,const SourceFile * file) const412 bool Analyzer::ItemRefersToFile(const Item* item,
413 const SourceFile* file) const {
414 for (const auto& cur_file : item->build_dependency_files()) {
415 if (cur_file == *file)
416 return true;
417 }
418
419 if (const Config* config = item->AsConfig()) {
420 for (const auto& config_pair: config->configs()) {
421 if (ItemRefersToFile(config_pair.ptr, file))
422 return true;
423 }
424 }
425
426 if (!item->AsTarget())
427 return false;
428
429 const Target* target = item->AsTarget();
430 for (const auto& cur_file : target->sources()) {
431 if (cur_file == *file)
432 return true;
433 }
434 for (const auto& cur_file : target->public_headers()) {
435 if (cur_file == *file)
436 return true;
437 }
438 for (ConfigValuesIterator iter(target); !iter.done(); iter.Next()) {
439 for (const auto& cur_file : iter.cur().inputs()) {
440 if (cur_file == *file)
441 return true;
442 }
443 }
444 for (const auto& cur_file : target->data()) {
445 if (cur_file == file->value())
446 return true;
447 if (cur_file.back() == '/' &&
448 base::StartsWith(file->value(), cur_file, base::CompareCase::SENSITIVE))
449 return true;
450 }
451
452 if (target->action_values().script().value() == file->value())
453 return true;
454
455 std::vector<SourceFile> outputs;
456 target->action_values().GetOutputsAsSourceFiles(target, &outputs);
457 for (const auto& cur_file : outputs) {
458 if (cur_file == *file)
459 return true;
460 }
461 return false;
462 }
463
AddItemsDirectlyReferringToFile(const SourceFile * file,std::set<const Item * > * directly_affected_items) const464 void Analyzer::AddItemsDirectlyReferringToFile(
465 const SourceFile* file,
466 std::set<const Item*>* directly_affected_items) const {
467 for (const auto* item : all_items_) {
468 if (ItemRefersToFile(item, file))
469 directly_affected_items->insert(item);
470 }
471 }
472
AddAllItemsReferringToItem(const Item * item,std::set<const Item * > * all_affected_items) const473 void Analyzer::AddAllItemsReferringToItem(
474 const Item* item,
475 std::set<const Item*>* all_affected_items) const {
476 if (all_affected_items->find(item) != all_affected_items->end())
477 return; // Already found this item.
478
479 all_affected_items->insert(item);
480
481 auto dep_begin = dep_map_.lower_bound(item);
482 auto dep_end = dep_map_.upper_bound(item);
483 for (auto cur_dep = dep_begin; cur_dep != dep_end; ++cur_dep)
484 AddAllItemsReferringToItem(cur_dep->second, all_affected_items);
485 }
486
WereMainGNFilesModified(const std::set<const SourceFile * > & modified_files) const487 bool Analyzer::WereMainGNFilesModified(
488 const std::set<const SourceFile*>& modified_files) const {
489 for (const auto* file : modified_files) {
490 if (*file == dot_file_)
491 return true;
492
493 if (*file == build_config_file_)
494 return true;
495
496 for (const auto& build_args_dependency_file :
497 build_args_dependency_files_) {
498 if (*file == build_args_dependency_file)
499 return true;
500 }
501 }
502
503 return false;
504 }
505