cmGlobalGenerator.cxx 102 KB

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