cmQtAutoGenInitializer.cxx 88 KB

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