cmGlobalGenerator.cxx 101 KB

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