[M85 Dev][EFL] Fix crashes at webview launch
[platform/framework/web/chromium-efl.git] / base / command_line.cc
1 // Copyright (c) 2012 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 "base/command_line.h"
6
7 #include <algorithm>
8 #include <ostream>
9
10 #include "base/containers/span.h"
11 #include "base/files/file_path.h"
12 #include "base/logging.h"
13 #include "base/notreached.h"
14 #include "base/stl_util.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_tokenizer.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "build/build_config.h"
20
21 #if defined(OS_WIN)
22 #include <windows.h>
23 #include <shellapi.h>
24
25 #include "base/strings/string_util_win.h"
26 #endif
27
28 namespace base {
29
30 CommandLine* CommandLine::current_process_commandline_ = nullptr;
31
32 namespace {
33
34 constexpr CommandLine::CharType kSwitchTerminator[] = FILE_PATH_LITERAL("--");
35 constexpr CommandLine::CharType kSwitchValueSeparator[] =
36     FILE_PATH_LITERAL("=");
37
38 // Since we use a lazy match, make sure that longer versions (like "--") are
39 // listed before shorter versions (like "-") of similar prefixes.
40 #if defined(OS_WIN)
41 // By putting slash last, we can control whether it is treaded as a switch
42 // value by changing the value of switch_prefix_count to be one less than
43 // the array size.
44 constexpr CommandLine::StringPieceType kSwitchPrefixes[] = {L"--", L"-", L"/"};
45 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
46 // Unixes don't use slash as a switch.
47 constexpr CommandLine::StringPieceType kSwitchPrefixes[] = {"--", "-"};
48 #endif
49 size_t switch_prefix_count = base::size(kSwitchPrefixes);
50
51 size_t GetSwitchPrefixLength(CommandLine::StringPieceType string) {
52   for (size_t i = 0; i < switch_prefix_count; ++i) {
53     CommandLine::StringType prefix(kSwitchPrefixes[i]);
54     if (string.substr(0, prefix.length()) == prefix)
55       return prefix.length();
56   }
57   return 0;
58 }
59
60 // Fills in |switch_string| and |switch_value| if |string| is a switch.
61 // This will preserve the input switch prefix in the output |switch_string|.
62 bool IsSwitch(const CommandLine::StringType& string,
63               CommandLine::StringType* switch_string,
64               CommandLine::StringType* switch_value) {
65   switch_string->clear();
66   switch_value->clear();
67   size_t prefix_length = GetSwitchPrefixLength(string);
68   if (prefix_length == 0 || prefix_length == string.length())
69     return false;
70
71   const size_t equals_position = string.find(kSwitchValueSeparator);
72   *switch_string = string.substr(0, equals_position);
73   if (equals_position != CommandLine::StringType::npos)
74     *switch_value = string.substr(equals_position + 1);
75   return true;
76 }
77
78 // Returns true iff |string| represents a switch with key
79 // |switch_key_without_prefix|, regardless of value.
80 bool IsSwitchWithKey(CommandLine::StringPieceType string,
81                      CommandLine::StringPieceType switch_key_without_prefix) {
82   size_t prefix_length = GetSwitchPrefixLength(string);
83   if (prefix_length == 0 || prefix_length == string.length())
84     return false;
85
86   const size_t equals_position = string.find(kSwitchValueSeparator);
87   return string.substr(prefix_length, equals_position - prefix_length) ==
88          switch_key_without_prefix;
89 }
90
91 // Append switches and arguments, keeping switches before arguments.
92 void AppendSwitchesAndArguments(CommandLine* command_line,
93                                 const CommandLine::StringVector& argv) {
94   bool parse_switches = true;
95   for (size_t i = 1; i < argv.size(); ++i) {
96     CommandLine::StringType arg = argv[i];
97 #if defined(OS_WIN)
98     arg = CommandLine::StringType(TrimWhitespace(arg, TRIM_ALL));
99 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
100     TrimWhitespaceASCII(arg, TRIM_ALL, &arg);
101 #endif
102
103     CommandLine::StringType switch_string;
104     CommandLine::StringType switch_value;
105     parse_switches &= (arg != kSwitchTerminator);
106     if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
107 #if defined(OS_WIN)
108       command_line->AppendSwitchNative(WideToUTF8(switch_string), switch_value);
109 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
110       command_line->AppendSwitchNative(switch_string, switch_value);
111 #else
112 #error Unsupported platform
113 #endif
114     } else {
115       command_line->AppendArgNative(arg);
116     }
117   }
118 }
119
120 #if defined(OS_WIN)
121 // Quote a string as necessary for CommandLineToArgvW compatiblity *on Windows*.
122 std::wstring QuoteForCommandLineToArgvW(const std::wstring& arg,
123                                         bool quote_placeholders) {
124   // We follow the quoting rules of CommandLineToArgvW.
125   // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
126   std::wstring quotable_chars(L" \\\"");
127   // We may also be required to quote '%', which is commonly used in a command
128   // line as a placeholder. (It may be substituted for a string with spaces.)
129   if (quote_placeholders)
130     quotable_chars.push_back('%');
131   if (arg.find_first_of(quotable_chars) == std::wstring::npos) {
132     // No quoting necessary.
133     return arg;
134   }
135
136   std::wstring out;
137   out.push_back('"');
138   for (size_t i = 0; i < arg.size(); ++i) {
139     if (arg[i] == '\\') {
140       // Find the extent of this run of backslashes.
141       size_t start = i, end = start + 1;
142       for (; end < arg.size() && arg[end] == '\\'; ++end) {}
143       size_t backslash_count = end - start;
144
145       // Backslashes are escapes only if the run is followed by a double quote.
146       // Since we also will end the string with a double quote, we escape for
147       // either a double quote or the end of the string.
148       if (end == arg.size() || arg[end] == '"') {
149         // To quote, we need to output 2x as many backslashes.
150         backslash_count *= 2;
151       }
152       for (size_t j = 0; j < backslash_count; ++j)
153         out.push_back('\\');
154
155       // Advance i to one before the end to balance i++ in loop.
156       i = end - 1;
157     } else if (arg[i] == '"') {
158       out.push_back('\\');
159       out.push_back('"');
160     } else {
161       out.push_back(arg[i]);
162     }
163   }
164   out.push_back('"');
165
166   return out;
167 }
168 #endif
169
170 }  // namespace
171
172 CommandLine::CommandLine(NoProgram no_program)
173     : argv_(1),
174       begin_args_(1) {
175 }
176
177 CommandLine::CommandLine(const FilePath& program)
178     : argv_(1),
179       begin_args_(1) {
180   SetProgram(program);
181 }
182
183 CommandLine::CommandLine(int argc, const CommandLine::CharType* const* argv)
184     : argv_(1),
185       begin_args_(1) {
186   InitFromArgv(argc, argv);
187 }
188
189 CommandLine::CommandLine(const StringVector& argv)
190     : argv_(1),
191       begin_args_(1) {
192   InitFromArgv(argv);
193 }
194
195 CommandLine::CommandLine(const CommandLine& other) = default;
196
197 CommandLine& CommandLine::operator=(const CommandLine& other) = default;
198
199 CommandLine::~CommandLine() = default;
200
201 #if defined(OS_WIN)
202 // static
203 void CommandLine::set_slash_is_not_a_switch() {
204   // The last switch prefix should be slash, so adjust the size to skip it.
205   static_assert(base::make_span(kSwitchPrefixes).back() == L"/",
206                 "Error: Last switch prefix is not a slash.");
207   switch_prefix_count = base::size(kSwitchPrefixes) - 1;
208 }
209
210 // static
211 void CommandLine::InitUsingArgvForTesting(int argc, const char* const* argv) {
212   DCHECK(!current_process_commandline_);
213   current_process_commandline_ = new CommandLine(NO_PROGRAM);
214   // On Windows we need to convert the command line arguments to std::wstring.
215   CommandLine::StringVector argv_vector;
216   for (int i = 0; i < argc; ++i)
217     argv_vector.push_back(UTF8ToWide(argv[i]));
218   current_process_commandline_->InitFromArgv(argv_vector);
219 }
220 #endif
221
222 // static
223 bool CommandLine::Init(int argc, const char* const* argv) {
224   if (current_process_commandline_) {
225     // If this is intentional, Reset() must be called first. If we are using
226     // the shared build mode, we have to share a single object across multiple
227     // shared libraries.
228     return false;
229   }
230
231   current_process_commandline_ = new CommandLine(NO_PROGRAM);
232 #if defined(OS_WIN)
233   current_process_commandline_->ParseFromString(::GetCommandLineW());
234 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
235   current_process_commandline_->InitFromArgv(argc, argv);
236 #else
237 #error Unsupported platform
238 #endif
239
240   return true;
241 }
242
243 // static
244 void CommandLine::Reset() {
245   DCHECK(current_process_commandline_);
246   delete current_process_commandline_;
247   current_process_commandline_ = nullptr;
248 }
249
250 // static
251 CommandLine* CommandLine::ForCurrentProcess() {
252   DCHECK(current_process_commandline_);
253   return current_process_commandline_;
254 }
255
256 // static
257 bool CommandLine::InitializedForCurrentProcess() {
258   return !!current_process_commandline_;
259 }
260
261 #if defined(OS_WIN)
262 // static
263 CommandLine CommandLine::FromString(StringPieceType command_line) {
264   CommandLine cmd(NO_PROGRAM);
265   cmd.ParseFromString(command_line);
266   return cmd;
267 }
268 #endif
269
270 void CommandLine::InitFromArgv(int argc,
271                                const CommandLine::CharType* const* argv) {
272   StringVector new_argv;
273   for (int i = 0; i < argc; ++i)
274     new_argv.push_back(argv[i]);
275   InitFromArgv(new_argv);
276 }
277
278 void CommandLine::InitFromArgv(const StringVector& argv) {
279   argv_ = StringVector(1);
280   switches_.clear();
281   begin_args_ = 1;
282   SetProgram(argv.empty() ? FilePath() : FilePath(argv[0]));
283   AppendSwitchesAndArguments(this, argv);
284 }
285
286 FilePath CommandLine::GetProgram() const {
287   return FilePath(argv_[0]);
288 }
289
290 void CommandLine::SetProgram(const FilePath& program) {
291 #if defined(OS_WIN)
292   argv_[0] = StringType(TrimWhitespace(program.value(), TRIM_ALL));
293 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
294   TrimWhitespaceASCII(program.value(), TRIM_ALL, &argv_[0]);
295 #else
296 #error Unsupported platform
297 #endif
298 }
299
300 bool CommandLine::HasSwitch(const StringPiece& switch_string) const {
301   DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
302   return Contains(switches_, switch_string);
303 }
304
305 bool CommandLine::HasSwitch(const char switch_constant[]) const {
306   return HasSwitch(StringPiece(switch_constant));
307 }
308
309 std::string CommandLine::GetSwitchValueASCII(
310     const StringPiece& switch_string) const {
311   StringType value = GetSwitchValueNative(switch_string);
312 #if defined(OS_WIN)
313   if (!IsStringASCII(base::AsStringPiece16(value))) {
314 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
315   if (!IsStringASCII(value)) {
316 #endif
317     DLOG(WARNING) << "Value of switch (" << switch_string << ") must be ASCII.";
318     return std::string();
319   }
320 #if defined(OS_WIN)
321   return WideToUTF8(value);
322 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
323   return value;
324 #endif
325 }
326
327 FilePath CommandLine::GetSwitchValuePath(
328     const StringPiece& switch_string) const {
329   return FilePath(GetSwitchValueNative(switch_string));
330 }
331
332 CommandLine::StringType CommandLine::GetSwitchValueNative(
333     const StringPiece& switch_string) const {
334   DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
335   auto result = switches_.find(switch_string);
336   return result == switches_.end() ? StringType() : result->second;
337 }
338
339 void CommandLine::AppendSwitch(const std::string& switch_string) {
340   AppendSwitchNative(switch_string, StringType());
341 }
342
343 void CommandLine::AppendSwitchPath(const std::string& switch_string,
344                                    const FilePath& path) {
345   AppendSwitchNative(switch_string, path.value());
346 }
347
348 void CommandLine::AppendSwitchNative(const std::string& switch_string,
349                                      const CommandLine::StringType& value) {
350 #if defined(OS_WIN)
351   const std::string switch_key = ToLowerASCII(switch_string);
352   StringType combined_switch_string(UTF8ToWide(switch_key));
353 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
354   const std::string& switch_key = switch_string;
355   StringType combined_switch_string(switch_key);
356 #endif
357   size_t prefix_length = GetSwitchPrefixLength(combined_switch_string);
358   auto insertion =
359       switches_.insert(make_pair(switch_key.substr(prefix_length), value));
360   if (!insertion.second)
361     insertion.first->second = value;
362   // Preserve existing switch prefixes in |argv_|; only append one if necessary.
363   if (prefix_length == 0) {
364     combined_switch_string.insert(0, kSwitchPrefixes[0].data(),
365                                   kSwitchPrefixes[0].size());
366   }
367   if (!value.empty())
368     combined_switch_string += kSwitchValueSeparator + value;
369   // Append the switch and update the switches/arguments divider |begin_args_|.
370   argv_.insert(argv_.begin() + begin_args_++, combined_switch_string);
371 }
372
373 void CommandLine::AppendSwitchASCII(const std::string& switch_string,
374                                     const std::string& value_string) {
375 #if defined(OS_WIN)
376   AppendSwitchNative(switch_string, UTF8ToWide(value_string));
377 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
378   AppendSwitchNative(switch_string, value_string);
379 #else
380 #error Unsupported platform
381 #endif
382 }
383
384 void CommandLine::RemoveSwitch(base::StringPiece switch_key_without_prefix) {
385 #if defined(OS_WIN)
386   StringType switch_key_native = UTF8ToWide(switch_key_without_prefix);
387 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
388   StringType switch_key_native = switch_key_without_prefix.as_string();
389 #endif
390
391   DCHECK_EQ(ToLowerASCII(switch_key_without_prefix), switch_key_without_prefix);
392   DCHECK_EQ(0u, GetSwitchPrefixLength(switch_key_native));
393   size_t erased_from_switches =
394       switches_.erase(switch_key_without_prefix.as_string());
395   DCHECK(erased_from_switches <= 1);
396   if (!erased_from_switches)
397     return;
398
399   // Also erase from the switches section of |argv_| and update |begin_args_|
400   // accordingly.
401   // Switches in |argv_| have indices [1, begin_args_).
402   auto argv_switches_begin = argv_.begin() + 1;
403   auto argv_switches_end = argv_.begin() + begin_args_;
404   DCHECK(argv_switches_begin <= argv_switches_end);
405   DCHECK(argv_switches_end <= argv_.end());
406   auto expell = std::remove_if(argv_switches_begin, argv_switches_end,
407                                [&switch_key_native](const StringType& arg) {
408                                  return IsSwitchWithKey(arg, switch_key_native);
409                                });
410   if (expell == argv_switches_end) {
411     NOTREACHED();
412     return;
413   }
414   begin_args_ -= argv_switches_end - expell;
415   argv_.erase(expell, argv_switches_end);
416 }
417
418 void CommandLine::CopySwitchesFrom(const CommandLine& source,
419                                    const char* const switches[],
420                                    size_t count) {
421   for (size_t i = 0; i < count; ++i) {
422     if (source.HasSwitch(switches[i]))
423       AppendSwitchNative(switches[i], source.GetSwitchValueNative(switches[i]));
424   }
425 }
426
427 CommandLine::StringVector CommandLine::GetArgs() const {
428   // Gather all arguments after the last switch (may include kSwitchTerminator).
429   StringVector args(argv_.begin() + begin_args_, argv_.end());
430   // Erase only the first kSwitchTerminator (maybe "--" is a legitimate page?)
431   auto switch_terminator =
432       std::find(args.begin(), args.end(), kSwitchTerminator);
433   if (switch_terminator != args.end())
434     args.erase(switch_terminator);
435   return args;
436 }
437
438 void CommandLine::AppendArg(const std::string& value) {
439 #if defined(OS_WIN)
440   DCHECK(IsStringUTF8(value));
441   AppendArgNative(UTF8ToWide(value));
442 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
443   AppendArgNative(value);
444 #else
445 #error Unsupported platform
446 #endif
447 }
448
449 void CommandLine::AppendArgPath(const FilePath& path) {
450   AppendArgNative(path.value());
451 }
452
453 void CommandLine::AppendArgNative(const CommandLine::StringType& value) {
454   argv_.push_back(value);
455 }
456
457 void CommandLine::AppendArguments(const CommandLine& other,
458                                   bool include_program) {
459   if (include_program)
460     SetProgram(other.GetProgram());
461   AppendSwitchesAndArguments(this, other.argv());
462 }
463
464 void CommandLine::PrependWrapper(const CommandLine::StringType& wrapper) {
465   if (wrapper.empty())
466     return;
467   // Split the wrapper command based on whitespace (with quoting).
468   using CommandLineTokenizer =
469       StringTokenizerT<StringType, StringType::const_iterator>;
470   CommandLineTokenizer tokenizer(wrapper, FILE_PATH_LITERAL(" "));
471   tokenizer.set_quote_chars(FILE_PATH_LITERAL("'\""));
472   std::vector<StringType> wrapper_argv;
473   while (tokenizer.GetNext())
474     wrapper_argv.emplace_back(tokenizer.token());
475
476   // Prepend the wrapper and update the switches/arguments |begin_args_|.
477   argv_.insert(argv_.begin(), wrapper_argv.begin(), wrapper_argv.end());
478   begin_args_ += wrapper_argv.size();
479 }
480
481 #if defined(OS_WIN)
482 void CommandLine::ParseFromString(StringPieceType command_line) {
483   command_line = TrimWhitespace(command_line, TRIM_ALL);
484   if (command_line.empty())
485     return;
486
487   int num_args = 0;
488   wchar_t** args = NULL;
489   // When calling CommandLineToArgvW, use the apiset if available.
490   // Doing so will bypass loading shell32.dll on Win8+.
491   HMODULE downlevel_shell32_dll =
492       ::LoadLibraryEx(L"api-ms-win-downlevel-shell32-l1-1-0.dll", nullptr,
493                       LOAD_LIBRARY_SEARCH_SYSTEM32);
494   if (downlevel_shell32_dll) {
495     auto command_line_to_argv_w_proc =
496         reinterpret_cast<decltype(::CommandLineToArgvW)*>(
497             ::GetProcAddress(downlevel_shell32_dll, "CommandLineToArgvW"));
498     if (command_line_to_argv_w_proc)
499       args = command_line_to_argv_w_proc(command_line.data(), &num_args);
500   } else {
501     // Since the apiset is not available, allow the delayload of shell32.dll
502     // to take place.
503     args = ::CommandLineToArgvW(command_line.data(), &num_args);
504   }
505
506   DPLOG_IF(FATAL, !args) << "CommandLineToArgvW failed on command line: "
507                          << command_line;
508   StringVector argv(args, args + num_args);
509   InitFromArgv(argv);
510   LocalFree(args);
511
512   if (downlevel_shell32_dll)
513     ::FreeLibrary(downlevel_shell32_dll);
514 }
515 #endif
516
517 CommandLine::StringType CommandLine::GetCommandLineStringInternal(
518     bool quote_placeholders) const {
519   StringType string(argv_[0]);
520 #if defined(OS_WIN)
521   string = QuoteForCommandLineToArgvW(string, quote_placeholders);
522 #endif
523   StringType params(GetArgumentsStringInternal(quote_placeholders));
524   if (!params.empty()) {
525     string.append(FILE_PATH_LITERAL(" "));
526     string.append(params);
527   }
528   return string;
529 }
530
531 CommandLine::StringType CommandLine::GetArgumentsStringInternal(
532     bool quote_placeholders) const {
533   StringType params;
534   // Append switches and arguments.
535   bool parse_switches = true;
536   for (size_t i = 1; i < argv_.size(); ++i) {
537     StringType arg = argv_[i];
538     StringType switch_string;
539     StringType switch_value;
540     parse_switches &= arg != kSwitchTerminator;
541     if (i > 1)
542       params.append(FILE_PATH_LITERAL(" "));
543     if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
544       params.append(switch_string);
545       if (!switch_value.empty()) {
546 #if defined(OS_WIN)
547         switch_value =
548             QuoteForCommandLineToArgvW(switch_value, quote_placeholders);
549 #endif
550         params.append(kSwitchValueSeparator + switch_value);
551       }
552     } else {
553 #if defined(OS_WIN)
554       arg = QuoteForCommandLineToArgvW(arg, quote_placeholders);
555 #endif
556       params.append(arg);
557     }
558   }
559   return params;
560 }
561
562 }  // namespace base