command_line.cc 23 KB

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