cmStringCommand.cxx 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  4. #define _SCL_SECURE_NO_WARNINGS
  5. #include "cmStringCommand.h"
  6. #include <algorithm>
  7. #include <cstdio>
  8. #include <cstdlib>
  9. #include <limits>
  10. #include <memory>
  11. #include <stdexcept>
  12. #include <utility>
  13. #include <cm/iterator>
  14. #include <cm/optional>
  15. #include <cm/string_view>
  16. #include <cmext/string_view>
  17. #include <cm3p/json/reader.h>
  18. #include <cm3p/json/value.h>
  19. #include <cm3p/json/writer.h>
  20. #include "cmsys/RegularExpression.hxx"
  21. #include "cmCryptoHash.h"
  22. #include "cmExecutionStatus.h"
  23. #include "cmGeneratorExpression.h"
  24. #include "cmMakefile.h"
  25. #include "cmMessageType.h"
  26. #include "cmPolicies.h"
  27. #include "cmRange.h"
  28. #include "cmStringAlgorithms.h"
  29. #include "cmStringReplaceHelper.h"
  30. #include "cmSubcommandTable.h"
  31. #include "cmSystemTools.h"
  32. #include "cmTimestamp.h"
  33. #include "cmUuid.h"
  34. #include "cmValue.h"
  35. namespace {
  36. bool RegexMatch(std::vector<std::string> const& args,
  37. cmExecutionStatus& status);
  38. bool RegexMatchAll(std::vector<std::string> const& args,
  39. cmExecutionStatus& status);
  40. bool RegexReplace(std::vector<std::string> const& args,
  41. cmExecutionStatus& status);
  42. bool joinImpl(std::vector<std::string> const& args, std::string const& glue,
  43. size_t varIdx, cmMakefile& makefile);
  44. bool HandleHashCommand(std::vector<std::string> const& args,
  45. cmExecutionStatus& status)
  46. {
  47. if (args.size() != 3) {
  48. status.SetError(
  49. cmStrCat(args[0], " requires an output variable and an input string"));
  50. return false;
  51. }
  52. std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0]));
  53. if (hash) {
  54. std::string out = hash->HashString(args[2]);
  55. status.GetMakefile().AddDefinition(args[1], out);
  56. return true;
  57. }
  58. return false;
  59. }
  60. bool HandleToUpperLowerCommand(std::vector<std::string> const& args,
  61. bool toUpper, cmExecutionStatus& status)
  62. {
  63. if (args.size() < 3) {
  64. status.SetError("no output variable specified");
  65. return false;
  66. }
  67. std::string const& outvar = args[2];
  68. std::string output;
  69. if (toUpper) {
  70. output = cmSystemTools::UpperCase(args[1]);
  71. } else {
  72. output = cmSystemTools::LowerCase(args[1]);
  73. }
  74. // Store the output in the provided variable.
  75. status.GetMakefile().AddDefinition(outvar, output);
  76. return true;
  77. }
  78. bool HandleToUpperCommand(std::vector<std::string> const& args,
  79. cmExecutionStatus& status)
  80. {
  81. return HandleToUpperLowerCommand(args, true, status);
  82. }
  83. bool HandleToLowerCommand(std::vector<std::string> const& args,
  84. cmExecutionStatus& status)
  85. {
  86. return HandleToUpperLowerCommand(args, false, status);
  87. }
  88. bool HandleAsciiCommand(std::vector<std::string> const& args,
  89. cmExecutionStatus& status)
  90. {
  91. if (args.size() < 3) {
  92. status.SetError("No output variable specified");
  93. return false;
  94. }
  95. std::string::size_type cc;
  96. std::string const& outvar = args.back();
  97. std::string output;
  98. for (cc = 1; cc < args.size() - 1; cc++) {
  99. int ch = atoi(args[cc].c_str());
  100. if (ch > 0 && ch < 256) {
  101. output += static_cast<char>(ch);
  102. } else {
  103. std::string error =
  104. cmStrCat("Character with code ", args[cc], " does not exist.");
  105. status.SetError(error);
  106. return false;
  107. }
  108. }
  109. // Store the output in the provided variable.
  110. status.GetMakefile().AddDefinition(outvar, output);
  111. return true;
  112. }
  113. bool HandleHexCommand(std::vector<std::string> const& args,
  114. cmExecutionStatus& status)
  115. {
  116. if (args.size() != 3) {
  117. status.SetError("Incorrect number of arguments");
  118. return false;
  119. }
  120. auto const& instr = args[1];
  121. auto const& outvar = args[2];
  122. std::string output(instr.size() * 2, ' ');
  123. std::string::size_type hexIndex = 0;
  124. for (auto const& c : instr) {
  125. snprintf(&output[hexIndex], 3, "%.2x",
  126. static_cast<unsigned char>(c) & 0xFF);
  127. hexIndex += 2;
  128. }
  129. status.GetMakefile().AddDefinition(outvar, output);
  130. return true;
  131. }
  132. bool HandleConfigureCommand(std::vector<std::string> const& args,
  133. cmExecutionStatus& status)
  134. {
  135. if (args.size() < 2) {
  136. status.SetError("No input string specified.");
  137. return false;
  138. }
  139. if (args.size() < 3) {
  140. status.SetError("No output variable specified.");
  141. return false;
  142. }
  143. // Parse options.
  144. bool escapeQuotes = false;
  145. bool atOnly = false;
  146. for (unsigned int i = 3; i < args.size(); ++i) {
  147. if (args[i] == "@ONLY") {
  148. atOnly = true;
  149. } else if (args[i] == "ESCAPE_QUOTES") {
  150. escapeQuotes = true;
  151. } else {
  152. status.SetError(cmStrCat("Unrecognized argument \"", args[i], "\""));
  153. return false;
  154. }
  155. }
  156. // Configure the string.
  157. std::string output;
  158. status.GetMakefile().ConfigureString(args[1], output, atOnly, escapeQuotes);
  159. // Store the output in the provided variable.
  160. status.GetMakefile().AddDefinition(args[2], output);
  161. return true;
  162. }
  163. bool HandleRegexCommand(std::vector<std::string> const& args,
  164. cmExecutionStatus& status)
  165. {
  166. if (args.size() < 2) {
  167. status.SetError("sub-command REGEX requires a mode to be specified.");
  168. return false;
  169. }
  170. std::string const& mode = args[1];
  171. if (mode == "MATCH") {
  172. if (args.size() < 5) {
  173. status.SetError("sub-command REGEX, mode MATCH needs "
  174. "at least 5 arguments total to command.");
  175. return false;
  176. }
  177. return RegexMatch(args, status);
  178. }
  179. if (mode == "MATCHALL") {
  180. if (args.size() < 5) {
  181. status.SetError("sub-command REGEX, mode MATCHALL needs "
  182. "at least 5 arguments total to command.");
  183. return false;
  184. }
  185. return RegexMatchAll(args, status);
  186. }
  187. if (mode == "REPLACE") {
  188. if (args.size() < 6) {
  189. status.SetError("sub-command REGEX, mode REPLACE needs "
  190. "at least 6 arguments total to command.");
  191. return false;
  192. }
  193. return RegexReplace(args, status);
  194. }
  195. std::string e = "sub-command REGEX does not recognize mode " + mode;
  196. status.SetError(e);
  197. return false;
  198. }
  199. bool RegexMatch(std::vector<std::string> const& args,
  200. cmExecutionStatus& status)
  201. {
  202. //"STRING(REGEX MATCH <regular_expression> <output variable>
  203. // <input> [<input>...])\n";
  204. std::string const& regex = args[2];
  205. std::string const& outvar = args[3];
  206. status.GetMakefile().ClearMatches();
  207. // Compile the regular expression.
  208. cmsys::RegularExpression re;
  209. if (!re.compile(regex)) {
  210. std::string e =
  211. "sub-command REGEX, mode MATCH failed to compile regex \"" + regex +
  212. "\".";
  213. status.SetError(e);
  214. return false;
  215. }
  216. // Concatenate all the last arguments together.
  217. std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
  218. // Scan through the input for all matches.
  219. std::string output;
  220. if (re.find(input)) {
  221. status.GetMakefile().StoreMatches(re);
  222. std::string::size_type l = re.start();
  223. std::string::size_type r = re.end();
  224. if (r - l == 0) {
  225. std::string e = "sub-command REGEX, mode MATCH regex \"" + regex +
  226. "\" matched an empty string.";
  227. status.SetError(e);
  228. return false;
  229. }
  230. output = input.substr(l, r - l);
  231. }
  232. // Store the output in the provided variable.
  233. status.GetMakefile().AddDefinition(outvar, output);
  234. return true;
  235. }
  236. bool RegexMatchAll(std::vector<std::string> const& args,
  237. cmExecutionStatus& status)
  238. {
  239. //"STRING(REGEX MATCHALL <regular_expression> <output variable> <input>
  240. // [<input>...])\n";
  241. std::string const& regex = args[2];
  242. std::string const& outvar = args[3];
  243. status.GetMakefile().ClearMatches();
  244. // Compile the regular expression.
  245. cmsys::RegularExpression re;
  246. if (!re.compile(regex)) {
  247. std::string e =
  248. "sub-command REGEX, mode MATCHALL failed to compile regex \"" + regex +
  249. "\".";
  250. status.SetError(e);
  251. return false;
  252. }
  253. // Concatenate all the last arguments together.
  254. std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
  255. unsigned optAnchor = 0;
  256. if (status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0186) !=
  257. cmPolicies::NEW) {
  258. optAnchor = cmsys::RegularExpression::BOL_AT_OFFSET;
  259. }
  260. // Scan through the input for all matches.
  261. std::string output;
  262. std::string::size_type base = 0;
  263. while (re.find(input, base, optAnchor)) {
  264. status.GetMakefile().ClearMatches();
  265. status.GetMakefile().StoreMatches(re);
  266. std::string::size_type l = re.start();
  267. std::string::size_type r = re.end();
  268. if (r - l == 0) {
  269. std::string e = "sub-command REGEX, mode MATCHALL regex \"" + regex +
  270. "\" matched an empty string.";
  271. status.SetError(e);
  272. return false;
  273. }
  274. if (!output.empty()) {
  275. output += ";";
  276. }
  277. output += re.match();
  278. base = r;
  279. }
  280. // Store the output in the provided variable.
  281. status.GetMakefile().AddDefinition(outvar, output);
  282. return true;
  283. }
  284. bool RegexReplace(std::vector<std::string> const& args,
  285. cmExecutionStatus& status)
  286. {
  287. //"STRING(REGEX REPLACE <regular_expression> <replace_expression>
  288. // <output variable> <input> [<input>...])\n"
  289. std::string const& regex = args[2];
  290. std::string const& replace = args[3];
  291. std::string const& outvar = args[4];
  292. cmStringReplaceHelper replaceHelper(regex, replace, &status.GetMakefile());
  293. if (!replaceHelper.IsReplaceExpressionValid()) {
  294. status.SetError(
  295. "sub-command REGEX, mode REPLACE: " + replaceHelper.GetError() + ".");
  296. return false;
  297. }
  298. status.GetMakefile().ClearMatches();
  299. if (!replaceHelper.IsRegularExpressionValid()) {
  300. std::string e =
  301. "sub-command REGEX, mode REPLACE failed to compile regex \"" + regex +
  302. "\".";
  303. status.SetError(e);
  304. return false;
  305. }
  306. // Concatenate all the last arguments together.
  307. std::string const input =
  308. cmJoin(cmMakeRange(args).advance(5), std::string());
  309. std::string output;
  310. if (!replaceHelper.Replace(input, output)) {
  311. status.SetError(
  312. "sub-command REGEX, mode REPLACE: " + replaceHelper.GetError() + ".");
  313. return false;
  314. }
  315. // Store the output in the provided variable.
  316. status.GetMakefile().AddDefinition(outvar, output);
  317. return true;
  318. }
  319. bool HandleFindCommand(std::vector<std::string> const& args,
  320. cmExecutionStatus& status)
  321. {
  322. // check if all required parameters were passed
  323. if (args.size() < 4 || args.size() > 5) {
  324. status.SetError("sub-command FIND requires 3 or 4 parameters.");
  325. return false;
  326. }
  327. // check if the reverse flag was set or not
  328. bool reverseMode = false;
  329. if (args.size() == 5 && args[4] == "REVERSE") {
  330. reverseMode = true;
  331. }
  332. // if we have 5 arguments the last one must be REVERSE
  333. if (args.size() == 5 && args[4] != "REVERSE") {
  334. status.SetError("sub-command FIND: unknown last parameter");
  335. return false;
  336. }
  337. // local parameter names.
  338. std::string const& sstring = args[1];
  339. std::string const& schar = args[2];
  340. std::string const& outvar = args[3];
  341. // ensure that the user cannot accidentally specify REVERSE as a variable
  342. if (outvar == "REVERSE") {
  343. status.SetError("sub-command FIND does not allow one to select REVERSE as "
  344. "the output variable. "
  345. "Maybe you missed the actual output variable?");
  346. return false;
  347. }
  348. // try to find the character and return its position
  349. size_t pos;
  350. if (!reverseMode) {
  351. pos = sstring.find(schar);
  352. } else {
  353. pos = sstring.rfind(schar);
  354. }
  355. if (std::string::npos != pos) {
  356. status.GetMakefile().AddDefinition(outvar, std::to_string(pos));
  357. return true;
  358. }
  359. // the character was not found, but this is not really an error
  360. status.GetMakefile().AddDefinition(outvar, "-1");
  361. return true;
  362. }
  363. bool HandleCompareCommand(std::vector<std::string> const& args,
  364. cmExecutionStatus& status)
  365. {
  366. if (args.size() < 2) {
  367. status.SetError("sub-command COMPARE requires a mode to be specified.");
  368. return false;
  369. }
  370. std::string const& mode = args[1];
  371. if ((mode == "EQUAL") || (mode == "NOTEQUAL") || (mode == "LESS") ||
  372. (mode == "LESS_EQUAL") || (mode == "GREATER") ||
  373. (mode == "GREATER_EQUAL")) {
  374. if (args.size() < 5) {
  375. std::string e =
  376. cmStrCat("sub-command COMPARE, mode ", mode,
  377. " needs at least 5 arguments total to command.");
  378. status.SetError(e);
  379. return false;
  380. }
  381. std::string const& left = args[2];
  382. std::string const& right = args[3];
  383. std::string const& outvar = args[4];
  384. bool result;
  385. if (mode == "LESS") {
  386. result = (left < right);
  387. } else if (mode == "LESS_EQUAL") {
  388. result = (left <= right);
  389. } else if (mode == "GREATER") {
  390. result = (left > right);
  391. } else if (mode == "GREATER_EQUAL") {
  392. result = (left >= right);
  393. } else if (mode == "EQUAL") {
  394. result = (left == right);
  395. } else // if(mode == "NOTEQUAL")
  396. {
  397. result = !(left == right);
  398. }
  399. if (result) {
  400. status.GetMakefile().AddDefinition(outvar, "1");
  401. } else {
  402. status.GetMakefile().AddDefinition(outvar, "0");
  403. }
  404. return true;
  405. }
  406. std::string e = "sub-command COMPARE does not recognize mode " + mode;
  407. status.SetError(e);
  408. return false;
  409. }
  410. bool HandleReplaceCommand(std::vector<std::string> const& args,
  411. cmExecutionStatus& status)
  412. {
  413. if (args.size() < 5) {
  414. status.SetError("sub-command REPLACE requires at least four arguments.");
  415. return false;
  416. }
  417. std::string const& matchExpression = args[1];
  418. std::string const& replaceExpression = args[2];
  419. std::string const& variableName = args[3];
  420. std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
  421. cmsys::SystemTools::ReplaceString(input, matchExpression.c_str(),
  422. replaceExpression.c_str());
  423. status.GetMakefile().AddDefinition(variableName, input);
  424. return true;
  425. }
  426. bool HandleSubstringCommand(std::vector<std::string> const& args,
  427. cmExecutionStatus& status)
  428. {
  429. if (args.size() != 5) {
  430. status.SetError("sub-command SUBSTRING requires four arguments.");
  431. return false;
  432. }
  433. std::string const& stringValue = args[1];
  434. int begin = atoi(args[2].c_str());
  435. int end = atoi(args[3].c_str());
  436. std::string const& variableName = args[4];
  437. size_t stringLength = stringValue.size();
  438. int intStringLength = static_cast<int>(stringLength);
  439. if (begin < 0 || begin > intStringLength) {
  440. status.SetError(
  441. cmStrCat("begin index: ", begin, " is out of range 0 - ", stringLength));
  442. return false;
  443. }
  444. if (end < -1) {
  445. status.SetError(cmStrCat("end index: ", end, " should be -1 or greater"));
  446. return false;
  447. }
  448. status.GetMakefile().AddDefinition(variableName,
  449. stringValue.substr(begin, end));
  450. return true;
  451. }
  452. bool HandleLengthCommand(std::vector<std::string> const& args,
  453. cmExecutionStatus& status)
  454. {
  455. if (args.size() != 3) {
  456. status.SetError("sub-command LENGTH requires two arguments.");
  457. return false;
  458. }
  459. std::string const& stringValue = args[1];
  460. std::string const& variableName = args[2];
  461. size_t length = stringValue.size();
  462. char buffer[1024];
  463. snprintf(buffer, sizeof(buffer), "%d", static_cast<int>(length));
  464. status.GetMakefile().AddDefinition(variableName, buffer);
  465. return true;
  466. }
  467. bool HandleAppendCommand(std::vector<std::string> const& args,
  468. cmExecutionStatus& status)
  469. {
  470. if (args.size() < 2) {
  471. status.SetError("sub-command APPEND requires at least one argument.");
  472. return false;
  473. }
  474. // Skip if nothing to append.
  475. if (args.size() < 3) {
  476. return true;
  477. }
  478. auto const& variableName = args[1];
  479. cm::string_view oldView{ status.GetMakefile().GetSafeDefinition(
  480. variableName) };
  481. auto const newValue = cmJoin(cmMakeRange(args).advance(2), {}, oldView);
  482. status.GetMakefile().AddDefinition(variableName, newValue);
  483. return true;
  484. }
  485. bool HandlePrependCommand(std::vector<std::string> const& args,
  486. cmExecutionStatus& status)
  487. {
  488. if (args.size() < 2) {
  489. status.SetError("sub-command PREPEND requires at least one argument.");
  490. return false;
  491. }
  492. // Skip if nothing to prepend.
  493. if (args.size() < 3) {
  494. return true;
  495. }
  496. std::string const& variable = args[1];
  497. std::string value = cmJoin(cmMakeRange(args).advance(2), std::string());
  498. cmValue oldValue = status.GetMakefile().GetDefinition(variable);
  499. if (oldValue) {
  500. value += *oldValue;
  501. }
  502. status.GetMakefile().AddDefinition(variable, value);
  503. return true;
  504. }
  505. bool HandleConcatCommand(std::vector<std::string> const& args,
  506. cmExecutionStatus& status)
  507. {
  508. if (args.size() < 2) {
  509. status.SetError("sub-command CONCAT requires at least one argument.");
  510. return false;
  511. }
  512. return joinImpl(args, std::string(), 1, status.GetMakefile());
  513. }
  514. bool HandleJoinCommand(std::vector<std::string> const& args,
  515. cmExecutionStatus& status)
  516. {
  517. if (args.size() < 3) {
  518. status.SetError("sub-command JOIN requires at least two arguments.");
  519. return false;
  520. }
  521. return joinImpl(args, args[1], 2, status.GetMakefile());
  522. }
  523. bool joinImpl(std::vector<std::string> const& args, std::string const& glue,
  524. size_t const varIdx, cmMakefile& makefile)
  525. {
  526. std::string const& variableName = args[varIdx];
  527. // NOTE Items to concat/join placed right after the variable for
  528. // both `CONCAT` and `JOIN` sub-commands.
  529. std::string value = cmJoin(cmMakeRange(args).advance(varIdx + 1), glue);
  530. makefile.AddDefinition(variableName, value);
  531. return true;
  532. }
  533. bool HandleMakeCIdentifierCommand(std::vector<std::string> const& args,
  534. cmExecutionStatus& status)
  535. {
  536. if (args.size() != 3) {
  537. status.SetError("sub-command MAKE_C_IDENTIFIER requires two arguments.");
  538. return false;
  539. }
  540. std::string const& input = args[1];
  541. std::string const& variableName = args[2];
  542. status.GetMakefile().AddDefinition(variableName,
  543. cmSystemTools::MakeCidentifier(input));
  544. return true;
  545. }
  546. bool HandleGenexStripCommand(std::vector<std::string> const& args,
  547. cmExecutionStatus& status)
  548. {
  549. if (args.size() != 3) {
  550. status.SetError("sub-command GENEX_STRIP requires two arguments.");
  551. return false;
  552. }
  553. std::string const& input = args[1];
  554. std::string result = cmGeneratorExpression::Preprocess(
  555. input, cmGeneratorExpression::StripAllGeneratorExpressions);
  556. std::string const& variableName = args[2];
  557. status.GetMakefile().AddDefinition(variableName, result);
  558. return true;
  559. }
  560. bool HandleStripCommand(std::vector<std::string> const& args,
  561. cmExecutionStatus& status)
  562. {
  563. if (args.size() != 3) {
  564. status.SetError("sub-command STRIP requires two arguments.");
  565. return false;
  566. }
  567. std::string const& stringValue = args[1];
  568. std::string const& variableName = args[2];
  569. size_t inStringLength = stringValue.size();
  570. size_t startPos = inStringLength + 1;
  571. size_t endPos = 0;
  572. char const* ptr = stringValue.c_str();
  573. size_t cc;
  574. for (cc = 0; cc < inStringLength; ++cc) {
  575. if (!cmIsSpace(*ptr)) {
  576. if (startPos > inStringLength) {
  577. startPos = cc;
  578. }
  579. endPos = cc;
  580. }
  581. ++ptr;
  582. }
  583. size_t outLength = 0;
  584. // if the input string didn't contain any non-space characters, return
  585. // an empty string
  586. if (startPos > inStringLength) {
  587. outLength = 0;
  588. startPos = 0;
  589. } else {
  590. outLength = endPos - startPos + 1;
  591. }
  592. status.GetMakefile().AddDefinition(variableName,
  593. stringValue.substr(startPos, outLength));
  594. return true;
  595. }
  596. bool HandleRepeatCommand(std::vector<std::string> const& args,
  597. cmExecutionStatus& status)
  598. {
  599. cmMakefile& makefile = status.GetMakefile();
  600. // `string(REPEAT "<str>" <times> OUTPUT_VARIABLE)`
  601. enum ArgPos : std::size_t
  602. {
  603. SUB_COMMAND,
  604. VALUE,
  605. TIMES,
  606. OUTPUT_VARIABLE,
  607. TOTAL_ARGS
  608. };
  609. if (args.size() != ArgPos::TOTAL_ARGS) {
  610. makefile.IssueMessage(MessageType::FATAL_ERROR,
  611. "sub-command REPEAT requires three arguments.");
  612. return true;
  613. }
  614. unsigned long times;
  615. if (!cmStrToULong(args[ArgPos::TIMES], &times)) {
  616. makefile.IssueMessage(MessageType::FATAL_ERROR,
  617. "repeat count is not a positive number.");
  618. return true;
  619. }
  620. auto const& stringValue = args[ArgPos::VALUE];
  621. auto const& variableName = args[ArgPos::OUTPUT_VARIABLE];
  622. auto const inStringLength = stringValue.size();
  623. std::string result;
  624. switch (inStringLength) {
  625. case 0u:
  626. // Nothing to do for zero length input strings
  627. break;
  628. case 1u:
  629. // NOTE If the string to repeat consists of the only character,
  630. // use the appropriate constructor.
  631. result = std::string(times, stringValue[0]);
  632. break;
  633. default:
  634. result = std::string(inStringLength * times, char{});
  635. for (auto i = 0u; i < times; ++i) {
  636. std::copy(cm::cbegin(stringValue), cm::cend(stringValue),
  637. &result[i * inStringLength]);
  638. }
  639. break;
  640. }
  641. makefile.AddDefinition(variableName, result);
  642. return true;
  643. }
  644. bool HandleRandomCommand(std::vector<std::string> const& args,
  645. cmExecutionStatus& status)
  646. {
  647. if (args.size() < 2 || args.size() == 3 || args.size() == 5) {
  648. status.SetError("sub-command RANDOM requires at least one argument.");
  649. return false;
  650. }
  651. static bool seeded = false;
  652. bool force_seed = false;
  653. unsigned int seed = 0;
  654. int length = 5;
  655. char const cmStringCommandDefaultAlphabet[] = "qwertyuiopasdfghjklzxcvbnm"
  656. "QWERTYUIOPASDFGHJKLZXCVBNM"
  657. "0123456789";
  658. std::string alphabet;
  659. if (args.size() > 3) {
  660. size_t i = 1;
  661. size_t stopAt = args.size() - 2;
  662. for (; i < stopAt; ++i) {
  663. if (args[i] == "LENGTH") {
  664. ++i;
  665. length = atoi(args[i].c_str());
  666. } else if (args[i] == "ALPHABET") {
  667. ++i;
  668. alphabet = args[i];
  669. } else if (args[i] == "RANDOM_SEED") {
  670. ++i;
  671. seed = static_cast<unsigned int>(atoi(args[i].c_str()));
  672. force_seed = true;
  673. }
  674. }
  675. }
  676. if (alphabet.empty()) {
  677. alphabet = cmStringCommandDefaultAlphabet;
  678. }
  679. double sizeofAlphabet = static_cast<double>(alphabet.size());
  680. if (sizeofAlphabet < 1) {
  681. status.SetError("sub-command RANDOM invoked with bad alphabet.");
  682. return false;
  683. }
  684. if (length < 1) {
  685. status.SetError("sub-command RANDOM invoked with bad length.");
  686. return false;
  687. }
  688. std::string const& variableName = args.back();
  689. std::vector<char> result;
  690. if (!seeded || force_seed) {
  691. seeded = true;
  692. srand(force_seed ? seed : cmSystemTools::RandomSeed());
  693. }
  694. char const* alphaPtr = alphabet.c_str();
  695. for (int cc = 0; cc < length; cc++) {
  696. int idx = static_cast<int>(sizeofAlphabet * rand() / (RAND_MAX + 1.0));
  697. result.push_back(*(alphaPtr + idx));
  698. }
  699. result.push_back(0);
  700. status.GetMakefile().AddDefinition(variableName, result.data());
  701. return true;
  702. }
  703. bool HandleTimestampCommand(std::vector<std::string> const& args,
  704. cmExecutionStatus& status)
  705. {
  706. if (args.size() < 2) {
  707. status.SetError("sub-command TIMESTAMP requires at least one argument.");
  708. return false;
  709. }
  710. if (args.size() > 4) {
  711. status.SetError("sub-command TIMESTAMP takes at most three arguments.");
  712. return false;
  713. }
  714. unsigned int argsIndex = 1;
  715. std::string const& outputVariable = args[argsIndex++];
  716. std::string formatString;
  717. if (args.size() > argsIndex && args[argsIndex] != "UTC") {
  718. formatString = args[argsIndex++];
  719. }
  720. bool utcFlag = false;
  721. if (args.size() > argsIndex) {
  722. if (args[argsIndex] == "UTC") {
  723. utcFlag = true;
  724. } else {
  725. std::string e = " TIMESTAMP sub-command does not recognize option " +
  726. args[argsIndex] + ".";
  727. status.SetError(e);
  728. return false;
  729. }
  730. }
  731. cmTimestamp timestamp;
  732. std::string result = timestamp.CurrentTime(formatString, utcFlag);
  733. status.GetMakefile().AddDefinition(outputVariable, result);
  734. return true;
  735. }
  736. bool HandleUuidCommand(std::vector<std::string> const& args,
  737. cmExecutionStatus& status)
  738. {
  739. #if !defined(CMAKE_BOOTSTRAP)
  740. unsigned int argsIndex = 1;
  741. if (args.size() < 2) {
  742. status.SetError("UUID sub-command requires an output variable.");
  743. return false;
  744. }
  745. std::string const& outputVariable = args[argsIndex++];
  746. std::string uuidNamespaceString;
  747. std::string uuidName;
  748. std::string uuidType;
  749. bool uuidUpperCase = false;
  750. while (args.size() > argsIndex) {
  751. if (args[argsIndex] == "NAMESPACE") {
  752. ++argsIndex;
  753. if (argsIndex >= args.size()) {
  754. status.SetError("UUID sub-command, NAMESPACE requires a value.");
  755. return false;
  756. }
  757. uuidNamespaceString = args[argsIndex++];
  758. } else if (args[argsIndex] == "NAME") {
  759. ++argsIndex;
  760. if (argsIndex >= args.size()) {
  761. status.SetError("UUID sub-command, NAME requires a value.");
  762. return false;
  763. }
  764. uuidName = args[argsIndex++];
  765. } else if (args[argsIndex] == "TYPE") {
  766. ++argsIndex;
  767. if (argsIndex >= args.size()) {
  768. status.SetError("UUID sub-command, TYPE requires a value.");
  769. return false;
  770. }
  771. uuidType = args[argsIndex++];
  772. } else if (args[argsIndex] == "UPPER") {
  773. ++argsIndex;
  774. uuidUpperCase = true;
  775. } else {
  776. std::string e =
  777. "UUID sub-command does not recognize option " + args[argsIndex] + ".";
  778. status.SetError(e);
  779. return false;
  780. }
  781. }
  782. std::string uuid;
  783. cmUuid uuidGenerator;
  784. std::vector<unsigned char> uuidNamespace;
  785. if (!uuidGenerator.StringToBinary(uuidNamespaceString, uuidNamespace)) {
  786. status.SetError("UUID sub-command, malformed NAMESPACE UUID.");
  787. return false;
  788. }
  789. if (uuidType == "MD5") {
  790. uuid = uuidGenerator.FromMd5(uuidNamespace, uuidName);
  791. } else if (uuidType == "SHA1") {
  792. uuid = uuidGenerator.FromSha1(uuidNamespace, uuidName);
  793. } else {
  794. std::string e = "UUID sub-command, unknown TYPE '" + uuidType + "'.";
  795. status.SetError(e);
  796. return false;
  797. }
  798. if (uuid.empty()) {
  799. status.SetError("UUID sub-command, generation failed.");
  800. return false;
  801. }
  802. if (uuidUpperCase) {
  803. uuid = cmSystemTools::UpperCase(uuid);
  804. }
  805. status.GetMakefile().AddDefinition(outputVariable, uuid);
  806. return true;
  807. #else
  808. status.SetError(cmStrCat(args[0], " not available during bootstrap"));
  809. return false;
  810. #endif
  811. }
  812. #if !defined(CMAKE_BOOTSTRAP)
  813. // Helpers for string(JSON ...)
  814. struct Args : cmRange<typename std::vector<std::string>::const_iterator>
  815. {
  816. using cmRange<typename std::vector<std::string>::const_iterator>::cmRange;
  817. auto PopFront(cm::string_view error) -> std::string const&;
  818. auto PopBack(cm::string_view error) -> std::string const&;
  819. };
  820. class json_error : public std::runtime_error
  821. {
  822. public:
  823. json_error(std::string const& message,
  824. cm::optional<Args> errorPath = cm::nullopt)
  825. : std::runtime_error(message)
  826. , ErrorPath{
  827. std::move(errorPath) // NOLINT(performance-move-const-arg)
  828. }
  829. {
  830. }
  831. cm::optional<Args> ErrorPath;
  832. };
  833. std::string const& Args::PopFront(cm::string_view error)
  834. {
  835. if (this->empty()) {
  836. throw json_error(std::string(error));
  837. }
  838. std::string const& res = *this->begin();
  839. this->advance(1);
  840. return res;
  841. }
  842. std::string const& Args::PopBack(cm::string_view error)
  843. {
  844. if (this->empty()) {
  845. throw json_error(std::string(error));
  846. }
  847. std::string const& res = *(this->end() - 1);
  848. this->retreat(1);
  849. return res;
  850. }
  851. cm::string_view JsonTypeToString(Json::ValueType type)
  852. {
  853. switch (type) {
  854. case Json::ValueType::nullValue:
  855. return "NULL"_s;
  856. case Json::ValueType::intValue:
  857. case Json::ValueType::uintValue:
  858. case Json::ValueType::realValue:
  859. return "NUMBER"_s;
  860. case Json::ValueType::stringValue:
  861. return "STRING"_s;
  862. case Json::ValueType::booleanValue:
  863. return "BOOLEAN"_s;
  864. case Json::ValueType::arrayValue:
  865. return "ARRAY"_s;
  866. case Json::ValueType::objectValue:
  867. return "OBJECT"_s;
  868. }
  869. throw json_error("invalid JSON type found");
  870. }
  871. int ParseIndex(
  872. std::string const& str, cm::optional<Args> const& progress = cm::nullopt,
  873. Json::ArrayIndex max = std::numeric_limits<Json::ArrayIndex>::max())
  874. {
  875. unsigned long lindex;
  876. if (!cmStrToULong(str, &lindex)) {
  877. throw json_error(cmStrCat("expected an array index, got: '"_s, str, "'"_s),
  878. progress);
  879. }
  880. Json::ArrayIndex index = static_cast<Json::ArrayIndex>(lindex);
  881. if (index >= max) {
  882. cmAlphaNum sizeStr{ max };
  883. throw json_error(cmStrCat("expected an index less than "_s, sizeStr.View(),
  884. " got '"_s, str, "'"_s),
  885. progress);
  886. }
  887. return index;
  888. }
  889. Json::Value& ResolvePath(Json::Value& json, Args path)
  890. {
  891. Json::Value* search = &json;
  892. for (auto curr = path.begin(); curr != path.end(); ++curr) {
  893. std::string const& field = *curr;
  894. Args progress{ path.begin(), curr + 1 };
  895. if (search->isArray()) {
  896. auto index = ParseIndex(field, progress, search->size());
  897. search = &(*search)[index];
  898. } else if (search->isObject()) {
  899. if (!search->isMember(field)) {
  900. auto const progressStr = cmJoin(progress, " "_s);
  901. throw json_error(cmStrCat("member '"_s, progressStr, "' not found"_s),
  902. progress);
  903. }
  904. search = &(*search)[field];
  905. } else {
  906. auto const progressStr = cmJoin(progress, " "_s);
  907. throw json_error(
  908. cmStrCat("invalid path '"_s, progressStr,
  909. "', need element of OBJECT or ARRAY type to lookup '"_s,
  910. field, "' got "_s, JsonTypeToString(search->type())),
  911. progress);
  912. }
  913. }
  914. return *search;
  915. }
  916. Json::Value ReadJson(std::string const& jsonstr)
  917. {
  918. Json::CharReaderBuilder builder;
  919. builder["collectComments"] = false;
  920. auto jsonReader = std::unique_ptr<Json::CharReader>(builder.newCharReader());
  921. Json::Value json;
  922. std::string error;
  923. if (!jsonReader->parse(jsonstr.data(), jsonstr.data() + jsonstr.size(),
  924. &json, &error)) {
  925. throw json_error(cmStrCat("failed parsing json string: "_s, error));
  926. }
  927. return json;
  928. }
  929. std::string WriteJson(Json::Value const& value)
  930. {
  931. Json::StreamWriterBuilder writer;
  932. writer["indentation"] = " ";
  933. writer["commentStyle"] = "None";
  934. return Json::writeString(writer, value);
  935. }
  936. #endif
  937. bool HandleJSONCommand(std::vector<std::string> const& arguments,
  938. cmExecutionStatus& status)
  939. {
  940. #if !defined(CMAKE_BOOTSTRAP)
  941. auto& makefile = status.GetMakefile();
  942. Args args{ arguments.begin() + 1, arguments.end() };
  943. std::string const* errorVariable = nullptr;
  944. std::string const* outputVariable = nullptr;
  945. bool success = true;
  946. try {
  947. outputVariable = &args.PopFront("missing out-var argument"_s);
  948. if (!args.empty() && *args.begin() == "ERROR_VARIABLE"_s) {
  949. args.PopFront("");
  950. errorVariable = &args.PopFront("missing error-var argument"_s);
  951. makefile.AddDefinition(*errorVariable, "NOTFOUND"_s);
  952. }
  953. auto const& mode = args.PopFront("missing mode argument"_s);
  954. if (mode != "GET"_s && mode != "TYPE"_s && mode != "MEMBER"_s &&
  955. mode != "LENGTH"_s && mode != "REMOVE"_s && mode != "SET"_s &&
  956. mode != "EQUAL"_s) {
  957. throw json_error(
  958. cmStrCat("got an invalid mode '"_s, mode,
  959. "', expected one of GET, TYPE, MEMBER, LENGTH, REMOVE, SET, "
  960. " EQUAL"_s));
  961. }
  962. auto const& jsonstr = args.PopFront("missing json string argument"_s);
  963. Json::Value json = ReadJson(jsonstr);
  964. if (mode == "GET"_s) {
  965. auto const& value = ResolvePath(json, args);
  966. if (value.isObject() || value.isArray()) {
  967. makefile.AddDefinition(*outputVariable, WriteJson(value));
  968. } else if (value.isBool()) {
  969. makefile.AddDefinitionBool(*outputVariable, value.asBool());
  970. } else {
  971. makefile.AddDefinition(*outputVariable, value.asString());
  972. }
  973. } else if (mode == "TYPE"_s) {
  974. auto const& value = ResolvePath(json, args);
  975. makefile.AddDefinition(*outputVariable, JsonTypeToString(value.type()));
  976. } else if (mode == "MEMBER"_s) {
  977. auto const& indexStr = args.PopBack("missing member index"_s);
  978. auto const& value = ResolvePath(json, args);
  979. if (!value.isObject()) {
  980. throw json_error(
  981. cmStrCat("MEMBER needs to be called with an element of "
  982. "type OBJECT, got "_s,
  983. JsonTypeToString(value.type())),
  984. args);
  985. }
  986. auto const index = ParseIndex(
  987. indexStr, Args{ args.begin(), args.end() + 1 }, value.size());
  988. auto const memIt = std::next(value.begin(), index);
  989. makefile.AddDefinition(*outputVariable, memIt.name());
  990. } else if (mode == "LENGTH"_s) {
  991. auto const& value = ResolvePath(json, args);
  992. if (!value.isArray() && !value.isObject()) {
  993. throw json_error(cmStrCat("LENGTH needs to be called with an "
  994. "element of type ARRAY or OBJECT, got "_s,
  995. JsonTypeToString(value.type())),
  996. args);
  997. }
  998. cmAlphaNum sizeStr{ value.size() };
  999. makefile.AddDefinition(*outputVariable, sizeStr.View());
  1000. } else if (mode == "REMOVE"_s) {
  1001. auto const& toRemove =
  1002. args.PopBack("missing member or index to remove"_s);
  1003. auto& value = ResolvePath(json, args);
  1004. if (value.isArray()) {
  1005. auto const index = ParseIndex(
  1006. toRemove, Args{ args.begin(), args.end() + 1 }, value.size());
  1007. Json::Value removed;
  1008. value.removeIndex(index, &removed);
  1009. } else if (value.isObject()) {
  1010. Json::Value removed;
  1011. value.removeMember(toRemove, &removed);
  1012. } else {
  1013. throw json_error(cmStrCat("REMOVE needs to be called with an "
  1014. "element of type ARRAY or OBJECT, got "_s,
  1015. JsonTypeToString(value.type())),
  1016. args);
  1017. }
  1018. makefile.AddDefinition(*outputVariable, WriteJson(json));
  1019. } else if (mode == "SET"_s) {
  1020. auto const& newValueStr = args.PopBack("missing new value remove"_s);
  1021. auto const& toAdd = args.PopBack("missing member name to add"_s);
  1022. auto& value = ResolvePath(json, args);
  1023. Json::Value newValue = ReadJson(newValueStr);
  1024. if (value.isObject()) {
  1025. value[toAdd] = newValue;
  1026. } else if (value.isArray()) {
  1027. auto const index =
  1028. ParseIndex(toAdd, Args{ args.begin(), args.end() + 1 });
  1029. if (value.isValidIndex(index)) {
  1030. value[static_cast<int>(index)] = newValue;
  1031. } else {
  1032. value.append(newValue);
  1033. }
  1034. } else {
  1035. throw json_error(cmStrCat("SET needs to be called with an "
  1036. "element of type OBJECT or ARRAY, got "_s,
  1037. JsonTypeToString(value.type())));
  1038. }
  1039. makefile.AddDefinition(*outputVariable, WriteJson(json));
  1040. } else if (mode == "EQUAL"_s) {
  1041. auto const& jsonstr2 =
  1042. args.PopFront("missing second json string argument"_s);
  1043. Json::Value json2 = ReadJson(jsonstr2);
  1044. makefile.AddDefinitionBool(*outputVariable, json == json2);
  1045. }
  1046. } catch (json_error const& e) {
  1047. if (outputVariable && e.ErrorPath) {
  1048. auto const errorPath = cmJoin(*e.ErrorPath, "-");
  1049. makefile.AddDefinition(*outputVariable,
  1050. cmStrCat(errorPath, "-NOTFOUND"_s));
  1051. } else if (outputVariable) {
  1052. makefile.AddDefinition(*outputVariable, "NOTFOUND"_s);
  1053. }
  1054. if (errorVariable) {
  1055. makefile.AddDefinition(*errorVariable, e.what());
  1056. } else {
  1057. status.SetError(cmStrCat("sub-command JSON "_s, e.what(), "."_s));
  1058. success = false;
  1059. }
  1060. }
  1061. return success;
  1062. #else
  1063. status.SetError(cmStrCat(arguments[0], " not available during bootstrap"_s));
  1064. return false;
  1065. #endif
  1066. }
  1067. } // namespace
  1068. bool cmStringCommand(std::vector<std::string> const& args,
  1069. cmExecutionStatus& status)
  1070. {
  1071. if (args.empty()) {
  1072. status.SetError("must be called with at least one argument.");
  1073. return false;
  1074. }
  1075. static cmSubcommandTable const subcommand{
  1076. { "REGEX"_s, HandleRegexCommand },
  1077. { "REPLACE"_s, HandleReplaceCommand },
  1078. { "MD5"_s, HandleHashCommand },
  1079. { "SHA1"_s, HandleHashCommand },
  1080. { "SHA224"_s, HandleHashCommand },
  1081. { "SHA256"_s, HandleHashCommand },
  1082. { "SHA384"_s, HandleHashCommand },
  1083. { "SHA512"_s, HandleHashCommand },
  1084. { "SHA3_224"_s, HandleHashCommand },
  1085. { "SHA3_256"_s, HandleHashCommand },
  1086. { "SHA3_384"_s, HandleHashCommand },
  1087. { "SHA3_512"_s, HandleHashCommand },
  1088. { "TOLOWER"_s, HandleToLowerCommand },
  1089. { "TOUPPER"_s, HandleToUpperCommand },
  1090. { "COMPARE"_s, HandleCompareCommand },
  1091. { "ASCII"_s, HandleAsciiCommand },
  1092. { "HEX"_s, HandleHexCommand },
  1093. { "CONFIGURE"_s, HandleConfigureCommand },
  1094. { "LENGTH"_s, HandleLengthCommand },
  1095. { "APPEND"_s, HandleAppendCommand },
  1096. { "PREPEND"_s, HandlePrependCommand },
  1097. { "CONCAT"_s, HandleConcatCommand },
  1098. { "JOIN"_s, HandleJoinCommand },
  1099. { "SUBSTRING"_s, HandleSubstringCommand },
  1100. { "STRIP"_s, HandleStripCommand },
  1101. { "REPEAT"_s, HandleRepeatCommand },
  1102. { "RANDOM"_s, HandleRandomCommand },
  1103. { "FIND"_s, HandleFindCommand },
  1104. { "TIMESTAMP"_s, HandleTimestampCommand },
  1105. { "MAKE_C_IDENTIFIER"_s, HandleMakeCIdentifierCommand },
  1106. { "GENEX_STRIP"_s, HandleGenexStripCommand },
  1107. { "UUID"_s, HandleUuidCommand },
  1108. { "JSON"_s, HandleJSONCommand },
  1109. };
  1110. return subcommand(args[0], args, status);
  1111. }