cmQtAutoGenInitializer.cxx 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmQtAutoGenInitializer.h"
  4. #include <array>
  5. #include <cstddef>
  6. #include <deque>
  7. #include <initializer_list>
  8. #include <limits>
  9. #include <map>
  10. #include <set>
  11. #include <sstream> // for basic_ios, istringstream
  12. #include <string>
  13. #include <unordered_set>
  14. #include <utility>
  15. #include <vector>
  16. #include <cm/algorithm>
  17. #include <cm/iterator>
  18. #include <cm/memory>
  19. #include <cm/string_view>
  20. #include <cmext/algorithm>
  21. #include <cmext/string_view>
  22. #include <cm3p/json/value.h>
  23. #include <cm3p/json/writer.h>
  24. #include "cmsys/SystemInformation.hxx"
  25. #include "cmAlgorithms.h"
  26. #include "cmCustomCommand.h"
  27. #include "cmCustomCommandLines.h"
  28. #include "cmEvaluatedTargetProperty.h"
  29. #include "cmGeneratedFileStream.h"
  30. #include "cmGeneratorExpression.h"
  31. #include "cmGeneratorExpressionDAGChecker.h"
  32. #include "cmGeneratorTarget.h"
  33. #include "cmGlobalGenerator.h"
  34. #include "cmLinkItem.h"
  35. #include "cmList.h"
  36. #include "cmListFileCache.h"
  37. #include "cmLocalGenerator.h"
  38. #include "cmMakefile.h"
  39. #include "cmMessageType.h"
  40. #include "cmPolicies.h"
  41. #include "cmQtAutoGen.h"
  42. #include "cmQtAutoGenGlobalInitializer.h"
  43. #include "cmSourceFile.h"
  44. #include "cmSourceFileLocationKind.h"
  45. #include "cmSourceGroup.h"
  46. #include "cmStandardLevelResolver.h"
  47. #include "cmState.h"
  48. #include "cmStateTypes.h"
  49. #include "cmStringAlgorithms.h"
  50. #include "cmSystemTools.h"
  51. #include "cmTarget.h"
  52. #include "cmValue.h"
  53. #include "cmake.h"
  54. namespace {
  55. unsigned int GetParallelCPUCount()
  56. {
  57. static unsigned int count = 0;
  58. // Detect only on the first call
  59. if (count == 0) {
  60. cmsys::SystemInformation info;
  61. info.RunCPUCheck();
  62. count =
  63. cm::clamp(info.GetNumberOfPhysicalCPU(), 1u, cmQtAutoGen::ParallelMax);
  64. }
  65. return count;
  66. }
  67. std::string FileProjectRelativePath(cmMakefile const* makefile,
  68. std::string const& fileName)
  69. {
  70. std::string res;
  71. {
  72. std::string pSource = cmSystemTools::RelativePath(
  73. makefile->GetCurrentSourceDirectory(), fileName);
  74. std::string pBinary = cmSystemTools::RelativePath(
  75. makefile->GetCurrentBinaryDirectory(), fileName);
  76. if (pSource.size() < pBinary.size()) {
  77. res = std::move(pSource);
  78. } else if (pBinary.size() < fileName.size()) {
  79. res = std::move(pBinary);
  80. } else {
  81. res = fileName;
  82. }
  83. }
  84. return res;
  85. }
  86. /**
  87. * Tests if targetDepend is a STATIC_LIBRARY and if any of its
  88. * recursive STATIC_LIBRARY dependencies depends on targetOrigin
  89. * (STATIC_LIBRARY cycle).
  90. */
  91. bool StaticLibraryCycle(cmGeneratorTarget const* targetOrigin,
  92. cmGeneratorTarget const* targetDepend,
  93. std::string const& config)
  94. {
  95. bool cycle = false;
  96. if ((targetOrigin->GetType() == cmStateEnums::STATIC_LIBRARY) &&
  97. (targetDepend->GetType() == cmStateEnums::STATIC_LIBRARY)) {
  98. std::set<cmGeneratorTarget const*> knownLibs;
  99. std::deque<cmGeneratorTarget const*> testLibs;
  100. // Insert initial static_library dependency
  101. knownLibs.insert(targetDepend);
  102. testLibs.push_back(targetDepend);
  103. while (!testLibs.empty()) {
  104. cmGeneratorTarget const* testTarget = testLibs.front();
  105. testLibs.pop_front();
  106. // Check if the test target is the origin target (cycle)
  107. if (testTarget == targetOrigin) {
  108. cycle = true;
  109. break;
  110. }
  111. // Collect all static_library dependencies from the test target
  112. cmLinkImplementationLibraries const* libs =
  113. testTarget->GetLinkImplementationLibraries(
  114. config, cmGeneratorTarget::UseTo::Link);
  115. if (libs) {
  116. for (cmLinkItem const& item : libs->Libraries) {
  117. cmGeneratorTarget const* depTarget = item.Target;
  118. if (depTarget &&
  119. (depTarget->GetType() == cmStateEnums::STATIC_LIBRARY) &&
  120. knownLibs.insert(depTarget).second) {
  121. testLibs.push_back(depTarget);
  122. }
  123. }
  124. }
  125. }
  126. }
  127. return cycle;
  128. }
  129. /** Sanitizes file search paths. */
  130. class SearchPathSanitizer
  131. {
  132. public:
  133. SearchPathSanitizer(cmMakefile* makefile)
  134. : SourcePath_(makefile->GetCurrentSourceDirectory())
  135. {
  136. }
  137. std::vector<std::string> operator()(
  138. std::vector<std::string> const& paths) const;
  139. private:
  140. std::string SourcePath_;
  141. };
  142. std::vector<std::string> SearchPathSanitizer::operator()(
  143. std::vector<std::string> const& paths) const
  144. {
  145. std::vector<std::string> res;
  146. res.reserve(paths.size());
  147. for (std::string const& srcPath : paths) {
  148. // Collapse relative paths
  149. std::string path =
  150. cmSystemTools::CollapseFullPath(srcPath, this->SourcePath_);
  151. // Remove suffix slashes
  152. while (cmHasSuffix(path, '/')) {
  153. path.pop_back();
  154. }
  155. // Accept only non empty paths
  156. if (!path.empty()) {
  157. res.emplace_back(std::move(path));
  158. }
  159. }
  160. return res;
  161. }
  162. /** @brief Writes a CMake info file. */
  163. class InfoWriter
  164. {
  165. public:
  166. // -- Single value
  167. void Set(std::string const& key, std::string const& value)
  168. {
  169. this->Value_[key] = value;
  170. }
  171. void SetConfig(std::string const& key,
  172. cmQtAutoGenInitializer::ConfigString const& cfgStr);
  173. void SetBool(std::string const& key, bool value)
  174. {
  175. this->Value_[key] = value;
  176. }
  177. void SetUInt(std::string const& key, unsigned int value)
  178. {
  179. this->Value_[key] = value;
  180. }
  181. // -- Array utility
  182. template <typename CONT>
  183. static bool MakeArray(Json::Value& jval, CONT const& container);
  184. template <typename CONT>
  185. static void MakeStringArray(Json::Value& jval, CONT const& container);
  186. // -- Array value
  187. template <typename CONT>
  188. void SetArray(std::string const& key, CONT const& container);
  189. template <typename CONT>
  190. void SetConfigArray(
  191. std::string const& key,
  192. cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr);
  193. // -- Array of arrays
  194. template <typename CONT, typename FUNC>
  195. void SetArrayArray(std::string const& key, CONT const& container, FUNC func);
  196. // -- Save to json file
  197. bool Save(std::string const& filename);
  198. private:
  199. Json::Value Value_;
  200. };
  201. void InfoWriter::SetConfig(std::string const& key,
  202. cmQtAutoGenInitializer::ConfigString const& cfgStr)
  203. {
  204. this->Set(key, cfgStr.Default);
  205. for (auto const& item : cfgStr.Config) {
  206. this->Set(cmStrCat(key, '_', item.first), item.second);
  207. }
  208. }
  209. template <typename CONT>
  210. bool InfoWriter::MakeArray(Json::Value& jval, CONT const& container)
  211. {
  212. jval = Json::arrayValue;
  213. std::size_t const listSize = cm::size(container);
  214. if (listSize == 0) {
  215. return false;
  216. }
  217. jval.resize(static_cast<unsigned int>(listSize));
  218. return true;
  219. }
  220. template <typename CONT>
  221. void InfoWriter::MakeStringArray(Json::Value& jval, CONT const& container)
  222. {
  223. if (MakeArray(jval, container)) {
  224. Json::ArrayIndex ii = 0;
  225. for (std::string const& item : container) {
  226. jval[ii++] = item;
  227. }
  228. }
  229. }
  230. template <typename CONT>
  231. void InfoWriter::SetArray(std::string const& key, CONT const& container)
  232. {
  233. MakeStringArray(this->Value_[key], container);
  234. }
  235. template <typename CONT, typename FUNC>
  236. void InfoWriter::SetArrayArray(std::string const& key, CONT const& container,
  237. FUNC func)
  238. {
  239. Json::Value& jval = this->Value_[key];
  240. if (MakeArray(jval, container)) {
  241. Json::ArrayIndex ii = 0;
  242. for (auto const& citem : container) {
  243. Json::Value& aval = jval[ii++];
  244. aval = Json::arrayValue;
  245. func(aval, citem);
  246. }
  247. }
  248. }
  249. template <typename CONT>
  250. void InfoWriter::SetConfigArray(
  251. std::string const& key,
  252. cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr)
  253. {
  254. this->SetArray(key, cfgStr.Default);
  255. for (auto const& item : cfgStr.Config) {
  256. this->SetArray(cmStrCat(key, '_', item.first), item.second);
  257. }
  258. }
  259. bool InfoWriter::Save(std::string const& filename)
  260. {
  261. cmGeneratedFileStream fileStream;
  262. fileStream.SetCopyIfDifferent(true);
  263. fileStream.Open(filename, false, true);
  264. if (!fileStream) {
  265. return false;
  266. }
  267. Json::StyledStreamWriter jsonWriter;
  268. try {
  269. jsonWriter.write(fileStream, this->Value_);
  270. } catch (...) {
  271. return false;
  272. }
  273. return fileStream.Close();
  274. }
  275. cmQtAutoGen::ConfigStrings<std::vector<std::string>> generateListOptions(
  276. cmQtAutoGen::ConfigStrings<cmQtAutoGen::CompilerFeaturesHandle> const&
  277. executableFeatures,
  278. bool IsMultiConfig)
  279. {
  280. cmQtAutoGen::ConfigStrings<std::vector<std::string>> tempListOptions;
  281. if (IsMultiConfig) {
  282. for (auto const& executableFeature : executableFeatures.Config) {
  283. tempListOptions.Config[executableFeature.first] =
  284. executableFeature.second->ListOptions;
  285. }
  286. } else {
  287. tempListOptions.Default = executableFeatures.Default->ListOptions;
  288. }
  289. return tempListOptions;
  290. }
  291. } // End of unnamed namespace
  292. cmQtAutoGenInitializer::cmQtAutoGenInitializer(
  293. cmQtAutoGenGlobalInitializer* globalInitializer,
  294. cmGeneratorTarget* genTarget, IntegerVersion const& qtVersion,
  295. bool mocEnabled, bool uicEnabled, bool rccEnabled, bool globalAutogenTarget,
  296. bool globalAutoRccTarget)
  297. : GlobalInitializer(globalInitializer)
  298. , GenTarget(genTarget)
  299. , GlobalGen(genTarget->GetGlobalGenerator())
  300. , LocalGen(genTarget->GetLocalGenerator())
  301. , Makefile(genTarget->Makefile)
  302. , PathCheckSum(genTarget->Makefile)
  303. , QtVersion(qtVersion)
  304. {
  305. this->AutogenTarget.GlobalTarget = globalAutogenTarget;
  306. this->Moc.Enabled = mocEnabled;
  307. this->Uic.Enabled = uicEnabled;
  308. this->Rcc.Enabled = rccEnabled;
  309. this->Rcc.GlobalTarget = globalAutoRccTarget;
  310. this->CrossConfig =
  311. !this->Makefile->GetSafeDefinition("CMAKE_CROSS_CONFIGS").empty();
  312. this->UseBetterGraph =
  313. this->GenTarget->GetProperty("AUTOGEN_BETTER_GRAPH_MULTI_CONFIG").IsSet()
  314. ? this->GenTarget->GetProperty("AUTOGEN_BETTER_GRAPH_MULTI_CONFIG").IsOn()
  315. : (this->QtVersion >= IntegerVersion(6, 8));
  316. // AUTOGEN_BETTER_GRAPH_MULTI_CONFIG is set explicitly because it is read by
  317. // the qt library
  318. this->GenTarget->Target->SetProperty("AUTOGEN_BETTER_GRAPH_MULTI_CONFIG",
  319. this->UseBetterGraph ? "ON" : "OFF");
  320. }
  321. void cmQtAutoGenInitializer::AddAutogenExecutableToDependencies(
  322. cmQtAutoGenInitializer::GenVarsT const& genVars,
  323. std::vector<std::string>& dependencies) const
  324. {
  325. if (genVars.ExecutableTarget) {
  326. dependencies.push_back(genVars.ExecutableTarget->Target->GetName());
  327. } else if (this->MultiConfig && this->UseBetterGraph) {
  328. cm::string_view const configGenexWithCommandConfig =
  329. "$<COMMAND_CONFIG:$<$<CONFIG:";
  330. cm::string_view const configGenex = "$<$<CONFIG:";
  331. cm::string_view const configGenexEnd = ">";
  332. cm::string_view const configGenexEndWithCommandConfig = ">>";
  333. auto genexBegin =
  334. this->CrossConfig ? configGenexWithCommandConfig : configGenex;
  335. auto genexEnd =
  336. this->CrossConfig ? configGenexEndWithCommandConfig : configGenexEnd;
  337. for (auto const& config : genVars.Executable.Config) {
  338. auto executableWithConfig =
  339. cmStrCat(genexBegin, config.first, ">:", config.second, genexEnd);
  340. dependencies.emplace_back(std::move(executableWithConfig));
  341. }
  342. } else {
  343. if (!genVars.Executable.Default.empty()) {
  344. dependencies.push_back(genVars.Executable.Default);
  345. }
  346. }
  347. }
  348. bool cmQtAutoGenInitializer::InitCustomTargets()
  349. {
  350. // Configurations
  351. this->MultiConfig = this->GlobalGen->IsMultiConfig();
  352. this->ConfigDefault = this->Makefile->GetDefaultConfiguration();
  353. this->ConfigsList =
  354. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  355. // Verbosity
  356. {
  357. std::string const def =
  358. this->Makefile->GetSafeDefinition("CMAKE_AUTOGEN_VERBOSE");
  359. if (!def.empty()) {
  360. unsigned long iVerb = 0;
  361. if (cmStrToULong(def, &iVerb)) {
  362. // Numeric verbosity
  363. this->Verbosity = static_cast<unsigned int>(iVerb);
  364. } else {
  365. // Non numeric verbosity
  366. if (cmIsOn(def)) {
  367. this->Verbosity = 1;
  368. }
  369. }
  370. }
  371. }
  372. // Targets FOLDER
  373. {
  374. cmValue folder =
  375. this->Makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
  376. if (!folder) {
  377. folder = this->Makefile->GetState()->GetGlobalProperty(
  378. "AUTOGEN_TARGETS_FOLDER");
  379. }
  380. // Inherit FOLDER property from target (#13688)
  381. if (!folder) {
  382. folder = this->GenTarget->GetProperty("FOLDER");
  383. }
  384. if (folder) {
  385. this->TargetsFolder = *folder;
  386. }
  387. }
  388. // Check status of policy CMP0071 regarding handling of GENERATED files
  389. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0071)) {
  390. case cmPolicies::WARN:
  391. // Ignore GENERATED files but warn
  392. this->CMP0071Warn = true;
  393. CM_FALLTHROUGH;
  394. case cmPolicies::OLD:
  395. // Ignore GENERATED files
  396. break;
  397. case cmPolicies::NEW:
  398. // Process GENERATED files
  399. this->CMP0071Accept = true;
  400. break;
  401. }
  402. // Check status of policy CMP0100 regarding handling of .hh headers
  403. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0100)) {
  404. case cmPolicies::WARN:
  405. // Ignore but .hh files but warn
  406. this->CMP0100Warn = true;
  407. CM_FALLTHROUGH;
  408. case cmPolicies::OLD:
  409. // Ignore .hh files
  410. break;
  411. case cmPolicies::NEW:
  412. // Process .hh file
  413. this->CMP0100Accept = true;
  414. break;
  415. }
  416. // Common directories
  417. std::string relativeBuildDir;
  418. {
  419. // Collapsed current binary directory
  420. std::string const cbd = cmSystemTools::CollapseFullPath(
  421. std::string(), this->Makefile->GetCurrentBinaryDirectory());
  422. // Info directory
  423. // TODO: Split this? `AutogenInfo.json` is expected to always be under the
  424. // `CMakeFiles` directory, but not all generators places its `<tgt>.dir`
  425. // directories there.
  426. this->Dir.Info = cmStrCat(cbd, "/CMakeFiles/", this->GenTarget->GetName(),
  427. "_autogen.dir");
  428. cmSystemTools::ConvertToUnixSlashes(this->Dir.Info);
  429. // Build directory
  430. this->Dir.Build = this->GenTarget->GetSafeProperty("AUTOGEN_BUILD_DIR");
  431. if (this->Dir.Build.empty()) {
  432. this->Dir.Build =
  433. cmStrCat(cbd, '/', this->GenTarget->GetName(), "_autogen");
  434. }
  435. cmSystemTools::ConvertToUnixSlashes(this->Dir.Build);
  436. this->Dir.RelativeBuild =
  437. cmSystemTools::RelativePath(cbd, this->Dir.Build);
  438. // Cleanup build directory
  439. this->AddCleanFile(this->Dir.Build);
  440. // Working directory
  441. this->Dir.Work = cbd;
  442. cmSystemTools::ConvertToUnixSlashes(this->Dir.Work);
  443. // Include directory
  444. this->ConfigFileNamesAndGenex(this->Dir.Include, this->Dir.IncludeGenExp,
  445. cmStrCat(this->Dir.Build, "/include"), "");
  446. }
  447. // Moc, Uic and _autogen target settings
  448. if (this->MocOrUicEnabled()) {
  449. // Init moc specific settings
  450. if (this->Moc.Enabled && !this->InitMoc()) {
  451. return false;
  452. }
  453. // Init uic specific settings
  454. if (this->Uic.Enabled && !this->InitUic()) {
  455. return false;
  456. }
  457. // Autogen target name
  458. this->AutogenTarget.Name =
  459. cmStrCat(this->GenTarget->GetName(), "_autogen");
  460. // Autogen target parallel processing
  461. {
  462. using ParallelType = decltype(this->AutogenTarget.Parallel);
  463. unsigned long propInt = 0;
  464. std::string const& prop =
  465. this->GenTarget->GetSafeProperty("AUTOGEN_PARALLEL");
  466. if (prop.empty() || (prop == "AUTO")) {
  467. // Autodetect number of CPUs
  468. this->AutogenTarget.Parallel = GetParallelCPUCount();
  469. } else if (cmStrToULong(prop, &propInt) && propInt > 0 &&
  470. propInt <= std::numeric_limits<ParallelType>::max()) {
  471. this->AutogenTarget.Parallel = static_cast<ParallelType>(propInt);
  472. } else {
  473. // Warn the project author that AUTOGEN_PARALLEL is not valid.
  474. this->Makefile->IssueMessage(
  475. MessageType::AUTHOR_WARNING,
  476. cmStrCat("AUTOGEN_PARALLEL=\"", prop, "\" for target \"",
  477. this->GenTarget->GetName(),
  478. "\" is not valid. Using AUTOGEN_PARALLEL=1"));
  479. this->AutogenTarget.Parallel = 1;
  480. }
  481. }
  482. #ifdef _WIN32
  483. {
  484. auto const& value =
  485. this->GenTarget->GetProperty("AUTOGEN_COMMAND_LINE_LENGTH_MAX");
  486. if (value.IsSet()) {
  487. using maxCommandLineLengthType =
  488. decltype(this->AutogenTarget.MaxCommandLineLength);
  489. unsigned long propInt = 0;
  490. if (cmStrToULong(value, &propInt) && propInt > 0 &&
  491. propInt <= std::numeric_limits<maxCommandLineLengthType>::max()) {
  492. this->AutogenTarget.MaxCommandLineLength =
  493. static_cast<maxCommandLineLengthType>(propInt);
  494. } else {
  495. // Warn the project author that AUTOGEN_PARALLEL is not valid.
  496. this->Makefile->IssueMessage(
  497. MessageType::AUTHOR_WARNING,
  498. cmStrCat("AUTOGEN_COMMAND_LINE_LENGTH_MAX=\"", *value,
  499. "\" for target \"", this->GenTarget->GetName(),
  500. "\" is not valid. Using no limit for "
  501. "AUTOGEN_COMMAND_LINE_LENGTH_MAX"));
  502. this->AutogenTarget.MaxCommandLineLength =
  503. std::numeric_limits<maxCommandLineLengthType>::max();
  504. }
  505. } else {
  506. // Actually 32767 (see
  507. // https://devblogs.microsoft.com/oldnewthing/20031210-00/?p=41553) but
  508. // we allow for a small margin
  509. this->AutogenTarget.MaxCommandLineLength = 32000;
  510. }
  511. }
  512. #endif
  513. // Autogen target info and settings files
  514. {
  515. // Info file
  516. this->AutogenTarget.InfoFile =
  517. cmStrCat(this->Dir.Info, "/AutogenInfo.json");
  518. // Used settings file
  519. this->ConfigFileNames(this->AutogenTarget.SettingsFile,
  520. cmStrCat(this->Dir.Info, "/AutogenUsed"), ".txt");
  521. this->ConfigFileClean(this->AutogenTarget.SettingsFile);
  522. // Parse cache file
  523. this->ConfigFileNames(this->AutogenTarget.ParseCacheFile,
  524. cmStrCat(this->Dir.Info, "/ParseCache"), ".txt");
  525. this->ConfigFileClean(this->AutogenTarget.ParseCacheFile);
  526. }
  527. // Autogen target: Compute user defined dependencies
  528. {
  529. this->AutogenTarget.DependOrigin =
  530. this->GenTarget->GetPropertyAsBool("AUTOGEN_ORIGIN_DEPENDS");
  531. std::string const& deps =
  532. this->GenTarget->GetSafeProperty("AUTOGEN_TARGET_DEPENDS");
  533. if (!deps.empty()) {
  534. for (auto const& depName : cmList{ deps }) {
  535. // Allow target and file dependencies
  536. auto* depTarget = this->Makefile->FindTargetToUse(depName);
  537. if (depTarget) {
  538. this->AutogenTarget.DependTargets.insert(depTarget);
  539. } else {
  540. this->AutogenTarget.DependFiles.insert(depName);
  541. }
  542. }
  543. }
  544. }
  545. if (this->Moc.Enabled) {
  546. // Path prefix
  547. if (this->GenTarget->GetProperty("AUTOMOC_PATH_PREFIX").IsOn()) {
  548. this->Moc.PathPrefix = true;
  549. }
  550. // CMAKE_AUTOMOC_RELAXED_MODE
  551. if (this->Makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE")) {
  552. this->Moc.RelaxedMode = true;
  553. this->Makefile->IssueMessage(
  554. MessageType::AUTHOR_WARNING,
  555. cmStrCat("AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is "
  556. "deprecated an will be removed in the future. Consider "
  557. "disabling it and converting the target ",
  558. this->GenTarget->GetName(), " to regular mode."));
  559. }
  560. // Options
  561. cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MOC_OPTIONS"),
  562. this->Moc.Options);
  563. // Filters
  564. cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MACRO_NAMES"),
  565. this->Moc.MacroNames);
  566. this->Moc.MacroNames.erase(cmRemoveDuplicates(this->Moc.MacroNames),
  567. this->Moc.MacroNames.end());
  568. {
  569. cmList const filterList = { this->GenTarget->GetSafeProperty(
  570. "AUTOMOC_DEPEND_FILTERS") };
  571. if ((filterList.size() % 2) != 0) {
  572. cmSystemTools::Error(
  573. cmStrCat("AutoMoc: AUTOMOC_DEPEND_FILTERS predefs size ",
  574. filterList.size(), " is not a multiple of 2."));
  575. return false;
  576. }
  577. this->Moc.DependFilters.reserve(1 + (filterList.size() / 2));
  578. this->Moc.DependFilters.emplace_back(
  579. "Q_PLUGIN_METADATA",
  580. "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
  581. "[^\\)]*FILE[ \t]*\"([^\"]+)\"");
  582. for (cmList::size_type ii = 0; ii != filterList.size(); ii += 2) {
  583. this->Moc.DependFilters.emplace_back(filterList[ii],
  584. filterList[ii + 1]);
  585. }
  586. }
  587. }
  588. }
  589. // Init rcc specific settings
  590. if (this->Rcc.Enabled && !this->InitRcc()) {
  591. return false;
  592. }
  593. // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
  594. if (this->MocOrUicEnabled() || (this->Rcc.Enabled && this->MultiConfig)) {
  595. auto addBefore = false;
  596. auto const& value =
  597. this->GenTarget->GetProperty("AUTOGEN_USE_SYSTEM_INCLUDE");
  598. if (value.IsSet()) {
  599. if (value.IsOn()) {
  600. this->GenTarget->AddSystemIncludeDirectory(this->Dir.IncludeGenExp,
  601. "CXX");
  602. } else {
  603. addBefore = true;
  604. }
  605. } else {
  606. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0151)) {
  607. case cmPolicies::WARN:
  608. case cmPolicies::OLD:
  609. addBefore = true;
  610. break;
  611. case cmPolicies::NEW:
  612. this->GenTarget->AddSystemIncludeDirectory(this->Dir.IncludeGenExp,
  613. "CXX");
  614. break;
  615. }
  616. }
  617. this->GenTarget->AddIncludeDirectory(this->Dir.IncludeGenExp, addBefore);
  618. }
  619. // Scan files
  620. if (!this->InitScanFiles()) {
  621. return false;
  622. }
  623. // Create autogen target
  624. if (this->MocOrUicEnabled() && !this->InitAutogenTarget()) {
  625. return false;
  626. }
  627. // Create rcc targets
  628. if (this->Rcc.Enabled && !this->InitRccTargets()) {
  629. return false;
  630. }
  631. return true;
  632. }
  633. bool cmQtAutoGenInitializer::InitMoc()
  634. {
  635. // Mocs compilation file
  636. if (this->GlobalGen->IsXcode()) {
  637. // XXX(xcode-per-cfg-src): Drop this Xcode-specific code path
  638. // when the Xcode generator supports per-config sources.
  639. this->Moc.CompilationFile.Default =
  640. cmStrCat(this->Dir.Build, "/mocs_compilation.cpp");
  641. this->Moc.CompilationFileGenex = this->Moc.CompilationFile.Default;
  642. } else {
  643. this->ConfigFileNamesAndGenex(
  644. this->Moc.CompilationFile, this->Moc.CompilationFileGenex,
  645. cmStrCat(this->Dir.Build, "/mocs_compilation"_s), ".cpp"_s);
  646. }
  647. // Moc predefs
  648. if (this->GenTarget->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
  649. (this->QtVersion >= IntegerVersion(5, 8))) {
  650. // Command
  651. cmList::assign(
  652. this->Moc.PredefsCmd,
  653. this->Makefile->GetDefinition("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND"));
  654. // Header
  655. if (!this->Moc.PredefsCmd.empty()) {
  656. this->ConfigFileNames(this->Moc.PredefsFile,
  657. cmStrCat(this->Dir.Build, "/moc_predefs"), ".h");
  658. }
  659. }
  660. // Moc includes
  661. {
  662. // If the property AUTOMOC_INCLUDE_DIRECTORIES is set on the target,
  663. // use its value for moc include paths instead of gathering all
  664. // include directories from the target.
  665. cmValue autoIncDirs =
  666. this->GenTarget->GetProperty("AUTOMOC_INCLUDE_DIRECTORIES");
  667. if (autoIncDirs) {
  668. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  669. cmGeneratorExpression ge(*this->Makefile->GetCMakeInstance(), lfbt);
  670. auto cge = ge.Parse(*autoIncDirs);
  671. // Build a single list of configs to iterate, whether single or multi
  672. std::vector<std::string> configs = this->MultiConfig
  673. ? this->ConfigsList
  674. : std::vector<std::string>{ this->ConfigDefault };
  675. for (auto const& cfg : configs) {
  676. std::string eval = cge->Evaluate(this->LocalGen, cfg);
  677. std::vector<std::string> incList = cmList(eval);
  678. // Validate absolute paths
  679. for (auto const& path : incList) {
  680. if (!cmGeneratorExpression::StartsWithGeneratorExpression(path) &&
  681. !cmSystemTools::FileIsFullPath(path)) {
  682. this->Makefile->IssueMessage(
  683. MessageType::FATAL_ERROR,
  684. cmStrCat("AUTOMOC_INCLUDE_DIRECTORIES: path '", path,
  685. "' is not absolute."));
  686. return false;
  687. }
  688. }
  689. if (this->MultiConfig) {
  690. this->Moc.Includes.Config[cfg] = std::move(incList);
  691. } else {
  692. this->Moc.Includes.Default = std::move(incList);
  693. }
  694. }
  695. } else {
  696. // Otherwise, discover include directories from the target for moc.
  697. SearchPathSanitizer const sanitizer(this->Makefile);
  698. auto getDirs = [this, &sanitizer](
  699. std::string const& cfg) -> std::vector<std::string> {
  700. // Get the include dirs for this target, without stripping the implicit
  701. // include dirs off, see issue #13667.
  702. std::vector<std::string> dirs;
  703. bool const appendImplicit = (this->QtVersion.Major >= 5);
  704. this->LocalGen->GetIncludeDirectoriesImplicit(
  705. dirs, this->GenTarget, "CXX", cfg, false, appendImplicit);
  706. return sanitizer(dirs);
  707. };
  708. // Other configuration settings
  709. if (this->MultiConfig) {
  710. for (std::string const& cfg : this->ConfigsList) {
  711. std::vector<std::string> dirs = getDirs(cfg);
  712. if (dirs == this->Moc.Includes.Default) {
  713. continue;
  714. }
  715. this->Moc.Includes.Config[cfg] = std::move(dirs);
  716. }
  717. } else {
  718. // Default configuration include directories
  719. this->Moc.Includes.Default = getDirs(this->ConfigDefault);
  720. }
  721. }
  722. }
  723. // Moc compile definitions
  724. {
  725. auto getDefs = [this](std::string const& cfg) -> std::set<std::string> {
  726. std::set<std::string> defines;
  727. this->LocalGen->GetTargetDefines(this->GenTarget, cfg, "CXX", defines);
  728. if (this->Moc.PredefsCmd.empty() &&
  729. this->Makefile->GetSafeDefinition("CMAKE_SYSTEM_NAME") ==
  730. "Windows") {
  731. // Add WIN32 definition if we don't have a moc_predefs.h
  732. defines.insert("WIN32");
  733. }
  734. return defines;
  735. };
  736. // Other configuration defines
  737. if (this->MultiConfig) {
  738. for (std::string const& cfg : this->ConfigsList) {
  739. std::set<std::string> defines = getDefs(cfg);
  740. if (defines == this->Moc.Defines.Default) {
  741. continue;
  742. }
  743. this->Moc.Defines.Config[cfg] = std::move(defines);
  744. }
  745. } else {
  746. // Default configuration defines
  747. this->Moc.Defines.Default = getDefs(this->ConfigDefault);
  748. }
  749. }
  750. // Moc executable
  751. {
  752. if (!this->GetQtExecutable(this->Moc, "moc", false)) {
  753. return false;
  754. }
  755. // Let the _autogen target depend on the moc executable
  756. if (this->Moc.ExecutableTarget) {
  757. this->AutogenTarget.DependTargets.insert(
  758. this->Moc.ExecutableTarget->Target);
  759. }
  760. }
  761. return true;
  762. }
  763. bool cmQtAutoGenInitializer::InitUic()
  764. {
  765. // Uic search paths
  766. {
  767. std::string const& usp =
  768. this->GenTarget->GetSafeProperty("AUTOUIC_SEARCH_PATHS");
  769. if (!usp.empty()) {
  770. this->Uic.SearchPaths =
  771. SearchPathSanitizer(this->Makefile)(cmList{ usp });
  772. }
  773. }
  774. // Uic target options
  775. {
  776. auto getOpts = [this](std::string const& cfg) -> std::vector<std::string> {
  777. std::vector<std::string> opts;
  778. this->GenTarget->GetAutoUicOptions(opts, cfg);
  779. return opts;
  780. };
  781. // Default options
  782. this->Uic.Options.Default = getOpts(this->ConfigDefault);
  783. // Configuration specific options
  784. if (this->MultiConfig) {
  785. for (std::string const& cfg : this->ConfigsList) {
  786. std::vector<std::string> options = getOpts(cfg);
  787. if (options == this->Uic.Options.Default) {
  788. continue;
  789. }
  790. this->Uic.Options.Config[cfg] = std::move(options);
  791. }
  792. }
  793. }
  794. // Uic executable
  795. {
  796. if (!this->GetQtExecutable(this->Uic, "uic", true)) {
  797. return false;
  798. }
  799. // Let the _autogen target depend on the uic executable
  800. if (this->Uic.ExecutableTarget) {
  801. this->AutogenTarget.DependTargets.insert(
  802. this->Uic.ExecutableTarget->Target);
  803. }
  804. }
  805. return true;
  806. }
  807. bool cmQtAutoGenInitializer::InitRcc()
  808. {
  809. // Rcc executable
  810. {
  811. if (!this->GetQtExecutable(this->Rcc, "rcc", false)) {
  812. return false;
  813. }
  814. // Evaluate test output on demand
  815. auto& features = this->Rcc.ExecutableFeatures;
  816. auto checkAndAddOptions = [this](CompilerFeaturesHandle& feature) {
  817. if (!feature->Evaluated) {
  818. // Look for list options
  819. if (this->QtVersion.Major == 5 || this->QtVersion.Major == 6) {
  820. static std::array<std::string, 2> const listOptions{ { "--list",
  821. "-list" } };
  822. for (std::string const& opt : listOptions) {
  823. if (feature->HelpOutput.find(opt) != std::string::npos) {
  824. feature->ListOptions.emplace_back(opt);
  825. break;
  826. }
  827. }
  828. }
  829. // Evaluation finished
  830. feature->Evaluated = true;
  831. }
  832. };
  833. if (this->MultiConfig && this->UseBetterGraph) {
  834. for (auto const& config : this->ConfigsList) {
  835. checkAndAddOptions(features.Config[config]);
  836. }
  837. } else {
  838. checkAndAddOptions(features.Default);
  839. }
  840. }
  841. // Disable zstd if it is not supported
  842. {
  843. std::string const qtFeatureZSTD = "QT_FEATURE_zstd";
  844. if (this->GenTarget->Target->GetMakefile()->IsDefinitionSet(
  845. qtFeatureZSTD)) {
  846. auto const zstdDef =
  847. this->GenTarget->Target->GetMakefile()->GetSafeDefinition(
  848. qtFeatureZSTD);
  849. auto const zstdVal = cmValue(zstdDef);
  850. if (zstdVal.IsOff()) {
  851. auto const& kw = this->GlobalInitializer->kw();
  852. auto rccOptions = this->GenTarget->GetSafeProperty(kw.AUTORCC_OPTIONS);
  853. std::string const nozstd = "--no-zstd";
  854. if (rccOptions.find(nozstd) == std::string::npos) {
  855. rccOptions.append(";" + nozstd + ";");
  856. }
  857. this->GenTarget->Target->SetProperty(kw.AUTORCC_OPTIONS, rccOptions);
  858. }
  859. }
  860. }
  861. return true;
  862. }
  863. bool cmQtAutoGenInitializer::InitScanFiles()
  864. {
  865. cmake const* cm = this->Makefile->GetCMakeInstance();
  866. auto const& kw = this->GlobalInitializer->kw();
  867. auto makeMUFile = [this, &kw](cmSourceFile* sf, std::string const& fullPath,
  868. std::vector<size_t> const& configs,
  869. bool muIt) -> MUFileHandle {
  870. MUFileHandle muf = cm::make_unique<MUFile>();
  871. muf->FullPath = fullPath;
  872. muf->SF = sf;
  873. if (!configs.empty() && configs.size() != this->ConfigsList.size()) {
  874. muf->Configs = configs;
  875. }
  876. muf->Generated = sf->GetIsGenerated();
  877. bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
  878. muf->SkipMoc = this->Moc.Enabled &&
  879. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOMOC));
  880. muf->SkipUic = this->Uic.Enabled &&
  881. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
  882. if (muIt) {
  883. muf->MocIt = this->Moc.Enabled && !muf->SkipMoc;
  884. muf->UicIt = this->Uic.Enabled && !muf->SkipUic;
  885. }
  886. return muf;
  887. };
  888. auto addMUHeader = [this](MUFileHandle&& muf, cm::string_view extension) {
  889. cmSourceFile* sf = muf->SF;
  890. bool const muIt = (muf->MocIt || muf->UicIt);
  891. if (this->CMP0100Accept || (extension != "hh")) {
  892. // Accept
  893. if (muIt && muf->Generated) {
  894. this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
  895. }
  896. this->AutogenTarget.Headers.emplace(sf, std::move(muf));
  897. } else if (muIt && this->CMP0100Warn) {
  898. // Store file for warning message
  899. this->AutogenTarget.CMP0100HeadersWarn.push_back(sf);
  900. }
  901. };
  902. auto addMUSource = [this](MUFileHandle&& muf) {
  903. if ((muf->MocIt || muf->UicIt) && muf->Generated) {
  904. this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
  905. }
  906. this->AutogenTarget.Sources.emplace(muf->SF, std::move(muf));
  907. };
  908. // Scan through target files
  909. {
  910. // Scan through target files
  911. for (cmGeneratorTarget::AllConfigSource const& acs :
  912. this->GenTarget->GetAllConfigSources()) {
  913. std::string const& fullPath = acs.Source->GetFullPath();
  914. std::string const& extLower =
  915. cmSystemTools::LowerCase(acs.Source->GetExtension());
  916. // Register files that will be scanned by moc or uic
  917. if (this->MocOrUicEnabled()) {
  918. if (cm->IsAHeaderExtension(extLower)) {
  919. addMUHeader(makeMUFile(acs.Source, fullPath, acs.Configs, true),
  920. extLower);
  921. } else if (cm->IsACLikeSourceExtension(extLower)) {
  922. addMUSource(makeMUFile(acs.Source, fullPath, acs.Configs, true));
  923. }
  924. }
  925. // Register rcc enabled files
  926. if (this->Rcc.Enabled) {
  927. if ((extLower == kw.qrc) &&
  928. !acs.Source->GetPropertyAsBool(kw.SKIP_AUTOGEN) &&
  929. !acs.Source->GetPropertyAsBool(kw.SKIP_AUTORCC)) {
  930. // Register qrc file
  931. Qrc qrc;
  932. qrc.QrcFile = fullPath;
  933. qrc.QrcName =
  934. cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
  935. qrc.Generated = acs.Source->GetIsGenerated();
  936. // RCC options
  937. {
  938. std::string const& opts =
  939. acs.Source->GetSafeProperty(kw.AUTORCC_OPTIONS);
  940. if (!opts.empty()) {
  941. cmExpandList(opts, qrc.Options);
  942. }
  943. }
  944. this->Rcc.Qrcs.push_back(std::move(qrc));
  945. }
  946. }
  947. }
  948. }
  949. // cmGeneratorTarget::GetAllConfigSources computes the target's
  950. // sources meta data cache. Clear it so that OBJECT library targets that
  951. // are AUTOGEN initialized after this target get their added
  952. // mocs_compilation.cpp source acknowledged by this target.
  953. this->GenTarget->ClearSourcesCache();
  954. // For source files find additional headers and private headers
  955. if (this->MocOrUicEnabled()) {
  956. // Header search suffixes and extensions
  957. static std::initializer_list<cm::string_view> const suffixes{ "", "_p" };
  958. auto const& exts = cm->GetHeaderExtensions();
  959. // Scan through sources
  960. for (auto const& pair : this->AutogenTarget.Sources) {
  961. MUFile const& muf = *pair.second;
  962. if (muf.MocIt || muf.UicIt) {
  963. // Search for the default header file and a private header
  964. std::string const& srcFullPath = muf.SF->ResolveFullPath();
  965. std::string const basePath = cmStrCat(
  966. cmQtAutoGen::SubDirPrefix(srcFullPath),
  967. cmSystemTools::GetFilenameWithoutLastExtension(srcFullPath));
  968. for (auto const& suffix : suffixes) {
  969. std::string const suffixedPath = cmStrCat(basePath, suffix);
  970. for (auto const& ext : exts) {
  971. std::string const fullPath = cmStrCat(suffixedPath, '.', ext);
  972. auto constexpr locationKind = cmSourceFileLocationKind::Known;
  973. cmSourceFile* sf =
  974. this->Makefile->GetSource(fullPath, locationKind);
  975. if (sf) {
  976. // Check if we know about this header already
  977. if (cm::contains(this->AutogenTarget.Headers, sf)) {
  978. continue;
  979. }
  980. // We only accept not-GENERATED files that do exist.
  981. if (!sf->GetIsGenerated() &&
  982. !cmSystemTools::FileExists(fullPath)) {
  983. continue;
  984. }
  985. } else if (cmSystemTools::FileExists(fullPath)) {
  986. // Create a new source file for the existing file
  987. sf = this->Makefile->CreateSource(fullPath, false, locationKind);
  988. }
  989. if (sf) {
  990. auto eMuf = makeMUFile(sf, fullPath, muf.Configs, true);
  991. // Only process moc/uic when the parent is processed as well
  992. if (!muf.MocIt) {
  993. eMuf->MocIt = false;
  994. }
  995. if (!muf.UicIt) {
  996. eMuf->UicIt = false;
  997. }
  998. addMUHeader(std::move(eMuf), ext);
  999. }
  1000. }
  1001. }
  1002. }
  1003. }
  1004. }
  1005. // Scan through all source files in the makefile to extract moc and uic
  1006. // parameters. Historically we support non target source file parameters.
  1007. // The reason is that their file names might be discovered from source files
  1008. // at generation time.
  1009. if (this->MocOrUicEnabled()) {
  1010. for (auto const& sf : this->Makefile->GetSourceFiles()) {
  1011. // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
  1012. // Since we're iterating over source files that might be not in the
  1013. // target we need to check for path errors (not existing files).
  1014. std::string pathError;
  1015. std::string const& fullPath = sf->ResolveFullPath(&pathError);
  1016. if (!pathError.empty() || fullPath.empty()) {
  1017. continue;
  1018. }
  1019. std::string const& extLower =
  1020. cmSystemTools::LowerCase(sf->GetExtension());
  1021. if (cm->IsAHeaderExtension(extLower)) {
  1022. if (!cm::contains(this->AutogenTarget.Headers, sf.get())) {
  1023. auto muf = makeMUFile(sf.get(), fullPath, {}, false);
  1024. if (muf->SkipMoc || muf->SkipUic) {
  1025. addMUHeader(std::move(muf), extLower);
  1026. }
  1027. }
  1028. } else if (cm->IsACLikeSourceExtension(extLower)) {
  1029. if (!cm::contains(this->AutogenTarget.Sources, sf.get())) {
  1030. auto muf = makeMUFile(sf.get(), fullPath, {}, false);
  1031. if (muf->SkipMoc || muf->SkipUic) {
  1032. addMUSource(std::move(muf));
  1033. }
  1034. }
  1035. } else if (this->Uic.Enabled && (extLower == kw.ui)) {
  1036. // .ui file
  1037. bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
  1038. bool const skipUic =
  1039. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
  1040. if (!skipUic) {
  1041. // Check if the .ui file has uic options
  1042. std::string const uicOpts = sf->GetSafeProperty(kw.AUTOUIC_OPTIONS);
  1043. if (uicOpts.empty()) {
  1044. this->Uic.UiFilesNoOptions.emplace_back(fullPath);
  1045. } else {
  1046. this->Uic.UiFilesWithOptions.emplace_back(
  1047. fullPath, std::move(cmList{ uicOpts }.data()));
  1048. }
  1049. auto uiHeaderRelativePath = cmSystemTools::RelativePath(
  1050. this->LocalGen->GetCurrentSourceDirectory(),
  1051. cmSystemTools::GetFilenamePath(fullPath));
  1052. // Avoid creating a path containing adjacent slashes
  1053. if (!uiHeaderRelativePath.empty() &&
  1054. uiHeaderRelativePath.back() != '/') {
  1055. uiHeaderRelativePath += '/';
  1056. }
  1057. auto uiHeaderFilePath = cmStrCat(
  1058. '/', uiHeaderRelativePath, "ui_"_s,
  1059. cmSystemTools::GetFilenameWithoutLastExtension(fullPath), ".h"_s);
  1060. ConfigString uiHeader;
  1061. std::string uiHeaderGenex;
  1062. this->ConfigFileNamesAndGenex(
  1063. uiHeader, uiHeaderGenex, cmStrCat(this->Dir.Build, "/include"_s),
  1064. uiHeaderFilePath);
  1065. this->Uic.UiHeaders.emplace_back(uiHeader, uiHeaderGenex);
  1066. } else {
  1067. // Register skipped .ui file
  1068. this->Uic.SkipUi.insert(fullPath);
  1069. }
  1070. }
  1071. }
  1072. }
  1073. // Process GENERATED sources and headers
  1074. if (this->MocOrUicEnabled() && !this->AutogenTarget.FilesGenerated.empty()) {
  1075. if (this->CMP0071Accept) {
  1076. // Let the autogen target depend on the GENERATED files
  1077. if (this->MultiConfig && !this->CrossConfig) {
  1078. for (MUFile const* muf : this->AutogenTarget.FilesGenerated) {
  1079. if (muf->Configs.empty()) {
  1080. this->AutogenTarget.DependFiles.insert(muf->FullPath);
  1081. } else {
  1082. for (size_t ci : muf->Configs) {
  1083. std::string const& config = this->ConfigsList[ci];
  1084. std::string const& pathWithConfig =
  1085. cmStrCat("$<$<CONFIG:", config, ">:", muf->FullPath, '>');
  1086. this->AutogenTarget.DependFiles.insert(pathWithConfig);
  1087. }
  1088. }
  1089. }
  1090. } else {
  1091. for (MUFile const* muf : this->AutogenTarget.FilesGenerated) {
  1092. this->AutogenTarget.DependFiles.insert(muf->FullPath);
  1093. }
  1094. }
  1095. } else if (this->CMP0071Warn) {
  1096. cm::string_view property;
  1097. if (this->Moc.Enabled && this->Uic.Enabled) {
  1098. property = "SKIP_AUTOGEN";
  1099. } else if (this->Moc.Enabled) {
  1100. property = "SKIP_AUTOMOC";
  1101. } else if (this->Uic.Enabled) {
  1102. property = "SKIP_AUTOUIC";
  1103. }
  1104. std::string files;
  1105. for (MUFile const* muf : this->AutogenTarget.FilesGenerated) {
  1106. files += cmStrCat(" ", Quoted(muf->FullPath), '\n');
  1107. }
  1108. this->Makefile->IssueMessage(
  1109. MessageType::AUTHOR_WARNING,
  1110. cmStrCat(
  1111. cmPolicies::GetPolicyWarning(cmPolicies::CMP0071),
  1112. "\n"
  1113. "For compatibility, CMake is excluding the GENERATED source "
  1114. "file(s):\n",
  1115. files, "from processing by ",
  1116. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  1117. ". If any of the files should be processed, set CMP0071 to NEW. "
  1118. "If any of the files should not be processed, "
  1119. "explicitly exclude them by setting the source file property ",
  1120. property, ":\n set_property(SOURCE file.h PROPERTY ", property,
  1121. " ON)\n"));
  1122. }
  1123. }
  1124. // Generate CMP0100 warning
  1125. if (this->MocOrUicEnabled() &&
  1126. !this->AutogenTarget.CMP0100HeadersWarn.empty()) {
  1127. cm::string_view property;
  1128. if (this->Moc.Enabled && this->Uic.Enabled) {
  1129. property = "SKIP_AUTOGEN";
  1130. } else if (this->Moc.Enabled) {
  1131. property = "SKIP_AUTOMOC";
  1132. } else if (this->Uic.Enabled) {
  1133. property = "SKIP_AUTOUIC";
  1134. }
  1135. std::string files;
  1136. for (cmSourceFile const* sf : this->AutogenTarget.CMP0100HeadersWarn) {
  1137. files += cmStrCat(" ", Quoted(sf->GetFullPath()), '\n');
  1138. }
  1139. this->Makefile->IssueMessage(
  1140. MessageType::AUTHOR_WARNING,
  1141. cmStrCat(
  1142. cmPolicies::GetPolicyWarning(cmPolicies::CMP0100),
  1143. "\n"
  1144. "For compatibility, CMake is excluding the header file(s):\n",
  1145. files, "from processing by ",
  1146. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  1147. ". If any of the files should be processed, set CMP0100 to NEW. "
  1148. "If any of the files should not be processed, "
  1149. "explicitly exclude them by setting the source file property ",
  1150. property, ":\n set_property(SOURCE file.hh PROPERTY ", property,
  1151. " ON)\n"));
  1152. }
  1153. // Process qrc files
  1154. if (!this->Rcc.Qrcs.empty()) {
  1155. bool const modernQt = (this->QtVersion.Major >= 5);
  1156. // Target rcc options
  1157. cmList const optionsTarget{ this->GenTarget->GetSafeProperty(
  1158. kw.AUTORCC_OPTIONS) };
  1159. // Check if file name is unique
  1160. for (Qrc& qrc : this->Rcc.Qrcs) {
  1161. qrc.Unique = true;
  1162. for (Qrc const& qrc2 : this->Rcc.Qrcs) {
  1163. if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
  1164. qrc.Unique = false;
  1165. break;
  1166. }
  1167. }
  1168. }
  1169. // Path checksum and file names
  1170. for (Qrc& qrc : this->Rcc.Qrcs) {
  1171. // Path checksum
  1172. qrc.QrcPathChecksum = this->PathCheckSum.getPart(qrc.QrcFile);
  1173. // Output file name
  1174. if (this->MultiConfig && !this->GlobalGen->IsXcode() &&
  1175. this->UseBetterGraph) {
  1176. qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
  1177. "_$<CONFIG>/qrc_", qrc.QrcName, ".cpp");
  1178. } else {
  1179. qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
  1180. "/qrc_", qrc.QrcName, ".cpp");
  1181. }
  1182. std::string const base = cmStrCat(this->Dir.Info, "/AutoRcc_",
  1183. qrc.QrcName, '_', qrc.QrcPathChecksum);
  1184. qrc.LockFile = cmStrCat(base, "_Lock.lock");
  1185. qrc.InfoFile = cmStrCat(base, "_Info.json");
  1186. this->ConfigFileNames(qrc.SettingsFile, cmStrCat(base, "_Used"), ".txt");
  1187. }
  1188. // rcc options
  1189. for (Qrc& qrc : this->Rcc.Qrcs) {
  1190. // Target options
  1191. std::vector<std::string> opts = optionsTarget;
  1192. // Merge computed "-name XYZ" option
  1193. {
  1194. std::string name = qrc.QrcName;
  1195. // Replace '-' with '_'. The former is not valid for symbol names.
  1196. std::replace(name.begin(), name.end(), '-', '_');
  1197. if (!qrc.Unique) {
  1198. name += cmStrCat('_', qrc.QrcPathChecksum);
  1199. }
  1200. std::vector<std::string> nameOpts;
  1201. nameOpts.emplace_back("-name");
  1202. nameOpts.emplace_back(std::move(name));
  1203. RccMergeOptions(opts, nameOpts, modernQt);
  1204. }
  1205. // Merge file option
  1206. RccMergeOptions(opts, qrc.Options, modernQt);
  1207. qrc.Options = std::move(opts);
  1208. }
  1209. // rcc resources
  1210. for (Qrc& qrc : this->Rcc.Qrcs) {
  1211. if (!qrc.Generated) {
  1212. std::string error;
  1213. if (this->MultiConfig && this->UseBetterGraph) {
  1214. for (auto const& config : this->ConfigsList) {
  1215. RccLister const lister(
  1216. this->Rcc.Executable.Config[config],
  1217. this->Rcc.ExecutableFeatures.Config[config]->ListOptions);
  1218. if (!lister.list(qrc.QrcFile, qrc.Resources.Config[config],
  1219. error)) {
  1220. cmSystemTools::Error(error);
  1221. return false;
  1222. }
  1223. }
  1224. } else {
  1225. RccLister const lister(
  1226. this->Rcc.Executable.Default,
  1227. this->Rcc.ExecutableFeatures.Default->ListOptions);
  1228. if (!lister.list(qrc.QrcFile, qrc.Resources.Default, error)) {
  1229. cmSystemTools::Error(error);
  1230. return false;
  1231. }
  1232. }
  1233. }
  1234. }
  1235. }
  1236. return true;
  1237. }
  1238. bool cmQtAutoGenInitializer::InitAutogenTarget()
  1239. {
  1240. // Register info file as generated by CMake
  1241. this->Makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
  1242. // Determine whether to use a depfile for the AUTOGEN target.
  1243. bool const useDepfile = [this]() -> bool {
  1244. auto const& gen = this->GlobalGen->GetName();
  1245. return this->QtVersion >= IntegerVersion(5, 15) &&
  1246. (gen.find("Ninja") != std::string::npos ||
  1247. gen.find("Make") != std::string::npos);
  1248. }();
  1249. // Files provided by the autogen target
  1250. std::vector<std::string> autogenByproducts;
  1251. std::vector<std::string> timestampByproducts;
  1252. if (this->Moc.Enabled) {
  1253. this->AddGeneratedSource(this->Moc.CompilationFile, this->Moc, true);
  1254. if (useDepfile) {
  1255. if (this->CrossConfig &&
  1256. this->GlobalGen->GetName().find("Ninja") != std::string::npos &&
  1257. !this->UseBetterGraph) {
  1258. // Make all mocs_compilation_<CONFIG>.cpp files byproducts of the
  1259. // ${target}_autogen/timestamp custom command.
  1260. // We cannot just use Moc.CompilationFileGenex here, because that
  1261. // custom command runs cmake_autogen for each configuration.
  1262. for (auto const& p : this->Moc.CompilationFile.Config) {
  1263. timestampByproducts.push_back(p.second);
  1264. }
  1265. } else {
  1266. timestampByproducts.push_back(this->Moc.CompilationFileGenex);
  1267. }
  1268. } else {
  1269. autogenByproducts.push_back(this->Moc.CompilationFileGenex);
  1270. }
  1271. }
  1272. if (this->Uic.Enabled) {
  1273. for (auto const& file : this->Uic.UiHeaders) {
  1274. this->AddGeneratedSource(file.first, this->Uic);
  1275. autogenByproducts.push_back(file.second);
  1276. }
  1277. }
  1278. // Compose target comment
  1279. std::string autogenComment;
  1280. {
  1281. std::string tools;
  1282. if (this->Moc.Enabled) {
  1283. tools += "MOC";
  1284. }
  1285. if (this->Uic.Enabled) {
  1286. if (!tools.empty()) {
  1287. tools += " and ";
  1288. }
  1289. tools += "UIC";
  1290. }
  1291. autogenComment = cmStrCat("Automatic ", tools, " for target ",
  1292. this->GenTarget->GetName());
  1293. }
  1294. // Compose command lines
  1295. // FIXME: Take advantage of our per-config mocs_compilation_$<CONFIG>.cpp
  1296. // instead of fiddling with the include directories
  1297. bool constexpr stdPipesUTF8 = true;
  1298. cmCustomCommandLines commandLines;
  1299. AddCMakeProcessToCommandLines(this->AutogenTarget.InfoFile, "cmake_autogen",
  1300. commandLines);
  1301. // Use PRE_BUILD on demand
  1302. bool usePRE_BUILD = false;
  1303. if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
  1304. // Under VS use a PRE_BUILD event instead of a separate target to
  1305. // reduce the number of targets loaded into the IDE.
  1306. // This also works around a VS 11 bug that may skip updating the target:
  1307. // https://connect.microsoft.com/VisualStudio/feedback/details/769495
  1308. usePRE_BUILD = true;
  1309. }
  1310. // Disable PRE_BUILD in some cases
  1311. if (usePRE_BUILD) {
  1312. // Cannot use PRE_BUILD with file depends
  1313. if (!this->AutogenTarget.DependFiles.empty()) {
  1314. usePRE_BUILD = false;
  1315. }
  1316. // Cannot use PRE_BUILD when a global autogen target is in place
  1317. if (this->AutogenTarget.GlobalTarget) {
  1318. usePRE_BUILD = false;
  1319. }
  1320. }
  1321. // Create the autogen target/command
  1322. if (usePRE_BUILD) {
  1323. // Add additional autogen target dependencies to origin target
  1324. for (cmTarget const* depTarget : this->AutogenTarget.DependTargets) {
  1325. this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
  1326. this->Makefile);
  1327. }
  1328. if (!this->Uic.UiFilesNoOptions.empty() ||
  1329. !this->Uic.UiFilesWithOptions.empty()) {
  1330. // Add a generated timestamp file
  1331. ConfigString timestampFile;
  1332. std::string timestampFileGenex;
  1333. ConfigFileNamesAndGenex(timestampFile, timestampFileGenex,
  1334. cmStrCat(this->Dir.Build, "/autouic"_s),
  1335. ".stamp"_s);
  1336. this->AddGeneratedSource(timestampFile, this->Uic);
  1337. // Add a step in the pre-build command to touch the timestamp file
  1338. commandLines.push_back(
  1339. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E", "touch",
  1340. timestampFileGenex }));
  1341. // UIC needs to be re-run if any of the known UI files change or the
  1342. // executable itself has been updated
  1343. auto uicDependencies = this->Uic.UiFilesNoOptions;
  1344. for (auto const& uiFile : this->Uic.UiFilesWithOptions) {
  1345. uicDependencies.push_back(uiFile.first);
  1346. }
  1347. AddAutogenExecutableToDependencies(this->Uic, uicDependencies);
  1348. // Add a rule file to cause the target to build if a dependency has
  1349. // changed, which will trigger the pre-build command to run autogen
  1350. auto cc = cm::make_unique<cmCustomCommand>();
  1351. cc->SetOutputs(timestampFileGenex);
  1352. cc->SetDepends(uicDependencies);
  1353. cc->SetComment("");
  1354. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1355. cc->SetEscapeOldStyle(false);
  1356. cc->SetStdPipesUTF8(stdPipesUTF8);
  1357. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1358. }
  1359. // Add the pre-build command directly to bypass the OBJECT_LIBRARY
  1360. // rejection in cmMakefile::AddCustomCommandToTarget because we know
  1361. // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
  1362. //
  1363. // PRE_BUILD does not support file dependencies!
  1364. cmCustomCommand cc;
  1365. cc.SetByproducts(autogenByproducts);
  1366. cc.SetCommandLines(commandLines);
  1367. cc.SetComment(autogenComment.c_str());
  1368. cc.SetBacktrace(this->Makefile->GetBacktrace());
  1369. cc.SetWorkingDirectory(this->Dir.Work.c_str());
  1370. cc.SetStdPipesUTF8(stdPipesUTF8);
  1371. cc.SetEscapeOldStyle(false);
  1372. cc.SetEscapeAllowMakeVars(true);
  1373. this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
  1374. } else {
  1375. // Add link library target dependencies to the autogen target
  1376. // dependencies
  1377. if (this->AutogenTarget.DependOrigin) {
  1378. // add_dependencies/addUtility do not support generator expressions.
  1379. // We depend only on the libraries found in all configs therefore.
  1380. std::map<cmGeneratorTarget const*, std::size_t> targetsPartOfAllConfigs;
  1381. for (std::string const& config : this->ConfigsList) {
  1382. // The same target might appear multiple times in a config, but we
  1383. // should only count it once.
  1384. std::set<cmGeneratorTarget const*> seenTargets;
  1385. cmLinkImplementationLibraries const* libs =
  1386. this->GenTarget->GetLinkImplementationLibraries(
  1387. config, cmGeneratorTarget::UseTo::Link);
  1388. if (libs) {
  1389. for (cmLinkItem const& item : libs->Libraries) {
  1390. cmGeneratorTarget const* libTarget = item.Target;
  1391. if (libTarget &&
  1392. !StaticLibraryCycle(this->GenTarget, libTarget, config) &&
  1393. seenTargets.insert(libTarget).second) {
  1394. // Increment target config count
  1395. targetsPartOfAllConfigs[libTarget]++;
  1396. }
  1397. }
  1398. }
  1399. }
  1400. for (auto const& item : targetsPartOfAllConfigs) {
  1401. if (item.second == this->ConfigsList.size()) {
  1402. this->AutogenTarget.DependTargets.insert(item.first->Target);
  1403. }
  1404. }
  1405. }
  1406. cmTarget* timestampTarget = nullptr;
  1407. std::vector<std::string> dependencies(
  1408. this->AutogenTarget.DependFiles.begin(),
  1409. this->AutogenTarget.DependFiles.end());
  1410. if (useDepfile) {
  1411. // Create a custom command that generates a timestamp file and
  1412. // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
  1413. //
  1414. // Also create an additional '_autogen_timestamp_deps' that the custom
  1415. // command will depend on. It will have no sources or commands to
  1416. // execute, but it will have dependencies that would originally be
  1417. // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
  1418. // serve as a list of order-only dependencies for the custom command,
  1419. // without forcing the custom command to re-execute.
  1420. //
  1421. // The dependency tree would then look like
  1422. // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
  1423. // '_autogen' target.
  1424. auto const timestampTargetName =
  1425. cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
  1426. auto cc = cm::make_unique<cmCustomCommand>();
  1427. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1428. cc->SetDepends(dependencies);
  1429. cc->SetEscapeOldStyle(false);
  1430. timestampTarget = this->LocalGen->AddUtilityCommand(timestampTargetName,
  1431. true, std::move(cc));
  1432. this->LocalGen->AddGeneratorTarget(
  1433. cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
  1434. // Set FOLDER property on the timestamp target, so it appears in the
  1435. // appropriate folder in an IDE or in the file api.
  1436. if (!this->TargetsFolder.empty()) {
  1437. timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
  1438. }
  1439. // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
  1440. // moc and uic executables (whichever are enabled).
  1441. dependencies.clear();
  1442. dependencies.push_back(timestampTargetName);
  1443. AddAutogenExecutableToDependencies(this->Moc, dependencies);
  1444. AddAutogenExecutableToDependencies(this->Uic, dependencies);
  1445. std::string outputFile;
  1446. std::string depFile;
  1447. // Create the custom command that outputs the timestamp file.
  1448. if (this->MultiConfig && this->UseBetterGraph) {
  1449. // create timestamp file with $<CONFIG> in the name so that
  1450. // every cmake_autogen target has its own timestamp file
  1451. std::string const configView = "$<CONFIG>";
  1452. std::string const timestampFileWithoutConfig = "timestamp_";
  1453. std::string const depFileWithoutConfig =
  1454. cmStrCat(this->Dir.Build, "/deps_");
  1455. std::string const timestampFileName =
  1456. timestampFileWithoutConfig + configView;
  1457. outputFile = cmStrCat(this->Dir.Build, '/', timestampFileName);
  1458. auto const depFileWithConfig =
  1459. cmStrCat(depFileWithoutConfig, configView);
  1460. depFile = depFileWithConfig;
  1461. commandLines.push_back(cmMakeCommandLine(
  1462. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1463. ConfigString outputFileWithConfig;
  1464. for (std::string const& config : this->ConfigsList) {
  1465. auto tempTimestampFileName = timestampFileWithoutConfig + config;
  1466. auto tempDepFile = depFileWithoutConfig + config;
  1467. outputFileWithConfig.Config[config] = tempTimestampFileName;
  1468. this->AutogenTarget.DepFileRuleName.Config[config] =
  1469. cmStrCat(this->Dir.RelativeBuild, '/', tempTimestampFileName);
  1470. this->AutogenTarget.DepFile.Config[config] = tempDepFile;
  1471. }
  1472. this->AddGeneratedSource(outputFileWithConfig, this->Moc);
  1473. } else {
  1474. cm::string_view const timestampFileName = "timestamp";
  1475. outputFile = cmStrCat(this->Dir.Build, '/', timestampFileName);
  1476. this->AutogenTarget.DepFile.Default =
  1477. cmStrCat(this->Dir.Build, "/deps");
  1478. depFile = this->AutogenTarget.DepFile.Default;
  1479. this->AutogenTarget.DepFileRuleName.Default =
  1480. cmStrCat(this->Dir.RelativeBuild, '/', timestampFileName);
  1481. commandLines.push_back(cmMakeCommandLine(
  1482. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1483. this->AddGeneratedSource(outputFile, this->Moc);
  1484. }
  1485. cc = cm::make_unique<cmCustomCommand>();
  1486. cc->SetOutputs(outputFile);
  1487. cc->SetByproducts(timestampByproducts);
  1488. cc->SetDepends(dependencies);
  1489. cc->SetCommandLines(commandLines);
  1490. cc->SetComment(autogenComment.c_str());
  1491. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1492. cc->SetEscapeOldStyle(false);
  1493. cc->SetDepfile(depFile);
  1494. cc->SetStdPipesUTF8(stdPipesUTF8);
  1495. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1496. dependencies.clear();
  1497. dependencies.emplace_back(std::move(outputFile));
  1498. commandLines.clear();
  1499. autogenComment.clear();
  1500. }
  1501. // Create autogen target
  1502. auto cc = cm::make_unique<cmCustomCommand>();
  1503. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1504. cc->SetByproducts(autogenByproducts);
  1505. cc->SetDepends(dependencies);
  1506. cc->SetCommandLines(commandLines);
  1507. cc->SetEscapeOldStyle(false);
  1508. cc->SetComment(autogenComment.c_str());
  1509. cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
  1510. this->AutogenTarget.Name, true, std::move(cc));
  1511. // Create autogen generator target
  1512. this->LocalGen->AddGeneratorTarget(
  1513. cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
  1514. // Order the autogen target(s) just before the original target.
  1515. cmTarget* orderTarget = timestampTarget ? timestampTarget : autogenTarget;
  1516. // Forward origin utilities to autogen target
  1517. if (this->AutogenTarget.DependOrigin) {
  1518. for (BT<std::pair<std::string, bool>> const& depName :
  1519. this->GenTarget->GetUtilities()) {
  1520. orderTarget->AddUtility(depName.Value.first, false, this->Makefile);
  1521. }
  1522. }
  1523. // Add additional autogen target dependencies to autogen target
  1524. for (cmTarget const* depTarget : this->AutogenTarget.DependTargets) {
  1525. orderTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
  1526. }
  1527. // Set FOLDER property in autogen target
  1528. if (!this->TargetsFolder.empty()) {
  1529. autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
  1530. }
  1531. // Add autogen target to the origin target dependencies
  1532. this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
  1533. this->Makefile);
  1534. // Add autogen target to the global autogen target dependencies
  1535. if (this->AutogenTarget.GlobalTarget) {
  1536. this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
  1537. this->AutogenTarget.Name);
  1538. }
  1539. }
  1540. return true;
  1541. }
  1542. void cmQtAutoGenInitializer::AddCMakeProcessToCommandLines(
  1543. std::string const& infoFile, std::string const& processName,
  1544. cmCustomCommandLines& commandLines)
  1545. {
  1546. std::vector<std::string> autogenConfigs;
  1547. this->GlobalGen->GetQtAutoGenConfigs(autogenConfigs);
  1548. if (this->CrossConfig && this->UseBetterGraph) {
  1549. commandLines.push_back(cmMakeCommandLine(
  1550. { cmSystemTools::GetCMakeCommand(), "-E", processName, infoFile,
  1551. "$<CONFIG>", "$<COMMAND_CONFIG:$<CONFIG>>" }));
  1552. } else if ((this->MultiConfig && this->GlobalGen->IsXcode()) ||
  1553. this->CrossConfig) {
  1554. auto const& configs =
  1555. processName == "cmake_autorcc" ? this->ConfigsList : autogenConfigs;
  1556. for (std::string const& config : configs) {
  1557. commandLines.push_back(
  1558. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1559. processName, infoFile, config }));
  1560. }
  1561. } else {
  1562. std::string autoInfoFileConfig;
  1563. if (this->MultiConfig) {
  1564. autoInfoFileConfig = "$<CONFIG>";
  1565. } else {
  1566. autoInfoFileConfig = autogenConfigs[0];
  1567. }
  1568. commandLines.push_back(
  1569. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E", processName,
  1570. infoFile, autoInfoFileConfig }));
  1571. }
  1572. }
  1573. bool cmQtAutoGenInitializer::InitRccTargets()
  1574. {
  1575. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1576. // Register info file as generated by CMake
  1577. this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
  1578. // Register file at target
  1579. {
  1580. cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
  1581. sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
  1582. }
  1583. std::vector<std::string> ccOutput{ qrc.OutputFile };
  1584. // Add the .qrc and info file to the custom command dependencies
  1585. std::vector<std::string> ccDepends{ qrc.QrcFile, qrc.InfoFile };
  1586. cmCustomCommandLines commandLines;
  1587. AddCMakeProcessToCommandLines(qrc.InfoFile, "cmake_autorcc", commandLines);
  1588. std::string const ccComment =
  1589. cmStrCat("Automatic RCC for ",
  1590. FileProjectRelativePath(this->Makefile, qrc.QrcFile));
  1591. auto cc = cm::make_unique<cmCustomCommand>();
  1592. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1593. cc->SetCommandLines(commandLines);
  1594. cc->SetComment(ccComment.c_str());
  1595. cc->SetStdPipesUTF8(true);
  1596. if (qrc.Generated || this->Rcc.GlobalTarget) {
  1597. // Create custom rcc target
  1598. std::string ccName;
  1599. {
  1600. ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
  1601. if (!qrc.Unique) {
  1602. ccName += cmStrCat('_', qrc.QrcPathChecksum);
  1603. }
  1604. cc->SetByproducts(ccOutput);
  1605. cc->SetDepends(ccDepends);
  1606. cc->SetEscapeOldStyle(false);
  1607. cmTarget* autoRccTarget =
  1608. this->LocalGen->AddUtilityCommand(ccName, true, std::move(cc));
  1609. // Create autogen generator target
  1610. this->LocalGen->AddGeneratorTarget(
  1611. cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
  1612. // Set FOLDER property in autogen target
  1613. if (!this->TargetsFolder.empty()) {
  1614. autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
  1615. }
  1616. if (!this->Rcc.ExecutableTargetName.empty()) {
  1617. autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
  1618. this->Makefile);
  1619. }
  1620. }
  1621. // Add autogen target to the origin target dependencies
  1622. this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
  1623. // Add autogen target to the global autogen target dependencies
  1624. if (this->Rcc.GlobalTarget) {
  1625. this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
  1626. }
  1627. } else {
  1628. // Create custom rcc command
  1629. {
  1630. // Add the resource files to the dependencies
  1631. if (this->MultiConfig && this->UseBetterGraph) {
  1632. for (auto const& config : this->ConfigsList) {
  1633. // Add resource file to the custom command dependencies
  1634. auto resourceFilesWithConfig = cmStrCat(
  1635. "$<$<CONFIG:", config,
  1636. ">:", cmList{ qrc.Resources.Config.at(config) }.to_string(),
  1637. '>');
  1638. ccDepends.emplace_back(std::move(resourceFilesWithConfig));
  1639. }
  1640. } else {
  1641. for (std::string const& fileName : qrc.Resources.Default) {
  1642. // Add resource file to the custom command dependencies
  1643. ccDepends.push_back(fileName);
  1644. }
  1645. }
  1646. if (!this->Rcc.ExecutableTargetName.empty()) {
  1647. ccDepends.push_back(this->Rcc.ExecutableTargetName);
  1648. }
  1649. AddAutogenExecutableToDependencies(this->Rcc, ccDepends);
  1650. cc->SetOutputs(ccOutput);
  1651. cc->SetDepends(ccDepends);
  1652. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1653. }
  1654. // Reconfigure when .qrc file changes
  1655. this->Makefile->AddCMakeDependFile(qrc.QrcFile);
  1656. }
  1657. }
  1658. return true;
  1659. }
  1660. bool cmQtAutoGenInitializer::SetupCustomTargets()
  1661. {
  1662. // Create info directory on demand
  1663. if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
  1664. cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
  1665. Quoted(this->Dir.Info)));
  1666. return false;
  1667. }
  1668. // Generate autogen target info file
  1669. if (this->MocOrUicEnabled()) {
  1670. // Write autogen target info files
  1671. if (!this->SetupWriteAutogenInfo()) {
  1672. return false;
  1673. }
  1674. }
  1675. // Write AUTORCC info files
  1676. return !this->Rcc.Enabled || this->SetupWriteRccInfo();
  1677. }
  1678. bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
  1679. {
  1680. // Utility lambdas
  1681. auto MfDef = [this](std::string const& key) {
  1682. return this->Makefile->GetSafeDefinition(key);
  1683. };
  1684. // Filtered headers and sources
  1685. std::set<std::string> moc_skip;
  1686. std::set<std::string> uic_skip;
  1687. std::vector<MUFile const*> headers;
  1688. std::vector<MUFile const*> sources;
  1689. // Filter headers
  1690. {
  1691. headers.reserve(this->AutogenTarget.Headers.size());
  1692. for (auto const& pair : this->AutogenTarget.Headers) {
  1693. MUFile const* const muf = pair.second.get();
  1694. if (muf->SkipMoc) {
  1695. moc_skip.insert(muf->FullPath);
  1696. }
  1697. if (muf->SkipUic) {
  1698. uic_skip.insert(muf->FullPath);
  1699. }
  1700. if (muf->Generated && !this->CMP0071Accept) {
  1701. continue;
  1702. }
  1703. if (muf->MocIt || muf->UicIt) {
  1704. headers.emplace_back(muf);
  1705. }
  1706. }
  1707. std::sort(headers.begin(), headers.end(),
  1708. [](MUFile const* a, MUFile const* b) {
  1709. return (a->FullPath < b->FullPath);
  1710. });
  1711. }
  1712. // Filter sources
  1713. {
  1714. sources.reserve(this->AutogenTarget.Sources.size());
  1715. for (auto const& pair : this->AutogenTarget.Sources) {
  1716. MUFile const* const muf = pair.second.get();
  1717. if (muf->Generated && !this->CMP0071Accept) {
  1718. continue;
  1719. }
  1720. if (muf->SkipMoc) {
  1721. moc_skip.insert(muf->FullPath);
  1722. }
  1723. if (muf->SkipUic) {
  1724. uic_skip.insert(muf->FullPath);
  1725. }
  1726. if (muf->MocIt || muf->UicIt) {
  1727. sources.emplace_back(muf);
  1728. }
  1729. }
  1730. std::sort(sources.begin(), sources.end(),
  1731. [](MUFile const* a, MUFile const* b) {
  1732. return (a->FullPath < b->FullPath);
  1733. });
  1734. }
  1735. // Info writer
  1736. InfoWriter info;
  1737. // General
  1738. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1739. info.SetBool("CROSS_CONFIG", this->CrossConfig);
  1740. info.SetBool("USE_BETTER_GRAPH", this->UseBetterGraph);
  1741. info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
  1742. #ifdef _WIN32
  1743. info.SetUInt("AUTOGEN_COMMAND_LINE_LENGTH_MAX",
  1744. this->AutogenTarget.MaxCommandLineLength);
  1745. #endif
  1746. info.SetUInt("VERBOSITY", this->Verbosity);
  1747. // Directories
  1748. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1749. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1750. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1751. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1752. info.Set("BUILD_DIR", this->Dir.Build);
  1753. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1754. info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
  1755. info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
  1756. info.SetConfig("QT_MOC_EXECUTABLE", this->Moc.Executable);
  1757. info.SetConfig("QT_UIC_EXECUTABLE", this->Uic.Executable);
  1758. info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
  1759. info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
  1760. info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
  1761. info.SetConfig("DEP_FILE", this->AutogenTarget.DepFile);
  1762. info.SetConfig("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
  1763. info.SetArray("CMAKE_LIST_FILES", this->Makefile->GetListFiles());
  1764. info.SetArray("HEADER_EXTENSIONS",
  1765. this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
  1766. auto cfgArray = [this](std::vector<size_t> const& configs) -> Json::Value {
  1767. Json::Value value;
  1768. if (!configs.empty()) {
  1769. value = Json::arrayValue;
  1770. for (size_t ci : configs) {
  1771. value.append(this->ConfigsList[ci]);
  1772. }
  1773. }
  1774. return value;
  1775. };
  1776. info.SetArrayArray("HEADERS", headers,
  1777. [this, &cfgArray](Json::Value& jval, MUFile const* muf) {
  1778. jval.resize(4u);
  1779. jval[0u] = muf->FullPath;
  1780. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm',
  1781. muf->UicIt ? 'U' : 'u');
  1782. jval[2u] = this->GetMocBuildPath(*muf);
  1783. jval[3u] = cfgArray(muf->Configs);
  1784. });
  1785. info.SetArrayArray(
  1786. "SOURCES", sources, [&cfgArray](Json::Value& jval, MUFile const* muf) {
  1787. jval.resize(3u);
  1788. jval[0u] = muf->FullPath;
  1789. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
  1790. jval[2u] = cfgArray(muf->Configs);
  1791. });
  1792. // Write moc settings
  1793. if (this->Moc.Enabled) {
  1794. info.SetArray("MOC_SKIP", moc_skip);
  1795. info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
  1796. info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
  1797. info.SetArray("MOC_OPTIONS", this->Moc.Options);
  1798. info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
  1799. info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
  1800. EvaluatedTargetPropertyEntries InterfaceAutoMocMacroNamesEntries;
  1801. if (this->MultiConfig) {
  1802. for (auto const& cfg : this->ConfigsList) {
  1803. if (!cfg.empty()) {
  1804. cmGeneratorExpressionDAGChecker dagChecker{
  1805. this->GenTarget, "AUTOMOC_MACRO_NAMES", nullptr,
  1806. nullptr, this->LocalGen, cfg,
  1807. };
  1808. AddInterfaceEntries(this->GenTarget, cfg,
  1809. "INTERFACE_AUTOMOC_MACRO_NAMES", "CXX",
  1810. &dagChecker, InterfaceAutoMocMacroNamesEntries,
  1811. IncludeRuntimeInterface::Yes);
  1812. }
  1813. }
  1814. } else {
  1815. cmGeneratorExpressionDAGChecker dagChecker{
  1816. this->GenTarget, "AUTOMOC_MACRO_NAMES", nullptr,
  1817. nullptr, this->LocalGen, this->ConfigDefault,
  1818. };
  1819. AddInterfaceEntries(this->GenTarget, this->ConfigDefault,
  1820. "INTERFACE_AUTOMOC_MACRO_NAMES", "CXX", &dagChecker,
  1821. InterfaceAutoMocMacroNamesEntries,
  1822. IncludeRuntimeInterface::Yes);
  1823. }
  1824. for (auto const& entry : InterfaceAutoMocMacroNamesEntries.Entries) {
  1825. this->Moc.MacroNames.insert(this->Moc.MacroNames.end(),
  1826. entry.Values.begin(), entry.Values.end());
  1827. }
  1828. this->Moc.MacroNames.erase(cmRemoveDuplicates(this->Moc.MacroNames),
  1829. this->Moc.MacroNames.end());
  1830. info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
  1831. info.SetArrayArray(
  1832. "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
  1833. [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
  1834. jval.resize(2u);
  1835. jval[0u] = pair.first;
  1836. jval[1u] = pair.second;
  1837. });
  1838. info.SetConfig("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
  1839. info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
  1840. cmStandardLevelResolver const resolver{ this->Makefile };
  1841. auto const CompileOptionFlag =
  1842. resolver.GetCompileOptionDef(this->GenTarget, "CXX", "");
  1843. auto const CompileOptionValue =
  1844. this->GenTarget->Makefile->GetSafeDefinition(CompileOptionFlag);
  1845. if (!CompileOptionValue.empty()) {
  1846. if (this->Moc.PredefsCmd.size() >= 3) {
  1847. this->Moc.PredefsCmd.insert(this->Moc.PredefsCmd.begin() + 1,
  1848. CompileOptionValue);
  1849. }
  1850. }
  1851. info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
  1852. }
  1853. // Write uic settings
  1854. if (this->Uic.Enabled) {
  1855. // Add skipped .ui files
  1856. uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
  1857. info.SetArray("UIC_SKIP", uic_skip);
  1858. info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFilesWithOptions,
  1859. [](Json::Value& jval, UicT::UiFileT const& uiFile) {
  1860. jval.resize(2u);
  1861. jval[0u] = uiFile.first;
  1862. InfoWriter::MakeStringArray(jval[1u], uiFile.second);
  1863. });
  1864. info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
  1865. info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
  1866. }
  1867. info.Save(this->AutogenTarget.InfoFile);
  1868. return true;
  1869. }
  1870. bool cmQtAutoGenInitializer::SetupWriteRccInfo()
  1871. {
  1872. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1873. // Utility lambdas
  1874. auto MfDef = [this](std::string const& key) {
  1875. return this->Makefile->GetSafeDefinition(key);
  1876. };
  1877. InfoWriter info;
  1878. // General
  1879. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1880. info.SetBool("CROSS_CONFIG", this->CrossConfig);
  1881. info.SetBool("USE_BETTER_GRAPH", this->UseBetterGraph);
  1882. info.SetUInt("VERBOSITY", this->Verbosity);
  1883. info.Set("GENERATOR", this->GlobalGen->GetName());
  1884. // Files
  1885. info.Set("LOCK_FILE", qrc.LockFile);
  1886. info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
  1887. // Directories
  1888. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1889. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1890. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1891. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1892. info.Set("BUILD_DIR", this->Dir.Build);
  1893. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1894. // rcc executable
  1895. info.SetConfig("RCC_EXECUTABLE", this->Rcc.Executable);
  1896. info.SetConfigArray(
  1897. "RCC_LIST_OPTIONS",
  1898. generateListOptions(this->Rcc.ExecutableFeatures, this->MultiConfig));
  1899. // qrc file
  1900. info.Set("SOURCE", qrc.QrcFile);
  1901. info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
  1902. info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
  1903. info.SetArray("OPTIONS", qrc.Options);
  1904. info.SetConfigArray("INPUTS", qrc.Resources);
  1905. info.Save(qrc.InfoFile);
  1906. }
  1907. return true;
  1908. }
  1909. cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
  1910. std::string const& filename)
  1911. {
  1912. cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
  1913. gFile->MarkAsGenerated();
  1914. gFile->SetProperty("SKIP_AUTOGEN", "1");
  1915. gFile->SetProperty("SKIP_LINTING", "ON");
  1916. gFile->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  1917. return gFile;
  1918. }
  1919. cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
  1920. std::string const& filename, GenVarsT const& genVars, bool prepend)
  1921. {
  1922. // Register source at makefile
  1923. cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
  1924. // Add source file to target
  1925. this->GenTarget->AddSource(filename, prepend);
  1926. // Add source file to source group
  1927. this->AddToSourceGroup(filename, genVars.GenNameUpper);
  1928. return gFile;
  1929. }
  1930. void cmQtAutoGenInitializer::AddGeneratedSource(ConfigString const& filename,
  1931. GenVarsT const& genVars,
  1932. bool prepend)
  1933. {
  1934. // XXX(xcode-per-cfg-src): Drop the Xcode-specific part of the condition
  1935. // when the Xcode generator supports per-config sources.
  1936. if (!this->MultiConfig || this->GlobalGen->IsXcode()) {
  1937. cmSourceFile* sf =
  1938. this->AddGeneratedSource(filename.Default, genVars, prepend);
  1939. handleSkipPch(sf);
  1940. return;
  1941. }
  1942. for (auto const& cfg : this->ConfigsList) {
  1943. std::string const& filenameCfg = filename.Config.at(cfg);
  1944. // Register source at makefile
  1945. cmSourceFile* sf = this->RegisterGeneratedSource(filenameCfg);
  1946. handleSkipPch(sf);
  1947. // Add source file to target for this configuration.
  1948. this->GenTarget->AddSource(
  1949. cmStrCat("$<$<CONFIG:"_s, cfg, ">:"_s, filenameCfg, ">"_s), prepend);
  1950. // Add source file to source group
  1951. this->AddToSourceGroup(filenameCfg, genVars.GenNameUpper);
  1952. }
  1953. }
  1954. void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
  1955. cm::string_view genNameUpper)
  1956. {
  1957. cmSourceGroup* sourceGroup = nullptr;
  1958. // Acquire source group
  1959. {
  1960. std::string property;
  1961. std::string groupName;
  1962. {
  1963. // Prefer generator specific source group name
  1964. std::initializer_list<std::string> const props{
  1965. cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
  1966. };
  1967. for (std::string const& prop : props) {
  1968. cmValue propName = this->Makefile->GetState()->GetGlobalProperty(prop);
  1969. if (cmNonempty(propName)) {
  1970. groupName = *propName;
  1971. property = prop;
  1972. break;
  1973. }
  1974. }
  1975. }
  1976. // Generate a source group on demand
  1977. if (!groupName.empty()) {
  1978. sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
  1979. if (!sourceGroup) {
  1980. cmSystemTools::Error(
  1981. cmStrCat(genNameUpper, " error in ", property,
  1982. ": Could not find or create the source group ",
  1983. cmQtAutoGen::Quoted(groupName)));
  1984. }
  1985. }
  1986. }
  1987. if (sourceGroup) {
  1988. sourceGroup->AddGroupFile(fileName);
  1989. }
  1990. }
  1991. void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
  1992. {
  1993. this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName);
  1994. }
  1995. void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
  1996. cm::string_view prefix,
  1997. cm::string_view suffix)
  1998. {
  1999. configString.Default = cmStrCat(prefix, suffix);
  2000. if (this->MultiConfig) {
  2001. for (auto const& cfg : this->ConfigsList) {
  2002. configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
  2003. }
  2004. }
  2005. }
  2006. void cmQtAutoGenInitializer::ConfigFileNamesAndGenex(
  2007. ConfigString& configString, std::string& genex, cm::string_view const prefix,
  2008. cm::string_view const suffix)
  2009. {
  2010. this->ConfigFileNames(configString, prefix, suffix);
  2011. if (this->MultiConfig) {
  2012. genex = cmStrCat(prefix, "_$<CONFIG>"_s, suffix);
  2013. } else {
  2014. genex = configString.Default;
  2015. }
  2016. }
  2017. void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
  2018. {
  2019. this->AddCleanFile(configString.Default);
  2020. if (this->MultiConfig) {
  2021. for (auto const& pair : configString.Config) {
  2022. this->AddCleanFile(pair.second);
  2023. }
  2024. }
  2025. }
  2026. static cmQtAutoGen::IntegerVersion parseMocVersion(std::string str)
  2027. {
  2028. cmQtAutoGen::IntegerVersion result;
  2029. static std::string const prelude = "moc ";
  2030. size_t const pos = str.find(prelude);
  2031. if (pos == std::string::npos) {
  2032. return result;
  2033. }
  2034. str.erase(0, prelude.size() + pos);
  2035. std::istringstream iss(str);
  2036. std::string major;
  2037. std::string minor;
  2038. if (!std::getline(iss, major, '.') || !std::getline(iss, minor, '.')) {
  2039. return result;
  2040. }
  2041. result.Major = static_cast<unsigned int>(std::stoi(major));
  2042. result.Minor = static_cast<unsigned int>(std::stoi(minor));
  2043. return result;
  2044. }
  2045. static cmQtAutoGen::IntegerVersion GetMocVersion(
  2046. std::string const& mocExecutablePath)
  2047. {
  2048. std::string capturedStdOut;
  2049. int exitCode;
  2050. if (!cmSystemTools::RunSingleCommand({ mocExecutablePath, "--version" },
  2051. &capturedStdOut, nullptr, &exitCode,
  2052. nullptr, cmSystemTools::OUTPUT_NONE)) {
  2053. return {};
  2054. }
  2055. if (exitCode != 0) {
  2056. return {};
  2057. }
  2058. return parseMocVersion(capturedStdOut);
  2059. }
  2060. static std::string FindMocExecutableFromMocTarget(cmMakefile const* makefile,
  2061. unsigned int qtMajorVersion)
  2062. {
  2063. std::string result;
  2064. std::string const mocTargetName = cmStrCat("Qt", qtMajorVersion, "::moc");
  2065. cmTarget const* mocTarget = makefile->FindTargetToUse(mocTargetName);
  2066. if (mocTarget) {
  2067. result = mocTarget->GetSafeProperty("IMPORTED_LOCATION");
  2068. }
  2069. return result;
  2070. }
  2071. std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
  2072. cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target,
  2073. std::string mocExecutable)
  2074. {
  2075. // Converts a char ptr to an unsigned int value
  2076. auto toUInt = [](char const* const input) -> unsigned int {
  2077. unsigned long tmp = 0;
  2078. if (input && cmStrToULong(input, &tmp)) {
  2079. return static_cast<unsigned int>(tmp);
  2080. }
  2081. return 0u;
  2082. };
  2083. auto toUInt2 = [](cmValue input) -> unsigned int {
  2084. unsigned long tmp = 0;
  2085. if (input && cmStrToULong(*input, &tmp)) {
  2086. return static_cast<unsigned int>(tmp);
  2087. }
  2088. return 0u;
  2089. };
  2090. // Initialize return value to a default
  2091. std::pair<IntegerVersion, unsigned int> res(
  2092. IntegerVersion(),
  2093. toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
  2094. "")));
  2095. // Acquire known Qt versions
  2096. std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
  2097. {
  2098. // Qt version variable prefixes
  2099. static std::initializer_list<
  2100. std::pair<cm::string_view, cm::string_view>> const keys{
  2101. { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
  2102. { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
  2103. { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
  2104. };
  2105. knownQtVersions.reserve(keys.size() * 2);
  2106. // Adds a version to the result (nullptr safe)
  2107. auto addVersion = [&knownQtVersions, &toUInt2](cmValue major,
  2108. cmValue minor) {
  2109. cmQtAutoGen::IntegerVersion ver(toUInt2(major), toUInt2(minor));
  2110. if (ver.Major != 0) {
  2111. knownQtVersions.emplace_back(ver);
  2112. }
  2113. };
  2114. // Read versions from variables
  2115. for (auto const& keyPair : keys) {
  2116. addVersion(target->Makefile->GetDefinition(std::string(keyPair.first)),
  2117. target->Makefile->GetDefinition(std::string(keyPair.second)));
  2118. }
  2119. // Read versions from directory properties
  2120. for (auto const& keyPair : keys) {
  2121. addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
  2122. target->Makefile->GetProperty(std::string(keyPair.second)));
  2123. }
  2124. }
  2125. // Evaluate known Qt versions
  2126. if (!knownQtVersions.empty()) {
  2127. if (res.second == 0) {
  2128. // No specific version was requested by the target:
  2129. // Use highest known Qt version.
  2130. res.first = knownQtVersions.at(0);
  2131. } else {
  2132. // Pick a version from the known versions:
  2133. for (auto const& it : knownQtVersions) {
  2134. if (it.Major == res.second) {
  2135. res.first = it;
  2136. break;
  2137. }
  2138. }
  2139. }
  2140. }
  2141. if (res.first.Major == 0) {
  2142. // We could not get the version number from variables or directory
  2143. // properties. This might happen if the find_package call for Qt is wrapped
  2144. // in a function. Try to find the moc executable path from the available
  2145. // targets and call "moc --version" to get the Qt version.
  2146. if (mocExecutable.empty()) {
  2147. mocExecutable =
  2148. FindMocExecutableFromMocTarget(target->Makefile, res.second);
  2149. }
  2150. if (!mocExecutable.empty()) {
  2151. res.first = GetMocVersion(mocExecutable);
  2152. }
  2153. }
  2154. return res;
  2155. }
  2156. std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
  2157. {
  2158. std::string res;
  2159. if (!muf.MocIt) {
  2160. return res;
  2161. }
  2162. std::string basePath =
  2163. cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
  2164. FileNameWithoutLastExtension(muf.FullPath));
  2165. res = cmStrCat(basePath, ".cpp");
  2166. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2167. return res;
  2168. }
  2169. // File name already emitted.
  2170. // Try appending the header suffix to the base path.
  2171. basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
  2172. res = cmStrCat(basePath, ".cpp");
  2173. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2174. return res;
  2175. }
  2176. // File name with header extension already emitted.
  2177. // Try adding a number to the base path.
  2178. constexpr std::size_t number_begin = 2;
  2179. constexpr std::size_t number_end = 256;
  2180. for (std::size_t ii = number_begin; ii != number_end; ++ii) {
  2181. res = cmStrCat(basePath, '_', ii, ".cpp");
  2182. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2183. return res;
  2184. }
  2185. }
  2186. // Output file name conflict (unlikely, but still...)
  2187. cmSystemTools::Error(
  2188. cmStrCat("moc output file name conflict for ", muf.FullPath));
  2189. return res;
  2190. }
  2191. bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
  2192. std::string const& executable,
  2193. bool ignoreMissingTarget) const
  2194. {
  2195. auto print_err = [this, &genVars](std::string const& err) {
  2196. cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
  2197. this->GenTarget->GetName(), ": ", err));
  2198. };
  2199. // Custom executable
  2200. {
  2201. std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
  2202. std::string const& val = this->GenTarget->Target->GetSafeProperty(prop);
  2203. if (!val.empty()) {
  2204. // Evaluate generator expression
  2205. {
  2206. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  2207. cmGeneratorExpression ge(*this->Makefile->GetCMakeInstance(), lfbt);
  2208. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
  2209. if (this->MultiConfig && this->UseBetterGraph) {
  2210. for (auto const& config : this->ConfigsList) {
  2211. genVars.Executable.Config[config] =
  2212. cge->Evaluate(this->LocalGen, config);
  2213. }
  2214. } else {
  2215. genVars.Executable.Default = cge->Evaluate(this->LocalGen, "");
  2216. }
  2217. }
  2218. if (genVars.Executable.Default.empty() &&
  2219. genVars.Executable.Config.empty() && !ignoreMissingTarget) {
  2220. print_err(prop + " evaluates to an empty value");
  2221. return false;
  2222. }
  2223. // Create empty compiler features.
  2224. if (this->MultiConfig && this->UseBetterGraph) {
  2225. for (auto const& config : this->ConfigsList) {
  2226. genVars.ExecutableFeatures.Config[config] =
  2227. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2228. }
  2229. } else {
  2230. genVars.ExecutableFeatures.Default =
  2231. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2232. }
  2233. return true;
  2234. }
  2235. }
  2236. // Find executable target
  2237. {
  2238. // Find executable target name
  2239. cm::string_view prefix;
  2240. if (this->QtVersion.Major == 4) {
  2241. prefix = "Qt4::";
  2242. } else if (this->QtVersion.Major == 5) {
  2243. prefix = "Qt5::";
  2244. } else if (this->QtVersion.Major == 6) {
  2245. prefix = "Qt6::";
  2246. }
  2247. std::string const targetName = cmStrCat(prefix, executable);
  2248. // Find target
  2249. cmGeneratorTarget* genTarget =
  2250. this->LocalGen->FindGeneratorTargetToUse(targetName);
  2251. if (genTarget) {
  2252. genVars.ExecutableTargetName = targetName;
  2253. genVars.ExecutableTarget = genTarget;
  2254. if (genTarget->IsImported()) {
  2255. if (this->MultiConfig && this->UseBetterGraph) {
  2256. for (auto const& config : this->ConfigsList) {
  2257. genVars.Executable.Config[config] =
  2258. genTarget->ImportedGetLocation(config);
  2259. }
  2260. } else {
  2261. genVars.Executable.Default =
  2262. genTarget->ImportedGetLocation(this->ConfigDefault);
  2263. }
  2264. } else {
  2265. if (this->MultiConfig && this->UseBetterGraph) {
  2266. for (auto const& config : this->ConfigsList) {
  2267. genVars.Executable.Config[config] = genTarget->GetLocation(config);
  2268. }
  2269. } else {
  2270. genVars.Executable.Default =
  2271. genTarget->GetLocation(this->ConfigDefault);
  2272. }
  2273. }
  2274. } else {
  2275. if (ignoreMissingTarget) {
  2276. // Create empty compiler features.
  2277. if (this->MultiConfig && this->UseBetterGraph) {
  2278. for (auto const& config : this->ConfigsList) {
  2279. genVars.ExecutableFeatures.Config[config] =
  2280. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2281. }
  2282. } else {
  2283. genVars.ExecutableFeatures.Default =
  2284. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2285. }
  2286. return true;
  2287. }
  2288. print_err(cmStrCat("Could not find ", executable, " executable target ",
  2289. targetName));
  2290. return false;
  2291. }
  2292. }
  2293. // Get executable features
  2294. {
  2295. std::string err;
  2296. genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
  2297. executable, genVars.Executable, err, this->MultiConfig,
  2298. this->UseBetterGraph);
  2299. if (this->MultiConfig && this->UseBetterGraph) {
  2300. for (auto const& config : this->ConfigsList) {
  2301. if (!genVars.ExecutableFeatures.Config[config]) {
  2302. if (!genVars.ExecutableFeatures.Config[config]) {
  2303. print_err(err);
  2304. return false;
  2305. }
  2306. }
  2307. }
  2308. } else {
  2309. if (!genVars.ExecutableFeatures.Default) {
  2310. print_err(err);
  2311. return false;
  2312. }
  2313. }
  2314. }
  2315. return true;
  2316. }
  2317. void cmQtAutoGenInitializer::handleSkipPch(cmSourceFile* sf)
  2318. {
  2319. bool skipPch = true;
  2320. for (auto const& pair : this->AutogenTarget.Sources) {
  2321. if (!pair.first->GetIsGenerated() &&
  2322. !pair.first->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  2323. skipPch = false;
  2324. }
  2325. }
  2326. if (skipPch) {
  2327. sf->SetProperty("SKIP_PRECOMPILE_HEADERS", "ON");
  2328. }
  2329. }