1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "Command.h"
18
19 #include <iomanip>
20 #include <iostream>
21 #include <string>
22 #include <vector>
23
24 #include "android-base/stringprintf.h"
25 #include "android-base/utf8.h"
26 #include "androidfw/StringPiece.h"
27
28 #include "trace/TraceBuffer.h"
29 #include "util/Util.h"
30
31 using android::base::StringPrintf;
32 using android::StringPiece;
33
34 namespace aapt {
35
GetSafePath(StringPiece arg)36 std::string GetSafePath(StringPiece arg) {
37 #ifdef _WIN32
38 // If the path exceeds the maximum path length for Windows, encode the path using the
39 // extended-length prefix
40 std::wstring path16;
41 CHECK(android::base::UTF8PathToWindowsLongPath(arg.data(), &path16))
42 << "Failed to convert file path to UTF-16: file path " << arg.data();
43
44 std::string path8;
45 CHECK(android::base::WideToUTF8(path16, &path8))
46 << "Failed to convert file path back to UTF-8: file path " << arg.data();
47
48 return path8;
49 #else
50 return std::string(arg);
51 #endif
52 }
53
AddRequiredFlag(StringPiece name,StringPiece description,std::string * value,uint32_t flags)54 void Command::AddRequiredFlag(StringPiece name, StringPiece description, std::string* value,
55 uint32_t flags) {
56 auto func = [value, flags](StringPiece arg, std::ostream*) -> bool {
57 *value = (flags & Command::kPath) ? GetSafePath(arg) : std::string(arg);
58 return true;
59 };
60
61 flags_.emplace_back(
62 Flag(name, description, /* required */ true, /* num_args */ 1, std::move(func)));
63 }
64
AddRequiredFlagList(StringPiece name,StringPiece description,std::vector<std::string> * value,uint32_t flags)65 void Command::AddRequiredFlagList(StringPiece name, StringPiece description,
66 std::vector<std::string>* value, uint32_t flags) {
67 auto func = [value, flags](StringPiece arg, std::ostream*) -> bool {
68 value->push_back((flags & Command::kPath) ? GetSafePath(arg) : std::string(arg));
69 return true;
70 };
71
72 flags_.emplace_back(
73 Flag(name, description, /* required */ true, /* num_args */ 1, std::move(func)));
74 }
75
AddOptionalFlag(StringPiece name,StringPiece description,std::optional<std::string> * value,uint32_t flags)76 void Command::AddOptionalFlag(StringPiece name, StringPiece description,
77 std::optional<std::string>* value, uint32_t flags) {
78 auto func = [value, flags](StringPiece arg, std::ostream*) -> bool {
79 *value = (flags & Command::kPath) ? GetSafePath(arg) : std::string(arg);
80 return true;
81 };
82
83 flags_.emplace_back(
84 Flag(name, description, /* required */ false, /* num_args */ 1, std::move(func)));
85 }
86
AddOptionalFlagList(StringPiece name,StringPiece description,std::vector<std::string> * value,uint32_t flags)87 void Command::AddOptionalFlagList(StringPiece name, StringPiece description,
88 std::vector<std::string>* value, uint32_t flags) {
89 auto func = [value, flags](StringPiece arg, std::ostream*) -> bool {
90 value->push_back((flags & Command::kPath) ? GetSafePath(arg) : std::string(arg));
91 return true;
92 };
93
94 flags_.emplace_back(
95 Flag(name, description, /* required */ false, /* num_args */ 1, std::move(func)));
96 }
97
AddOptionalFlagList(StringPiece name,StringPiece description,std::unordered_set<std::string> * value)98 void Command::AddOptionalFlagList(StringPiece name, StringPiece description,
99 std::unordered_set<std::string>* value) {
100 auto func = [value](StringPiece arg, std::ostream* out_error) -> bool {
101 value->emplace(arg);
102 return true;
103 };
104
105 flags_.emplace_back(
106 Flag(name, description, /* required */ false, /* num_args */ 1, std::move(func)));
107 }
108
AddOptionalSwitch(StringPiece name,StringPiece description,bool * value)109 void Command::AddOptionalSwitch(StringPiece name, StringPiece description, bool* value) {
110 auto func = [value](StringPiece arg, std::ostream* out_error) -> bool {
111 *value = true;
112 return true;
113 };
114
115 flags_.emplace_back(
116 Flag(name, description, /* required */ false, /* num_args */ 0, std::move(func)));
117 }
118
AddOptionalSubcommand(std::unique_ptr<Command> && subcommand,bool experimental)119 void Command::AddOptionalSubcommand(std::unique_ptr<Command>&& subcommand, bool experimental) {
120 subcommand->full_subcommand_name_ = StringPrintf("%s %s", name_.data(), subcommand->name_.data());
121 if (experimental) {
122 experimental_subcommands_.push_back(std::move(subcommand));
123 } else {
124 subcommands_.push_back(std::move(subcommand));
125 }
126 }
127
SetDescription(StringPiece description)128 void Command::SetDescription(StringPiece description) {
129 description_ = std::string(description);
130 }
131
Usage(std::ostream * out)132 void Command::Usage(std::ostream* out) {
133 constexpr size_t kWidth = 50;
134
135 *out << full_subcommand_name_;
136
137 if (!subcommands_.empty()) {
138 *out << " [subcommand]";
139 }
140
141 *out << " [options]";
142 for (const Flag& flag : flags_) {
143 if (flag.is_required) {
144 *out << " " << flag.name << " arg";
145 }
146 }
147
148 *out << " files...\n";
149
150 if (!subcommands_.empty()) {
151 *out << "\nSubcommands:\n";
152 for (auto& subcommand : subcommands_) {
153 std::string argline = subcommand->name_;
154
155 // Split the description by newlines and write out the argument (which is
156 // empty after the first line) followed by the description line. This will make sure
157 // that multiline descriptions are still right justified and aligned.
158 for (StringPiece line : util::Tokenize(subcommand->description_, '\n')) {
159 *out << " " << std::setw(kWidth) << std::left << argline << line << "\n";
160 argline = " ";
161 }
162 }
163 }
164
165 *out << "\nOptions:\n";
166
167 for (const Flag& flag : flags_) {
168 std::string argline = flag.name;
169 if (flag.num_args > 0) {
170 argline += " arg";
171 }
172
173 // Split the description by newlines and write out the argument (which is
174 // empty after the first line) followed by the description line. This will make sure
175 // that multiline descriptions are still right justified and aligned.
176 for (StringPiece line : util::Tokenize(flag.description, '\n')) {
177 *out << " " << std::setw(kWidth) << std::left << argline << line << "\n";
178 argline = " ";
179 }
180 }
181 out->flush();
182 }
183
addEnvironmentArg(const Flag & flag,const char * env)184 const std::string& Command::addEnvironmentArg(const Flag& flag, const char* env) {
185 if (*env && flag.num_args > 0) {
186 return environment_args_.emplace_back(flag.name + '=' + env);
187 }
188 return flag.name;
189 }
190
191 //
192 // Looks for the flags specified in the environment and adds them to |args|.
193 // Expected format:
194 // - _AAPT2_UPPERCASE_NAME are added before all of the command line flags, so it's
195 // a default for the flag that may get overridden by the command line.
196 // - AAPT2_UPPERCASE_NAME_ are added after them, making this to be the final value
197 // even if there was something on the command line.
198 // - All dashes in the flag name get replaced with underscores, the rest of it is
199 // intact.
200 //
201 // E.g.
202 // --set-some-flag becomes either _AAPT2_SET_SOME_FLAG or AAPT2_SET_SOME_FLAG_
203 // --set-param=2 is _AAPT2_SET_SOME_FLAG=2
204 //
205 // Values get passed as it, with no processing or quoting.
206 //
207 // This way one can make sure aapt2 has the flags they need even when it is
208 // launched in a way they can't control, e.g. deep inside a build.
209 //
parseFlagsFromEnvironment(std::vector<StringPiece> & args)210 void Command::parseFlagsFromEnvironment(std::vector<StringPiece>& args) {
211 // If the first argument is a subcommand then skip it and prepend the flags past that (the root
212 // command should only have a single '-h' flag anyway).
213 const int insert_pos = args.empty() ? 0 : args.front().starts_with('-') ? 0 : 1;
214
215 std::string env_name;
216 for (const Flag& flag : flags_) {
217 // First, the prefix version.
218 env_name.assign("_AAPT2_");
219 // Append the uppercased flag name, skipping all dashes in front and replacing them with
220 // underscores later.
221 auto name_start = flag.name.begin();
222 while (name_start != flag.name.end() && *name_start == '-') {
223 ++name_start;
224 }
225 std::transform(name_start, flag.name.end(), std::back_inserter(env_name),
226 [](char c) { return c == '-' ? '_' : toupper(c); });
227 if (auto prefix_env = getenv(env_name.c_str())) {
228 args.insert(args.begin() + insert_pos, addEnvironmentArg(flag, prefix_env));
229 }
230 // Now reuse the same name variable to construct a suffix version: append the
231 // underscore and just skip the one in front.
232 env_name += '_';
233 if (auto suffix_env = getenv(env_name.c_str() + 1)) {
234 args.push_back(addEnvironmentArg(flag, suffix_env));
235 }
236 }
237 }
238
Execute(std::vector<StringPiece> & args,std::ostream * out_error)239 int Command::Execute(std::vector<StringPiece>& args, std::ostream* out_error) {
240 TRACE_NAME_ARGS("Command::Execute", args);
241 std::vector<std::string> file_args;
242
243 parseFlagsFromEnvironment(args);
244
245 for (size_t i = 0; i < args.size(); i++) {
246 StringPiece arg = args[i];
247 if (*(arg.data()) != '-') {
248 // Continue parsing as a subcommand if the first argument matches one of the subcommands
249 if (i == 0) {
250 for (auto& subcommand : subcommands_) {
251 if (arg == subcommand->name_ || (!subcommand->short_name_.empty()
252 && arg == subcommand->short_name_)) {
253 return subcommand->Execute(
254 std::vector<StringPiece>(args.begin() + 1, args.end()), out_error);
255 }
256 }
257 for (auto& subcommand : experimental_subcommands_) {
258 if (arg == subcommand->name_ || (!subcommand->short_name_.empty()
259 && arg == subcommand->short_name_)) {
260 return subcommand->Execute(
261 std::vector<StringPiece>(args.begin() + 1, args.end()), out_error);
262 }
263 }
264 }
265
266 file_args.push_back(GetSafePath(arg));
267 continue;
268 }
269
270 if (arg == "-h" || arg == "--help") {
271 Usage(out_error);
272 return 1;
273 }
274
275 static constexpr auto matchShortArg = [](std::string_view arg, const Flag& flag) static {
276 return flag.name.starts_with("--") &&
277 arg.compare(0, 2, std::string_view(flag.name.c_str() + 1, 2)) == 0;
278 };
279
280 bool match = false;
281 for (Flag& flag : flags_) {
282 // Allow both "--arg value" and "--arg=value" syntax, and look for the cases where we can
283 // safely deduce the "--arg" flag from the short "-a" version when there's no value expected
284 bool matched_current = false;
285 if (arg.starts_with(flag.name) &&
286 (arg.size() == flag.name.size() || (flag.num_args > 0 && arg[flag.name.size()] == '='))) {
287 matched_current = true;
288 } else if (flag.num_args == 0 && matchShortArg(arg, flag)) {
289 matched_current = true;
290 // It matches, now need to make sure no other flag would match as well.
291 // This is really inefficient, but we don't expect to have enough flags for it to matter
292 // (famous last words).
293 for (const Flag& other_flag : flags_) {
294 if (&other_flag == &flag) {
295 continue;
296 }
297 if (matchShortArg(arg, other_flag)) {
298 matched_current = false; // ambiguous, skip this match
299 break;
300 }
301 }
302 }
303 if (!matched_current) {
304 continue;
305 }
306
307 if (flag.num_args > 0) {
308 if (arg.size() == flag.name.size()) {
309 i++;
310 if (i >= args.size()) {
311 *out_error << flag.name << " missing argument.\n\n";
312 Usage(out_error);
313 return 1;
314 }
315 arg = args[i];
316 } else {
317 arg.remove_prefix(flag.name.size() + 1);
318 // Disallow empty arguments after '='.
319 if (arg.empty()) {
320 *out_error << flag.name << " has empty argument.\n\n";
321 Usage(out_error);
322 return 1;
323 }
324 }
325 if (!flag.action(arg, out_error)) {
326 return 1;
327 }
328 } else {
329 if (!flag.action({}, out_error)) {
330 return 1;
331 }
332 }
333 flag.found = true;
334 match = true;
335 break;
336 }
337
338 if (!match) {
339 *out_error << "unknown option '" << arg << "'.\n\n";
340 Usage(out_error);
341 return 1;
342 }
343 }
344
345 for (const Flag& flag : flags_) {
346 if (flag.is_required && !flag.found) {
347 *out_error << "missing required flag " << flag.name << "\n\n";
348 Usage(out_error);
349 return 1;
350 }
351 }
352
353 return Action(file_args);
354 }
355
356 } // namespace aapt
357