cmStringCommand.cxx 37 KB

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