cmOutputConverter.cxx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmOutputConverter.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cctype>
  7. #include <set>
  8. #include <vector>
  9. #include "cmState.h"
  10. #include "cmStateDirectory.h"
  11. #include "cmStringAlgorithms.h"
  12. #include "cmSystemTools.h"
  13. #include "cmValue.h"
  14. namespace {
  15. bool PathEqOrSubDir(std::string const& a, std::string const& b)
  16. {
  17. return (cmSystemTools::ComparePath(a, b) ||
  18. cmSystemTools::IsSubDirectory(a, b));
  19. }
  20. }
  21. cmOutputConverter::cmOutputConverter(cmStateSnapshot const& snapshot)
  22. : StateSnapshot(snapshot)
  23. , LinkScriptShell(false)
  24. {
  25. assert(this->StateSnapshot.IsValid());
  26. this->ComputeRelativePathTopSource();
  27. this->ComputeRelativePathTopBinary();
  28. }
  29. void cmOutputConverter::ComputeRelativePathTopSource()
  30. {
  31. // Walk up the buildsystem directory tree to find the highest source
  32. // directory that contains the current source directory.
  33. cmStateSnapshot snapshot = this->StateSnapshot;
  34. for (cmStateSnapshot parent = snapshot.GetBuildsystemDirectoryParent();
  35. parent.IsValid(); parent = parent.GetBuildsystemDirectoryParent()) {
  36. if (cmSystemTools::IsSubDirectory(
  37. snapshot.GetDirectory().GetCurrentSource(),
  38. parent.GetDirectory().GetCurrentSource())) {
  39. snapshot = parent;
  40. }
  41. }
  42. this->RelativePathTopSource = snapshot.GetDirectory().GetCurrentSource();
  43. }
  44. void cmOutputConverter::ComputeRelativePathTopBinary()
  45. {
  46. // Walk up the buildsystem directory tree to find the highest binary
  47. // directory that contains the current binary directory.
  48. cmStateSnapshot snapshot = this->StateSnapshot;
  49. for (cmStateSnapshot parent = snapshot.GetBuildsystemDirectoryParent();
  50. parent.IsValid(); parent = parent.GetBuildsystemDirectoryParent()) {
  51. if (cmSystemTools::IsSubDirectory(
  52. snapshot.GetDirectory().GetCurrentBinary(),
  53. parent.GetDirectory().GetCurrentBinary())) {
  54. snapshot = parent;
  55. }
  56. }
  57. this->RelativePathTopBinary = snapshot.GetDirectory().GetCurrentBinary();
  58. }
  59. std::string const& cmOutputConverter::GetRelativePathTopSource() const
  60. {
  61. return this->RelativePathTopSource;
  62. }
  63. std::string const& cmOutputConverter::GetRelativePathTopBinary() const
  64. {
  65. return this->RelativePathTopBinary;
  66. }
  67. void cmOutputConverter::SetRelativePathTopSource(std::string const& top)
  68. {
  69. this->RelativePathTopSource = top;
  70. }
  71. void cmOutputConverter::SetRelativePathTopBinary(std::string const& top)
  72. {
  73. this->RelativePathTopBinary = top;
  74. }
  75. std::string cmOutputConverter::MaybeRelativeTo(
  76. std::string const& local_path, std::string const& remote_path) const
  77. {
  78. bool bothInBinary =
  79. PathEqOrSubDir(local_path, this->RelativePathTopBinary) &&
  80. PathEqOrSubDir(remote_path, this->RelativePathTopBinary);
  81. bool bothInSource =
  82. PathEqOrSubDir(local_path, this->RelativePathTopSource) &&
  83. PathEqOrSubDir(remote_path, this->RelativePathTopSource);
  84. if (bothInBinary || bothInSource) {
  85. return cmSystemTools::ForceToRelativePath(local_path, remote_path);
  86. }
  87. return remote_path;
  88. }
  89. std::string cmOutputConverter::MaybeRelativeToTopBinDir(
  90. std::string const& path) const
  91. {
  92. return this->MaybeRelativeTo(this->GetState()->GetBinaryDirectory(), path);
  93. }
  94. std::string cmOutputConverter::MaybeRelativeToCurBinDir(
  95. std::string const& path) const
  96. {
  97. return this->MaybeRelativeTo(
  98. this->StateSnapshot.GetDirectory().GetCurrentBinary(), path);
  99. }
  100. std::string cmOutputConverter::ConvertToOutputForExisting(
  101. const std::string& remote, OutputFormat format) const
  102. {
  103. // If this is a windows shell, the result has a space, and the path
  104. // already exists, we can use a short-path to reference it without a
  105. // space.
  106. if (this->GetState()->UseWindowsShell() &&
  107. remote.find_first_of(" #") != std::string::npos &&
  108. cmSystemTools::FileExists(remote)) {
  109. std::string tmp;
  110. if (cmSystemTools::GetShortPath(remote, tmp)) {
  111. return this->ConvertToOutputFormat(tmp, format);
  112. }
  113. }
  114. // Otherwise, perform standard conversion.
  115. return this->ConvertToOutputFormat(remote, format);
  116. }
  117. std::string cmOutputConverter::ConvertToOutputFormat(cm::string_view source,
  118. OutputFormat output) const
  119. {
  120. std::string result(source);
  121. // Convert it to an output path.
  122. if (output == SHELL || output == WATCOMQUOTE || output == NINJAMULTI) {
  123. result = this->ConvertDirectorySeparatorsForShell(source);
  124. result = this->EscapeForShell(result, true, false, output == WATCOMQUOTE,
  125. output == NINJAMULTI);
  126. } else if (output == RESPONSE) {
  127. result = this->EscapeForShell(result, false, false, false);
  128. }
  129. return result;
  130. }
  131. std::string cmOutputConverter::ConvertDirectorySeparatorsForShell(
  132. cm::string_view source) const
  133. {
  134. std::string result(source);
  135. // For the MSYS shell convert drive letters to posix paths, so
  136. // that c:/some/path becomes /c/some/path. This is needed to
  137. // avoid problems with the shell path translation.
  138. if (this->GetState()->UseMSYSShell() && !this->LinkScriptShell) {
  139. if (result.size() > 2 && result[1] == ':') {
  140. result[1] = result[0];
  141. result[0] = '/';
  142. }
  143. }
  144. if (this->GetState()->UseWindowsShell()) {
  145. std::replace(result.begin(), result.end(), '/', '\\');
  146. }
  147. return result;
  148. }
  149. static bool cmOutputConverterIsShellOperator(cm::string_view str)
  150. {
  151. static std::set<cm::string_view> const shellOperators{
  152. "<", ">", "<<", ">>", "|", "||", "&&", "&>", "1>", "2>", "2>&1", "1>&2"
  153. };
  154. return (shellOperators.count(str) != 0);
  155. }
  156. std::string cmOutputConverter::EscapeForShell(
  157. cm::string_view str, bool makeVars, bool forEcho, bool useWatcomQuote,
  158. bool unescapeNinjaConfiguration) const
  159. {
  160. // Do not escape shell operators.
  161. if (cmOutputConverterIsShellOperator(str)) {
  162. return std::string(str);
  163. }
  164. // Compute the flags for the target shell environment.
  165. int flags = 0;
  166. if (this->GetState()->UseWindowsVSIDE()) {
  167. flags |= Shell_Flag_VSIDE;
  168. } else if (!this->LinkScriptShell) {
  169. flags |= Shell_Flag_Make;
  170. }
  171. if (unescapeNinjaConfiguration) {
  172. flags |= Shell_Flag_UnescapeNinjaConfiguration;
  173. }
  174. if (makeVars) {
  175. flags |= Shell_Flag_AllowMakeVariables;
  176. }
  177. if (forEcho) {
  178. flags |= Shell_Flag_EchoWindows;
  179. }
  180. if (useWatcomQuote) {
  181. flags |= Shell_Flag_WatcomQuote;
  182. }
  183. if (this->GetState()->UseWatcomWMake()) {
  184. flags |= Shell_Flag_WatcomWMake;
  185. }
  186. if (this->GetState()->UseMinGWMake()) {
  187. flags |= Shell_Flag_MinGWMake;
  188. }
  189. if (this->GetState()->UseNMake()) {
  190. flags |= Shell_Flag_NMake;
  191. }
  192. if (!this->GetState()->UseWindowsShell()) {
  193. flags |= Shell_Flag_IsUnix;
  194. }
  195. return Shell_GetArgument(str, flags);
  196. }
  197. std::string cmOutputConverter::EscapeForCMake(cm::string_view str,
  198. WrapQuotes wrapQuotes)
  199. {
  200. // Always double-quote the argument to take care of most escapes.
  201. std::string result = (wrapQuotes == WrapQuotes::Wrap) ? "\"" : "";
  202. for (const char c : str) {
  203. if (c == '"') {
  204. // Escape the double quote to avoid ending the argument.
  205. result += "\\\"";
  206. } else if (c == '$') {
  207. // Escape the dollar to avoid expanding variables.
  208. result += "\\$";
  209. } else if (c == '\\') {
  210. // Escape the backslash to avoid other escapes.
  211. result += "\\\\";
  212. } else {
  213. // Other characters will be parsed correctly.
  214. result += c;
  215. }
  216. }
  217. if (wrapQuotes == WrapQuotes::Wrap) {
  218. result += "\"";
  219. }
  220. return result;
  221. }
  222. std::string cmOutputConverter::EscapeWindowsShellArgument(cm::string_view arg,
  223. int shell_flags)
  224. {
  225. return Shell_GetArgument(arg, shell_flags);
  226. }
  227. cmOutputConverter::FortranFormat cmOutputConverter::GetFortranFormat(
  228. cm::string_view value)
  229. {
  230. FortranFormat format = FortranFormatNone;
  231. if (!value.empty()) {
  232. for (std::string const& fi : cmExpandedList(value)) {
  233. if (fi == "FIXED") {
  234. format = FortranFormatFixed;
  235. }
  236. if (fi == "FREE") {
  237. format = FortranFormatFree;
  238. }
  239. }
  240. }
  241. return format;
  242. }
  243. cmOutputConverter::FortranPreprocess cmOutputConverter::GetFortranPreprocess(
  244. cm::string_view value)
  245. {
  246. if (value.empty()) {
  247. return FortranPreprocess::Unset;
  248. }
  249. return cmIsOn(value) ? FortranPreprocess::Needed
  250. : FortranPreprocess::NotNeeded;
  251. }
  252. void cmOutputConverter::SetLinkScriptShell(bool linkScriptShell)
  253. {
  254. this->LinkScriptShell = linkScriptShell;
  255. }
  256. cmState* cmOutputConverter::GetState() const
  257. {
  258. return this->StateSnapshot.GetState();
  259. }
  260. /*
  261. Notes:
  262. Make variable replacements open a can of worms. Sometimes they should
  263. be quoted and sometimes not. Sometimes their replacement values are
  264. already quoted.
  265. VS variables cause problems. In order to pass the referenced value
  266. with spaces the reference must be quoted. If the variable value ends
  267. in a backslash then it will escape the ending quote! In order to make
  268. the ending backslash appear we need this:
  269. "$(InputDir)\"
  270. However if there is not a trailing backslash then this will put a
  271. quote in the value so we need:
  272. "$(InputDir)"
  273. Make variable references are platform specific so we should probably
  274. just NOT quote them and let the listfile author deal with it.
  275. */
  276. /*
  277. TODO: For windows echo:
  278. To display a pipe (|) or redirection character (< or >) when using the
  279. echo command, use a caret character immediately before the pipe or
  280. redirection character (for example, ^>, ^<, or ^| ). If you need to
  281. use the caret character itself (^), use two in a row (^^).
  282. */
  283. /* Some helpers to identify character classes */
  284. static bool Shell_CharIsWhitespace(char c)
  285. {
  286. return ((c == ' ') || (c == '\t'));
  287. }
  288. static bool Shell_CharNeedsQuotesOnUnix(char c)
  289. {
  290. return ((c == '\'') || (c == '`') || (c == ';') || (c == '#') ||
  291. (c == '&') || (c == '$') || (c == '(') || (c == ')') || (c == '~') ||
  292. (c == '<') || (c == '>') || (c == '|') || (c == '*') || (c == '^') ||
  293. (c == '\\'));
  294. }
  295. static bool Shell_CharNeedsQuotesOnWindows(char c)
  296. {
  297. return ((c == '\'') || (c == '#') || (c == '&') || (c == '<') ||
  298. (c == '>') || (c == '|') || (c == '^'));
  299. }
  300. static bool Shell_CharIsMakeVariableName(char c)
  301. {
  302. return c && (c == '_' || isalpha((static_cast<int>(c))));
  303. }
  304. bool cmOutputConverter::Shell_CharNeedsQuotes(char c, int flags)
  305. {
  306. /* On Windows the built-in command shell echo never needs quotes. */
  307. if (!(flags & Shell_Flag_IsUnix) && (flags & Shell_Flag_EchoWindows)) {
  308. return false;
  309. }
  310. /* On all platforms quotes are needed to preserve whitespace. */
  311. if (Shell_CharIsWhitespace(c)) {
  312. return true;
  313. }
  314. if (flags & Shell_Flag_IsUnix) {
  315. /* On UNIX several special characters need quotes to preserve them. */
  316. if (Shell_CharNeedsQuotesOnUnix(c)) {
  317. return true;
  318. }
  319. } else {
  320. /* On Windows several special characters need quotes to preserve them. */
  321. if (Shell_CharNeedsQuotesOnWindows(c)) {
  322. return true;
  323. }
  324. }
  325. return false;
  326. }
  327. cm::string_view::iterator cmOutputConverter::Shell_SkipMakeVariables(
  328. cm::string_view::iterator c, cm::string_view::iterator end)
  329. {
  330. while ((c != end && (c + 1) != end) && (*c == '$' && *(c + 1) == '(')) {
  331. cm::string_view::iterator skip = c + 2;
  332. while ((skip != end) && Shell_CharIsMakeVariableName(*skip)) {
  333. ++skip;
  334. }
  335. if ((skip != end) && *skip == ')') {
  336. c = skip + 1;
  337. } else {
  338. break;
  339. }
  340. }
  341. return c;
  342. }
  343. /*
  344. Allowing make variable replacements opens a can of worms. Sometimes
  345. they should be quoted and sometimes not. Sometimes their replacement
  346. values are already quoted or contain escapes.
  347. Some Visual Studio variables cause problems. In order to pass the
  348. referenced value with spaces the reference must be quoted. If the
  349. variable value ends in a backslash then it will escape the ending
  350. quote! In order to make the ending backslash appear we need this:
  351. "$(InputDir)\"
  352. However if there is not a trailing backslash then this will put a
  353. quote in the value so we need:
  354. "$(InputDir)"
  355. This macro decides whether we quote an argument just because it
  356. contains a make variable reference. This should be replaced with a
  357. flag later when we understand applications of this better.
  358. */
  359. #define KWSYS_SYSTEM_SHELL_QUOTE_MAKE_VARIABLES 0
  360. bool cmOutputConverter::Shell_ArgumentNeedsQuotes(cm::string_view in,
  361. int flags)
  362. {
  363. /* The empty string needs quotes. */
  364. if (in.empty()) {
  365. return true;
  366. }
  367. /* Scan the string for characters that require quoting. */
  368. for (cm::string_view::iterator cit = in.begin(), cend = in.end();
  369. cit != cend; ++cit) {
  370. /* Look for $(MAKEVAR) syntax if requested. */
  371. if (flags & Shell_Flag_AllowMakeVariables) {
  372. #if KWSYS_SYSTEM_SHELL_QUOTE_MAKE_VARIABLES
  373. cm::string_view::iterator skip = Shell_SkipMakeVariables(cit, cend);
  374. if (skip != cit) {
  375. /* We need to quote make variable references to preserve the
  376. string with contents substituted in its place. */
  377. return true;
  378. }
  379. #else
  380. /* Skip over the make variable references if any are present. */
  381. cit = Shell_SkipMakeVariables(cit, cend);
  382. /* Stop if we have reached the end of the string. */
  383. if (cit == cend) {
  384. break;
  385. }
  386. #endif
  387. }
  388. /* Check whether this character needs quotes. */
  389. if (Shell_CharNeedsQuotes(*cit, flags)) {
  390. return true;
  391. }
  392. }
  393. /* On Windows some single character arguments need quotes. */
  394. if (flags & Shell_Flag_IsUnix && in.size() == 1) {
  395. char c = in[0];
  396. if ((c == '?') || (c == '&') || (c == '^') || (c == '|') || (c == '#')) {
  397. return true;
  398. }
  399. }
  400. return false;
  401. }
  402. std::string cmOutputConverter::Shell_GetArgument(cm::string_view in, int flags)
  403. {
  404. /* Output will be at least as long as input string. */
  405. std::string out;
  406. out.reserve(in.size());
  407. /* Keep track of how many backslashes have been encountered in a row. */
  408. int windows_backslashes = 0;
  409. /* Whether the argument must be quoted. */
  410. int needQuotes = Shell_ArgumentNeedsQuotes(in, flags);
  411. if (needQuotes) {
  412. /* Add the opening quote for this argument. */
  413. if (flags & Shell_Flag_WatcomQuote) {
  414. if (flags & Shell_Flag_IsUnix) {
  415. out += '"';
  416. }
  417. out += '\'';
  418. } else {
  419. out += '"';
  420. }
  421. }
  422. /* Scan the string for characters that require escaping or quoting. */
  423. for (cm::string_view::iterator cit = in.begin(), cend = in.end();
  424. cit != cend; ++cit) {
  425. /* Look for $(MAKEVAR) syntax if requested. */
  426. if (flags & Shell_Flag_AllowMakeVariables) {
  427. cm::string_view::iterator skip = Shell_SkipMakeVariables(cit, cend);
  428. if (skip != cit) {
  429. /* Copy to the end of the make variable references. */
  430. while (cit != skip) {
  431. out += *cit++;
  432. }
  433. /* The make variable reference eliminates any escaping needed
  434. for preceding backslashes. */
  435. windows_backslashes = 0;
  436. /* Stop if we have reached the end of the string. */
  437. if (cit == cend) {
  438. break;
  439. }
  440. }
  441. }
  442. /* Check whether this character needs escaping for the shell. */
  443. if (flags & Shell_Flag_IsUnix) {
  444. /* On Unix a few special characters need escaping even inside a
  445. quoted argument. */
  446. if (*cit == '\\' || *cit == '"' || *cit == '`' || *cit == '$') {
  447. /* This character needs a backslash to escape it. */
  448. out += '\\';
  449. }
  450. } else if (flags & Shell_Flag_EchoWindows) {
  451. /* On Windows the built-in command shell echo never needs escaping. */
  452. } else {
  453. /* On Windows only backslashes and double-quotes need escaping. */
  454. if (*cit == '\\') {
  455. /* Found a backslash. It may need to be escaped later. */
  456. ++windows_backslashes;
  457. } else if (*cit == '"') {
  458. /* Found a double-quote. Escape all immediately preceding
  459. backslashes. */
  460. while (windows_backslashes > 0) {
  461. --windows_backslashes;
  462. out += '\\';
  463. }
  464. /* Add the backslash to escape the double-quote. */
  465. out += '\\';
  466. } else {
  467. /* We encountered a normal character. This eliminates any
  468. escaping needed for preceding backslashes. */
  469. windows_backslashes = 0;
  470. }
  471. }
  472. /* Check whether this character needs escaping for a make tool. */
  473. if (*cit == '$') {
  474. if (flags & Shell_Flag_Make) {
  475. /* In Makefiles a dollar is written $$. The make tool will
  476. replace it with just $ before passing it to the shell. */
  477. out += "$$";
  478. } else if (flags & Shell_Flag_VSIDE) {
  479. /* In a VS IDE a dollar is written "$". If this is written in
  480. an un-quoted argument it starts a quoted segment, inserts
  481. the $ and ends the segment. If it is written in a quoted
  482. argument it ends quoting, inserts the $ and restarts
  483. quoting. Either way the $ is isolated from surrounding
  484. text to avoid looking like a variable reference. */
  485. out += "\"$\"";
  486. } else {
  487. /* Otherwise a dollar is written just $. */
  488. out += '$';
  489. }
  490. } else if (*cit == '#') {
  491. if ((flags & Shell_Flag_Make) && (flags & Shell_Flag_WatcomWMake)) {
  492. /* In Watcom WMake makefiles a pound is written $#. The make
  493. tool will replace it with just # before passing it to the
  494. shell. */
  495. out += "$#";
  496. } else {
  497. /* Otherwise a pound is written just #. */
  498. out += '#';
  499. }
  500. } else if (*cit == '%') {
  501. if ((flags & Shell_Flag_VSIDE) ||
  502. ((flags & Shell_Flag_Make) &&
  503. ((flags & Shell_Flag_MinGWMake) || (flags & Shell_Flag_NMake)))) {
  504. /* In the VS IDE, NMake, or MinGW make a percent is written %%. */
  505. out += "%%";
  506. } else {
  507. /* Otherwise a percent is written just %. */
  508. out += '%';
  509. }
  510. } else if (*cit == ';') {
  511. if (flags & Shell_Flag_VSIDE) {
  512. /* In a VS IDE a semicolon is written ";". If this is written
  513. in an un-quoted argument it starts a quoted segment,
  514. inserts the ; and ends the segment. If it is written in a
  515. quoted argument it ends quoting, inserts the ; and restarts
  516. quoting. Either way the ; is isolated. */
  517. out += "\";\"";
  518. } else {
  519. /* Otherwise a semicolon is written just ;. */
  520. out += ';';
  521. }
  522. } else {
  523. /* Store this character. */
  524. out += *cit;
  525. }
  526. }
  527. if (needQuotes) {
  528. /* Add enough backslashes to escape any trailing ones. */
  529. while (windows_backslashes > 0) {
  530. --windows_backslashes;
  531. out += '\\';
  532. }
  533. /* Add the closing quote for this argument. */
  534. if (flags & Shell_Flag_WatcomQuote) {
  535. out += '\'';
  536. if (flags & Shell_Flag_IsUnix) {
  537. out += '"';
  538. }
  539. } else {
  540. out += '"';
  541. }
  542. }
  543. if (flags & Shell_Flag_UnescapeNinjaConfiguration) {
  544. std::string ninjaConfigReplace;
  545. if (flags & Shell_Flag_IsUnix) {
  546. ninjaConfigReplace += '\\';
  547. }
  548. ninjaConfigReplace += "$${CONFIGURATION}";
  549. cmSystemTools::ReplaceString(out, ninjaConfigReplace, "${CONFIGURATION}");
  550. }
  551. return out;
  552. }