cmGlobalGenerator.cxx 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmGlobalGenerator.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cstdio>
  7. #include <cstdlib>
  8. #include <cstring>
  9. #include <functional>
  10. #include <initializer_list>
  11. #include <iterator>
  12. #include <sstream>
  13. #include <utility>
  14. #include <cm/memory>
  15. #include <cmext/algorithm>
  16. #include "cmsys/Directory.hxx"
  17. #include "cmsys/FStream.hxx"
  18. #if defined(_WIN32) && !defined(__CYGWIN__)
  19. # include <windows.h>
  20. #endif
  21. #include "cmAlgorithms.h"
  22. #include "cmCPackPropertiesGenerator.h"
  23. #include "cmComputeTargetDepends.h"
  24. #include "cmCustomCommand.h"
  25. #include "cmCustomCommandLines.h"
  26. #include "cmDuration.h"
  27. #include "cmExportBuildFileGenerator.h"
  28. #include "cmExternalMakefileProjectGenerator.h"
  29. #include "cmGeneratedFileStream.h"
  30. #include "cmGeneratorExpression.h"
  31. #include "cmGeneratorTarget.h"
  32. #include "cmInstallGenerator.h"
  33. #include "cmLinkLineComputer.h"
  34. #include "cmListFileCache.h"
  35. #include "cmLocalGenerator.h"
  36. #include "cmMSVC60LinkLineComputer.h"
  37. #include "cmMakefile.h"
  38. #include "cmMessageType.h"
  39. #include "cmPolicies.h"
  40. #include "cmProperty.h"
  41. #include "cmRange.h"
  42. #include "cmSourceFile.h"
  43. #include "cmState.h"
  44. #include "cmStateDirectory.h"
  45. #include "cmStateTypes.h"
  46. #include "cmVersion.h"
  47. #include "cmWorkingDirectory.h"
  48. #include "cmake.h"
  49. #if !defined(CMAKE_BOOTSTRAP)
  50. # include <cm3p/json/value.h>
  51. # include <cm3p/json/writer.h>
  52. # include "cmCryptoHash.h"
  53. # include "cmQtAutoGenGlobalInitializer.h"
  54. #endif
  55. #if defined(_MSC_VER) && _MSC_VER >= 1800
  56. # define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
  57. #endif
  58. const std::string kCMAKE_PLATFORM_INFO_INITIALIZED =
  59. "CMAKE_PLATFORM_INFO_INITIALIZED";
  60. class cmInstalledFile;
  61. bool cmTarget::StrictTargetComparison::operator()(cmTarget const* t1,
  62. cmTarget const* t2) const
  63. {
  64. int nameResult = strcmp(t1->GetName().c_str(), t2->GetName().c_str());
  65. if (nameResult == 0) {
  66. return strcmp(t1->GetMakefile()->GetCurrentBinaryDirectory().c_str(),
  67. t2->GetMakefile()->GetCurrentBinaryDirectory().c_str()) < 0;
  68. }
  69. return nameResult < 0;
  70. }
  71. cmGlobalGenerator::cmGlobalGenerator(cmake* cm)
  72. : CMakeInstance(cm)
  73. {
  74. // By default the .SYMBOLIC dependency is not needed on symbolic rules.
  75. this->NeedSymbolicMark = false;
  76. // by default use the native paths
  77. this->ForceUnixPaths = false;
  78. // By default do not try to support color.
  79. this->ToolSupportsColor = false;
  80. // By default do not use link scripts.
  81. this->UseLinkScript = false;
  82. // Whether an install target is needed.
  83. this->InstallTargetEnabled = false;
  84. // how long to let try compiles run
  85. this->TryCompileTimeout = cmDuration::zero();
  86. this->CurrentConfigureMakefile = nullptr;
  87. this->TryCompileOuterMakefile = nullptr;
  88. this->ConfigureDoneCMP0026AndCMP0024 = false;
  89. this->FirstTimeProgress = 0.0f;
  90. this->RecursionDepth = 0;
  91. cm->GetState()->SetIsGeneratorMultiConfig(false);
  92. cm->GetState()->SetMinGWMake(false);
  93. cm->GetState()->SetMSYSShell(false);
  94. cm->GetState()->SetNMake(false);
  95. cm->GetState()->SetWatcomWMake(false);
  96. cm->GetState()->SetWindowsShell(false);
  97. cm->GetState()->SetWindowsVSIDE(false);
  98. }
  99. cmGlobalGenerator::~cmGlobalGenerator()
  100. {
  101. this->ClearGeneratorMembers();
  102. }
  103. #if !defined(CMAKE_BOOTSTRAP)
  104. Json::Value cmGlobalGenerator::GetJson() const
  105. {
  106. Json::Value generator = Json::objectValue;
  107. generator["name"] = this->GetName();
  108. generator["multiConfig"] = this->IsMultiConfig();
  109. return generator;
  110. }
  111. #endif
  112. bool cmGlobalGenerator::SetGeneratorInstance(std::string const& i,
  113. cmMakefile* mf)
  114. {
  115. if (i.empty()) {
  116. return true;
  117. }
  118. std::ostringstream e;
  119. /* clang-format off */
  120. e <<
  121. "Generator\n"
  122. " " << this->GetName() << "\n"
  123. "does not support instance specification, but instance\n"
  124. " " << i << "\n"
  125. "was specified.";
  126. /* clang-format on */
  127. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  128. return false;
  129. }
  130. bool cmGlobalGenerator::SetGeneratorPlatform(std::string const& p,
  131. cmMakefile* mf)
  132. {
  133. if (p.empty()) {
  134. return true;
  135. }
  136. std::ostringstream e;
  137. /* clang-format off */
  138. e <<
  139. "Generator\n"
  140. " " << this->GetName() << "\n"
  141. "does not support platform specification, but platform\n"
  142. " " << p << "\n"
  143. "was specified.";
  144. /* clang-format on */
  145. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  146. return false;
  147. }
  148. bool cmGlobalGenerator::SetGeneratorToolset(std::string const& ts, bool,
  149. cmMakefile* mf)
  150. {
  151. if (ts.empty()) {
  152. return true;
  153. }
  154. std::ostringstream e;
  155. /* clang-format off */
  156. e <<
  157. "Generator\n"
  158. " " << this->GetName() << "\n"
  159. "does not support toolset specification, but toolset\n"
  160. " " << ts << "\n"
  161. "was specified.";
  162. /* clang-format on */
  163. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  164. return false;
  165. }
  166. std::string cmGlobalGenerator::SelectMakeProgram(
  167. const std::string& inMakeProgram, const std::string& makeDefault) const
  168. {
  169. std::string makeProgram = inMakeProgram;
  170. if (cmIsOff(makeProgram)) {
  171. const char* makeProgramCSTR =
  172. this->CMakeInstance->GetCacheDefinition("CMAKE_MAKE_PROGRAM");
  173. if (cmIsOff(makeProgramCSTR)) {
  174. makeProgram = makeDefault;
  175. } else {
  176. makeProgram = makeProgramCSTR;
  177. }
  178. if (cmIsOff(makeProgram) && !makeProgram.empty()) {
  179. makeProgram = "CMAKE_MAKE_PROGRAM-NOTFOUND";
  180. }
  181. }
  182. return makeProgram;
  183. }
  184. void cmGlobalGenerator::ResolveLanguageCompiler(const std::string& lang,
  185. cmMakefile* mf,
  186. bool optional) const
  187. {
  188. std::string langComp = cmStrCat("CMAKE_", lang, "_COMPILER");
  189. if (!mf->GetDefinition(langComp)) {
  190. if (!optional) {
  191. cmSystemTools::Error(langComp + " not set, after EnableLanguage");
  192. }
  193. return;
  194. }
  195. std::string const& name = mf->GetRequiredDefinition(langComp);
  196. std::string path;
  197. if (!cmSystemTools::FileIsFullPath(name)) {
  198. path = cmSystemTools::FindProgram(name);
  199. } else {
  200. path = name;
  201. }
  202. if (!optional && (path.empty() || !cmSystemTools::FileExists(path))) {
  203. return;
  204. }
  205. cmProp cname =
  206. this->GetCMakeInstance()->GetState()->GetInitializedCacheValue(langComp);
  207. // Split compiler from arguments
  208. std::vector<std::string> cnameArgVec;
  209. if (cname && !cname->empty()) {
  210. cmExpandList(*cname, cnameArgVec);
  211. cname = &cnameArgVec.front();
  212. }
  213. std::string changeVars;
  214. if (cname && !optional) {
  215. std::string cnameString;
  216. if (!cmSystemTools::FileIsFullPath(*cname)) {
  217. cnameString = cmSystemTools::FindProgram(*cname);
  218. } else {
  219. cnameString = *cname;
  220. }
  221. std::string pathString = path;
  222. // get rid of potentially multiple slashes:
  223. cmSystemTools::ConvertToUnixSlashes(cnameString);
  224. cmSystemTools::ConvertToUnixSlashes(pathString);
  225. if (cnameString != pathString) {
  226. cmProp cvars = this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  227. "__CMAKE_DELETE_CACHE_CHANGE_VARS_");
  228. if (cvars) {
  229. changeVars += *cvars;
  230. changeVars += ";";
  231. }
  232. changeVars += langComp;
  233. changeVars += ";";
  234. changeVars += *cname;
  235. this->GetCMakeInstance()->GetState()->SetGlobalProperty(
  236. "__CMAKE_DELETE_CACHE_CHANGE_VARS_", changeVars.c_str());
  237. }
  238. }
  239. }
  240. void cmGlobalGenerator::AddBuildExportSet(cmExportBuildFileGenerator* gen)
  241. {
  242. this->BuildExportSets[gen->GetMainExportFileName()] = gen;
  243. }
  244. void cmGlobalGenerator::AddBuildExportExportSet(
  245. cmExportBuildFileGenerator* gen)
  246. {
  247. this->BuildExportExportSets[gen->GetMainExportFileName()] = gen;
  248. this->AddBuildExportSet(gen);
  249. }
  250. bool cmGlobalGenerator::GenerateImportFile(const std::string& file)
  251. {
  252. auto const it = this->BuildExportSets.find(file);
  253. if (it != this->BuildExportSets.end()) {
  254. bool result = it->second->GenerateImportFile();
  255. if (!this->ConfigureDoneCMP0026AndCMP0024) {
  256. for (const auto& m : this->Makefiles) {
  257. m->RemoveExportBuildFileGeneratorCMP0024(it->second);
  258. }
  259. }
  260. this->BuildExportSets.erase(it);
  261. return result;
  262. }
  263. return false;
  264. }
  265. void cmGlobalGenerator::ForceLinkerLanguages()
  266. {
  267. }
  268. bool cmGlobalGenerator::CheckTargetsForMissingSources() const
  269. {
  270. bool failed = false;
  271. for (const auto& localGen : this->LocalGenerators) {
  272. for (const auto& target : localGen->GetGeneratorTargets()) {
  273. if (!target->CanCompileSources() ||
  274. cmIsOn(target->GetProperty("ghs_integrity_app"))) {
  275. continue;
  276. }
  277. if (target->GetAllConfigSources().empty()) {
  278. std::ostringstream e;
  279. e << "No SOURCES given to target: " << target->GetName();
  280. this->GetCMakeInstance()->IssueMessage(
  281. MessageType::FATAL_ERROR, e.str(), target->GetBacktrace());
  282. failed = true;
  283. }
  284. }
  285. }
  286. return failed;
  287. }
  288. bool cmGlobalGenerator::CheckTargetsForType() const
  289. {
  290. if (!this->GetLanguageEnabled("Swift")) {
  291. return false;
  292. }
  293. bool failed = false;
  294. for (const auto& generator : this->LocalGenerators) {
  295. for (const auto& target : generator->GetGeneratorTargets()) {
  296. if (target->GetType() == cmStateEnums::EXECUTABLE) {
  297. std::vector<std::string> const& configs =
  298. target->Makefile->GetGeneratorConfigs(
  299. cmMakefile::IncludeEmptyConfig);
  300. for (std::string const& config : configs) {
  301. if (target->IsWin32Executable(config) &&
  302. target->GetLinkerLanguage(config) == "Swift") {
  303. this->GetCMakeInstance()->IssueMessage(
  304. MessageType::FATAL_ERROR,
  305. "WIN32_EXECUTABLE property is not supported on Swift "
  306. "executables",
  307. target->GetBacktrace());
  308. failed = true;
  309. }
  310. }
  311. }
  312. }
  313. }
  314. return failed;
  315. }
  316. bool cmGlobalGenerator::CheckTargetsForPchCompilePdb() const
  317. {
  318. if (!this->GetLanguageEnabled("C") && !this->GetLanguageEnabled("CXX")) {
  319. return false;
  320. }
  321. bool failed = false;
  322. for (const auto& generator : this->LocalGenerators) {
  323. for (const auto& target : generator->GetGeneratorTargets()) {
  324. if (!target->CanCompileSources() ||
  325. cmIsOn(target->GetProperty("ghs_integrity_app"))) {
  326. continue;
  327. }
  328. std::string const& reuseFrom =
  329. target->GetSafeProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  330. std::string const& compilePdb =
  331. target->GetSafeProperty("COMPILE_PDB_NAME");
  332. if (!reuseFrom.empty() && reuseFrom != compilePdb) {
  333. const std::string e = cmStrCat(
  334. "PRECOMPILE_HEADERS_REUSE_FROM property is set on target (\"",
  335. target->GetName(),
  336. "\"). Reusable precompile headers requires the COMPILE_PDB_NAME"
  337. " property to have the value \"",
  338. reuseFrom, "\"\n");
  339. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e,
  340. target->GetBacktrace());
  341. failed = true;
  342. }
  343. }
  344. }
  345. return failed;
  346. }
  347. bool cmGlobalGenerator::IsExportedTargetsFile(
  348. const std::string& filename) const
  349. {
  350. auto const it = this->BuildExportSets.find(filename);
  351. if (it == this->BuildExportSets.end()) {
  352. return false;
  353. }
  354. return !cm::contains(this->BuildExportExportSets, filename);
  355. }
  356. // Find the make program for the generator, required for try compiles
  357. bool cmGlobalGenerator::FindMakeProgram(cmMakefile* mf)
  358. {
  359. if (this->FindMakeProgramFile.empty()) {
  360. cmSystemTools::Error(
  361. "Generator implementation error, "
  362. "all generators must specify this->FindMakeProgramFile");
  363. return false;
  364. }
  365. if (cmIsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) {
  366. std::string setMakeProgram = mf->GetModulesFile(this->FindMakeProgramFile);
  367. if (!setMakeProgram.empty()) {
  368. mf->ReadListFile(setMakeProgram);
  369. }
  370. }
  371. if (cmIsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) {
  372. std::ostringstream err;
  373. err << "CMake was unable to find a build program corresponding to \""
  374. << this->GetName() << "\". CMAKE_MAKE_PROGRAM is not set. You "
  375. << "probably need to select a different build tool.";
  376. cmSystemTools::Error(err.str());
  377. cmSystemTools::SetFatalErrorOccured();
  378. return false;
  379. }
  380. std::string makeProgram = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
  381. // if there are spaces in the make program use short path
  382. // but do not short path the actual program name, as
  383. // this can cause trouble with VSExpress
  384. if (makeProgram.find(' ') != std::string::npos) {
  385. std::string dir;
  386. std::string file;
  387. cmSystemTools::SplitProgramPath(makeProgram, dir, file);
  388. std::string saveFile = file;
  389. cmSystemTools::GetShortPath(makeProgram, makeProgram);
  390. cmSystemTools::SplitProgramPath(makeProgram, dir, file);
  391. makeProgram = cmStrCat(dir, '/', saveFile);
  392. mf->AddCacheDefinition("CMAKE_MAKE_PROGRAM", makeProgram, "make program",
  393. cmStateEnums::FILEPATH);
  394. }
  395. return true;
  396. }
  397. bool cmGlobalGenerator::CheckLanguages(
  398. std::vector<std::string> const& /* languages */, cmMakefile* /* mf */) const
  399. {
  400. return true;
  401. }
  402. // enable the given language
  403. //
  404. // The following files are loaded in this order:
  405. //
  406. // First figure out what OS we are running on:
  407. //
  408. // CMakeSystem.cmake - configured file created by CMakeDetermineSystem.cmake
  409. // CMakeDetermineSystem.cmake - figure out os info and create
  410. // CMakeSystem.cmake IF CMAKE_SYSTEM
  411. // not set
  412. // CMakeSystem.cmake - configured file created by
  413. // CMakeDetermineSystem.cmake IF CMAKE_SYSTEM_LOADED
  414. // CMakeSystemSpecificInitialize.cmake
  415. // - includes Platform/${CMAKE_SYSTEM_NAME}-Initialize.cmake
  416. // Next try and enable all languages found in the languages vector
  417. //
  418. // FOREACH LANG in languages
  419. // CMake(LANG)Compiler.cmake - configured file create by
  420. // CMakeDetermine(LANG)Compiler.cmake
  421. // CMakeDetermine(LANG)Compiler.cmake - Finds compiler for LANG and
  422. // creates CMake(LANG)Compiler.cmake
  423. // CMake(LANG)Compiler.cmake - configured file created by
  424. // CMakeDetermine(LANG)Compiler.cmake
  425. //
  426. // CMakeSystemSpecificInformation.cmake
  427. // - includes Platform/${CMAKE_SYSTEM_NAME}.cmake
  428. // may use compiler stuff
  429. // FOREACH LANG in languages
  430. // CMake(LANG)Information.cmake
  431. // - loads Platform/${CMAKE_SYSTEM_NAME}-${COMPILER}.cmake
  432. // CMakeTest(LANG)Compiler.cmake
  433. // - Make sure the compiler works with a try compile if
  434. // CMakeDetermine(LANG) was loaded
  435. //
  436. // Now load a few files that can override values set in any of the above
  437. // (PROJECTNAME)Compatibility.cmake
  438. // - load any backwards compatibility stuff for current project
  439. // ${CMAKE_USER_MAKE_RULES_OVERRIDE}
  440. // - allow users a chance to override system variables
  441. //
  442. //
  443. void cmGlobalGenerator::EnableLanguage(
  444. std::vector<std::string> const& languages, cmMakefile* mf, bool optional)
  445. {
  446. if (languages.empty()) {
  447. cmSystemTools::Error("EnableLanguage must have a lang specified!");
  448. cmSystemTools::SetFatalErrorOccured();
  449. return;
  450. }
  451. std::set<std::string> cur_languages(languages.begin(), languages.end());
  452. for (std::string const& li : cur_languages) {
  453. if (!this->LanguagesInProgress.insert(li).second) {
  454. std::ostringstream e;
  455. e << "Language '" << li
  456. << "' is currently being enabled. "
  457. "Recursive call not allowed.";
  458. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  459. cmSystemTools::SetFatalErrorOccured();
  460. return;
  461. }
  462. }
  463. if (this->TryCompileOuterMakefile) {
  464. // In a try-compile we can only enable languages provided by caller.
  465. for (std::string const& lang : languages) {
  466. if (lang == "NONE") {
  467. this->SetLanguageEnabled("NONE", mf);
  468. } else {
  469. if (!cm::contains(this->LanguagesReady, lang)) {
  470. std::ostringstream e;
  471. e << "The test project needs language " << lang
  472. << " which is not enabled.";
  473. this->TryCompileOuterMakefile->IssueMessage(MessageType::FATAL_ERROR,
  474. e.str());
  475. cmSystemTools::SetFatalErrorOccured();
  476. return;
  477. }
  478. }
  479. }
  480. }
  481. bool fatalError = false;
  482. mf->AddDefinitionBool("RUN_CONFIGURE", true);
  483. std::string rootBin =
  484. cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), "/CMakeFiles");
  485. // If the configuration files path has been set,
  486. // then we are in a try compile and need to copy the enable language
  487. // files from the parent cmake bin dir, into the try compile bin dir
  488. if (!this->ConfiguredFilesPath.empty()) {
  489. rootBin = this->ConfiguredFilesPath;
  490. }
  491. rootBin += '/';
  492. rootBin += cmVersion::GetCMakeVersion();
  493. // set the dir for parent files so they can be used by modules
  494. mf->AddDefinition("CMAKE_PLATFORM_INFO_DIR", rootBin);
  495. if (!this->CMakeInstance->GetIsInTryCompile()) {
  496. // Keep a mark in the cache to indicate that we've initialized the
  497. // platform information directory. If the platform information
  498. // directory exists but the mark is missing then CMakeCache.txt
  499. // has been removed or replaced without also removing the CMakeFiles/
  500. // directory. In this case remove the platform information directory
  501. // so that it will be re-initialized and the relevant information
  502. // restored in the cache.
  503. if (cmSystemTools::FileIsDirectory(rootBin) &&
  504. !mf->IsOn(kCMAKE_PLATFORM_INFO_INITIALIZED)) {
  505. cmSystemTools::RemoveADirectory(rootBin);
  506. }
  507. this->GetCMakeInstance()->AddCacheEntry(
  508. kCMAKE_PLATFORM_INFO_INITIALIZED, "1",
  509. "Platform information initialized", cmStateEnums::INTERNAL);
  510. }
  511. // try and load the CMakeSystem.cmake if it is there
  512. std::string fpath = rootBin;
  513. bool const readCMakeSystem = !mf->GetDefinition("CMAKE_SYSTEM_LOADED");
  514. if (readCMakeSystem) {
  515. fpath += "/CMakeSystem.cmake";
  516. if (cmSystemTools::FileExists(fpath)) {
  517. mf->ReadListFile(fpath);
  518. }
  519. }
  520. if (readCMakeSystem) {
  521. // Find the native build tool for this generator.
  522. // This has to be done early so that MSBuild can be used to examine the
  523. // cross-compilation environment.
  524. if (!this->FindMakeProgram(mf)) {
  525. return;
  526. }
  527. }
  528. // Load the CMakeDetermineSystem.cmake file and find out
  529. // what platform we are running on
  530. if (!mf->GetDefinition("CMAKE_SYSTEM")) {
  531. #if defined(_WIN32) && !defined(__CYGWIN__)
  532. /* Windows version number data. */
  533. OSVERSIONINFOEXW osviex;
  534. ZeroMemory(&osviex, sizeof(osviex));
  535. osviex.dwOSVersionInfoSize = sizeof(osviex);
  536. # ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
  537. # pragma warning(push)
  538. # ifdef __INTEL_COMPILER
  539. # pragma warning(disable : 1478)
  540. # elif defined __clang__
  541. # pragma clang diagnostic push
  542. # pragma clang diagnostic ignored "-Wdeprecated-declarations"
  543. # else
  544. # pragma warning(disable : 4996)
  545. # endif
  546. # endif
  547. GetVersionExW((OSVERSIONINFOW*)&osviex);
  548. # ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
  549. # ifdef __clang__
  550. # pragma clang diagnostic pop
  551. # else
  552. # pragma warning(pop)
  553. # endif
  554. # endif
  555. std::ostringstream windowsVersionString;
  556. windowsVersionString << osviex.dwMajorVersion << "."
  557. << osviex.dwMinorVersion << "."
  558. << osviex.dwBuildNumber;
  559. mf->AddDefinition("CMAKE_HOST_SYSTEM_VERSION", windowsVersionString.str());
  560. #endif
  561. // Read the DetermineSystem file
  562. std::string systemFile = mf->GetModulesFile("CMakeDetermineSystem.cmake");
  563. mf->ReadListFile(systemFile);
  564. // load the CMakeSystem.cmake from the binary directory
  565. // this file is configured by the CMakeDetermineSystem.cmake file
  566. fpath = cmStrCat(rootBin, "/CMakeSystem.cmake");
  567. mf->ReadListFile(fpath);
  568. }
  569. if (readCMakeSystem) {
  570. // Tell the generator about the instance, if any.
  571. std::string instance = mf->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE");
  572. if (!this->SetGeneratorInstance(instance, mf)) {
  573. cmSystemTools::SetFatalErrorOccured();
  574. return;
  575. }
  576. // Tell the generator about the target system.
  577. std::string system = mf->GetSafeDefinition("CMAKE_SYSTEM_NAME");
  578. if (!this->SetSystemName(system, mf)) {
  579. cmSystemTools::SetFatalErrorOccured();
  580. return;
  581. }
  582. // Tell the generator about the platform, if any.
  583. std::string platform = mf->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM");
  584. if (!this->SetGeneratorPlatform(platform, mf)) {
  585. cmSystemTools::SetFatalErrorOccured();
  586. return;
  587. }
  588. // Tell the generator about the toolset, if any.
  589. std::string toolset = mf->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET");
  590. if (!this->SetGeneratorToolset(toolset, false, mf)) {
  591. cmSystemTools::SetFatalErrorOccured();
  592. return;
  593. }
  594. }
  595. // Check that the languages are supported by the generator and its
  596. // native build tool found above.
  597. if (!this->CheckLanguages(languages, mf)) {
  598. return;
  599. }
  600. // **** Load the system specific initialization if not yet loaded
  601. if (!mf->GetDefinition("CMAKE_SYSTEM_SPECIFIC_INITIALIZE_LOADED")) {
  602. fpath = mf->GetModulesFile("CMakeSystemSpecificInitialize.cmake");
  603. if (!mf->ReadListFile(fpath)) {
  604. cmSystemTools::Error("Could not find cmake module file: "
  605. "CMakeSystemSpecificInitialize.cmake");
  606. }
  607. }
  608. std::map<std::string, bool> needTestLanguage;
  609. std::map<std::string, bool> needSetLanguageEnabledMaps;
  610. // foreach language
  611. // load the CMakeDetermine(LANG)Compiler.cmake file to find
  612. // the compiler
  613. for (std::string const& lang : languages) {
  614. needSetLanguageEnabledMaps[lang] = false;
  615. if (lang == "NONE") {
  616. this->SetLanguageEnabled("NONE", mf);
  617. continue;
  618. }
  619. std::string loadedLang = cmStrCat("CMAKE_", lang, "_COMPILER_LOADED");
  620. if (!mf->GetDefinition(loadedLang)) {
  621. fpath = cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake");
  622. // If the existing build tree was already configured with this
  623. // version of CMake then try to load the configured file first
  624. // to avoid duplicate compiler tests.
  625. if (cmSystemTools::FileExists(fpath)) {
  626. if (!mf->ReadListFile(fpath)) {
  627. cmSystemTools::Error("Could not find cmake module file: " + fpath);
  628. }
  629. // if this file was found then the language was already determined
  630. // to be working
  631. needTestLanguage[lang] = false;
  632. this->SetLanguageEnabledFlag(lang, mf);
  633. needSetLanguageEnabledMaps[lang] = true;
  634. // this can only be called after loading CMake(LANG)Compiler.cmake
  635. }
  636. }
  637. if (!this->GetLanguageEnabled(lang)) {
  638. if (this->CMakeInstance->GetIsInTryCompile()) {
  639. cmSystemTools::Error("This should not have happened. "
  640. "If you see this message, you are probably "
  641. "using a broken CMakeLists.txt file or a "
  642. "problematic release of CMake");
  643. }
  644. // if the CMake(LANG)Compiler.cmake file was not found then
  645. // load CMakeDetermine(LANG)Compiler.cmake
  646. std::string determineCompiler =
  647. cmStrCat("CMakeDetermine", lang, "Compiler.cmake");
  648. std::string determineFile = mf->GetModulesFile(determineCompiler);
  649. if (!mf->ReadListFile(determineFile)) {
  650. cmSystemTools::Error("Could not find cmake module file: " +
  651. determineCompiler);
  652. }
  653. if (cmSystemTools::GetFatalErrorOccured()) {
  654. return;
  655. }
  656. needTestLanguage[lang] = true;
  657. // Some generators like visual studio should not use the env variables
  658. // So the global generator can specify that in this variable
  659. if (!mf->GetDefinition("CMAKE_GENERATOR_NO_COMPILER_ENV")) {
  660. // put ${CMake_(LANG)_COMPILER_ENV_VAR}=${CMAKE_(LANG)_COMPILER
  661. // into the environment, in case user scripts want to run
  662. // configure, or sub cmakes
  663. std::string compilerName = cmStrCat("CMAKE_", lang, "_COMPILER");
  664. std::string compilerEnv =
  665. cmStrCat("CMAKE_", lang, "_COMPILER_ENV_VAR");
  666. const std::string& envVar = mf->GetRequiredDefinition(compilerEnv);
  667. const std::string& envVarValue =
  668. mf->GetRequiredDefinition(compilerName);
  669. std::string env = cmStrCat(envVar, '=', envVarValue);
  670. cmSystemTools::PutEnv(env);
  671. }
  672. // if determineLanguage was called then load the file it
  673. // configures CMake(LANG)Compiler.cmake
  674. fpath = cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake");
  675. if (!mf->ReadListFile(fpath)) {
  676. cmSystemTools::Error("Could not find cmake module file: " + fpath);
  677. }
  678. this->SetLanguageEnabledFlag(lang, mf);
  679. needSetLanguageEnabledMaps[lang] = true;
  680. // this can only be called after loading CMake(LANG)Compiler.cmake
  681. // the language must be enabled for try compile to work, but we do
  682. // not know if it is a working compiler yet so set the test language
  683. // flag
  684. needTestLanguage[lang] = true;
  685. } // end if(!this->GetLanguageEnabled(lang) )
  686. } // end loop over languages
  687. // **** Load the system specific information if not yet loaded
  688. if (!mf->GetDefinition("CMAKE_SYSTEM_SPECIFIC_INFORMATION_LOADED")) {
  689. fpath = mf->GetModulesFile("CMakeSystemSpecificInformation.cmake");
  690. if (!mf->ReadListFile(fpath)) {
  691. cmSystemTools::Error("Could not find cmake module file: "
  692. "CMakeSystemSpecificInformation.cmake");
  693. }
  694. }
  695. // loop over languages again loading CMake(LANG)Information.cmake
  696. //
  697. for (std::string const& lang : languages) {
  698. if (lang == "NONE") {
  699. this->SetLanguageEnabled("NONE", mf);
  700. continue;
  701. }
  702. // Check that the compiler was found.
  703. std::string compilerName = cmStrCat("CMAKE_", lang, "_COMPILER");
  704. std::string compilerEnv = cmStrCat("CMAKE_", lang, "_COMPILER_ENV_VAR");
  705. std::ostringstream noCompiler;
  706. cmProp compilerFile = mf->GetDefinition(compilerName);
  707. if (!cmNonempty(compilerFile) || cmIsNOTFOUND(*compilerFile)) {
  708. /* clang-format off */
  709. noCompiler <<
  710. "No " << compilerName << " could be found.\n"
  711. ;
  712. /* clang-format on */
  713. } else if ((lang != "RC") && (lang != "ASM_MASM")) {
  714. if (!cmSystemTools::FileIsFullPath(*compilerFile)) {
  715. /* clang-format off */
  716. noCompiler <<
  717. "The " << compilerName << ":\n"
  718. " " << *compilerFile << "\n"
  719. "is not a full path and was not found in the PATH.\n"
  720. ;
  721. /* clang-format on */
  722. } else if (!cmSystemTools::FileExists(*compilerFile)) {
  723. /* clang-format off */
  724. noCompiler <<
  725. "The " << compilerName << ":\n"
  726. " " << *compilerFile << "\n"
  727. "is not a full path to an existing compiler tool.\n"
  728. ;
  729. /* clang-format on */
  730. }
  731. }
  732. if (!noCompiler.str().empty()) {
  733. // Skip testing this language since the compiler is not found.
  734. needTestLanguage[lang] = false;
  735. if (!optional) {
  736. // The compiler was not found and it is not optional. Remove
  737. // CMake(LANG)Compiler.cmake so we try again next time CMake runs.
  738. std::string compilerLangFile =
  739. cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake");
  740. cmSystemTools::RemoveFile(compilerLangFile);
  741. if (!this->CMakeInstance->GetIsInTryCompile()) {
  742. this->PrintCompilerAdvice(noCompiler, lang,
  743. cmToCStr(mf->GetDefinition(compilerEnv)));
  744. mf->IssueMessage(MessageType::FATAL_ERROR, noCompiler.str());
  745. fatalError = true;
  746. }
  747. }
  748. }
  749. std::string langLoadedVar =
  750. cmStrCat("CMAKE_", lang, "_INFORMATION_LOADED");
  751. if (!mf->GetDefinition(langLoadedVar)) {
  752. fpath = cmStrCat("CMake", lang, "Information.cmake");
  753. std::string informationFile = mf->GetModulesFile(fpath);
  754. if (informationFile.empty()) {
  755. cmSystemTools::Error("Could not find cmake module file: " + fpath);
  756. } else if (!mf->ReadListFile(informationFile)) {
  757. cmSystemTools::Error("Could not process cmake module file: " +
  758. informationFile);
  759. }
  760. }
  761. if (needSetLanguageEnabledMaps[lang]) {
  762. this->SetLanguageEnabledMaps(lang, mf);
  763. }
  764. this->LanguagesReady.insert(lang);
  765. // Test the compiler for the language just setup
  766. // (but only if a compiler has been actually found)
  767. // At this point we should have enough info for a try compile
  768. // which is used in the backward stuff
  769. // If the language is untested then test it now with a try compile.
  770. if (needTestLanguage[lang]) {
  771. if (!this->CMakeInstance->GetIsInTryCompile()) {
  772. std::string testLang = cmStrCat("CMakeTest", lang, "Compiler.cmake");
  773. std::string ifpath = mf->GetModulesFile(testLang);
  774. if (!mf->ReadListFile(ifpath)) {
  775. cmSystemTools::Error("Could not find cmake module file: " +
  776. testLang);
  777. }
  778. std::string compilerWorks =
  779. cmStrCat("CMAKE_", lang, "_COMPILER_WORKS");
  780. // if the compiler did not work, then remove the
  781. // CMake(LANG)Compiler.cmake file so that it will get tested the
  782. // next time cmake is run
  783. if (!mf->IsOn(compilerWorks)) {
  784. std::string compilerLangFile =
  785. cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake");
  786. cmSystemTools::RemoveFile(compilerLangFile);
  787. }
  788. } // end if in try compile
  789. } // end need test language
  790. // Store the shared library flags so that we can satisfy CMP0018
  791. std::string sharedLibFlagsVar =
  792. cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
  793. this->LanguageToOriginalSharedLibFlags[lang] =
  794. mf->GetSafeDefinition(sharedLibFlagsVar);
  795. // Translate compiler ids for compatibility.
  796. this->CheckCompilerIdCompatibility(mf, lang);
  797. } // end for each language
  798. // Now load files that can override any settings on the platform or for
  799. // the project First load the project compatibility file if it is in
  800. // cmake
  801. std::string projectCompatibility =
  802. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/",
  803. mf->GetSafeDefinition("PROJECT_NAME"), "Compatibility.cmake");
  804. if (cmSystemTools::FileExists(projectCompatibility)) {
  805. mf->ReadListFile(projectCompatibility);
  806. }
  807. // Inform any extra generator of the new language.
  808. if (this->ExtraGenerator) {
  809. this->ExtraGenerator->EnableLanguage(languages, mf, false);
  810. }
  811. if (fatalError) {
  812. cmSystemTools::SetFatalErrorOccured();
  813. }
  814. for (std::string const& lang : cur_languages) {
  815. this->LanguagesInProgress.erase(lang);
  816. }
  817. }
  818. void cmGlobalGenerator::PrintCompilerAdvice(std::ostream& os,
  819. std::string const& lang,
  820. const char* envVar) const
  821. {
  822. // Subclasses override this method if they do not support this advice.
  823. os << "Tell CMake where to find the compiler by setting ";
  824. if (envVar) {
  825. os << "either the environment variable \"" << envVar << "\" or ";
  826. }
  827. os << "the CMake cache entry CMAKE_" << lang
  828. << "_COMPILER "
  829. "to the full path to the compiler, or to the compiler name "
  830. "if it is in the PATH.";
  831. }
  832. void cmGlobalGenerator::CheckCompilerIdCompatibility(
  833. cmMakefile* mf, std::string const& lang) const
  834. {
  835. std::string compilerIdVar = "CMAKE_" + lang + "_COMPILER_ID";
  836. std::string const compilerId = mf->GetSafeDefinition(compilerIdVar);
  837. if (compilerId == "AppleClang") {
  838. switch (mf->GetPolicyStatus(cmPolicies::CMP0025)) {
  839. case cmPolicies::WARN:
  840. if (!this->CMakeInstance->GetIsInTryCompile() &&
  841. mf->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0025")) {
  842. std::ostringstream w;
  843. /* clang-format off */
  844. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0025) << "\n"
  845. "Converting " << lang <<
  846. R"( compiler id "AppleClang" to "Clang" for compatibility.)"
  847. ;
  848. /* clang-format on */
  849. mf->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  850. }
  851. CM_FALLTHROUGH;
  852. case cmPolicies::OLD:
  853. // OLD behavior is to convert AppleClang to Clang.
  854. mf->AddDefinition(compilerIdVar, "Clang");
  855. break;
  856. case cmPolicies::REQUIRED_IF_USED:
  857. case cmPolicies::REQUIRED_ALWAYS:
  858. mf->IssueMessage(
  859. MessageType::FATAL_ERROR,
  860. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0025));
  861. case cmPolicies::NEW:
  862. // NEW behavior is to keep AppleClang.
  863. break;
  864. }
  865. }
  866. if (compilerId == "QCC") {
  867. switch (mf->GetPolicyStatus(cmPolicies::CMP0047)) {
  868. case cmPolicies::WARN:
  869. if (!this->CMakeInstance->GetIsInTryCompile() &&
  870. mf->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0047")) {
  871. std::ostringstream w;
  872. /* clang-format off */
  873. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0047) << "\n"
  874. "Converting " << lang <<
  875. R"( compiler id "QCC" to "GNU" for compatibility.)"
  876. ;
  877. /* clang-format on */
  878. mf->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  879. }
  880. CM_FALLTHROUGH;
  881. case cmPolicies::OLD:
  882. // OLD behavior is to convert QCC to GNU.
  883. mf->AddDefinition(compilerIdVar, "GNU");
  884. if (lang == "C") {
  885. mf->AddDefinition("CMAKE_COMPILER_IS_GNUCC", "1");
  886. } else if (lang == "CXX") {
  887. mf->AddDefinition("CMAKE_COMPILER_IS_GNUCXX", "1");
  888. }
  889. break;
  890. case cmPolicies::REQUIRED_IF_USED:
  891. case cmPolicies::REQUIRED_ALWAYS:
  892. mf->IssueMessage(
  893. MessageType::FATAL_ERROR,
  894. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0047));
  895. CM_FALLTHROUGH;
  896. case cmPolicies::NEW:
  897. // NEW behavior is to keep QCC.
  898. break;
  899. }
  900. }
  901. if (compilerId == "XLClang") {
  902. switch (mf->GetPolicyStatus(cmPolicies::CMP0089)) {
  903. case cmPolicies::WARN:
  904. if (!this->CMakeInstance->GetIsInTryCompile() &&
  905. mf->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0089")) {
  906. std::ostringstream w;
  907. /* clang-format off */
  908. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0089) << "\n"
  909. "Converting " << lang <<
  910. R"( compiler id "XLClang" to "XL" for compatibility.)"
  911. ;
  912. /* clang-format on */
  913. mf->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  914. }
  915. CM_FALLTHROUGH;
  916. case cmPolicies::OLD:
  917. // OLD behavior is to convert XLClang to XL.
  918. mf->AddDefinition(compilerIdVar, "XL");
  919. break;
  920. case cmPolicies::REQUIRED_IF_USED:
  921. case cmPolicies::REQUIRED_ALWAYS:
  922. mf->IssueMessage(
  923. MessageType::FATAL_ERROR,
  924. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0089));
  925. case cmPolicies::NEW:
  926. // NEW behavior is to keep AppleClang.
  927. break;
  928. }
  929. }
  930. }
  931. std::string cmGlobalGenerator::GetLanguageOutputExtension(
  932. cmSourceFile const& source) const
  933. {
  934. const std::string& lang = source.GetLanguage();
  935. if (!lang.empty()) {
  936. auto const it = this->LanguageToOutputExtension.find(lang);
  937. if (it != this->LanguageToOutputExtension.end()) {
  938. return it->second;
  939. }
  940. } else {
  941. // if no language is found then check to see if it is already an
  942. // output extension for some language. In that case it should be ignored
  943. // and in this map, so it will not be compiled but will just be used.
  944. std::string const& ext = source.GetExtension();
  945. if (!ext.empty()) {
  946. if (this->OutputExtensions.count(ext)) {
  947. return ext;
  948. }
  949. }
  950. }
  951. return "";
  952. }
  953. std::string cmGlobalGenerator::GetLanguageFromExtension(const char* ext) const
  954. {
  955. // if there is an extension and it starts with . then move past the
  956. // . because the extensions are not stored with a . in the map
  957. if (ext && *ext == '.') {
  958. ++ext;
  959. }
  960. auto const it = this->ExtensionToLanguage.find(ext);
  961. if (it != this->ExtensionToLanguage.end()) {
  962. return it->second;
  963. }
  964. return "";
  965. }
  966. /* SetLanguageEnabled() is now split in two parts:
  967. at first the enabled-flag is set. This can then be used in EnabledLanguage()
  968. for checking whether the language is already enabled. After setting this
  969. flag still the values from the cmake variables have to be copied into the
  970. internal maps, this is done in SetLanguageEnabledMaps() which is called
  971. after the system- and compiler specific files have been loaded.
  972. This split was done originally so that compiler-specific configuration
  973. files could change the object file extension
  974. (CMAKE_<LANG>_OUTPUT_EXTENSION) before the CMake variables were copied
  975. to the C++ maps.
  976. */
  977. void cmGlobalGenerator::SetLanguageEnabled(const std::string& l,
  978. cmMakefile* mf)
  979. {
  980. this->SetLanguageEnabledFlag(l, mf);
  981. this->SetLanguageEnabledMaps(l, mf);
  982. }
  983. void cmGlobalGenerator::SetLanguageEnabledFlag(const std::string& l,
  984. cmMakefile* mf)
  985. {
  986. this->CMakeInstance->GetState()->SetLanguageEnabled(l);
  987. // Fill the language-to-extension map with the current variable
  988. // settings to make sure it is available for the try_compile()
  989. // command source file signature. In SetLanguageEnabledMaps this
  990. // will be done again to account for any compiler- or
  991. // platform-specific entries.
  992. this->FillExtensionToLanguageMap(l, mf);
  993. }
  994. void cmGlobalGenerator::SetLanguageEnabledMaps(const std::string& l,
  995. cmMakefile* mf)
  996. {
  997. // use LanguageToLinkerPreference to detect whether this functions has
  998. // run before
  999. if (cm::contains(this->LanguageToLinkerPreference, l)) {
  1000. return;
  1001. }
  1002. std::string linkerPrefVar = "CMAKE_" + l + "_LINKER_PREFERENCE";
  1003. cmProp linkerPref = mf->GetDefinition(linkerPrefVar);
  1004. int preference = 0;
  1005. if (cmNonempty(linkerPref)) {
  1006. if (sscanf(linkerPref->c_str(), "%d", &preference) != 1) {
  1007. // backward compatibility: before 2.6 LINKER_PREFERENCE
  1008. // was either "None" or "Preferred", and only the first character was
  1009. // tested. So if there is a custom language out there and it is
  1010. // "Preferred", set its preference high
  1011. if ((*linkerPref)[0] == 'P') {
  1012. preference = 100;
  1013. } else {
  1014. preference = 0;
  1015. }
  1016. }
  1017. }
  1018. if (preference < 0) {
  1019. std::string msg =
  1020. cmStrCat(linkerPrefVar, " is negative, adjusting it to 0");
  1021. cmSystemTools::Message(msg, "Warning");
  1022. preference = 0;
  1023. }
  1024. this->LanguageToLinkerPreference[l] = preference;
  1025. std::string outputExtensionVar = "CMAKE_" + l + "_OUTPUT_EXTENSION";
  1026. if (cmProp p = mf->GetDefinition(outputExtensionVar)) {
  1027. std::string outputExtension = *p;
  1028. this->LanguageToOutputExtension[l] = outputExtension;
  1029. this->OutputExtensions[outputExtension] = outputExtension;
  1030. if (cmHasPrefix(outputExtension, ".")) {
  1031. outputExtension = outputExtension.substr(1);
  1032. this->OutputExtensions[outputExtension] = outputExtension;
  1033. }
  1034. }
  1035. // The map was originally filled by SetLanguageEnabledFlag, but
  1036. // since then the compiler- and platform-specific files have been
  1037. // loaded which might have added more entries.
  1038. this->FillExtensionToLanguageMap(l, mf);
  1039. std::string ignoreExtensionsVar =
  1040. std::string("CMAKE_") + std::string(l) + std::string("_IGNORE_EXTENSIONS");
  1041. std::string ignoreExts = mf->GetSafeDefinition(ignoreExtensionsVar);
  1042. std::vector<std::string> extensionList = cmExpandedList(ignoreExts);
  1043. for (std::string const& i : extensionList) {
  1044. this->IgnoreExtensions[i] = true;
  1045. }
  1046. }
  1047. void cmGlobalGenerator::FillExtensionToLanguageMap(const std::string& l,
  1048. cmMakefile* mf)
  1049. {
  1050. std::string extensionsVar = std::string("CMAKE_") + std::string(l) +
  1051. std::string("_SOURCE_FILE_EXTENSIONS");
  1052. const std::string& exts = mf->GetSafeDefinition(extensionsVar);
  1053. std::vector<std::string> extensionList = cmExpandedList(exts);
  1054. for (std::string const& i : extensionList) {
  1055. this->ExtensionToLanguage[i] = l;
  1056. }
  1057. }
  1058. const char* cmGlobalGenerator::GetGlobalSetting(std::string const& name) const
  1059. {
  1060. assert(!this->Makefiles.empty());
  1061. return cmToCStr(this->Makefiles[0]->GetDefinition(name));
  1062. }
  1063. bool cmGlobalGenerator::GlobalSettingIsOn(std::string const& name) const
  1064. {
  1065. assert(!this->Makefiles.empty());
  1066. return this->Makefiles[0]->IsOn(name);
  1067. }
  1068. std::string cmGlobalGenerator::GetSafeGlobalSetting(
  1069. std::string const& name) const
  1070. {
  1071. assert(!this->Makefiles.empty());
  1072. return this->Makefiles[0]->GetSafeDefinition(name);
  1073. }
  1074. bool cmGlobalGenerator::IgnoreFile(const char* ext) const
  1075. {
  1076. if (!this->GetLanguageFromExtension(ext).empty()) {
  1077. return false;
  1078. }
  1079. return (this->IgnoreExtensions.count(ext) > 0);
  1080. }
  1081. bool cmGlobalGenerator::GetLanguageEnabled(const std::string& l) const
  1082. {
  1083. return this->CMakeInstance->GetState()->GetLanguageEnabled(l);
  1084. }
  1085. void cmGlobalGenerator::ClearEnabledLanguages()
  1086. {
  1087. this->CMakeInstance->GetState()->ClearEnabledLanguages();
  1088. }
  1089. void cmGlobalGenerator::CreateLocalGenerators()
  1090. {
  1091. this->LocalGeneratorSearchIndex.clear();
  1092. this->LocalGenerators.clear();
  1093. this->LocalGenerators.reserve(this->Makefiles.size());
  1094. for (const auto& m : this->Makefiles) {
  1095. auto lg = this->CreateLocalGenerator(m.get());
  1096. this->IndexLocalGenerator(lg.get());
  1097. this->LocalGenerators.push_back(std::move(lg));
  1098. }
  1099. }
  1100. void cmGlobalGenerator::Configure()
  1101. {
  1102. this->FirstTimeProgress = 0.0f;
  1103. this->ClearGeneratorMembers();
  1104. cmStateSnapshot snapshot = this->CMakeInstance->GetCurrentSnapshot();
  1105. snapshot.GetDirectory().SetCurrentSource(
  1106. this->CMakeInstance->GetHomeDirectory());
  1107. snapshot.GetDirectory().SetCurrentBinary(
  1108. this->CMakeInstance->GetHomeOutputDirectory());
  1109. auto dirMfu = cm::make_unique<cmMakefile>(this, snapshot);
  1110. auto dirMf = dirMfu.get();
  1111. this->Makefiles.push_back(std::move(dirMfu));
  1112. dirMf->SetRecursionDepth(this->RecursionDepth);
  1113. this->IndexMakefile(dirMf);
  1114. this->BinaryDirectories.insert(
  1115. this->CMakeInstance->GetHomeOutputDirectory());
  1116. // now do it
  1117. this->ConfigureDoneCMP0026AndCMP0024 = false;
  1118. dirMf->Configure();
  1119. dirMf->EnforceDirectoryLevelRules();
  1120. this->ConfigureDoneCMP0026AndCMP0024 = true;
  1121. // Put a copy of each global target in every directory.
  1122. {
  1123. std::vector<GlobalTargetInfo> globalTargets;
  1124. this->CreateDefaultGlobalTargets(globalTargets);
  1125. for (const auto& mf : this->Makefiles) {
  1126. auto& targets = mf->GetTargets();
  1127. for (GlobalTargetInfo const& globalTarget : globalTargets) {
  1128. targets.emplace(globalTarget.Name,
  1129. this->CreateGlobalTarget(globalTarget, mf.get()));
  1130. }
  1131. }
  1132. }
  1133. // update the cache entry for the number of local generators, this is used
  1134. // for progress
  1135. char num[100];
  1136. sprintf(num, "%d", static_cast<int>(this->Makefiles.size()));
  1137. this->GetCMakeInstance()->AddCacheEntry("CMAKE_NUMBER_OF_MAKEFILES", num,
  1138. "number of local generators",
  1139. cmStateEnums::INTERNAL);
  1140. if (this->CMakeInstance->GetWorkingMode() == cmake::NORMAL_MODE) {
  1141. std::ostringstream msg;
  1142. if (cmSystemTools::GetErrorOccuredFlag()) {
  1143. msg << "Configuring incomplete, errors occurred!";
  1144. const char* logs[] = { "CMakeOutput.log", "CMakeError.log", nullptr };
  1145. for (const char** log = logs; *log; ++log) {
  1146. std::string f = cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(),
  1147. "/CMakeFiles/", *log);
  1148. if (cmSystemTools::FileExists(f)) {
  1149. msg << "\nSee also \"" << f << "\".";
  1150. }
  1151. }
  1152. } else {
  1153. msg << "Configuring done";
  1154. }
  1155. this->CMakeInstance->UpdateProgress(msg.str(), -1);
  1156. }
  1157. }
  1158. void cmGlobalGenerator::CreateGenerationObjects(TargetTypes targetTypes)
  1159. {
  1160. this->CreateLocalGenerators();
  1161. // Commit side effects only if we are actually generating
  1162. if (this->GetConfigureDoneCMP0026()) {
  1163. this->CheckTargetProperties();
  1164. }
  1165. this->CreateGeneratorTargets(targetTypes);
  1166. this->ComputeBuildFileGenerators();
  1167. }
  1168. void cmGlobalGenerator::CreateImportedGenerationObjects(
  1169. cmMakefile* mf, const std::vector<std::string>& targets,
  1170. std::vector<const cmGeneratorTarget*>& exports)
  1171. {
  1172. this->CreateGenerationObjects(ImportedOnly);
  1173. auto const mfit =
  1174. std::find_if(this->Makefiles.begin(), this->Makefiles.end(),
  1175. [mf](const std::unique_ptr<cmMakefile>& item) {
  1176. return item.get() == mf;
  1177. });
  1178. auto& lg =
  1179. this->LocalGenerators[std::distance(this->Makefiles.begin(), mfit)];
  1180. for (std::string const& t : targets) {
  1181. cmGeneratorTarget* gt = lg->FindGeneratorTargetToUse(t);
  1182. if (gt) {
  1183. exports.push_back(gt);
  1184. }
  1185. }
  1186. }
  1187. cmExportBuildFileGenerator* cmGlobalGenerator::GetExportedTargetsFile(
  1188. const std::string& filename) const
  1189. {
  1190. auto const it = this->BuildExportSets.find(filename);
  1191. return it == this->BuildExportSets.end() ? nullptr : it->second;
  1192. }
  1193. void cmGlobalGenerator::AddCMP0042WarnTarget(const std::string& target)
  1194. {
  1195. this->CMP0042WarnTargets.insert(target);
  1196. }
  1197. void cmGlobalGenerator::AddCMP0068WarnTarget(const std::string& target)
  1198. {
  1199. this->CMP0068WarnTargets.insert(target);
  1200. }
  1201. bool cmGlobalGenerator::CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const
  1202. {
  1203. // If the property is not enabled then okay.
  1204. if (!this->CMakeInstance->GetState()->GetGlobalPropertyAsBool(
  1205. "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
  1206. return true;
  1207. }
  1208. // This generator does not support duplicate custom targets.
  1209. std::ostringstream e;
  1210. e << "This project has enabled the ALLOW_DUPLICATE_CUSTOM_TARGETS "
  1211. << "global property. "
  1212. << "The \"" << this->GetName() << "\" generator does not support "
  1213. << "duplicate custom targets. "
  1214. << "Consider using a Makefiles generator or fix the project to not "
  1215. << "use duplicate target names.";
  1216. cmSystemTools::Error(e.str());
  1217. return false;
  1218. }
  1219. void cmGlobalGenerator::ComputeBuildFileGenerators()
  1220. {
  1221. for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
  1222. std::vector<std::unique_ptr<cmExportBuildFileGenerator>> const& gens =
  1223. this->Makefiles[i]->GetExportBuildFileGenerators();
  1224. for (std::unique_ptr<cmExportBuildFileGenerator> const& g : gens) {
  1225. g->Compute(this->LocalGenerators[i].get());
  1226. }
  1227. }
  1228. }
  1229. bool cmGlobalGenerator::UnsupportedVariableIsDefined(const std::string& name,
  1230. bool supported) const
  1231. {
  1232. if (!supported && this->Makefiles.front()->GetDefinition(name)) {
  1233. std::ostringstream e;
  1234. /* clang-format off */
  1235. e <<
  1236. "Generator\n"
  1237. " " << this->GetName() << "\n"
  1238. "does not support variable\n"
  1239. " " << name << "\n"
  1240. "but it has been specified."
  1241. ;
  1242. /* clang-format on */
  1243. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1244. return true;
  1245. }
  1246. return false;
  1247. }
  1248. bool cmGlobalGenerator::Compute()
  1249. {
  1250. // Make sure unsupported variables are not used.
  1251. if (this->UnsupportedVariableIsDefined("CMAKE_DEFAULT_BUILD_TYPE",
  1252. this->SupportsDefaultBuildType())) {
  1253. return false;
  1254. }
  1255. if (this->UnsupportedVariableIsDefined("CMAKE_CROSS_CONFIGS",
  1256. this->SupportsCrossConfigs())) {
  1257. return false;
  1258. }
  1259. if (this->UnsupportedVariableIsDefined("CMAKE_DEFAULT_CONFIGS",
  1260. this->SupportsDefaultConfigs())) {
  1261. return false;
  1262. }
  1263. // Some generators track files replaced during the Generate.
  1264. // Start with an empty vector:
  1265. this->FilesReplacedDuringGenerate.clear();
  1266. // clear targets to issue warning CMP0042 for
  1267. this->CMP0042WarnTargets.clear();
  1268. // clear targets to issue warning CMP0068 for
  1269. this->CMP0068WarnTargets.clear();
  1270. // Check whether this generator is allowed to run.
  1271. if (!this->CheckALLOW_DUPLICATE_CUSTOM_TARGETS()) {
  1272. return false;
  1273. }
  1274. this->FinalizeTargetCompileInfo();
  1275. this->CreateGenerationObjects();
  1276. // at this point this->LocalGenerators has been filled,
  1277. // so create the map from project name to vector of local generators
  1278. this->FillProjectMap();
  1279. // Add automatically generated sources (e.g. unity build).
  1280. if (!this->AddAutomaticSources()) {
  1281. return false;
  1282. }
  1283. // Iterate through all targets and set up AUTOMOC, AUTOUIC and AUTORCC
  1284. if (!this->QtAutoGen()) {
  1285. return false;
  1286. }
  1287. // Add generator specific helper commands
  1288. for (const auto& localGen : this->LocalGenerators) {
  1289. localGen->AddHelperCommands();
  1290. }
  1291. // Perform up-front computation in order to handle errors (such as unknown
  1292. // features) at this point. While processing the compile features we also
  1293. // calculate and cache the language standard required by the compile
  1294. // features.
  1295. for (const auto& localGen : this->LocalGenerators) {
  1296. if (!localGen->ComputeTargetCompileFeatures()) {
  1297. return false;
  1298. }
  1299. }
  1300. for (const auto& localGen : this->LocalGenerators) {
  1301. cmMakefile* mf = localGen->GetMakefile();
  1302. for (const auto& g : mf->GetInstallGenerators()) {
  1303. if (!g->Compute(localGen.get())) {
  1304. return false;
  1305. }
  1306. }
  1307. }
  1308. this->AddExtraIDETargets();
  1309. // Trace the dependencies, after that no custom commands should be added
  1310. // because their dependencies might not be handled correctly
  1311. for (const auto& localGen : this->LocalGenerators) {
  1312. localGen->TraceDependencies();
  1313. }
  1314. // Make sure that all (non-imported) targets have source files added!
  1315. if (this->CheckTargetsForMissingSources()) {
  1316. return false;
  1317. }
  1318. this->ForceLinkerLanguages();
  1319. // Compute the manifest of main targets generated.
  1320. for (const auto& localGen : this->LocalGenerators) {
  1321. localGen->ComputeTargetManifest();
  1322. }
  1323. // Compute the inter-target dependencies.
  1324. if (!this->ComputeTargetDepends()) {
  1325. return false;
  1326. }
  1327. this->ComputeTargetOrder();
  1328. if (this->CheckTargetsForType()) {
  1329. return false;
  1330. }
  1331. if (this->CheckTargetsForPchCompilePdb()) {
  1332. return false;
  1333. }
  1334. for (const auto& localGen : this->LocalGenerators) {
  1335. localGen->ComputeHomeRelativeOutputPath();
  1336. }
  1337. return true;
  1338. }
  1339. void cmGlobalGenerator::Generate()
  1340. {
  1341. // Create a map from local generator to the complete set of targets
  1342. // it builds by default.
  1343. this->InitializeProgressMarks();
  1344. this->ProcessEvaluationFiles();
  1345. this->CMakeInstance->UpdateProgress("Generating", 0.1f);
  1346. // Generate project files
  1347. for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
  1348. this->SetCurrentMakefile(this->LocalGenerators[i]->GetMakefile());
  1349. this->LocalGenerators[i]->Generate();
  1350. if (!this->LocalGenerators[i]->GetMakefile()->IsOn(
  1351. "CMAKE_SKIP_INSTALL_RULES")) {
  1352. this->LocalGenerators[i]->GenerateInstallRules();
  1353. }
  1354. this->LocalGenerators[i]->GenerateTestFiles();
  1355. this->CMakeInstance->UpdateProgress(
  1356. "Generating",
  1357. 0.1f +
  1358. 0.9f * (static_cast<float>(i) + 1.0f) /
  1359. static_cast<float>(this->LocalGenerators.size()));
  1360. }
  1361. this->SetCurrentMakefile(nullptr);
  1362. if (!this->GenerateCPackPropertiesFile()) {
  1363. this->GetCMakeInstance()->IssueMessage(
  1364. MessageType::FATAL_ERROR, "Could not write CPack properties file.");
  1365. }
  1366. for (auto& buildExpSet : this->BuildExportSets) {
  1367. if (!buildExpSet.second->GenerateImportFile()) {
  1368. if (!cmSystemTools::GetErrorOccuredFlag()) {
  1369. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  1370. "Could not write export file.");
  1371. }
  1372. return;
  1373. }
  1374. }
  1375. // Update rule hashes.
  1376. this->CheckRuleHashes();
  1377. this->WriteSummary();
  1378. if (this->ExtraGenerator) {
  1379. this->ExtraGenerator->Generate();
  1380. }
  1381. if (!this->CMP0042WarnTargets.empty()) {
  1382. std::ostringstream w;
  1383. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0042) << "\n";
  1384. w << "MACOSX_RPATH is not specified for"
  1385. " the following targets:\n";
  1386. for (std::string const& t : this->CMP0042WarnTargets) {
  1387. w << " " << t << "\n";
  1388. }
  1389. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  1390. w.str());
  1391. }
  1392. if (!this->CMP0068WarnTargets.empty()) {
  1393. std::ostringstream w;
  1394. /* clang-format off */
  1395. w <<
  1396. cmPolicies::GetPolicyWarning(cmPolicies::CMP0068) << "\n"
  1397. "For compatibility with older versions of CMake, the install_name "
  1398. "fields for the following targets are still affected by RPATH "
  1399. "settings:\n"
  1400. ;
  1401. /* clang-format on */
  1402. for (std::string const& t : this->CMP0068WarnTargets) {
  1403. w << " " << t << "\n";
  1404. }
  1405. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  1406. w.str());
  1407. }
  1408. this->CMakeInstance->UpdateProgress("Generating done", -1);
  1409. }
  1410. bool cmGlobalGenerator::ComputeTargetDepends()
  1411. {
  1412. cmComputeTargetDepends ctd(this);
  1413. if (!ctd.Compute()) {
  1414. return false;
  1415. }
  1416. for (cmGeneratorTarget const* target : ctd.GetTargets()) {
  1417. ctd.GetTargetDirectDepends(target, this->TargetDependencies[target]);
  1418. }
  1419. return true;
  1420. }
  1421. std::vector<cmGeneratorTarget*>
  1422. cmGlobalGenerator::GetLocalGeneratorTargetsInOrder(cmLocalGenerator* lg) const
  1423. {
  1424. std::vector<cmGeneratorTarget*> gts;
  1425. cm::append(gts, lg->GetGeneratorTargets());
  1426. std::sort(gts.begin(), gts.end(),
  1427. [this](cmGeneratorTarget const* l, cmGeneratorTarget const* r) {
  1428. return this->TargetOrderIndex.at(l) <
  1429. this->TargetOrderIndex.at(r);
  1430. });
  1431. return gts;
  1432. }
  1433. void cmGlobalGenerator::ComputeTargetOrder()
  1434. {
  1435. size_t index = 0;
  1436. auto const& lgens = this->GetLocalGenerators();
  1437. for (auto const& lgen : lgens) {
  1438. const auto& targets = lgen->GetGeneratorTargets();
  1439. for (const auto& gt : targets) {
  1440. this->ComputeTargetOrder(gt.get(), index);
  1441. }
  1442. }
  1443. assert(index == this->TargetOrderIndex.size());
  1444. }
  1445. void cmGlobalGenerator::ComputeTargetOrder(cmGeneratorTarget const* gt,
  1446. size_t& index)
  1447. {
  1448. std::map<cmGeneratorTarget const*, size_t>::value_type value(gt, 0);
  1449. auto insertion = this->TargetOrderIndex.insert(value);
  1450. if (!insertion.second) {
  1451. return;
  1452. }
  1453. auto entry = insertion.first;
  1454. auto& deps = this->GetTargetDirectDepends(gt);
  1455. for (auto& d : deps) {
  1456. this->ComputeTargetOrder(d, index);
  1457. }
  1458. entry->second = index++;
  1459. }
  1460. bool cmGlobalGenerator::QtAutoGen()
  1461. {
  1462. #ifndef CMAKE_BOOTSTRAP
  1463. cmQtAutoGenGlobalInitializer initializer(this->LocalGenerators);
  1464. return initializer.generate();
  1465. #else
  1466. return true;
  1467. #endif
  1468. }
  1469. bool cmGlobalGenerator::AddAutomaticSources()
  1470. {
  1471. for (const auto& lg : this->LocalGenerators) {
  1472. lg->CreateEvaluationFileOutputs();
  1473. for (const auto& gt : lg->GetGeneratorTargets()) {
  1474. if (!gt->CanCompileSources()) {
  1475. continue;
  1476. }
  1477. lg->AddUnityBuild(gt.get());
  1478. lg->AddISPCDependencies(gt.get());
  1479. // Targets that re-use a PCH are handled below.
  1480. if (!gt->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM")) {
  1481. lg->AddPchDependencies(gt.get());
  1482. }
  1483. }
  1484. }
  1485. for (const auto& lg : this->LocalGenerators) {
  1486. for (const auto& gt : lg->GetGeneratorTargets()) {
  1487. if (!gt->CanCompileSources()) {
  1488. continue;
  1489. }
  1490. // Handle targets that re-use a PCH from an above-handled target.
  1491. if (gt->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM")) {
  1492. lg->AddPchDependencies(gt.get());
  1493. }
  1494. }
  1495. }
  1496. // The above transformations may have changed the classification of sources.
  1497. // Clear the source list and classification cache (KindedSources) of all
  1498. // targets so that it will be recomputed correctly by the generators later
  1499. // now that the above transformations are done for all targets.
  1500. for (const auto& lg : this->LocalGenerators) {
  1501. for (const auto& gt : lg->GetGeneratorTargets()) {
  1502. gt->ClearSourcesCache();
  1503. }
  1504. }
  1505. return true;
  1506. }
  1507. std::unique_ptr<cmLinkLineComputer> cmGlobalGenerator::CreateLinkLineComputer(
  1508. cmOutputConverter* outputConverter, cmStateDirectory const& stateDir) const
  1509. {
  1510. return cm::make_unique<cmLinkLineComputer>(outputConverter, stateDir);
  1511. }
  1512. std::unique_ptr<cmLinkLineComputer>
  1513. cmGlobalGenerator::CreateMSVC60LinkLineComputer(
  1514. cmOutputConverter* outputConverter, cmStateDirectory const& stateDir) const
  1515. {
  1516. return std::unique_ptr<cmLinkLineComputer>(
  1517. cm::make_unique<cmMSVC60LinkLineComputer>(outputConverter, stateDir));
  1518. }
  1519. void cmGlobalGenerator::FinalizeTargetCompileInfo()
  1520. {
  1521. std::vector<std::string> const langs =
  1522. this->CMakeInstance->GetState()->GetEnabledLanguages();
  1523. // Construct per-target generator information.
  1524. for (const auto& mf : this->Makefiles) {
  1525. const cmStringRange noconfig_compile_definitions =
  1526. mf->GetCompileDefinitionsEntries();
  1527. const cmBacktraceRange noconfig_compile_definitions_bts =
  1528. mf->GetCompileDefinitionsBacktraces();
  1529. for (auto& target : mf->GetTargets()) {
  1530. cmTarget* t = &target.second;
  1531. if (t->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1532. continue;
  1533. }
  1534. t->AppendBuildInterfaceIncludes();
  1535. if (t->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  1536. continue;
  1537. }
  1538. {
  1539. auto btIt = noconfig_compile_definitions_bts.begin();
  1540. auto it = noconfig_compile_definitions.begin();
  1541. for (; it != noconfig_compile_definitions.end(); ++it, ++btIt) {
  1542. t->InsertCompileDefinition(*it, *btIt);
  1543. }
  1544. }
  1545. cmPolicies::PolicyStatus polSt =
  1546. mf->GetPolicyStatus(cmPolicies::CMP0043);
  1547. if (polSt == cmPolicies::WARN || polSt == cmPolicies::OLD) {
  1548. std::vector<std::string> configs =
  1549. mf->GetGeneratorConfigs(cmMakefile::ExcludeEmptyConfig);
  1550. for (std::string const& c : configs) {
  1551. std::string defPropName =
  1552. cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(c));
  1553. if (cmProp val = mf->GetProperty(defPropName)) {
  1554. t->AppendProperty(defPropName, *val);
  1555. }
  1556. }
  1557. }
  1558. }
  1559. // The standard include directories for each language
  1560. // should be treated as system include directories.
  1561. std::set<std::string> standardIncludesSet;
  1562. for (std::string const& li : langs) {
  1563. std::string const standardIncludesVar =
  1564. "CMAKE_" + li + "_STANDARD_INCLUDE_DIRECTORIES";
  1565. std::string const& standardIncludesStr =
  1566. mf->GetSafeDefinition(standardIncludesVar);
  1567. std::vector<std::string> standardIncludesVec =
  1568. cmExpandedList(standardIncludesStr);
  1569. standardIncludesSet.insert(standardIncludesVec.begin(),
  1570. standardIncludesVec.end());
  1571. }
  1572. mf->AddSystemIncludeDirectories(standardIncludesSet);
  1573. }
  1574. }
  1575. void cmGlobalGenerator::CreateGeneratorTargets(
  1576. TargetTypes targetTypes, cmMakefile* mf, cmLocalGenerator* lg,
  1577. std::map<cmTarget*, cmGeneratorTarget*> const& importedMap)
  1578. {
  1579. if (targetTypes == AllTargets) {
  1580. for (auto& target : mf->GetTargets()) {
  1581. cmTarget* t = &target.second;
  1582. lg->AddGeneratorTarget(cm::make_unique<cmGeneratorTarget>(t, lg));
  1583. }
  1584. }
  1585. for (cmTarget* t : mf->GetImportedTargets()) {
  1586. lg->AddImportedGeneratorTarget(importedMap.find(t)->second);
  1587. }
  1588. }
  1589. void cmGlobalGenerator::CreateGeneratorTargets(TargetTypes targetTypes)
  1590. {
  1591. std::map<cmTarget*, cmGeneratorTarget*> importedMap;
  1592. for (unsigned int i = 0; i < this->Makefiles.size(); ++i) {
  1593. auto& mf = this->Makefiles[i];
  1594. for (const auto& ownedImpTgt : mf->GetOwnedImportedTargets()) {
  1595. cmLocalGenerator* lg = this->LocalGenerators[i].get();
  1596. auto gt = cm::make_unique<cmGeneratorTarget>(ownedImpTgt.get(), lg);
  1597. importedMap[ownedImpTgt.get()] = gt.get();
  1598. lg->AddOwnedImportedGeneratorTarget(std::move(gt));
  1599. }
  1600. }
  1601. // Construct per-target generator information.
  1602. for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
  1603. this->CreateGeneratorTargets(targetTypes, this->Makefiles[i].get(),
  1604. this->LocalGenerators[i].get(), importedMap);
  1605. }
  1606. }
  1607. void cmGlobalGenerator::ClearGeneratorMembers()
  1608. {
  1609. this->BuildExportSets.clear();
  1610. this->Makefiles.clear();
  1611. this->LocalGenerators.clear();
  1612. this->AliasTargets.clear();
  1613. this->ExportSets.clear();
  1614. this->TargetDependencies.clear();
  1615. this->TargetSearchIndex.clear();
  1616. this->GeneratorTargetSearchIndex.clear();
  1617. this->MakefileSearchIndex.clear();
  1618. this->LocalGeneratorSearchIndex.clear();
  1619. this->TargetOrderIndex.clear();
  1620. this->ProjectMap.clear();
  1621. this->RuleHashes.clear();
  1622. this->DirectoryContentMap.clear();
  1623. this->BinaryDirectories.clear();
  1624. }
  1625. void cmGlobalGenerator::ComputeTargetObjectDirectory(
  1626. cmGeneratorTarget* /*unused*/) const
  1627. {
  1628. }
  1629. void cmGlobalGenerator::CheckTargetProperties()
  1630. {
  1631. // check for link libraries and include directories containing "NOTFOUND"
  1632. // and for infinite loops
  1633. std::map<std::string, std::string> notFoundMap;
  1634. cmState* state = this->GetCMakeInstance()->GetState();
  1635. for (unsigned int i = 0; i < this->Makefiles.size(); ++i) {
  1636. this->Makefiles[i]->Generate(*this->LocalGenerators[i]);
  1637. for (auto const& target : this->Makefiles[i]->GetTargets()) {
  1638. if (target.second.GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  1639. continue;
  1640. }
  1641. for (auto const& lib : target.second.GetOriginalLinkLibraries()) {
  1642. if (lib.first.size() > 9 && cmIsNOTFOUND(lib.first)) {
  1643. std::string varName = lib.first.substr(0, lib.first.size() - 9);
  1644. if (state->GetCacheEntryPropertyAsBool(varName, "ADVANCED")) {
  1645. varName += " (ADVANCED)";
  1646. }
  1647. std::string text =
  1648. cmStrCat(notFoundMap[varName], "\n linked by target \"",
  1649. target.second.GetName(), "\" in directory ",
  1650. this->Makefiles[i]->GetCurrentSourceDirectory());
  1651. notFoundMap[varName] = text;
  1652. }
  1653. }
  1654. std::vector<std::string> incs;
  1655. cmProp incDirProp = target.second.GetProperty("INCLUDE_DIRECTORIES");
  1656. if (!incDirProp) {
  1657. continue;
  1658. }
  1659. std::string incDirs = cmGeneratorExpression::Preprocess(
  1660. *incDirProp, cmGeneratorExpression::StripAllGeneratorExpressions);
  1661. cmExpandList(incDirs, incs);
  1662. for (std::string const& incDir : incs) {
  1663. if (incDir.size() > 9 && cmIsNOTFOUND(incDir)) {
  1664. std::string varName = incDir.substr(0, incDir.size() - 9);
  1665. if (state->GetCacheEntryPropertyAsBool(varName, "ADVANCED")) {
  1666. varName += " (ADVANCED)";
  1667. }
  1668. std::string text =
  1669. cmStrCat(notFoundMap[varName],
  1670. "\n used as include directory in directory ",
  1671. this->Makefiles[i]->GetCurrentSourceDirectory());
  1672. notFoundMap[varName] = text;
  1673. }
  1674. }
  1675. }
  1676. }
  1677. if (!notFoundMap.empty()) {
  1678. std::string notFoundVars;
  1679. for (auto const& notFound : notFoundMap) {
  1680. notFoundVars += notFound.first;
  1681. notFoundVars += notFound.second;
  1682. notFoundVars += "\n";
  1683. }
  1684. cmSystemTools::Error("The following variables are used in this project, "
  1685. "but they are set to NOTFOUND.\n"
  1686. "Please set them or make sure they are set and "
  1687. "tested correctly in the CMake files:\n" +
  1688. notFoundVars);
  1689. }
  1690. }
  1691. int cmGlobalGenerator::TryCompile(int jobs, const std::string& srcdir,
  1692. const std::string& bindir,
  1693. const std::string& projectName,
  1694. const std::string& target, bool fast,
  1695. std::string& output, cmMakefile* mf)
  1696. {
  1697. // if this is not set, then this is a first time configure
  1698. // and there is a good chance that the try compile stuff will
  1699. // take the bulk of the time, so try and guess some progress
  1700. // by getting closer and closer to 100 without actually getting there.
  1701. if (!this->CMakeInstance->GetState()->GetInitializedCacheValue(
  1702. "CMAKE_NUMBER_OF_MAKEFILES")) {
  1703. // If CMAKE_NUMBER_OF_MAKEFILES is not set
  1704. // we are in the first time progress and we have no
  1705. // idea how long it will be. So, just move 1/10th of the way
  1706. // there each time, and don't go over 95%
  1707. this->FirstTimeProgress += ((1.0f - this->FirstTimeProgress) / 30.0f);
  1708. if (this->FirstTimeProgress > 0.95f) {
  1709. this->FirstTimeProgress = 0.95f;
  1710. }
  1711. this->CMakeInstance->UpdateProgress("Configuring",
  1712. this->FirstTimeProgress);
  1713. }
  1714. std::vector<std::string> newTarget = {};
  1715. if (!target.empty()) {
  1716. newTarget = { target };
  1717. }
  1718. std::string config =
  1719. mf->GetSafeDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  1720. return this->Build(jobs, srcdir, bindir, projectName, newTarget, output, "",
  1721. config, false, fast, false, this->TryCompileTimeout);
  1722. }
  1723. std::vector<cmGlobalGenerator::GeneratedMakeCommand>
  1724. cmGlobalGenerator::GenerateBuildCommand(
  1725. const std::string& /*unused*/, const std::string& /*unused*/,
  1726. const std::string& /*unused*/, std::vector<std::string> const& /*unused*/,
  1727. const std::string& /*unused*/, bool /*unused*/, int /*unused*/,
  1728. bool /*unused*/, std::vector<std::string> const& /*unused*/)
  1729. {
  1730. GeneratedMakeCommand makeCommand;
  1731. makeCommand.Add("cmGlobalGenerator::GenerateBuildCommand not implemented");
  1732. return { std::move(makeCommand) };
  1733. }
  1734. void cmGlobalGenerator::PrintBuildCommandAdvice(std::ostream& /*os*/,
  1735. int /*jobs*/) const
  1736. {
  1737. // Subclasses override this method if they e.g want to give a warning that
  1738. // they do not support certain build command line options
  1739. }
  1740. int cmGlobalGenerator::Build(
  1741. int jobs, const std::string& /*unused*/, const std::string& bindir,
  1742. const std::string& projectName, const std::vector<std::string>& targets,
  1743. std::string& output, const std::string& makeCommandCSTR,
  1744. const std::string& config, bool clean, bool fast, bool verbose,
  1745. cmDuration timeout, cmSystemTools::OutputOption outputflag,
  1746. std::vector<std::string> const& nativeOptions)
  1747. {
  1748. bool hideconsole = cmSystemTools::GetRunCommandHideConsole();
  1749. /**
  1750. * Run an executable command and put the stdout in output.
  1751. */
  1752. cmWorkingDirectory workdir(bindir);
  1753. output += "Change Dir: ";
  1754. output += bindir;
  1755. output += "\n";
  1756. if (workdir.Failed()) {
  1757. cmSystemTools::SetRunCommandHideConsole(hideconsole);
  1758. std::string err = cmStrCat("Failed to change directory: ",
  1759. std::strerror(workdir.GetLastResult()));
  1760. cmSystemTools::Error(err);
  1761. output += err;
  1762. output += "\n";
  1763. return 1;
  1764. }
  1765. std::string realConfig = config;
  1766. if (realConfig.empty()) {
  1767. realConfig = this->GetDefaultBuildConfig();
  1768. }
  1769. int retVal = 0;
  1770. cmSystemTools::SetRunCommandHideConsole(true);
  1771. std::string outputBuffer;
  1772. std::string* outputPtr = &outputBuffer;
  1773. std::vector<GeneratedMakeCommand> makeCommand =
  1774. this->GenerateBuildCommand(makeCommandCSTR, projectName, bindir, targets,
  1775. realConfig, fast, jobs, verbose, nativeOptions);
  1776. // Workaround to convince some commands to produce output.
  1777. if (outputflag == cmSystemTools::OUTPUT_PASSTHROUGH &&
  1778. makeCommand.back().RequiresOutputForward) {
  1779. outputflag = cmSystemTools::OUTPUT_FORWARD;
  1780. }
  1781. // should we do a clean first?
  1782. if (clean) {
  1783. std::vector<GeneratedMakeCommand> cleanCommand =
  1784. this->GenerateBuildCommand(makeCommandCSTR, projectName, bindir,
  1785. { "clean" }, realConfig, fast, jobs, verbose);
  1786. output += "\nRun Clean Command:";
  1787. output += cleanCommand.front().Printable();
  1788. output += "\n";
  1789. if (cleanCommand.size() != 1) {
  1790. this->GetCMakeInstance()->IssueMessage(MessageType::INTERNAL_ERROR,
  1791. "The generator did not produce "
  1792. "exactly one command for the "
  1793. "'clean' target");
  1794. return 1;
  1795. }
  1796. if (!cmSystemTools::RunSingleCommand(cleanCommand.front().PrimaryCommand,
  1797. outputPtr, outputPtr, &retVal,
  1798. nullptr, outputflag, timeout)) {
  1799. cmSystemTools::SetRunCommandHideConsole(hideconsole);
  1800. cmSystemTools::Error("Generator: execution of make clean failed.");
  1801. output += *outputPtr;
  1802. output += "\nGenerator: execution of make clean failed.\n";
  1803. return 1;
  1804. }
  1805. output += *outputPtr;
  1806. }
  1807. // now build
  1808. std::string makeCommandStr;
  1809. output += "\nRun Build Command(s):";
  1810. retVal = 0;
  1811. for (auto command = makeCommand.begin();
  1812. command != makeCommand.end() && retVal == 0; ++command) {
  1813. makeCommandStr = command->Printable();
  1814. if (command != makeCommand.end()) {
  1815. makeCommandStr += " && ";
  1816. }
  1817. output += makeCommandStr;
  1818. if (!cmSystemTools::RunSingleCommand(command->PrimaryCommand, outputPtr,
  1819. outputPtr, &retVal, nullptr,
  1820. outputflag, timeout)) {
  1821. cmSystemTools::SetRunCommandHideConsole(hideconsole);
  1822. cmSystemTools::Error(
  1823. "Generator: execution of make failed. Make command was: " +
  1824. makeCommandStr);
  1825. output += *outputPtr;
  1826. output += "\nGenerator: execution of make failed. Make command was: " +
  1827. makeCommandStr + "\n";
  1828. return 1;
  1829. }
  1830. output += *outputPtr;
  1831. }
  1832. output += "\n";
  1833. cmSystemTools::SetRunCommandHideConsole(hideconsole);
  1834. // The OpenWatcom tools do not return an error code when a link
  1835. // library is not found!
  1836. if (this->CMakeInstance->GetState()->UseWatcomWMake() && retVal == 0 &&
  1837. output.find("W1008: cannot open") != std::string::npos) {
  1838. retVal = 1;
  1839. }
  1840. return retVal;
  1841. }
  1842. bool cmGlobalGenerator::Open(const std::string& bindir,
  1843. const std::string& projectName, bool dryRun)
  1844. {
  1845. if (this->ExtraGenerator) {
  1846. return this->ExtraGenerator->Open(bindir, projectName, dryRun);
  1847. }
  1848. return false;
  1849. }
  1850. std::string cmGlobalGenerator::GenerateCMakeBuildCommand(
  1851. const std::string& target, const std::string& config,
  1852. const std::string& native, bool ignoreErrors)
  1853. {
  1854. std::string makeCommand = cmSystemTools::GetCMakeCommand();
  1855. makeCommand =
  1856. cmStrCat(cmSystemTools::ConvertToOutputPath(makeCommand), " --build .");
  1857. if (!config.empty()) {
  1858. makeCommand += " --config \"";
  1859. makeCommand += config;
  1860. makeCommand += "\"";
  1861. }
  1862. if (!target.empty()) {
  1863. makeCommand += " --target \"";
  1864. makeCommand += target;
  1865. makeCommand += "\"";
  1866. }
  1867. const char* sep = " -- ";
  1868. if (ignoreErrors) {
  1869. const char* iflag = this->GetBuildIgnoreErrorsFlag();
  1870. if (iflag && *iflag) {
  1871. makeCommand += sep;
  1872. makeCommand += iflag;
  1873. sep = " ";
  1874. }
  1875. }
  1876. if (!native.empty()) {
  1877. makeCommand += sep;
  1878. makeCommand += native;
  1879. }
  1880. return makeCommand;
  1881. }
  1882. void cmGlobalGenerator::AddMakefile(std::unique_ptr<cmMakefile> mf)
  1883. {
  1884. this->IndexMakefile(mf.get());
  1885. this->Makefiles.push_back(std::move(mf));
  1886. // update progress
  1887. // estimate how many lg there will be
  1888. cmProp numGenC = this->CMakeInstance->GetState()->GetInitializedCacheValue(
  1889. "CMAKE_NUMBER_OF_MAKEFILES");
  1890. if (!numGenC) {
  1891. // If CMAKE_NUMBER_OF_MAKEFILES is not set
  1892. // we are in the first time progress and we have no
  1893. // idea how long it will be. So, just move half way
  1894. // there each time, and don't go over 95%
  1895. this->FirstTimeProgress += ((1.0f - this->FirstTimeProgress) / 30.0f);
  1896. if (this->FirstTimeProgress > 0.95f) {
  1897. this->FirstTimeProgress = 0.95f;
  1898. }
  1899. this->CMakeInstance->UpdateProgress("Configuring",
  1900. this->FirstTimeProgress);
  1901. return;
  1902. }
  1903. int numGen = atoi(numGenC->c_str());
  1904. float prog =
  1905. static_cast<float>(this->Makefiles.size()) / static_cast<float>(numGen);
  1906. if (prog > 1.0f) {
  1907. prog = 1.0f;
  1908. }
  1909. this->CMakeInstance->UpdateProgress("Configuring", prog);
  1910. }
  1911. void cmGlobalGenerator::AddInstallComponent(const std::string& component)
  1912. {
  1913. if (!component.empty()) {
  1914. this->InstallComponents.insert(component);
  1915. }
  1916. }
  1917. void cmGlobalGenerator::EnableInstallTarget()
  1918. {
  1919. this->InstallTargetEnabled = true;
  1920. }
  1921. std::unique_ptr<cmLocalGenerator> cmGlobalGenerator::CreateLocalGenerator(
  1922. cmMakefile* mf)
  1923. {
  1924. return cm::make_unique<cmLocalGenerator>(this, mf);
  1925. }
  1926. void cmGlobalGenerator::EnableLanguagesFromGenerator(cmGlobalGenerator* gen,
  1927. cmMakefile* mf)
  1928. {
  1929. this->SetConfiguredFilesPath(gen);
  1930. this->TryCompileOuterMakefile = mf;
  1931. const char* make =
  1932. gen->GetCMakeInstance()->GetCacheDefinition("CMAKE_MAKE_PROGRAM");
  1933. this->GetCMakeInstance()->AddCacheEntry(
  1934. "CMAKE_MAKE_PROGRAM", make, "make program", cmStateEnums::FILEPATH);
  1935. // copy the enabled languages
  1936. this->GetCMakeInstance()->GetState()->SetEnabledLanguages(
  1937. gen->GetCMakeInstance()->GetState()->GetEnabledLanguages());
  1938. this->LanguagesReady = gen->LanguagesReady;
  1939. this->ExtensionToLanguage = gen->ExtensionToLanguage;
  1940. this->IgnoreExtensions = gen->IgnoreExtensions;
  1941. this->LanguageToOutputExtension = gen->LanguageToOutputExtension;
  1942. this->LanguageToLinkerPreference = gen->LanguageToLinkerPreference;
  1943. this->OutputExtensions = gen->OutputExtensions;
  1944. }
  1945. void cmGlobalGenerator::SetConfiguredFilesPath(cmGlobalGenerator* gen)
  1946. {
  1947. if (!gen->ConfiguredFilesPath.empty()) {
  1948. this->ConfiguredFilesPath = gen->ConfiguredFilesPath;
  1949. } else {
  1950. this->ConfiguredFilesPath =
  1951. cmStrCat(gen->CMakeInstance->GetHomeOutputDirectory(), "/CMakeFiles");
  1952. }
  1953. }
  1954. bool cmGlobalGenerator::IsExcluded(cmStateSnapshot const& rootSnp,
  1955. cmStateSnapshot const& snp_) const
  1956. {
  1957. cmStateSnapshot snp = snp_;
  1958. while (snp.IsValid()) {
  1959. if (snp == rootSnp) {
  1960. // No directory excludes itself.
  1961. return false;
  1962. }
  1963. if (snp.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  1964. // This directory is excluded from its parent.
  1965. return true;
  1966. }
  1967. snp = snp.GetBuildsystemDirectoryParent();
  1968. }
  1969. return false;
  1970. }
  1971. bool cmGlobalGenerator::IsExcluded(cmLocalGenerator* root,
  1972. cmLocalGenerator* gen) const
  1973. {
  1974. assert(gen);
  1975. cmStateSnapshot rootSnp = root->GetStateSnapshot();
  1976. cmStateSnapshot snp = gen->GetStateSnapshot();
  1977. return this->IsExcluded(rootSnp, snp);
  1978. }
  1979. bool cmGlobalGenerator::IsExcluded(cmLocalGenerator* root,
  1980. const cmGeneratorTarget* target) const
  1981. {
  1982. if (!target->IsInBuildSystem()) {
  1983. return true;
  1984. }
  1985. cmMakefile* mf = root->GetMakefile();
  1986. const std::string EXCLUDE_FROM_ALL = "EXCLUDE_FROM_ALL";
  1987. if (cmProp exclude = target->GetProperty(EXCLUDE_FROM_ALL)) {
  1988. // Expand the property value per configuration.
  1989. unsigned int trueCount = 0;
  1990. unsigned int falseCount = 0;
  1991. const std::vector<std::string>& configs =
  1992. mf->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  1993. for (const std::string& config : configs) {
  1994. cmGeneratorExpressionInterpreter genexInterpreter(root, config, target);
  1995. if (cmIsOn(genexInterpreter.Evaluate(*exclude, EXCLUDE_FROM_ALL))) {
  1996. ++trueCount;
  1997. } else {
  1998. ++falseCount;
  1999. }
  2000. }
  2001. // Check whether the genex expansion of the property agrees in all
  2002. // configurations.
  2003. if (trueCount && falseCount) {
  2004. std::ostringstream e;
  2005. e << "The EXCLUDE_FROM_ALL property of target \"" << target->GetName()
  2006. << "\" varies by configuration. This is not supported by the \""
  2007. << root->GetGlobalGenerator()->GetName() << "\" generator.";
  2008. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2009. }
  2010. return trueCount;
  2011. }
  2012. // This target is included in its directory. Check whether the
  2013. // directory is excluded.
  2014. return this->IsExcluded(root, target->GetLocalGenerator());
  2015. }
  2016. void cmGlobalGenerator::GetEnabledLanguages(
  2017. std::vector<std::string>& lang) const
  2018. {
  2019. lang = this->CMakeInstance->GetState()->GetEnabledLanguages();
  2020. }
  2021. int cmGlobalGenerator::GetLinkerPreference(const std::string& lang) const
  2022. {
  2023. auto const it = this->LanguageToLinkerPreference.find(lang);
  2024. if (it != this->LanguageToLinkerPreference.end()) {
  2025. return it->second;
  2026. }
  2027. return 0;
  2028. }
  2029. void cmGlobalGenerator::FillProjectMap()
  2030. {
  2031. this->ProjectMap.clear(); // make sure we start with a clean map
  2032. for (const auto& localGen : this->LocalGenerators) {
  2033. // for each local generator add all projects
  2034. cmStateSnapshot snp = localGen->GetStateSnapshot();
  2035. std::string name;
  2036. do {
  2037. std::string snpProjName = snp.GetProjectName();
  2038. if (name != snpProjName) {
  2039. name = snpProjName;
  2040. this->ProjectMap[name].push_back(localGen.get());
  2041. }
  2042. snp = snp.GetBuildsystemDirectoryParent();
  2043. } while (snp.IsValid());
  2044. }
  2045. }
  2046. cmMakefile* cmGlobalGenerator::FindMakefile(const std::string& start_dir) const
  2047. {
  2048. auto const it = this->MakefileSearchIndex.find(start_dir);
  2049. if (it != this->MakefileSearchIndex.end()) {
  2050. return it->second;
  2051. }
  2052. return nullptr;
  2053. }
  2054. cmLocalGenerator* cmGlobalGenerator::FindLocalGenerator(
  2055. cmDirectoryId const& id) const
  2056. {
  2057. auto const it = this->LocalGeneratorSearchIndex.find(id.String);
  2058. if (it != this->LocalGeneratorSearchIndex.end()) {
  2059. return it->second;
  2060. }
  2061. return nullptr;
  2062. }
  2063. void cmGlobalGenerator::AddAlias(const std::string& name,
  2064. std::string const& tgtName)
  2065. {
  2066. this->AliasTargets[name] = tgtName;
  2067. }
  2068. bool cmGlobalGenerator::IsAlias(const std::string& name) const
  2069. {
  2070. return cm::contains(this->AliasTargets, name);
  2071. }
  2072. void cmGlobalGenerator::IndexTarget(cmTarget* t)
  2073. {
  2074. if (!t->IsImported() || t->IsImportedGloballyVisible()) {
  2075. this->TargetSearchIndex[t->GetName()] = t;
  2076. }
  2077. }
  2078. void cmGlobalGenerator::IndexGeneratorTarget(cmGeneratorTarget* gt)
  2079. {
  2080. if (!gt->IsImported() || gt->IsImportedGloballyVisible()) {
  2081. this->GeneratorTargetSearchIndex[gt->GetName()] = gt;
  2082. }
  2083. }
  2084. static char const hexDigits[] = "0123456789abcdef";
  2085. std::string cmGlobalGenerator::IndexGeneratorTargetUniquely(
  2086. cmGeneratorTarget const* gt)
  2087. {
  2088. // Use the pointer value to uniquely identify the target instance.
  2089. // Use a ":" prefix to avoid conflict with project-defined targets.
  2090. // We must satisfy cmGeneratorExpression::IsValidTargetName so use no
  2091. // other special characters.
  2092. constexpr size_t sizeof_ptr =
  2093. sizeof(gt); // NOLINT(bugprone-sizeof-expression)
  2094. char buf[1 + sizeof_ptr * 2];
  2095. char* b = buf;
  2096. *b++ = ':';
  2097. for (size_t i = 0; i < sizeof_ptr; ++i) {
  2098. unsigned char const c = reinterpret_cast<unsigned char const*>(&gt)[i];
  2099. *b++ = hexDigits[(c & 0xf0) >> 4];
  2100. *b++ = hexDigits[(c & 0x0f)];
  2101. }
  2102. std::string id(buf, sizeof(buf));
  2103. // We internally index pointers to non-const generator targets
  2104. // but our callers only have pointers to const generator targets.
  2105. // They will give up non-const privileges when looking up anyway.
  2106. this->GeneratorTargetSearchIndex[id] = const_cast<cmGeneratorTarget*>(gt);
  2107. return id;
  2108. }
  2109. void cmGlobalGenerator::IndexMakefile(cmMakefile* mf)
  2110. {
  2111. // FIXME: add_subdirectory supports multiple build directories
  2112. // sharing the same source directory. We currently index only the
  2113. // first one, because that is what FindMakefile has always returned.
  2114. // All of its callers will need to be modified to support looking
  2115. // up directories by build directory path.
  2116. this->MakefileSearchIndex.insert(
  2117. MakefileMap::value_type(mf->GetCurrentSourceDirectory(), mf));
  2118. }
  2119. void cmGlobalGenerator::IndexLocalGenerator(cmLocalGenerator* lg)
  2120. {
  2121. cmDirectoryId id = lg->GetMakefile()->GetDirectoryId();
  2122. this->LocalGeneratorSearchIndex[id.String] = lg;
  2123. }
  2124. cmTarget* cmGlobalGenerator::FindTargetImpl(std::string const& name) const
  2125. {
  2126. auto const it = this->TargetSearchIndex.find(name);
  2127. if (it != this->TargetSearchIndex.end()) {
  2128. return it->second;
  2129. }
  2130. return nullptr;
  2131. }
  2132. cmGeneratorTarget* cmGlobalGenerator::FindGeneratorTargetImpl(
  2133. std::string const& name) const
  2134. {
  2135. auto const it = this->GeneratorTargetSearchIndex.find(name);
  2136. if (it != this->GeneratorTargetSearchIndex.end()) {
  2137. return it->second;
  2138. }
  2139. return nullptr;
  2140. }
  2141. cmTarget* cmGlobalGenerator::FindTarget(const std::string& name,
  2142. bool excludeAliases) const
  2143. {
  2144. if (!excludeAliases) {
  2145. auto const ai = this->AliasTargets.find(name);
  2146. if (ai != this->AliasTargets.end()) {
  2147. return this->FindTargetImpl(ai->second);
  2148. }
  2149. }
  2150. return this->FindTargetImpl(name);
  2151. }
  2152. cmGeneratorTarget* cmGlobalGenerator::FindGeneratorTarget(
  2153. const std::string& name) const
  2154. {
  2155. auto const ai = this->AliasTargets.find(name);
  2156. if (ai != this->AliasTargets.end()) {
  2157. return this->FindGeneratorTargetImpl(ai->second);
  2158. }
  2159. return this->FindGeneratorTargetImpl(name);
  2160. }
  2161. bool cmGlobalGenerator::NameResolvesToFramework(
  2162. const std::string& libname) const
  2163. {
  2164. if (cmSystemTools::IsPathToFramework(libname)) {
  2165. return true;
  2166. }
  2167. if (cmTarget* tgt = this->FindTarget(libname)) {
  2168. if (tgt->IsFrameworkOnApple()) {
  2169. return true;
  2170. }
  2171. }
  2172. return false;
  2173. }
  2174. bool cmGlobalGenerator::CheckCMP0037(std::string const& targetName,
  2175. std::string const& reason) const
  2176. {
  2177. cmTarget* tgt = this->FindTarget(targetName);
  2178. if (!tgt) {
  2179. return true;
  2180. }
  2181. MessageType messageType = MessageType::AUTHOR_WARNING;
  2182. std::ostringstream e;
  2183. bool issueMessage = false;
  2184. switch (tgt->GetPolicyStatusCMP0037()) {
  2185. case cmPolicies::WARN:
  2186. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0037) << "\n";
  2187. issueMessage = true;
  2188. CM_FALLTHROUGH;
  2189. case cmPolicies::OLD:
  2190. break;
  2191. case cmPolicies::NEW:
  2192. case cmPolicies::REQUIRED_IF_USED:
  2193. case cmPolicies::REQUIRED_ALWAYS:
  2194. issueMessage = true;
  2195. messageType = MessageType::FATAL_ERROR;
  2196. break;
  2197. }
  2198. if (issueMessage) {
  2199. e << "The target name \"" << targetName << "\" is reserved " << reason
  2200. << ".";
  2201. if (messageType == MessageType::AUTHOR_WARNING) {
  2202. e << " It may result in undefined behavior.";
  2203. }
  2204. this->GetCMakeInstance()->IssueMessage(messageType, e.str(),
  2205. tgt->GetBacktrace());
  2206. if (messageType == MessageType::FATAL_ERROR) {
  2207. return false;
  2208. }
  2209. }
  2210. return true;
  2211. }
  2212. void cmGlobalGenerator::CreateDefaultGlobalTargets(
  2213. std::vector<GlobalTargetInfo>& targets)
  2214. {
  2215. this->AddGlobalTarget_Package(targets);
  2216. this->AddGlobalTarget_PackageSource(targets);
  2217. this->AddGlobalTarget_Test(targets);
  2218. this->AddGlobalTarget_EditCache(targets);
  2219. this->AddGlobalTarget_RebuildCache(targets);
  2220. this->AddGlobalTarget_Install(targets);
  2221. }
  2222. void cmGlobalGenerator::AddGlobalTarget_Package(
  2223. std::vector<GlobalTargetInfo>& targets)
  2224. {
  2225. auto& mf = this->Makefiles[0];
  2226. std::string configFile =
  2227. cmStrCat(mf->GetCurrentBinaryDirectory(), "/CPackConfig.cmake");
  2228. if (!cmSystemTools::FileExists(configFile)) {
  2229. return;
  2230. }
  2231. static const auto reservedTargets = { "package", "PACKAGE" };
  2232. for (auto const& target : reservedTargets) {
  2233. if (!this->CheckCMP0037(target, "when CPack packaging is enabled")) {
  2234. return;
  2235. }
  2236. }
  2237. const char* cmakeCfgIntDir = this->GetCMakeCFGIntDir();
  2238. GlobalTargetInfo gti;
  2239. gti.Name = this->GetPackageTargetName();
  2240. gti.Message = "Run CPack packaging tool...";
  2241. gti.UsesTerminal = true;
  2242. gti.WorkingDir = mf->GetCurrentBinaryDirectory();
  2243. cmCustomCommandLine singleLine;
  2244. singleLine.push_back(cmSystemTools::GetCPackCommand());
  2245. if (cmNonempty(cmakeCfgIntDir) && cmakeCfgIntDir[0] != '.') {
  2246. singleLine.push_back("-C");
  2247. singleLine.push_back(cmakeCfgIntDir);
  2248. }
  2249. singleLine.push_back("--config");
  2250. singleLine.push_back("./CPackConfig.cmake");
  2251. gti.CommandLines.push_back(std::move(singleLine));
  2252. if (this->GetPreinstallTargetName()) {
  2253. gti.Depends.emplace_back(this->GetPreinstallTargetName());
  2254. } else {
  2255. cmProp noPackageAll =
  2256. mf->GetDefinition("CMAKE_SKIP_PACKAGE_ALL_DEPENDENCY");
  2257. if (cmIsOff(noPackageAll)) {
  2258. gti.Depends.emplace_back(this->GetAllTargetName());
  2259. }
  2260. }
  2261. targets.push_back(std::move(gti));
  2262. }
  2263. void cmGlobalGenerator::AddGlobalTarget_PackageSource(
  2264. std::vector<GlobalTargetInfo>& targets)
  2265. {
  2266. const char* packageSourceTargetName = this->GetPackageSourceTargetName();
  2267. if (!packageSourceTargetName) {
  2268. return;
  2269. }
  2270. auto& mf = this->Makefiles[0];
  2271. std::string configFile =
  2272. cmStrCat(mf->GetCurrentBinaryDirectory(), "/CPackSourceConfig.cmake");
  2273. if (!cmSystemTools::FileExists(configFile)) {
  2274. return;
  2275. }
  2276. static const auto reservedTargets = { "package_source" };
  2277. for (auto const& target : reservedTargets) {
  2278. if (!this->CheckCMP0037(target,
  2279. "when CPack source packaging is enabled")) {
  2280. return;
  2281. }
  2282. }
  2283. GlobalTargetInfo gti;
  2284. gti.Name = packageSourceTargetName;
  2285. gti.Message = "Run CPack packaging tool for source...";
  2286. gti.WorkingDir = mf->GetCurrentBinaryDirectory();
  2287. gti.UsesTerminal = true;
  2288. cmCustomCommandLine singleLine;
  2289. singleLine.push_back(cmSystemTools::GetCPackCommand());
  2290. singleLine.push_back("--config");
  2291. singleLine.push_back("./CPackSourceConfig.cmake");
  2292. singleLine.push_back(std::move(configFile));
  2293. gti.CommandLines.push_back(std::move(singleLine));
  2294. targets.push_back(std::move(gti));
  2295. }
  2296. void cmGlobalGenerator::AddGlobalTarget_Test(
  2297. std::vector<GlobalTargetInfo>& targets)
  2298. {
  2299. auto& mf = this->Makefiles[0];
  2300. if (!mf->IsOn("CMAKE_TESTING_ENABLED")) {
  2301. return;
  2302. }
  2303. static const auto reservedTargets = { "test", "RUN_TESTS" };
  2304. for (auto const& target : reservedTargets) {
  2305. if (!this->CheckCMP0037(target, "when CTest testing is enabled")) {
  2306. return;
  2307. }
  2308. }
  2309. const char* cmakeCfgIntDir = this->GetCMakeCFGIntDir();
  2310. GlobalTargetInfo gti;
  2311. gti.Name = this->GetTestTargetName();
  2312. gti.Message = "Running tests...";
  2313. gti.UsesTerminal = true;
  2314. cmCustomCommandLine singleLine;
  2315. singleLine.push_back(cmSystemTools::GetCTestCommand());
  2316. singleLine.push_back("--force-new-ctest-process");
  2317. std::vector<std::string> args;
  2318. if (mf->GetDefExpandList("CMAKE_CTEST_ARGUMENTS", args)) {
  2319. for (auto const& arg : args) {
  2320. singleLine.push_back(arg);
  2321. }
  2322. }
  2323. if (cmNonempty(cmakeCfgIntDir) && cmakeCfgIntDir[0] != '.') {
  2324. singleLine.push_back("-C");
  2325. singleLine.push_back(cmakeCfgIntDir);
  2326. } else // TODO: This is a hack. Should be something to do with the
  2327. // generator
  2328. {
  2329. singleLine.push_back("$(ARGS)");
  2330. }
  2331. gti.CommandLines.push_back(std::move(singleLine));
  2332. targets.push_back(std::move(gti));
  2333. }
  2334. void cmGlobalGenerator::AddGlobalTarget_EditCache(
  2335. std::vector<GlobalTargetInfo>& targets)
  2336. {
  2337. const char* editCacheTargetName = this->GetEditCacheTargetName();
  2338. if (!editCacheTargetName) {
  2339. return;
  2340. }
  2341. GlobalTargetInfo gti;
  2342. gti.Name = editCacheTargetName;
  2343. gti.PerConfig = cmTarget::PerConfig::No;
  2344. cmCustomCommandLine singleLine;
  2345. // Use generator preference for the edit_cache rule if it is defined.
  2346. std::string edit_cmd = this->GetEditCacheCommand();
  2347. if (!edit_cmd.empty()) {
  2348. singleLine.push_back(std::move(edit_cmd));
  2349. singleLine.push_back("-S$(CMAKE_SOURCE_DIR)");
  2350. singleLine.push_back("-B$(CMAKE_BINARY_DIR)");
  2351. gti.Message = "Running CMake cache editor...";
  2352. gti.UsesTerminal = true;
  2353. } else {
  2354. singleLine.push_back(cmSystemTools::GetCMakeCommand());
  2355. singleLine.push_back("-E");
  2356. singleLine.push_back("echo");
  2357. singleLine.push_back("No interactive CMake dialog available.");
  2358. gti.Message = "No interactive CMake dialog available...";
  2359. gti.UsesTerminal = false;
  2360. gti.StdPipesUTF8 = true;
  2361. }
  2362. gti.CommandLines.push_back(std::move(singleLine));
  2363. targets.push_back(std::move(gti));
  2364. }
  2365. void cmGlobalGenerator::AddGlobalTarget_RebuildCache(
  2366. std::vector<GlobalTargetInfo>& targets)
  2367. {
  2368. const char* rebuildCacheTargetName = this->GetRebuildCacheTargetName();
  2369. if (!rebuildCacheTargetName) {
  2370. return;
  2371. }
  2372. GlobalTargetInfo gti;
  2373. gti.Name = rebuildCacheTargetName;
  2374. gti.Message = "Running CMake to regenerate build system...";
  2375. gti.UsesTerminal = true;
  2376. gti.PerConfig = cmTarget::PerConfig::No;
  2377. cmCustomCommandLine singleLine;
  2378. singleLine.push_back(cmSystemTools::GetCMakeCommand());
  2379. singleLine.push_back("--regenerate-during-build");
  2380. singleLine.push_back("-S$(CMAKE_SOURCE_DIR)");
  2381. singleLine.push_back("-B$(CMAKE_BINARY_DIR)");
  2382. gti.CommandLines.push_back(std::move(singleLine));
  2383. gti.StdPipesUTF8 = true;
  2384. targets.push_back(std::move(gti));
  2385. }
  2386. void cmGlobalGenerator::AddGlobalTarget_Install(
  2387. std::vector<GlobalTargetInfo>& targets)
  2388. {
  2389. auto& mf = this->Makefiles[0];
  2390. const char* cmakeCfgIntDir = this->GetCMakeCFGIntDir();
  2391. bool skipInstallRules = mf->IsOn("CMAKE_SKIP_INSTALL_RULES");
  2392. if (this->InstallTargetEnabled && skipInstallRules) {
  2393. this->CMakeInstance->IssueMessage(
  2394. MessageType::WARNING,
  2395. "CMAKE_SKIP_INSTALL_RULES was enabled even though "
  2396. "installation rules have been specified",
  2397. mf->GetBacktrace());
  2398. } else if (this->InstallTargetEnabled && !skipInstallRules) {
  2399. if (!(cmNonempty(cmakeCfgIntDir) && cmakeCfgIntDir[0] != '.')) {
  2400. std::set<std::string>* componentsSet = &this->InstallComponents;
  2401. std::ostringstream ostr;
  2402. if (!componentsSet->empty()) {
  2403. ostr << "Available install components are: ";
  2404. ostr << cmWrap('"', *componentsSet, '"', " ");
  2405. } else {
  2406. ostr << "Only default component available";
  2407. }
  2408. GlobalTargetInfo gti;
  2409. gti.Name = "list_install_components";
  2410. gti.Message = ostr.str();
  2411. gti.UsesTerminal = false;
  2412. targets.push_back(std::move(gti));
  2413. }
  2414. std::string cmd = cmSystemTools::GetCMakeCommand();
  2415. GlobalTargetInfo gti;
  2416. gti.Name = this->GetInstallTargetName();
  2417. gti.Message = "Install the project...";
  2418. gti.UsesTerminal = true;
  2419. gti.StdPipesUTF8 = true;
  2420. cmCustomCommandLine singleLine;
  2421. if (this->GetPreinstallTargetName()) {
  2422. gti.Depends.emplace_back(this->GetPreinstallTargetName());
  2423. } else {
  2424. cmProp noall = mf->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
  2425. if (cmIsOff(noall)) {
  2426. gti.Depends.emplace_back(this->GetAllTargetName());
  2427. }
  2428. }
  2429. if (mf->GetDefinition("CMake_BINARY_DIR") &&
  2430. !mf->IsOn("CMAKE_CROSSCOMPILING")) {
  2431. // We are building CMake itself. We cannot use the original
  2432. // executable to install over itself. The generator will
  2433. // automatically convert this name to the build-time location.
  2434. cmd = "cmake";
  2435. }
  2436. singleLine.push_back(cmd);
  2437. if (cmNonempty(cmakeCfgIntDir) && cmakeCfgIntDir[0] != '.') {
  2438. std::string cfgArg = "-DBUILD_TYPE=";
  2439. bool useEPN = this->UseEffectivePlatformName(mf.get());
  2440. if (useEPN) {
  2441. cfgArg += "$(CONFIGURATION)";
  2442. singleLine.push_back(cfgArg);
  2443. cfgArg = "-DEFFECTIVE_PLATFORM_NAME=$(EFFECTIVE_PLATFORM_NAME)";
  2444. } else {
  2445. cfgArg += cmToCStr(mf->GetDefinition("CMAKE_CFG_INTDIR"));
  2446. }
  2447. singleLine.push_back(cfgArg);
  2448. }
  2449. singleLine.push_back("-P");
  2450. singleLine.push_back("cmake_install.cmake");
  2451. gti.CommandLines.push_back(singleLine);
  2452. targets.push_back(gti);
  2453. // install_local
  2454. if (const char* install_local = this->GetInstallLocalTargetName()) {
  2455. gti.Name = install_local;
  2456. gti.Message = "Installing only the local directory...";
  2457. gti.UsesTerminal = true;
  2458. gti.CommandLines.clear();
  2459. cmCustomCommandLine localCmdLine = singleLine;
  2460. localCmdLine.insert(localCmdLine.begin() + 1,
  2461. "-DCMAKE_INSTALL_LOCAL_ONLY=1");
  2462. gti.CommandLines.push_back(std::move(localCmdLine));
  2463. targets.push_back(gti);
  2464. }
  2465. // install_strip
  2466. const char* install_strip = this->GetInstallStripTargetName();
  2467. if ((install_strip != nullptr) && (mf->IsSet("CMAKE_STRIP"))) {
  2468. gti.Name = install_strip;
  2469. gti.Message = "Installing the project stripped...";
  2470. gti.UsesTerminal = true;
  2471. gti.CommandLines.clear();
  2472. cmCustomCommandLine stripCmdLine = singleLine;
  2473. stripCmdLine.insert(stripCmdLine.begin() + 1,
  2474. "-DCMAKE_INSTALL_DO_STRIP=1");
  2475. gti.CommandLines.push_back(std::move(stripCmdLine));
  2476. targets.push_back(gti);
  2477. }
  2478. }
  2479. }
  2480. std::string cmGlobalGenerator::GetPredefinedTargetsFolder()
  2481. {
  2482. cmProp prop = this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  2483. "PREDEFINED_TARGETS_FOLDER");
  2484. if (prop) {
  2485. return *prop;
  2486. }
  2487. return "CMakePredefinedTargets";
  2488. }
  2489. bool cmGlobalGenerator::UseFolderProperty() const
  2490. {
  2491. cmProp prop =
  2492. this->GetCMakeInstance()->GetState()->GetGlobalProperty("USE_FOLDERS");
  2493. // If this property is defined, let the setter turn this on or off...
  2494. //
  2495. if (prop) {
  2496. return cmIsOn(*prop);
  2497. }
  2498. // By default, this feature is OFF, since it is not supported in the
  2499. // Visual Studio Express editions until VS11:
  2500. //
  2501. return false;
  2502. }
  2503. cmTarget cmGlobalGenerator::CreateGlobalTarget(GlobalTargetInfo const& gti,
  2504. cmMakefile* mf)
  2505. {
  2506. // Package
  2507. cmTarget target(gti.Name, cmStateEnums::GLOBAL_TARGET,
  2508. cmTarget::VisibilityNormal, mf, gti.PerConfig);
  2509. target.SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  2510. std::vector<std::string> no_outputs;
  2511. std::vector<std::string> no_byproducts;
  2512. std::vector<std::string> no_depends;
  2513. // Store the custom command in the target.
  2514. cmCustomCommand cc(no_outputs, no_byproducts, no_depends, gti.CommandLines,
  2515. cmListFileBacktrace(), nullptr, gti.WorkingDir.c_str(),
  2516. gti.StdPipesUTF8);
  2517. cc.SetUsesTerminal(gti.UsesTerminal);
  2518. target.AddPostBuildCommand(std::move(cc));
  2519. if (!gti.Message.empty()) {
  2520. target.SetProperty("EchoString", gti.Message);
  2521. }
  2522. for (std::string const& d : gti.Depends) {
  2523. target.AddUtility(d, false);
  2524. }
  2525. // Organize in the "predefined targets" folder:
  2526. //
  2527. if (this->UseFolderProperty()) {
  2528. target.SetProperty("FOLDER", this->GetPredefinedTargetsFolder());
  2529. }
  2530. return target;
  2531. }
  2532. std::string cmGlobalGenerator::GenerateRuleFile(
  2533. std::string const& output) const
  2534. {
  2535. std::string ruleFile = cmStrCat(output, ".rule");
  2536. const char* dir = this->GetCMakeCFGIntDir();
  2537. if (dir && dir[0] == '$') {
  2538. cmSystemTools::ReplaceString(ruleFile, dir, "/CMakeFiles");
  2539. }
  2540. return ruleFile;
  2541. }
  2542. bool cmGlobalGenerator::ShouldStripResourcePath(cmMakefile* mf) const
  2543. {
  2544. return mf->PlatformIsAppleEmbedded();
  2545. }
  2546. std::string cmGlobalGenerator::GetSharedLibFlagsForLanguage(
  2547. std::string const& l) const
  2548. {
  2549. auto const it = this->LanguageToOriginalSharedLibFlags.find(l);
  2550. if (it != this->LanguageToOriginalSharedLibFlags.end()) {
  2551. return it->second;
  2552. }
  2553. return "";
  2554. }
  2555. void cmGlobalGenerator::AppendDirectoryForConfig(const std::string& /*unused*/,
  2556. const std::string& /*unused*/,
  2557. const std::string& /*unused*/,
  2558. std::string& /*unused*/)
  2559. {
  2560. // Subclasses that support multiple configurations should implement
  2561. // this method to append the subdirectory for the given build
  2562. // configuration.
  2563. }
  2564. cmGlobalGenerator::TargetDependSet const&
  2565. cmGlobalGenerator::GetTargetDirectDepends(cmGeneratorTarget const* target)
  2566. {
  2567. return this->TargetDependencies[target];
  2568. }
  2569. bool cmGlobalGenerator::IsReservedTarget(std::string const& name)
  2570. {
  2571. // The following is a list of targets reserved
  2572. // by one or more of the cmake generators.
  2573. // Adding additional targets to this list will require a policy!
  2574. const char* reservedTargets[] = { "all", "ALL_BUILD", "help",
  2575. "install", "INSTALL", "preinstall",
  2576. "clean", "edit_cache", "rebuild_cache",
  2577. "ZERO_CHECK" };
  2578. return cm::contains(reservedTargets, name);
  2579. }
  2580. void cmGlobalGenerator::SetExternalMakefileProjectGenerator(
  2581. std::unique_ptr<cmExternalMakefileProjectGenerator> extraGenerator)
  2582. {
  2583. this->ExtraGenerator = std::move(extraGenerator);
  2584. if (this->ExtraGenerator) {
  2585. this->ExtraGenerator->SetGlobalGenerator(this);
  2586. }
  2587. }
  2588. std::string cmGlobalGenerator::GetExtraGeneratorName() const
  2589. {
  2590. return this->ExtraGenerator ? this->ExtraGenerator->GetName()
  2591. : std::string();
  2592. }
  2593. void cmGlobalGenerator::FileReplacedDuringGenerate(const std::string& filename)
  2594. {
  2595. this->FilesReplacedDuringGenerate.push_back(filename);
  2596. }
  2597. void cmGlobalGenerator::GetFilesReplacedDuringGenerate(
  2598. std::vector<std::string>& filenames)
  2599. {
  2600. filenames.clear();
  2601. std::copy(this->FilesReplacedDuringGenerate.begin(),
  2602. this->FilesReplacedDuringGenerate.end(),
  2603. std::back_inserter(filenames));
  2604. }
  2605. void cmGlobalGenerator::GetTargetSets(
  2606. TargetDependSet& projectTargets, TargetDependSet& originalTargets,
  2607. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  2608. {
  2609. // loop over all local generators
  2610. for (auto generator : generators) {
  2611. // check to make sure generator is not excluded
  2612. if (this->IsExcluded(root, generator)) {
  2613. continue;
  2614. }
  2615. // loop over all the generator targets in the makefile
  2616. for (const auto& target : generator->GetGeneratorTargets()) {
  2617. if (this->IsRootOnlyTarget(target.get()) &&
  2618. target->GetLocalGenerator() != root) {
  2619. continue;
  2620. }
  2621. // put the target in the set of original targets
  2622. originalTargets.insert(target.get());
  2623. // Get the set of targets that depend on target
  2624. this->AddTargetDepends(target.get(), projectTargets);
  2625. }
  2626. }
  2627. }
  2628. bool cmGlobalGenerator::IsRootOnlyTarget(cmGeneratorTarget* target) const
  2629. {
  2630. return (target->GetType() == cmStateEnums::GLOBAL_TARGET ||
  2631. target->GetName() == this->GetAllTargetName());
  2632. }
  2633. void cmGlobalGenerator::AddTargetDepends(cmGeneratorTarget const* target,
  2634. TargetDependSet& projectTargets)
  2635. {
  2636. // add the target itself
  2637. if (projectTargets.insert(target).second) {
  2638. // This is the first time we have encountered the target.
  2639. // Recursively follow its dependencies.
  2640. for (auto const& t : this->GetTargetDirectDepends(target)) {
  2641. this->AddTargetDepends(t, projectTargets);
  2642. }
  2643. }
  2644. }
  2645. void cmGlobalGenerator::AddToManifest(std::string const& f)
  2646. {
  2647. // Add to the content listing for the file's directory.
  2648. std::string dir = cmSystemTools::GetFilenamePath(f);
  2649. std::string file = cmSystemTools::GetFilenameName(f);
  2650. DirectoryContent& dc = this->DirectoryContentMap[dir];
  2651. dc.Generated.insert(file);
  2652. dc.All.insert(file);
  2653. }
  2654. std::set<std::string> const& cmGlobalGenerator::GetDirectoryContent(
  2655. std::string const& dir, bool needDisk)
  2656. {
  2657. DirectoryContent& dc = this->DirectoryContentMap[dir];
  2658. if (needDisk) {
  2659. long mt = cmSystemTools::ModifiedTime(dir);
  2660. if (mt != dc.LastDiskTime) {
  2661. // Reset to non-loaded directory content.
  2662. dc.All = dc.Generated;
  2663. // Load the directory content from disk.
  2664. cmsys::Directory d;
  2665. if (d.Load(dir)) {
  2666. unsigned long n = d.GetNumberOfFiles();
  2667. for (unsigned long i = 0; i < n; ++i) {
  2668. const char* f = d.GetFile(i);
  2669. if (strcmp(f, ".") != 0 && strcmp(f, "..") != 0) {
  2670. dc.All.insert(f);
  2671. }
  2672. }
  2673. }
  2674. dc.LastDiskTime = mt;
  2675. }
  2676. }
  2677. return dc.All;
  2678. }
  2679. void cmGlobalGenerator::AddRuleHash(const std::vector<std::string>& outputs,
  2680. std::string const& content)
  2681. {
  2682. #if !defined(CMAKE_BOOTSTRAP)
  2683. // Ignore if there are no outputs.
  2684. if (outputs.empty()) {
  2685. return;
  2686. }
  2687. // Compute a hash of the rule.
  2688. RuleHash hash;
  2689. {
  2690. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  2691. std::string const md5_hex = md5.HashString(content);
  2692. memcpy(hash.Data, md5_hex.c_str(), 32);
  2693. }
  2694. // Shorten the output name (in expected use case).
  2695. cmStateDirectory cmDir =
  2696. this->GetMakefiles()[0]->GetStateSnapshot().GetDirectory();
  2697. std::string fname = cmDir.ConvertToRelPathIfNotContained(
  2698. this->GetMakefiles()[0]->GetState()->GetBinaryDirectory(), outputs[0]);
  2699. // Associate the hash with this output.
  2700. this->RuleHashes[fname] = hash;
  2701. #else
  2702. (void)outputs;
  2703. (void)content;
  2704. #endif
  2705. }
  2706. void cmGlobalGenerator::CheckRuleHashes()
  2707. {
  2708. #if !defined(CMAKE_BOOTSTRAP)
  2709. std::string home = this->GetCMakeInstance()->GetHomeOutputDirectory();
  2710. std::string pfile = cmStrCat(home, "/CMakeFiles/CMakeRuleHashes.txt");
  2711. this->CheckRuleHashes(pfile, home);
  2712. this->WriteRuleHashes(pfile);
  2713. #endif
  2714. }
  2715. void cmGlobalGenerator::CheckRuleHashes(std::string const& pfile,
  2716. std::string const& home)
  2717. {
  2718. #if defined(_WIN32) || defined(__CYGWIN__)
  2719. cmsys::ifstream fin(pfile.c_str(), std::ios::in | std::ios::binary);
  2720. #else
  2721. cmsys::ifstream fin(pfile.c_str());
  2722. #endif
  2723. if (!fin) {
  2724. return;
  2725. }
  2726. std::string line;
  2727. std::string fname;
  2728. while (cmSystemTools::GetLineFromStream(fin, line)) {
  2729. // Line format is a 32-byte hex string followed by a space
  2730. // followed by a file name (with no escaping).
  2731. // Skip blank and comment lines.
  2732. if (line.size() < 34 || line[0] == '#') {
  2733. continue;
  2734. }
  2735. // Get the filename.
  2736. fname = line.substr(33);
  2737. // Look for a hash for this file's rule.
  2738. auto const rhi = this->RuleHashes.find(fname);
  2739. if (rhi != this->RuleHashes.end()) {
  2740. // Compare the rule hash in the file to that we were given.
  2741. if (strncmp(line.c_str(), rhi->second.Data, 32) != 0) {
  2742. // The rule has changed. Delete the output so it will be
  2743. // built again.
  2744. fname = cmSystemTools::CollapseFullPath(fname, home);
  2745. cmSystemTools::RemoveFile(fname);
  2746. }
  2747. } else {
  2748. // We have no hash for a rule previously listed. This may be a
  2749. // case where a user has turned off a build option and might
  2750. // want to turn it back on later, so do not delete the file.
  2751. // Instead, we keep the rule hash as long as the file exists so
  2752. // that if the feature is turned back on and the rule has
  2753. // changed the file is still rebuilt.
  2754. std::string fpath = cmSystemTools::CollapseFullPath(fname, home);
  2755. if (cmSystemTools::FileExists(fpath)) {
  2756. RuleHash hash;
  2757. memcpy(hash.Data, line.c_str(), 32);
  2758. this->RuleHashes[fname] = hash;
  2759. }
  2760. }
  2761. }
  2762. }
  2763. void cmGlobalGenerator::WriteRuleHashes(std::string const& pfile)
  2764. {
  2765. // Now generate a new persistence file with the current hashes.
  2766. if (this->RuleHashes.empty()) {
  2767. cmSystemTools::RemoveFile(pfile);
  2768. } else {
  2769. cmGeneratedFileStream fout(pfile);
  2770. fout << "# Hashes of file build rules.\n";
  2771. for (auto const& rh : this->RuleHashes) {
  2772. fout.write(rh.second.Data, 32);
  2773. fout << " " << rh.first << "\n";
  2774. }
  2775. }
  2776. }
  2777. void cmGlobalGenerator::WriteSummary()
  2778. {
  2779. // Record all target directories in a central location.
  2780. std::string fname = cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(),
  2781. "/CMakeFiles/TargetDirectories.txt");
  2782. cmGeneratedFileStream fout(fname);
  2783. for (const auto& lg : this->LocalGenerators) {
  2784. for (const auto& tgt : lg->GetGeneratorTargets()) {
  2785. if (!tgt->IsInBuildSystem()) {
  2786. continue;
  2787. }
  2788. this->WriteSummary(tgt.get());
  2789. fout << tgt->GetSupportDirectory() << "\n";
  2790. }
  2791. }
  2792. }
  2793. void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target)
  2794. {
  2795. // Place the labels file in a per-target support directory.
  2796. std::string dir = target->GetSupportDirectory();
  2797. std::string file = cmStrCat(dir, "/Labels.txt");
  2798. std::string json_file = dir + "/Labels.json";
  2799. #ifndef CMAKE_BOOTSTRAP
  2800. // Check whether labels are enabled for this target.
  2801. cmProp targetLabels = target->GetProperty("LABELS");
  2802. cmProp directoryLabels =
  2803. target->Target->GetMakefile()->GetProperty("LABELS");
  2804. cmProp cmakeDirectoryLabels =
  2805. target->Target->GetMakefile()->GetDefinition("CMAKE_DIRECTORY_LABELS");
  2806. if (targetLabels || directoryLabels || cmakeDirectoryLabels) {
  2807. Json::Value lj_root(Json::objectValue);
  2808. Json::Value& lj_target = lj_root["target"] = Json::objectValue;
  2809. lj_target["name"] = target->GetName();
  2810. Json::Value& lj_target_labels = lj_target["labels"] = Json::arrayValue;
  2811. Json::Value& lj_sources = lj_root["sources"] = Json::arrayValue;
  2812. cmSystemTools::MakeDirectory(dir);
  2813. cmGeneratedFileStream fout(file);
  2814. std::vector<std::string> labels;
  2815. // List the target-wide labels. All sources in the target get
  2816. // these labels.
  2817. if (targetLabels) {
  2818. cmExpandList(*targetLabels, labels);
  2819. if (!labels.empty()) {
  2820. fout << "# Target labels\n";
  2821. for (std::string const& l : labels) {
  2822. fout << " " << l << "\n";
  2823. lj_target_labels.append(l);
  2824. }
  2825. }
  2826. }
  2827. // List directory labels
  2828. std::vector<std::string> directoryLabelsList;
  2829. std::vector<std::string> cmakeDirectoryLabelsList;
  2830. if (directoryLabels) {
  2831. cmExpandList(*directoryLabels, directoryLabelsList);
  2832. }
  2833. if (cmakeDirectoryLabels) {
  2834. cmExpandList(*cmakeDirectoryLabels, cmakeDirectoryLabelsList);
  2835. }
  2836. if (!directoryLabelsList.empty() || !cmakeDirectoryLabelsList.empty()) {
  2837. fout << "# Directory labels\n";
  2838. }
  2839. for (std::string const& li : directoryLabelsList) {
  2840. fout << " " << li << "\n";
  2841. lj_target_labels.append(li);
  2842. }
  2843. for (std::string const& li : cmakeDirectoryLabelsList) {
  2844. fout << " " << li << "\n";
  2845. lj_target_labels.append(li);
  2846. }
  2847. // List the source files with any per-source labels.
  2848. fout << "# Source files and their labels\n";
  2849. std::vector<cmSourceFile*> sources;
  2850. std::vector<std::string> const& configs =
  2851. target->Target->GetMakefile()->GetGeneratorConfigs(
  2852. cmMakefile::IncludeEmptyConfig);
  2853. for (std::string const& c : configs) {
  2854. target->GetSourceFiles(sources, c);
  2855. }
  2856. auto const sourcesEnd = cmRemoveDuplicates(sources);
  2857. for (cmSourceFile* sf : cmMakeRange(sources.cbegin(), sourcesEnd)) {
  2858. Json::Value& lj_source = lj_sources.append(Json::objectValue);
  2859. std::string const& sfp = sf->ResolveFullPath();
  2860. fout << sfp << "\n";
  2861. lj_source["file"] = sfp;
  2862. if (cmProp svalue = sf->GetProperty("LABELS")) {
  2863. labels.clear();
  2864. Json::Value& lj_source_labels = lj_source["labels"] = Json::arrayValue;
  2865. cmExpandList(*svalue, labels);
  2866. for (std::string const& label : labels) {
  2867. fout << " " << label << "\n";
  2868. lj_source_labels.append(label);
  2869. }
  2870. }
  2871. }
  2872. cmGeneratedFileStream json_fout(json_file);
  2873. json_fout << lj_root;
  2874. } else
  2875. #endif
  2876. {
  2877. cmSystemTools::RemoveFile(file);
  2878. cmSystemTools::RemoveFile(json_file);
  2879. }
  2880. }
  2881. // static
  2882. std::string cmGlobalGenerator::EscapeJSON(const std::string& s)
  2883. {
  2884. std::string result;
  2885. result.reserve(s.size());
  2886. for (char i : s) {
  2887. switch (i) {
  2888. case '"':
  2889. case '\\':
  2890. result += '\\';
  2891. result += i;
  2892. break;
  2893. case '\n':
  2894. result += "\\n";
  2895. break;
  2896. case '\t':
  2897. result += "\\t";
  2898. break;
  2899. default:
  2900. result += i;
  2901. }
  2902. }
  2903. return result;
  2904. }
  2905. void cmGlobalGenerator::SetFilenameTargetDepends(
  2906. cmSourceFile* sf, std::set<cmGeneratorTarget const*> const& tgts)
  2907. {
  2908. this->FilenameTargetDepends[sf] = tgts;
  2909. }
  2910. std::set<cmGeneratorTarget const*> const&
  2911. cmGlobalGenerator::GetFilenameTargetDepends(cmSourceFile* sf) const
  2912. {
  2913. return this->FilenameTargetDepends[sf];
  2914. }
  2915. const std::string& cmGlobalGenerator::GetRealPath(const std::string& dir)
  2916. {
  2917. auto i = this->RealPaths.lower_bound(dir);
  2918. if (i == this->RealPaths.end() ||
  2919. this->RealPaths.key_comp()(dir, i->first)) {
  2920. i = this->RealPaths.emplace_hint(i, dir, cmSystemTools::GetRealPath(dir));
  2921. }
  2922. return i->second;
  2923. }
  2924. void cmGlobalGenerator::ProcessEvaluationFiles()
  2925. {
  2926. std::vector<std::string> generatedFiles;
  2927. for (auto& localGen : this->LocalGenerators) {
  2928. localGen->ProcessEvaluationFiles(generatedFiles);
  2929. }
  2930. }
  2931. std::string cmGlobalGenerator::ExpandCFGIntDir(
  2932. const std::string& str, const std::string& /*config*/) const
  2933. {
  2934. return str;
  2935. }
  2936. bool cmGlobalGenerator::GenerateCPackPropertiesFile()
  2937. {
  2938. cmake::InstalledFilesMap const& installedFiles =
  2939. this->CMakeInstance->GetInstalledFiles();
  2940. const auto& lg = this->LocalGenerators[0];
  2941. cmMakefile* mf = lg->GetMakefile();
  2942. std::vector<std::string> configs =
  2943. mf->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
  2944. std::string config = mf->GetDefaultConfiguration();
  2945. std::string path = cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(),
  2946. "/CPackProperties.cmake");
  2947. if (!cmSystemTools::FileExists(path) && installedFiles.empty()) {
  2948. return true;
  2949. }
  2950. cmGeneratedFileStream file(path);
  2951. file << "# CPack properties\n";
  2952. for (auto const& i : installedFiles) {
  2953. cmInstalledFile const& installedFile = i.second;
  2954. cmCPackPropertiesGenerator cpackPropertiesGenerator(
  2955. lg.get(), installedFile, configs);
  2956. cpackPropertiesGenerator.Generate(file, config, configs);
  2957. }
  2958. return true;
  2959. }