cmStringCommand.cxx 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  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 <cctype>
  8. #include <cstdio>
  9. #include <cstdlib>
  10. #include <initializer_list>
  11. #include <limits>
  12. #include <memory>
  13. #include <stdexcept>
  14. #include <utility>
  15. #include <cm/iterator>
  16. #include <cm/optional>
  17. #include <cm/string_view>
  18. #include <cmext/string_view>
  19. #include <cm3p/json/reader.h>
  20. #include <cm3p/json/value.h>
  21. #include <cm3p/json/writer.h>
  22. #include "cmsys/RegularExpression.hxx"
  23. #include "cmCryptoHash.h"
  24. #include "cmExecutionStatus.h"
  25. #include "cmGeneratorExpression.h"
  26. #include "cmMakefile.h"
  27. #include "cmMessageType.h"
  28. #include "cmProperty.h"
  29. #include "cmRange.h"
  30. #include "cmStringAlgorithms.h"
  31. #include "cmStringReplaceHelper.h"
  32. #include "cmSubcommandTable.h"
  33. #include "cmSystemTools.h"
  34. #include "cmTimestamp.h"
  35. #include "cmUuid.h"
  36. namespace {
  37. bool RegexMatch(std::vector<std::string> const& args,
  38. cmExecutionStatus& status);
  39. bool RegexMatchAll(std::vector<std::string> const& args,
  40. cmExecutionStatus& status);
  41. bool RegexReplace(std::vector<std::string> const& args,
  42. cmExecutionStatus& status);
  43. bool joinImpl(std::vector<std::string> const& args, std::string const& glue,
  44. size_t varIdx, cmMakefile& makefile);
  45. bool HandleHashCommand(std::vector<std::string> const& args,
  46. cmExecutionStatus& status)
  47. {
  48. #if !defined(CMAKE_BOOTSTRAP)
  49. if (args.size() != 3) {
  50. status.SetError(
  51. cmStrCat(args[0], " requires an output variable and an input string"));
  52. return false;
  53. }
  54. std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0]));
  55. if (hash) {
  56. std::string out = hash->HashString(args[2]);
  57. status.GetMakefile().AddDefinition(args[1], out);
  58. return true;
  59. }
  60. return false;
  61. #else
  62. status.SetError(cmStrCat(args[0], " not available during bootstrap"));
  63. return false;
  64. #endif
  65. }
  66. bool HandleToUpperLowerCommand(std::vector<std::string> const& args,
  67. bool toUpper, cmExecutionStatus& status)
  68. {
  69. if (args.size() < 3) {
  70. status.SetError("no output variable specified");
  71. return false;
  72. }
  73. std::string const& outvar = args[2];
  74. std::string output;
  75. if (toUpper) {
  76. output = cmSystemTools::UpperCase(args[1]);
  77. } else {
  78. output = cmSystemTools::LowerCase(args[1]);
  79. }
  80. // Store the output in the provided variable.
  81. status.GetMakefile().AddDefinition(outvar, output);
  82. return true;
  83. }
  84. bool HandleToUpperCommand(std::vector<std::string> const& args,
  85. cmExecutionStatus& status)
  86. {
  87. return HandleToUpperLowerCommand(args, true, status);
  88. }
  89. bool HandleToLowerCommand(std::vector<std::string> const& args,
  90. cmExecutionStatus& status)
  91. {
  92. return HandleToUpperLowerCommand(args, false, status);
  93. }
  94. bool HandleAsciiCommand(std::vector<std::string> const& args,
  95. cmExecutionStatus& status)
  96. {
  97. if (args.size() < 3) {
  98. status.SetError("No output variable specified");
  99. return false;
  100. }
  101. std::string::size_type cc;
  102. std::string const& outvar = args.back();
  103. std::string output;
  104. for (cc = 1; cc < args.size() - 1; cc++) {
  105. int ch = atoi(args[cc].c_str());
  106. if (ch > 0 && ch < 256) {
  107. output += static_cast<char>(ch);
  108. } else {
  109. std::string error =
  110. cmStrCat("Character with code ", args[cc], " does not exist.");
  111. status.SetError(error);
  112. return false;
  113. }
  114. }
  115. // Store the output in the provided variable.
  116. status.GetMakefile().AddDefinition(outvar, output);
  117. return true;
  118. }
  119. bool HandleHexCommand(std::vector<std::string> const& args,
  120. cmExecutionStatus& status)
  121. {
  122. if (args.size() != 3) {
  123. status.SetError("Incorrect number of arguments");
  124. return false;
  125. }
  126. auto const& instr = args[1];
  127. auto const& outvar = args[2];
  128. std::string output(instr.size() * 2, ' ');
  129. std::string::size_type hexIndex = 0;
  130. for (auto const& c : instr) {
  131. sprintf(&output[hexIndex], "%.2x", static_cast<unsigned char>(c) & 0xFF);
  132. hexIndex += 2;
  133. }
  134. status.GetMakefile().AddDefinition(outvar, output);
  135. return true;
  136. }
  137. bool HandleConfigureCommand(std::vector<std::string> const& args,
  138. cmExecutionStatus& status)
  139. {
  140. if (args.size() < 2) {
  141. status.SetError("No input string specified.");
  142. return false;
  143. }
  144. if (args.size() < 3) {
  145. status.SetError("No output variable specified.");
  146. return false;
  147. }
  148. // Parse options.
  149. bool escapeQuotes = false;
  150. bool atOnly = false;
  151. for (unsigned int i = 3; i < args.size(); ++i) {
  152. if (args[i] == "@ONLY") {
  153. atOnly = true;
  154. } else if (args[i] == "ESCAPE_QUOTES") {
  155. escapeQuotes = true;
  156. } else {
  157. status.SetError(cmStrCat("Unrecognized argument \"", args[i], "\""));
  158. return false;
  159. }
  160. }
  161. // Configure the string.
  162. std::string output;
  163. status.GetMakefile().ConfigureString(args[1], output, atOnly, escapeQuotes);
  164. // Store the output in the provided variable.
  165. status.GetMakefile().AddDefinition(args[2], output);
  166. return true;
  167. }
  168. bool HandleRegexCommand(std::vector<std::string> const& args,
  169. cmExecutionStatus& status)
  170. {
  171. if (args.size() < 2) {
  172. status.SetError("sub-command REGEX requires a mode to be specified.");
  173. return false;
  174. }
  175. std::string const& mode = args[1];
  176. if (mode == "MATCH") {
  177. if (args.size() < 5) {
  178. status.SetError("sub-command REGEX, mode MATCH needs "
  179. "at least 5 arguments total to command.");
  180. return false;
  181. }
  182. return RegexMatch(args, status);
  183. }
  184. if (mode == "MATCHALL") {
  185. if (args.size() < 5) {
  186. status.SetError("sub-command REGEX, mode MATCHALL needs "
  187. "at least 5 arguments total to command.");
  188. return false;
  189. }
  190. return RegexMatchAll(args, status);
  191. }
  192. if (mode == "REPLACE") {
  193. if (args.size() < 6) {
  194. status.SetError("sub-command REGEX, mode REPLACE needs "
  195. "at least 6 arguments total to command.");
  196. return false;
  197. }
  198. return RegexReplace(args, status);
  199. }
  200. std::string e = "sub-command REGEX does not recognize mode " + mode;
  201. status.SetError(e);
  202. return false;
  203. }
  204. bool RegexMatch(std::vector<std::string> const& args,
  205. cmExecutionStatus& status)
  206. {
  207. //"STRING(REGEX MATCH <regular_expression> <output variable>
  208. // <input> [<input>...])\n";
  209. std::string const& regex = args[2];
  210. std::string const& outvar = args[3];
  211. status.GetMakefile().ClearMatches();
  212. // Compile the regular expression.
  213. cmsys::RegularExpression re;
  214. if (!re.compile(regex.c_str())) {
  215. std::string e =
  216. "sub-command REGEX, mode MATCH failed to compile regex \"" + regex +
  217. "\".";
  218. status.SetError(e);
  219. return false;
  220. }
  221. // Concatenate all the last arguments together.
  222. std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
  223. // Scan through the input for all matches.
  224. std::string output;
  225. if (re.find(input)) {
  226. status.GetMakefile().StoreMatches(re);
  227. std::string::size_type l = re.start();
  228. std::string::size_type r = re.end();
  229. if (r - l == 0) {
  230. std::string e = "sub-command REGEX, mode MATCH regex \"" + regex +
  231. "\" matched an empty string.";
  232. status.SetError(e);
  233. return false;
  234. }
  235. output = input.substr(l, r - l);
  236. }
  237. // Store the output in the provided variable.
  238. status.GetMakefile().AddDefinition(outvar, output);
  239. return true;
  240. }
  241. bool RegexMatchAll(std::vector<std::string> const& args,
  242. cmExecutionStatus& status)
  243. {
  244. //"STRING(REGEX MATCHALL <regular_expression> <output variable> <input>
  245. // [<input>...])\n";
  246. std::string const& regex = args[2];
  247. std::string const& outvar = args[3];
  248. status.GetMakefile().ClearMatches();
  249. // Compile the regular expression.
  250. cmsys::RegularExpression re;
  251. if (!re.compile(regex.c_str())) {
  252. std::string e =
  253. "sub-command REGEX, mode MATCHALL failed to compile regex \"" + regex +
  254. "\".";
  255. status.SetError(e);
  256. return false;
  257. }
  258. // Concatenate all the last arguments together.
  259. std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
  260. // Scan through the input for all matches.
  261. std::string output;
  262. const char* p = input.c_str();
  263. while (re.find(p)) {
  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 += std::string(p + l, r - l);
  278. p += 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. const std::string 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. const std::string& sstring = args[1];
  339. const std::string& schar = args[2];
  340. const std::string& 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. const std::string& left = args[2];
  382. const std::string& right = args[3];
  383. const std::string& 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. const std::string& matchExpression = args[1];
  418. const std::string& replaceExpression = args[2];
  419. const std::string& 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. const std::string& stringValue = args[1];
  434. int begin = atoi(args[2].c_str());
  435. int end = atoi(args[3].c_str());
  436. const std::string& 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. const std::string& stringValue = args[1];
  460. const std::string& variableName = args[2];
  461. size_t length = stringValue.size();
  462. char buffer[1024];
  463. sprintf(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. const std::string& variable = args[1];
  497. std::string value = cmJoin(cmMakeRange(args).advance(2), std::string());
  498. cmProp 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. const size_t 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. const std::string& input = args[1];
  541. const std::string& 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. const std::string& input = args[1];
  554. std::string result = cmGeneratorExpression::Preprocess(
  555. input, cmGeneratorExpression::StripAllGeneratorExpressions);
  556. const std::string& 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. const std::string& stringValue = args[1];
  568. const std::string& variableName = args[2];
  569. size_t inStringLength = stringValue.size();
  570. size_t startPos = inStringLength + 1;
  571. size_t endPos = 0;
  572. const char* ptr = stringValue.c_str();
  573. size_t cc;
  574. for (cc = 0; cc < inStringLength; ++cc) {
  575. if (!isspace(*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. const auto& stringValue = args[ArgPos::VALUE];
  621. const auto& variableName = args[ArgPos::OUTPUT_VARIABLE];
  622. const auto 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. const char 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. const std::string& 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. const char* 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. const std::string& 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. const std::string& 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) -> const std::string&;
  818. auto PopBack(cm::string_view error) -> const std::string&;
  819. };
  820. class json_error : public std::runtime_error
  821. {
  822. public:
  823. json_error(std::initializer_list<cm::string_view> message,
  824. cm::optional<Args> errorPath = cm::nullopt)
  825. : std::runtime_error(cmCatViews(message))
  826. , ErrorPath{
  827. std::move(errorPath) // NOLINT(performance-move-const-arg)
  828. }
  829. {
  830. }
  831. cm::optional<Args> ErrorPath;
  832. };
  833. const std::string& Args::PopFront(cm::string_view error)
  834. {
  835. if (this->empty()) {
  836. throw json_error({ error });
  837. }
  838. const std::string& res = *this->begin();
  839. this->advance(1);
  840. return res;
  841. }
  842. const std::string& Args::PopBack(cm::string_view error)
  843. {
  844. if (this->empty()) {
  845. throw json_error({ error });
  846. }
  847. const std::string& 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"_s });
  870. }
  871. int ParseIndex(
  872. const std::string& 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({ "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({ "expected an index less then "_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. const std::string& 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. const auto progressStr = cmJoin(progress, " "_s);
  901. throw json_error({ "member '"_s, progressStr, "' not found"_s },
  902. progress);
  903. }
  904. search = &(*search)[field];
  905. } else {
  906. const auto progressStr = cmJoin(progress, " "_s);
  907. throw json_error(
  908. { "invalid path '"_s, progressStr,
  909. "', need element of OBJECT or ARRAY type to lookup '"_s, field,
  910. "' got "_s, JsonTypeToString(search->type()) },
  911. progress);
  912. }
  913. }
  914. return *search;
  915. };
  916. Json::Value ReadJson(const std::string& 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({ "failed parsing json string: "_s, error });
  926. }
  927. return json;
  928. }
  929. std::string WriteJson(const Json::Value& 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. const std::string* errorVariable = nullptr;
  944. const std::string* 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. const auto& 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. { "got an invalid mode '"_s, mode,
  959. "', expected one of GET, GET_ARRAY, TYPE, MEMBER, MEMBERS,"
  960. " LENGTH, REMOVE, SET, EQUAL"_s });
  961. }
  962. const auto& jsonstr = args.PopFront("missing json string argument"_s);
  963. Json::Value json = ReadJson(jsonstr);
  964. if (mode == "GET"_s) {
  965. const auto& 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. const auto& value = ResolvePath(json, args);
  975. makefile.AddDefinition(*outputVariable, JsonTypeToString(value.type()));
  976. } else if (mode == "MEMBER"_s) {
  977. const auto& indexStr = args.PopBack("missing member index"_s);
  978. const auto& value = ResolvePath(json, args);
  979. if (!value.isObject()) {
  980. throw json_error({ "MEMBER needs to be called with an element of "
  981. "type OBJECT, got "_s,
  982. JsonTypeToString(value.type()) },
  983. args);
  984. }
  985. const auto index = ParseIndex(
  986. indexStr, Args{ args.begin(), args.end() + 1 }, value.size());
  987. const auto memIt = std::next(value.begin(), index);
  988. makefile.AddDefinition(*outputVariable, memIt.name());
  989. } else if (mode == "LENGTH"_s) {
  990. const auto& value = ResolvePath(json, args);
  991. if (!value.isArray() && !value.isObject()) {
  992. throw json_error({ "LENGTH needs to be called with an "
  993. "element of type ARRAY or OBJECT, got "_s,
  994. JsonTypeToString(value.type()) },
  995. args);
  996. }
  997. cmAlphaNum sizeStr{ value.size() };
  998. makefile.AddDefinition(*outputVariable, sizeStr.View());
  999. } else if (mode == "REMOVE"_s) {
  1000. const auto& toRemove =
  1001. args.PopBack("missing member or index to remove"_s);
  1002. auto& value = ResolvePath(json, args);
  1003. if (value.isArray()) {
  1004. const auto index = ParseIndex(
  1005. toRemove, Args{ args.begin(), args.end() + 1 }, value.size());
  1006. Json::Value removed;
  1007. value.removeIndex(index, &removed);
  1008. } else if (value.isObject()) {
  1009. Json::Value removed;
  1010. value.removeMember(toRemove, &removed);
  1011. } else {
  1012. throw json_error({ "REMOVE needs to be called with an "
  1013. "element of type ARRAY or OBJECT, got "_s,
  1014. JsonTypeToString(value.type()) },
  1015. args);
  1016. }
  1017. makefile.AddDefinition(*outputVariable, WriteJson(json));
  1018. } else if (mode == "SET"_s) {
  1019. const auto& newValueStr = args.PopBack("missing new value remove"_s);
  1020. const auto& toAdd = args.PopBack("missing member name to add"_s);
  1021. auto& value = ResolvePath(json, args);
  1022. Json::Value newValue = ReadJson(newValueStr);
  1023. if (value.isObject()) {
  1024. value[toAdd] = newValue;
  1025. } else if (value.isArray()) {
  1026. const auto index =
  1027. ParseIndex(toAdd, Args{ args.begin(), args.end() + 1 });
  1028. if (value.isValidIndex(index)) {
  1029. value[static_cast<int>(index)] = newValue;
  1030. } else {
  1031. value.append(newValue);
  1032. }
  1033. } else {
  1034. throw json_error({ "SET needs to be called with an "
  1035. "element of type OBJECT or ARRAY, got "_s,
  1036. JsonTypeToString(value.type()) });
  1037. }
  1038. makefile.AddDefinition(*outputVariable, WriteJson(json));
  1039. } else if (mode == "EQUAL"_s) {
  1040. const auto& jsonstr2 =
  1041. args.PopFront("missing second json string argument"_s);
  1042. Json::Value json2 = ReadJson(jsonstr2);
  1043. makefile.AddDefinitionBool(*outputVariable, json == json2);
  1044. }
  1045. } catch (const json_error& e) {
  1046. if (outputVariable && e.ErrorPath) {
  1047. const auto errorPath = cmJoin(*e.ErrorPath, "-");
  1048. makefile.AddDefinition(*outputVariable,
  1049. cmCatViews({ errorPath, "-NOTFOUND"_s }));
  1050. } else if (outputVariable) {
  1051. makefile.AddDefinition(*outputVariable, "NOTFOUND"_s);
  1052. }
  1053. if (errorVariable) {
  1054. makefile.AddDefinition(*errorVariable, e.what());
  1055. } else {
  1056. status.SetError(cmCatViews({ "sub-command JSON "_s, e.what(), "."_s }));
  1057. success = false;
  1058. }
  1059. }
  1060. return success;
  1061. #else
  1062. status.SetError(cmStrCat(arguments[0], " not available during bootstrap"_s));
  1063. return false;
  1064. #endif
  1065. }
  1066. } // namespace
  1067. bool cmStringCommand(std::vector<std::string> const& args,
  1068. cmExecutionStatus& status)
  1069. {
  1070. if (args.empty()) {
  1071. status.SetError("must be called with at least one argument.");
  1072. return false;
  1073. }
  1074. static cmSubcommandTable const subcommand{
  1075. { "REGEX"_s, HandleRegexCommand },
  1076. { "REPLACE"_s, HandleReplaceCommand },
  1077. { "MD5"_s, HandleHashCommand },
  1078. { "SHA1"_s, HandleHashCommand },
  1079. { "SHA224"_s, HandleHashCommand },
  1080. { "SHA256"_s, HandleHashCommand },
  1081. { "SHA384"_s, HandleHashCommand },
  1082. { "SHA512"_s, HandleHashCommand },
  1083. { "SHA3_224"_s, HandleHashCommand },
  1084. { "SHA3_256"_s, HandleHashCommand },
  1085. { "SHA3_384"_s, HandleHashCommand },
  1086. { "SHA3_512"_s, HandleHashCommand },
  1087. { "TOLOWER"_s, HandleToLowerCommand },
  1088. { "TOUPPER"_s, HandleToUpperCommand },
  1089. { "COMPARE"_s, HandleCompareCommand },
  1090. { "ASCII"_s, HandleAsciiCommand },
  1091. { "HEX"_s, HandleHexCommand },
  1092. { "CONFIGURE"_s, HandleConfigureCommand },
  1093. { "LENGTH"_s, HandleLengthCommand },
  1094. { "APPEND"_s, HandleAppendCommand },
  1095. { "PREPEND"_s, HandlePrependCommand },
  1096. { "CONCAT"_s, HandleConcatCommand },
  1097. { "JOIN"_s, HandleJoinCommand },
  1098. { "SUBSTRING"_s, HandleSubstringCommand },
  1099. { "STRIP"_s, HandleStripCommand },
  1100. { "REPEAT"_s, HandleRepeatCommand },
  1101. { "RANDOM"_s, HandleRandomCommand },
  1102. { "FIND"_s, HandleFindCommand },
  1103. { "TIMESTAMP"_s, HandleTimestampCommand },
  1104. { "MAKE_C_IDENTIFIER"_s, HandleMakeCIdentifierCommand },
  1105. { "GENEX_STRIP"_s, HandleGenexStripCommand },
  1106. { "UUID"_s, HandleUuidCommand },
  1107. { "JSON"_s, HandleJSONCommand },
  1108. };
  1109. return subcommand(args[0], args, status);
  1110. }