cmake.cxx 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299
  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 "cmake.h"
  4. #include <algorithm>
  5. #include <cstdio>
  6. #include <cstdlib>
  7. #include <cstring>
  8. #include <initializer_list>
  9. #include <iostream>
  10. #include <sstream>
  11. #include <stdexcept>
  12. #include <utility>
  13. #include <cm/memory>
  14. #include <cm/optional>
  15. #include <cm/string_view>
  16. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  17. # include <cm/iterator>
  18. #endif
  19. #include <cmext/algorithm>
  20. #include <cmext/string_view>
  21. #include "cmsys/FStream.hxx"
  22. #include "cmsys/Glob.hxx"
  23. #include "cmsys/RegularExpression.hxx"
  24. #include "cm_sys_stat.h"
  25. #include "cmCMakePresetsFile.h"
  26. #include "cmCommands.h"
  27. #include "cmDocumentation.h"
  28. #include "cmDocumentationEntry.h"
  29. #include "cmDocumentationFormatter.h"
  30. #include "cmDuration.h"
  31. #include "cmExternalMakefileProjectGenerator.h"
  32. #include "cmFileTimeCache.h"
  33. #include "cmGeneratorTarget.h"
  34. #include "cmGlobalGenerator.h"
  35. #include "cmGlobalGeneratorFactory.h"
  36. #include "cmLinkLineComputer.h"
  37. #include "cmLocalGenerator.h"
  38. #include "cmMakefile.h"
  39. #if !defined(CMAKE_BOOTSTRAP)
  40. # include "cmMakefileProfilingData.h"
  41. #endif
  42. #include "cmMessenger.h"
  43. #include "cmState.h"
  44. #include "cmStateDirectory.h"
  45. #include "cmStringAlgorithms.h"
  46. #include "cmSystemTools.h"
  47. #include "cmTarget.h"
  48. #include "cmTargetLinkLibraryType.h"
  49. #include "cmUtils.hxx"
  50. #include "cmVersionConfig.h"
  51. #include "cmWorkingDirectory.h"
  52. #if !defined(CMAKE_BOOTSTRAP)
  53. # include <unordered_map>
  54. # include <cm3p/json/writer.h>
  55. # include "cmFileAPI.h"
  56. # include "cmGraphVizWriter.h"
  57. # include "cmVariableWatch.h"
  58. #endif
  59. #if defined(__MINGW32__) && defined(CMAKE_BOOTSTRAP)
  60. # define CMAKE_BOOT_MINGW
  61. #endif
  62. // include the generator
  63. #if defined(_WIN32) && !defined(__CYGWIN__)
  64. # if !defined(CMAKE_BOOT_MINGW)
  65. # include <cmext/memory>
  66. # include "cmGlobalBorlandMakefileGenerator.h"
  67. # include "cmGlobalJOMMakefileGenerator.h"
  68. # include "cmGlobalNMakeMakefileGenerator.h"
  69. # include "cmGlobalVisualStudio10Generator.h"
  70. # include "cmGlobalVisualStudio11Generator.h"
  71. # include "cmGlobalVisualStudio12Generator.h"
  72. # include "cmGlobalVisualStudio14Generator.h"
  73. # include "cmGlobalVisualStudio9Generator.h"
  74. # include "cmGlobalVisualStudioVersionedGenerator.h"
  75. # include "cmVSSetupHelper.h"
  76. # define CMAKE_HAVE_VS_GENERATORS
  77. # endif
  78. # include "cmGlobalMSYSMakefileGenerator.h"
  79. # include "cmGlobalMinGWMakefileGenerator.h"
  80. #else
  81. #endif
  82. #if defined(CMAKE_USE_WMAKE)
  83. # include "cmGlobalWatcomWMakeGenerator.h"
  84. #endif
  85. #if !defined(CMAKE_BOOTSTRAP)
  86. # include "cmGlobalNinjaGenerator.h"
  87. # include "cmGlobalUnixMakefileGenerator3.h"
  88. #elif defined(CMAKE_BOOTSTRAP_MAKEFILES)
  89. # include "cmGlobalUnixMakefileGenerator3.h"
  90. #elif defined(CMAKE_BOOTSTRAP_NINJA)
  91. # include "cmGlobalNinjaGenerator.h"
  92. #endif
  93. #if !defined(CMAKE_BOOTSTRAP)
  94. # include "cmExtraCodeBlocksGenerator.h"
  95. # include "cmExtraCodeLiteGenerator.h"
  96. # include "cmExtraEclipseCDT4Generator.h"
  97. # include "cmExtraKateGenerator.h"
  98. # include "cmExtraSublimeTextGenerator.h"
  99. #endif
  100. #if defined(__linux__) || defined(_WIN32)
  101. # include "cmGlobalGhsMultiGenerator.h"
  102. #endif
  103. #if defined(__APPLE__)
  104. # if !defined(CMAKE_BOOTSTRAP)
  105. # include "cmGlobalXCodeGenerator.h"
  106. # define CMAKE_USE_XCODE 1
  107. # endif
  108. # include <sys/resource.h>
  109. # include <sys/time.h>
  110. #endif
  111. namespace {
  112. #if !defined(CMAKE_BOOTSTRAP)
  113. using JsonValueMapType = std::unordered_map<std::string, Json::Value>;
  114. #endif
  115. } // namespace
  116. static bool cmakeCheckStampFile(const std::string& stampName);
  117. static bool cmakeCheckStampList(const std::string& stampList);
  118. #ifndef CMAKE_BOOTSTRAP
  119. static void cmWarnUnusedCliWarning(const std::string& variable, int /*unused*/,
  120. void* ctx, const char* /*unused*/,
  121. const cmMakefile* /*unused*/)
  122. {
  123. cmake* cm = reinterpret_cast<cmake*>(ctx);
  124. cm->MarkCliAsUsed(variable);
  125. }
  126. #endif
  127. cmake::cmake(Role role, cmState::Mode mode)
  128. : FileTimeCache(cm::make_unique<cmFileTimeCache>())
  129. #ifndef CMAKE_BOOTSTRAP
  130. , VariableWatch(cm::make_unique<cmVariableWatch>())
  131. #endif
  132. , State(cm::make_unique<cmState>())
  133. , Messenger(cm::make_unique<cmMessenger>())
  134. {
  135. this->TraceFile.close();
  136. this->State->SetMode(mode);
  137. this->CurrentSnapshot = this->State->CreateBaseSnapshot();
  138. #ifdef __APPLE__
  139. struct rlimit rlp;
  140. if (!getrlimit(RLIMIT_STACK, &rlp)) {
  141. if (rlp.rlim_cur != rlp.rlim_max) {
  142. rlp.rlim_cur = rlp.rlim_max;
  143. setrlimit(RLIMIT_STACK, &rlp);
  144. }
  145. }
  146. #endif
  147. this->AddDefaultGenerators();
  148. this->AddDefaultExtraGenerators();
  149. if (role == RoleScript || role == RoleProject) {
  150. this->AddScriptingCommands();
  151. }
  152. if (role == RoleProject) {
  153. this->AddProjectCommands();
  154. }
  155. if (mode == cmState::Project) {
  156. this->LoadEnvironmentPresets();
  157. }
  158. // Make sure we can capture the build tool output.
  159. cmSystemTools::EnableVSConsoleOutput();
  160. // Set up a list of source and header extensions.
  161. // These are used to find files when the extension is not given.
  162. {
  163. auto setupExts = [](FileExtensions& exts,
  164. std::initializer_list<cm::string_view> extList) {
  165. // Fill ordered vector
  166. exts.ordered.reserve(extList.size());
  167. for (cm::string_view ext : extList) {
  168. exts.ordered.emplace_back(ext);
  169. };
  170. // Fill unordered set
  171. exts.unordered.insert(exts.ordered.begin(), exts.ordered.end());
  172. };
  173. // The "c" extension MUST precede the "C" extension.
  174. setupExts(this->CLikeSourceFileExtensions,
  175. { "c", "C", "c++", "cc", "cpp", "cxx", "cu", "m", "M", "mm" });
  176. setupExts(this->HeaderFileExtensions,
  177. { "h", "hh", "h++", "hm", "hpp", "hxx", "in", "txx" });
  178. setupExts(this->CudaFileExtensions, { "cu" });
  179. setupExts(this->FortranFileExtensions,
  180. { "f", "F", "for", "f77", "f90", "f95", "f03" });
  181. setupExts(this->ISPCFileExtensions, { "ispc" });
  182. }
  183. }
  184. cmake::~cmake() = default;
  185. #if !defined(CMAKE_BOOTSTRAP)
  186. Json::Value cmake::ReportVersionJson() const
  187. {
  188. Json::Value version = Json::objectValue;
  189. version["string"] = CMake_VERSION;
  190. version["major"] = CMake_VERSION_MAJOR;
  191. version["minor"] = CMake_VERSION_MINOR;
  192. version["suffix"] = CMake_VERSION_SUFFIX;
  193. version["isDirty"] = (CMake_VERSION_IS_DIRTY == 1);
  194. version["patch"] = CMake_VERSION_PATCH;
  195. return version;
  196. }
  197. Json::Value cmake::ReportCapabilitiesJson() const
  198. {
  199. Json::Value obj = Json::objectValue;
  200. // Version information:
  201. obj["version"] = this->ReportVersionJson();
  202. // Generators:
  203. std::vector<cmake::GeneratorInfo> generatorInfoList;
  204. this->GetRegisteredGenerators(generatorInfoList);
  205. JsonValueMapType generatorMap;
  206. for (cmake::GeneratorInfo const& gi : generatorInfoList) {
  207. if (gi.isAlias) { // skip aliases, they are there for compatibility reasons
  208. // only
  209. continue;
  210. }
  211. if (gi.extraName.empty()) {
  212. Json::Value gen = Json::objectValue;
  213. gen["name"] = gi.name;
  214. gen["toolsetSupport"] = gi.supportsToolset;
  215. gen["platformSupport"] = gi.supportsPlatform;
  216. gen["extraGenerators"] = Json::arrayValue;
  217. generatorMap[gi.name] = gen;
  218. } else {
  219. Json::Value& gen = generatorMap[gi.baseName];
  220. gen["extraGenerators"].append(gi.extraName);
  221. }
  222. }
  223. Json::Value generators = Json::arrayValue;
  224. for (auto const& i : generatorMap) {
  225. generators.append(i.second);
  226. }
  227. obj["generators"] = generators;
  228. obj["fileApi"] = cmFileAPI::ReportCapabilities();
  229. obj["serverMode"] = true;
  230. return obj;
  231. }
  232. #endif
  233. std::string cmake::ReportCapabilities() const
  234. {
  235. std::string result;
  236. #if !defined(CMAKE_BOOTSTRAP)
  237. Json::FastWriter writer;
  238. result = writer.write(this->ReportCapabilitiesJson());
  239. #else
  240. result = "Not supported";
  241. #endif
  242. return result;
  243. }
  244. void cmake::CleanupCommandsAndMacros()
  245. {
  246. this->CurrentSnapshot = this->State->Reset();
  247. this->State->RemoveUserDefinedCommands();
  248. this->CurrentSnapshot.SetDefaultDefinitions();
  249. }
  250. #ifndef CMAKE_BOOTSTRAP
  251. void cmake::SetWarningFromPreset(const std::string& name,
  252. const cm::optional<bool>& warning,
  253. const cm::optional<bool>& error)
  254. {
  255. if (warning) {
  256. if (*warning) {
  257. this->DiagLevels[name] = std::max(this->DiagLevels[name], DIAG_WARN);
  258. } else {
  259. this->DiagLevels[name] = DIAG_IGNORE;
  260. }
  261. }
  262. if (error) {
  263. if (*error) {
  264. this->DiagLevels[name] = DIAG_ERROR;
  265. } else {
  266. this->DiagLevels[name] = std::min(this->DiagLevels[name], DIAG_WARN);
  267. }
  268. }
  269. }
  270. void cmake::ProcessPresetVariables()
  271. {
  272. for (auto const& var : this->UnprocessedPresetVariables) {
  273. if (!var.second) {
  274. continue;
  275. }
  276. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  277. if (!var.second->Type.empty()) {
  278. type = cmState::StringToCacheEntryType(var.second->Type);
  279. }
  280. this->ProcessCacheArg(var.first, var.second->Value, type);
  281. }
  282. }
  283. void cmake::PrintPresetVariables()
  284. {
  285. bool first = true;
  286. for (auto const& var : this->UnprocessedPresetVariables) {
  287. if (!var.second) {
  288. continue;
  289. }
  290. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  291. if (!var.second->Type.empty()) {
  292. type = cmState::StringToCacheEntryType(var.second->Type);
  293. }
  294. if (first) {
  295. std::cout << "Preset CMake variables:\n\n";
  296. first = false;
  297. }
  298. std::cout << " " << var.first;
  299. if (type != cmStateEnums::UNINITIALIZED) {
  300. std::cout << ':' << cmState::CacheEntryTypeToString(type);
  301. }
  302. std::cout << "=\"" << var.second->Value << "\"\n";
  303. }
  304. if (!first) {
  305. std::cout << '\n';
  306. }
  307. this->UnprocessedPresetVariables.clear();
  308. }
  309. void cmake::ProcessPresetEnvironment()
  310. {
  311. for (auto const& var : this->UnprocessedPresetEnvironment) {
  312. if (var.second) {
  313. cmSystemTools::PutEnv(cmStrCat(var.first, '=', *var.second));
  314. }
  315. }
  316. }
  317. void cmake::PrintPresetEnvironment()
  318. {
  319. bool first = true;
  320. for (auto const& var : this->UnprocessedPresetEnvironment) {
  321. if (!var.second) {
  322. continue;
  323. }
  324. if (first) {
  325. std::cout << "Preset environment variables:\n\n";
  326. first = false;
  327. }
  328. std::cout << " " << var.first << "=\"" << *var.second << "\"\n";
  329. }
  330. if (!first) {
  331. std::cout << '\n';
  332. }
  333. this->UnprocessedPresetEnvironment.clear();
  334. }
  335. #endif
  336. // Parse the args
  337. bool cmake::SetCacheArgs(const std::vector<std::string>& args)
  338. {
  339. auto findPackageMode = false;
  340. auto seenScriptOption = false;
  341. for (unsigned int i = 1; i < args.size(); ++i) {
  342. std::string const& arg = args[i];
  343. if (cmHasLiteralPrefix(arg, "-D")) {
  344. std::string entry = arg.substr(2);
  345. if (entry.empty()) {
  346. ++i;
  347. if (i < args.size()) {
  348. entry = args[i];
  349. } else {
  350. cmSystemTools::Error("-D must be followed with VAR=VALUE.");
  351. return false;
  352. }
  353. }
  354. std::string var;
  355. std::string value;
  356. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  357. if (cmState::ParseCacheEntry(entry, var, value, type)) {
  358. #ifndef CMAKE_BOOTSTRAP
  359. this->UnprocessedPresetVariables.erase(var);
  360. #endif
  361. this->ProcessCacheArg(var, value, type);
  362. } else {
  363. cmSystemTools::Error("Parse error in command line argument: " + arg +
  364. "\n" + "Should be: VAR:type=value\n");
  365. return false;
  366. }
  367. } else if (cmHasLiteralPrefix(arg, "-W")) {
  368. std::string entry = arg.substr(2);
  369. if (entry.empty()) {
  370. ++i;
  371. if (i < args.size()) {
  372. entry = args[i];
  373. } else {
  374. cmSystemTools::Error("-W must be followed with [no-]<name>.");
  375. return false;
  376. }
  377. }
  378. std::string name;
  379. bool foundNo = false;
  380. bool foundError = false;
  381. unsigned int nameStartPosition = 0;
  382. if (entry.find("no-", nameStartPosition) == 0) {
  383. foundNo = true;
  384. nameStartPosition += 3;
  385. }
  386. if (entry.find("error=", nameStartPosition) == 0) {
  387. foundError = true;
  388. nameStartPosition += 6;
  389. }
  390. name = entry.substr(nameStartPosition);
  391. if (name.empty()) {
  392. cmSystemTools::Error("No warning name provided.");
  393. return false;
  394. }
  395. if (!foundNo && !foundError) {
  396. // -W<name>
  397. this->DiagLevels[name] = std::max(this->DiagLevels[name], DIAG_WARN);
  398. } else if (foundNo && !foundError) {
  399. // -Wno<name>
  400. this->DiagLevels[name] = DIAG_IGNORE;
  401. } else if (!foundNo && foundError) {
  402. // -Werror=<name>
  403. this->DiagLevels[name] = DIAG_ERROR;
  404. } else {
  405. // -Wno-error=<name>
  406. this->DiagLevels[name] = std::min(this->DiagLevels[name], DIAG_WARN);
  407. }
  408. } else if (cmHasLiteralPrefix(arg, "-U")) {
  409. std::string entryPattern = arg.substr(2);
  410. if (entryPattern.empty()) {
  411. ++i;
  412. if (i < args.size()) {
  413. entryPattern = args[i];
  414. } else {
  415. cmSystemTools::Error("-U must be followed with VAR.");
  416. return false;
  417. }
  418. }
  419. cmsys::RegularExpression regex(
  420. cmsys::Glob::PatternToRegex(entryPattern, true, true));
  421. // go through all cache entries and collect the vars which will be
  422. // removed
  423. std::vector<std::string> entriesToDelete;
  424. std::vector<std::string> cacheKeys = this->State->GetCacheEntryKeys();
  425. for (std::string const& ck : cacheKeys) {
  426. cmStateEnums::CacheEntryType t = this->State->GetCacheEntryType(ck);
  427. if (t != cmStateEnums::STATIC) {
  428. if (regex.find(ck)) {
  429. entriesToDelete.push_back(ck);
  430. }
  431. }
  432. }
  433. // now remove them from the cache
  434. for (std::string const& currentEntry : entriesToDelete) {
  435. #ifndef CMAKE_BOOTSTRAP
  436. this->UnprocessedPresetVariables.erase(currentEntry);
  437. #endif
  438. this->State->RemoveCacheEntry(currentEntry);
  439. }
  440. } else if (cmHasLiteralPrefix(arg, "-C")) {
  441. std::string path = arg.substr(2);
  442. if (path.empty()) {
  443. ++i;
  444. if (i < args.size()) {
  445. path = args[i];
  446. } else {
  447. cmSystemTools::Error("-C must be followed by a file name.");
  448. return false;
  449. }
  450. }
  451. cmSystemTools::Stdout("loading initial cache file " + path + "\n");
  452. // Resolve script path specified on command line relative to $PWD.
  453. path = cmSystemTools::CollapseFullPath(path);
  454. this->ReadListFile(args, path);
  455. } else if (cmHasLiteralPrefix(arg, "-P")) {
  456. i++;
  457. if (i >= args.size()) {
  458. cmSystemTools::Error("-P must be followed by a file name.");
  459. return false;
  460. }
  461. std::string path = args[i];
  462. if (path.empty()) {
  463. cmSystemTools::Error("No cmake script provided.");
  464. return false;
  465. }
  466. // Register fake project commands that hint misuse in script mode.
  467. GetProjectCommandsInScriptMode(this->GetState());
  468. // Documented behaviour of CMAKE{,_CURRENT}_{SOURCE,BINARY}_DIR is to be
  469. // set to $PWD for -P mode.
  470. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  471. this->SetHomeOutputDirectory(
  472. cmSystemTools::GetCurrentWorkingDirectory());
  473. this->ReadListFile(args, path);
  474. seenScriptOption = true;
  475. } else if (arg == "--" && seenScriptOption) {
  476. // Stop processing CMake args and avoid possible errors
  477. // when arbitrary args are given to CMake script.
  478. break;
  479. } else if (cmHasLiteralPrefix(arg, "--find-package")) {
  480. findPackageMode = true;
  481. }
  482. }
  483. if (findPackageMode) {
  484. return this->FindPackage(args);
  485. }
  486. return true;
  487. }
  488. void cmake::ProcessCacheArg(const std::string& var, const std::string& value,
  489. cmStateEnums::CacheEntryType type)
  490. {
  491. // The value is transformed if it is a filepath for example, so
  492. // we can't compare whether the value is already in the cache until
  493. // after we call AddCacheEntry.
  494. bool haveValue = false;
  495. std::string cachedValue;
  496. if (this->WarnUnusedCli) {
  497. if (cmProp v = this->State->GetInitializedCacheValue(var)) {
  498. haveValue = true;
  499. cachedValue = *v;
  500. }
  501. }
  502. this->AddCacheEntry(var, value.c_str(),
  503. "No help, variable specified on the command line.",
  504. type);
  505. if (this->WarnUnusedCli) {
  506. if (!haveValue ||
  507. cachedValue != *this->State->GetInitializedCacheValue(var)) {
  508. this->WatchUnusedCli(var);
  509. }
  510. }
  511. }
  512. void cmake::ReadListFile(const std::vector<std::string>& args,
  513. const std::string& path)
  514. {
  515. // if a generator was not yet created, temporarily create one
  516. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  517. // if a generator was not specified use a generic one
  518. std::unique_ptr<cmGlobalGenerator> gen;
  519. if (!gg) {
  520. gen = cm::make_unique<cmGlobalGenerator>(this);
  521. gg = gen.get();
  522. }
  523. // read in the list file to fill the cache
  524. if (!path.empty()) {
  525. this->CurrentSnapshot = this->State->Reset();
  526. cmStateSnapshot snapshot = this->GetCurrentSnapshot();
  527. snapshot.GetDirectory().SetCurrentBinary(this->GetHomeOutputDirectory());
  528. snapshot.GetDirectory().SetCurrentSource(this->GetHomeDirectory());
  529. snapshot.SetDefaultDefinitions();
  530. cmMakefile mf(gg, snapshot);
  531. if (this->GetWorkingMode() != NORMAL_MODE) {
  532. std::string file(cmSystemTools::CollapseFullPath(path));
  533. cmSystemTools::ConvertToUnixSlashes(file);
  534. mf.SetScriptModeFile(file);
  535. mf.SetArgcArgv(args);
  536. }
  537. if (!mf.ReadListFile(path)) {
  538. cmSystemTools::Error("Error processing file: " + path);
  539. }
  540. }
  541. }
  542. bool cmake::FindPackage(const std::vector<std::string>& args)
  543. {
  544. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  545. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  546. this->SetGlobalGenerator(cm::make_unique<cmGlobalGenerator>(this));
  547. cmStateSnapshot snapshot = this->GetCurrentSnapshot();
  548. snapshot.GetDirectory().SetCurrentBinary(
  549. cmSystemTools::GetCurrentWorkingDirectory());
  550. snapshot.GetDirectory().SetCurrentSource(
  551. cmSystemTools::GetCurrentWorkingDirectory());
  552. // read in the list file to fill the cache
  553. snapshot.SetDefaultDefinitions();
  554. auto mfu = cm::make_unique<cmMakefile>(this->GetGlobalGenerator(), snapshot);
  555. cmMakefile* mf = mfu.get();
  556. this->GlobalGenerator->AddMakefile(std::move(mfu));
  557. mf->SetArgcArgv(args);
  558. std::string systemFile = mf->GetModulesFile("CMakeFindPackageMode.cmake");
  559. mf->ReadListFile(systemFile);
  560. std::string language = mf->GetSafeDefinition("LANGUAGE");
  561. std::string mode = mf->GetSafeDefinition("MODE");
  562. std::string packageName = mf->GetSafeDefinition("NAME");
  563. bool packageFound = mf->IsOn("PACKAGE_FOUND");
  564. bool quiet = mf->IsOn("PACKAGE_QUIET");
  565. if (!packageFound) {
  566. if (!quiet) {
  567. printf("%s not found.\n", packageName.c_str());
  568. }
  569. } else if (mode == "EXIST"_s) {
  570. if (!quiet) {
  571. printf("%s found.\n", packageName.c_str());
  572. }
  573. } else if (mode == "COMPILE"_s) {
  574. std::string includes = mf->GetSafeDefinition("PACKAGE_INCLUDE_DIRS");
  575. std::vector<std::string> includeDirs = cmExpandedList(includes);
  576. this->GlobalGenerator->CreateGenerationObjects();
  577. const auto& lg = this->GlobalGenerator->LocalGenerators[0];
  578. std::string includeFlags =
  579. lg->GetIncludeFlags(includeDirs, nullptr, language);
  580. std::string definitions = mf->GetSafeDefinition("PACKAGE_DEFINITIONS");
  581. printf("%s %s\n", includeFlags.c_str(), definitions.c_str());
  582. } else if (mode == "LINK"_s) {
  583. const char* targetName = "dummy";
  584. std::vector<std::string> srcs;
  585. cmTarget* tgt = mf->AddExecutable(targetName, srcs, true);
  586. tgt->SetProperty("LINKER_LANGUAGE", language);
  587. std::string libs = mf->GetSafeDefinition("PACKAGE_LIBRARIES");
  588. std::vector<std::string> libList = cmExpandedList(libs);
  589. for (std::string const& lib : libList) {
  590. tgt->AddLinkLibrary(*mf, lib, GENERAL_LibraryType);
  591. }
  592. std::string buildType = mf->GetSafeDefinition("CMAKE_BUILD_TYPE");
  593. buildType = cmSystemTools::UpperCase(buildType);
  594. std::string linkLibs;
  595. std::string frameworkPath;
  596. std::string linkPath;
  597. std::string flags;
  598. std::string linkFlags;
  599. this->GlobalGenerator->CreateGenerationObjects();
  600. cmGeneratorTarget* gtgt =
  601. this->GlobalGenerator->FindGeneratorTarget(tgt->GetName());
  602. cmLocalGenerator* lg = gtgt->GetLocalGenerator();
  603. cmLinkLineComputer linkLineComputer(lg,
  604. lg->GetStateSnapshot().GetDirectory());
  605. lg->GetTargetFlags(&linkLineComputer, buildType, linkLibs, flags,
  606. linkFlags, frameworkPath, linkPath, gtgt);
  607. linkLibs = frameworkPath + linkPath + linkLibs;
  608. printf("%s\n", linkLibs.c_str());
  609. /* if ( use_win32 )
  610. {
  611. tgt->SetProperty("WIN32_EXECUTABLE", "ON");
  612. }
  613. if ( use_macbundle)
  614. {
  615. tgt->SetProperty("MACOSX_BUNDLE", "ON");
  616. }*/
  617. }
  618. return packageFound;
  619. }
  620. void cmake::LoadEnvironmentPresets()
  621. {
  622. std::string envGenVar;
  623. bool hasEnvironmentGenerator = false;
  624. if (cmSystemTools::GetEnv("CMAKE_GENERATOR", envGenVar)) {
  625. hasEnvironmentGenerator = true;
  626. this->EnvironmentGenerator = envGenVar;
  627. }
  628. auto readGeneratorVar = [&](std::string const& name, std::string& key) {
  629. std::string varValue;
  630. if (cmSystemTools::GetEnv(name, varValue)) {
  631. if (hasEnvironmentGenerator) {
  632. key = varValue;
  633. } else if (!this->GetIsInTryCompile()) {
  634. std::string message =
  635. cmStrCat("Warning: Environment variable ", name,
  636. " will be ignored, because CMAKE_GENERATOR is not set.");
  637. cmSystemTools::Message(message, "Warning");
  638. }
  639. }
  640. };
  641. readGeneratorVar("CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance);
  642. readGeneratorVar("CMAKE_GENERATOR_PLATFORM", this->GeneratorPlatform);
  643. readGeneratorVar("CMAKE_GENERATOR_TOOLSET", this->GeneratorToolset);
  644. }
  645. // Parse the args
  646. void cmake::SetArgs(const std::vector<std::string>& args)
  647. {
  648. bool haveToolset = false;
  649. bool havePlatform = false;
  650. bool haveBArg = false;
  651. #if !defined(CMAKE_BOOTSTRAP)
  652. std::string profilingFormat;
  653. std::string profilingOutput;
  654. std::string presetName;
  655. bool listPresets = false;
  656. #endif
  657. for (unsigned int i = 1; i < args.size(); ++i) {
  658. std::string const& arg = args[i];
  659. if (cmHasLiteralPrefix(arg, "-H") || cmHasLiteralPrefix(arg, "-S")) {
  660. std::string path = arg.substr(2);
  661. if (path.empty()) {
  662. ++i;
  663. if (i >= args.size()) {
  664. cmSystemTools::Error("No source directory specified for -S");
  665. return;
  666. }
  667. path = args[i];
  668. if (path[0] == '-') {
  669. cmSystemTools::Error("No source directory specified for -S");
  670. return;
  671. }
  672. }
  673. path = cmSystemTools::CollapseFullPath(path);
  674. cmSystemTools::ConvertToUnixSlashes(path);
  675. this->SetHomeDirectory(path);
  676. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  677. // NOLINTNEXTLINE(bugprone-branch-clone)
  678. } else if (cmHasLiteralPrefix(arg, "-O")) {
  679. // There is no local generate anymore. Ignore -O option.
  680. } else if (cmHasLiteralPrefix(arg, "-B")) {
  681. std::string path = arg.substr(2);
  682. if (path.empty()) {
  683. ++i;
  684. if (i >= args.size()) {
  685. cmSystemTools::Error("No build directory specified for -B");
  686. return;
  687. }
  688. path = args[i];
  689. if (path[0] == '-') {
  690. cmSystemTools::Error("No build directory specified for -B");
  691. return;
  692. }
  693. }
  694. path = cmSystemTools::CollapseFullPath(path);
  695. cmSystemTools::ConvertToUnixSlashes(path);
  696. this->SetHomeOutputDirectory(path);
  697. haveBArg = true;
  698. } else if ((i < args.size() - 2) &&
  699. cmHasLiteralPrefix(arg, "--check-build-system")) {
  700. this->CheckBuildSystemArgument = args[++i];
  701. this->ClearBuildSystem = (atoi(args[++i].c_str()) > 0);
  702. } else if ((i < args.size() - 1) &&
  703. cmHasLiteralPrefix(arg, "--check-stamp-file")) {
  704. this->CheckStampFile = args[++i];
  705. } else if ((i < args.size() - 1) &&
  706. cmHasLiteralPrefix(arg, "--check-stamp-list")) {
  707. this->CheckStampList = args[++i];
  708. } else if (arg == "--regenerate-during-build"_s) {
  709. this->RegenerateDuringBuild = true;
  710. }
  711. #if defined(CMAKE_HAVE_VS_GENERATORS)
  712. else if ((i < args.size() - 1) &&
  713. cmHasLiteralPrefix(arg, "--vs-solution-file")) {
  714. this->VSSolutionFile = args[++i];
  715. }
  716. #endif
  717. else if (cmHasLiteralPrefix(arg, "-D") || cmHasLiteralPrefix(arg, "-U") ||
  718. cmHasLiteralPrefix(arg, "-C")) {
  719. // skip for now
  720. // in case '-[DUC] argval' var' is given, also skip the next
  721. // in case '-[DUC]argval' is given, don't skip the next
  722. if (arg.size() == 2) {
  723. ++i;
  724. }
  725. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  726. // NOLINTNEXTLINE(bugprone-branch-clone)
  727. } else if (cmHasLiteralPrefix(arg, "-P")) {
  728. // skip for now
  729. i++;
  730. } else if (cmHasLiteralPrefix(arg, "--find-package")) {
  731. // skip for now
  732. i++;
  733. } else if (cmHasLiteralPrefix(arg, "-W")) {
  734. // skip for now
  735. } else if (cmHasLiteralPrefix(arg, "--graphviz=")) {
  736. std::string path = arg.substr(strlen("--graphviz="));
  737. path = cmSystemTools::CollapseFullPath(path);
  738. cmSystemTools::ConvertToUnixSlashes(path);
  739. this->GraphVizFile = path;
  740. if (this->GraphVizFile.empty()) {
  741. cmSystemTools::Error("No file specified for --graphviz");
  742. return;
  743. }
  744. } else if (cmHasLiteralPrefix(arg, "--debug-trycompile")) {
  745. std::cout << "debug trycompile on\n";
  746. this->DebugTryCompileOn();
  747. } else if (cmHasLiteralPrefix(arg, "--debug-output")) {
  748. std::cout << "Running with debug output on.\n";
  749. this->SetDebugOutputOn(true);
  750. } else if (cmHasLiteralPrefix(arg, "--log-level=")) {
  751. const auto logLevel =
  752. StringToLogLevel(arg.substr(sizeof("--log-level=") - 1));
  753. if (logLevel == LogLevel::LOG_UNDEFINED) {
  754. cmSystemTools::Error("Invalid level specified for --log-level");
  755. return;
  756. }
  757. this->SetLogLevel(logLevel);
  758. this->LogLevelWasSetViaCLI = true;
  759. } else if (cmHasLiteralPrefix(arg, "--loglevel=")) {
  760. // This is supported for backward compatibility. This option only
  761. // appeared in the 3.15.x release series and was renamed to
  762. // --log-level in 3.16.0
  763. const auto logLevel =
  764. StringToLogLevel(arg.substr(sizeof("--loglevel=") - 1));
  765. if (logLevel == LogLevel::LOG_UNDEFINED) {
  766. cmSystemTools::Error("Invalid level specified for --loglevel");
  767. return;
  768. }
  769. this->SetLogLevel(logLevel);
  770. this->LogLevelWasSetViaCLI = true;
  771. } else if (arg == "--log-context"_s) {
  772. this->SetShowLogContext(true);
  773. } else if (cmHasLiteralPrefix(arg, "--debug-find")) {
  774. std::cout << "Running with debug output on for the `find` commands.\n";
  775. this->SetDebugFindOutputOn(true);
  776. } else if (cmHasLiteralPrefix(arg, "--trace-expand")) {
  777. std::cout << "Running with expanded trace output on.\n";
  778. this->SetTrace(true);
  779. this->SetTraceExpand(true);
  780. } else if (cmHasLiteralPrefix(arg, "--trace-format=")) {
  781. this->SetTrace(true);
  782. const auto traceFormat =
  783. StringToTraceFormat(arg.substr(strlen("--trace-format=")));
  784. if (traceFormat == TraceFormat::TRACE_UNDEFINED) {
  785. cmSystemTools::Error("Invalid format specified for --trace-format. "
  786. "Valid formats are human, json-v1.");
  787. return;
  788. }
  789. this->SetTraceFormat(traceFormat);
  790. } else if (cmHasLiteralPrefix(arg, "--trace-source=")) {
  791. std::string file = arg.substr(strlen("--trace-source="));
  792. cmSystemTools::ConvertToUnixSlashes(file);
  793. this->AddTraceSource(file);
  794. this->SetTrace(true);
  795. } else if (cmHasLiteralPrefix(arg, "--trace-redirect=")) {
  796. std::string file = arg.substr(strlen("--trace-redirect="));
  797. cmSystemTools::ConvertToUnixSlashes(file);
  798. this->SetTraceFile(file);
  799. this->SetTrace(true);
  800. } else if (cmHasLiteralPrefix(arg, "--trace")) {
  801. std::cout << "Running with trace output on.\n";
  802. this->SetTrace(true);
  803. this->SetTraceExpand(false);
  804. } else if (cmHasLiteralPrefix(arg, "--warn-uninitialized")) {
  805. std::cout << "Warn about uninitialized values.\n";
  806. this->SetWarnUninitialized(true);
  807. } else if (cmHasLiteralPrefix(arg, "--warn-unused-vars")) {
  808. // Option was removed.
  809. } else if (cmHasLiteralPrefix(arg, "--no-warn-unused-cli")) {
  810. std::cout << "Not searching for unused variables given on the "
  811. << "command line.\n";
  812. this->SetWarnUnusedCli(false);
  813. } else if (cmHasLiteralPrefix(arg, "--check-system-vars")) {
  814. std::cout << "Also check system files when warning about unused and "
  815. << "uninitialized variables.\n";
  816. this->SetCheckSystemVars(true);
  817. } else if (cmHasLiteralPrefix(arg, "-A")) {
  818. std::string value = arg.substr(2);
  819. if (value.empty()) {
  820. ++i;
  821. if (i >= args.size()) {
  822. cmSystemTools::Error("No platform specified for -A");
  823. return;
  824. }
  825. value = args[i];
  826. }
  827. if (havePlatform) {
  828. cmSystemTools::Error("Multiple -A options not allowed");
  829. return;
  830. }
  831. this->SetGeneratorPlatform(value);
  832. havePlatform = true;
  833. } else if (cmHasLiteralPrefix(arg, "-T")) {
  834. std::string value = arg.substr(2);
  835. if (value.empty()) {
  836. ++i;
  837. if (i >= args.size()) {
  838. cmSystemTools::Error("No toolset specified for -T");
  839. return;
  840. }
  841. value = args[i];
  842. }
  843. if (haveToolset) {
  844. cmSystemTools::Error("Multiple -T options not allowed");
  845. return;
  846. }
  847. this->SetGeneratorToolset(value);
  848. haveToolset = true;
  849. } else if (cmHasLiteralPrefix(arg, "-G")) {
  850. std::string value = arg.substr(2);
  851. if (value.empty()) {
  852. ++i;
  853. if (i >= args.size()) {
  854. cmSystemTools::Error("No generator specified for -G");
  855. this->PrintGeneratorList();
  856. return;
  857. }
  858. value = args[i];
  859. }
  860. if (!this->CreateAndSetGlobalGenerator(value, true)) {
  861. return;
  862. }
  863. #if !defined(CMAKE_BOOTSTRAP)
  864. } else if (cmHasLiteralPrefix(arg, "--profiling-format")) {
  865. profilingFormat = arg.substr(strlen("--profiling-format="));
  866. if (profilingFormat.empty()) {
  867. cmSystemTools::Error("No format specified for --profiling-format");
  868. }
  869. } else if (cmHasLiteralPrefix(arg, "--profiling-output")) {
  870. profilingOutput = arg.substr(strlen("--profiling-output="));
  871. profilingOutput = cmSystemTools::CollapseFullPath(profilingOutput);
  872. cmSystemTools::ConvertToUnixSlashes(profilingOutput);
  873. if (profilingOutput.empty()) {
  874. cmSystemTools::Error("No path specified for --profiling-output");
  875. }
  876. } else if (cmHasLiteralPrefix(arg, "--preset")) {
  877. presetName = arg.substr(strlen("--preset="));
  878. if (presetName.empty()) {
  879. cmSystemTools::Error("No preset specified for --preset");
  880. }
  881. } else if (cmHasLiteralPrefix(arg, "--list-presets")) {
  882. listPresets = true;
  883. #endif
  884. }
  885. // no option assume it is the path to the source or an existing build
  886. else {
  887. this->SetDirectoriesFromFile(arg);
  888. }
  889. // Empty instance, platform and toolset if only a generator is specified
  890. if (this->GlobalGenerator) {
  891. this->GeneratorInstance = "";
  892. if (!this->GeneratorPlatformSet) {
  893. this->GeneratorPlatform = "";
  894. }
  895. if (!this->GeneratorToolsetSet) {
  896. this->GeneratorToolset = "";
  897. }
  898. }
  899. }
  900. #if !defined(CMAKE_BOOTSTRAP)
  901. if (!profilingOutput.empty() || !profilingFormat.empty()) {
  902. if (profilingOutput.empty()) {
  903. cmSystemTools::Error(
  904. "--profiling-format specified but no --profiling-output!");
  905. return;
  906. }
  907. if (profilingFormat == "google-trace"_s) {
  908. try {
  909. this->ProfilingOutput =
  910. cm::make_unique<cmMakefileProfilingData>(profilingOutput);
  911. } catch (std::runtime_error& e) {
  912. cmSystemTools::Error(
  913. cmStrCat("Could not start profiling: ", e.what()));
  914. return;
  915. }
  916. } else {
  917. cmSystemTools::Error("Invalid format specified for --profiling-format");
  918. return;
  919. }
  920. }
  921. #endif
  922. const bool haveSourceDir = !this->GetHomeDirectory().empty();
  923. const bool haveBinaryDir = !this->GetHomeOutputDirectory().empty();
  924. if (this->CurrentWorkingMode == cmake::NORMAL_MODE && !haveSourceDir &&
  925. !haveBinaryDir) {
  926. this->IssueMessage(
  927. MessageType::WARNING,
  928. "No source or binary directory provided. Both will be assumed to be "
  929. "the same as the current working directory, but note that this "
  930. "warning will become a fatal error in future CMake releases.");
  931. }
  932. if (!haveSourceDir) {
  933. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  934. }
  935. if (!haveBinaryDir) {
  936. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  937. }
  938. #if !defined(CMAKE_BOOTSTRAP)
  939. if (listPresets || !presetName.empty()) {
  940. cmCMakePresetsFile settingsFile;
  941. auto result = settingsFile.ReadProjectPresets(this->GetHomeDirectory());
  942. if (result != cmCMakePresetsFile::ReadFileResult::READ_OK) {
  943. cmSystemTools::Error(
  944. cmStrCat("Could not read presets from ", this->GetHomeDirectory(),
  945. ": ", cmCMakePresetsFile::ResultToString(result)));
  946. return;
  947. }
  948. if (listPresets) {
  949. this->PrintPresetList(settingsFile);
  950. return;
  951. }
  952. auto preset = settingsFile.Presets.find(presetName);
  953. if (preset == settingsFile.Presets.end()) {
  954. cmSystemTools::Error(cmStrCat("No such preset in ",
  955. this->GetHomeDirectory(), ": \"",
  956. presetName, '"'));
  957. this->PrintPresetList(settingsFile);
  958. return;
  959. }
  960. if (preset->second.Unexpanded.Hidden) {
  961. cmSystemTools::Error(cmStrCat("Cannot use hidden preset in ",
  962. this->GetHomeDirectory(), ": \"",
  963. presetName, '"'));
  964. this->PrintPresetList(settingsFile);
  965. return;
  966. }
  967. auto const& expandedPreset = preset->second.Expanded;
  968. if (!expandedPreset) {
  969. cmSystemTools::Error(cmStrCat("Could not evaluate preset \"",
  970. preset->second.Unexpanded.Name,
  971. "\": Invalid macro expansion"));
  972. return;
  973. }
  974. if (!this->State->IsCacheLoaded() && !haveBArg) {
  975. this->SetHomeOutputDirectory(expandedPreset->BinaryDir);
  976. }
  977. if (!this->GlobalGenerator) {
  978. if (!this->CreateAndSetGlobalGenerator(expandedPreset->Generator,
  979. false)) {
  980. return;
  981. }
  982. }
  983. this->UnprocessedPresetVariables = expandedPreset->CacheVariables;
  984. this->UnprocessedPresetEnvironment = expandedPreset->Environment;
  985. if (!expandedPreset->ArchitectureStrategy ||
  986. expandedPreset->ArchitectureStrategy ==
  987. cmCMakePresetsFile::ArchToolsetStrategy::Set) {
  988. if (!this->GeneratorPlatformSet) {
  989. this->SetGeneratorPlatform(expandedPreset->Architecture);
  990. }
  991. }
  992. if (!expandedPreset->ToolsetStrategy ||
  993. expandedPreset->ToolsetStrategy ==
  994. cmCMakePresetsFile::ArchToolsetStrategy::Set) {
  995. if (!this->GeneratorToolsetSet) {
  996. this->SetGeneratorToolset(expandedPreset->Toolset);
  997. }
  998. }
  999. this->SetWarningFromPreset("dev", expandedPreset->WarnDev,
  1000. expandedPreset->ErrorDev);
  1001. this->SetWarningFromPreset("deprecated", expandedPreset->WarnDeprecated,
  1002. expandedPreset->ErrorDeprecated);
  1003. if (expandedPreset->WarnUninitialized == true) {
  1004. this->SetWarnUninitialized(true);
  1005. }
  1006. if (expandedPreset->WarnUnusedCli == false) {
  1007. this->SetWarnUnusedCli(false);
  1008. }
  1009. if (expandedPreset->WarnSystemVars == true) {
  1010. this->SetCheckSystemVars(true);
  1011. }
  1012. if (expandedPreset->DebugOutput == true) {
  1013. this->SetDebugOutputOn(true);
  1014. }
  1015. if (expandedPreset->DebugTryCompile == true) {
  1016. this->DebugTryCompileOn();
  1017. }
  1018. if (expandedPreset->DebugFind == true) {
  1019. this->SetDebugFindOutputOn(true);
  1020. }
  1021. }
  1022. #endif
  1023. }
  1024. cmake::LogLevel cmake::StringToLogLevel(const std::string& levelStr)
  1025. {
  1026. using LevelsPair = std::pair<std::string, LogLevel>;
  1027. static const std::vector<LevelsPair> levels = {
  1028. { "error", LogLevel::LOG_ERROR }, { "warning", LogLevel::LOG_WARNING },
  1029. { "notice", LogLevel::LOG_NOTICE }, { "status", LogLevel::LOG_STATUS },
  1030. { "verbose", LogLevel::LOG_VERBOSE }, { "debug", LogLevel::LOG_DEBUG },
  1031. { "trace", LogLevel::LOG_TRACE }
  1032. };
  1033. const auto levelStrLowCase = cmSystemTools::LowerCase(levelStr);
  1034. const auto it = std::find_if(levels.cbegin(), levels.cend(),
  1035. [&levelStrLowCase](const LevelsPair& p) {
  1036. return p.first == levelStrLowCase;
  1037. });
  1038. return (it != levels.cend()) ? it->second : LogLevel::LOG_UNDEFINED;
  1039. }
  1040. cmake::TraceFormat cmake::StringToTraceFormat(const std::string& traceStr)
  1041. {
  1042. using TracePair = std::pair<std::string, TraceFormat>;
  1043. static const std::vector<TracePair> levels = {
  1044. { "human", TraceFormat::TRACE_HUMAN },
  1045. { "json-v1", TraceFormat::TRACE_JSON_V1 },
  1046. };
  1047. const auto traceStrLowCase = cmSystemTools::LowerCase(traceStr);
  1048. const auto it = std::find_if(levels.cbegin(), levels.cend(),
  1049. [&traceStrLowCase](const TracePair& p) {
  1050. return p.first == traceStrLowCase;
  1051. });
  1052. return (it != levels.cend()) ? it->second : TraceFormat::TRACE_UNDEFINED;
  1053. }
  1054. void cmake::SetTraceFile(const std::string& file)
  1055. {
  1056. this->TraceFile.close();
  1057. this->TraceFile.open(file.c_str());
  1058. if (!this->TraceFile) {
  1059. std::stringstream ss;
  1060. ss << "Error opening trace file " << file << ": "
  1061. << cmSystemTools::GetLastSystemError();
  1062. cmSystemTools::Error(ss.str());
  1063. return;
  1064. }
  1065. std::cout << "Trace will be written to " << file << "\n";
  1066. }
  1067. void cmake::PrintTraceFormatVersion()
  1068. {
  1069. if (!this->GetTrace()) {
  1070. return;
  1071. }
  1072. std::string msg;
  1073. switch (this->GetTraceFormat()) {
  1074. case TraceFormat::TRACE_JSON_V1: {
  1075. #ifndef CMAKE_BOOTSTRAP
  1076. Json::Value val;
  1077. Json::Value version;
  1078. Json::StreamWriterBuilder builder;
  1079. builder["indentation"] = "";
  1080. version["major"] = 1;
  1081. version["minor"] = 1;
  1082. val["version"] = version;
  1083. msg = Json::writeString(builder, val);
  1084. #endif
  1085. break;
  1086. }
  1087. case TraceFormat::TRACE_HUMAN:
  1088. msg = "";
  1089. break;
  1090. case TraceFormat::TRACE_UNDEFINED:
  1091. msg = "INTERNAL ERROR: Trace format is TRACE_UNDEFINED";
  1092. break;
  1093. }
  1094. if (msg.empty()) {
  1095. return;
  1096. }
  1097. auto& f = this->GetTraceFile();
  1098. if (f) {
  1099. f << msg << '\n';
  1100. } else {
  1101. cmSystemTools::Message(msg);
  1102. }
  1103. }
  1104. void cmake::SetDirectoriesFromFile(const std::string& arg)
  1105. {
  1106. // Check if the argument refers to a CMakeCache.txt or
  1107. // CMakeLists.txt file.
  1108. std::string listPath;
  1109. std::string cachePath;
  1110. bool argIsFile = false;
  1111. if (cmSystemTools::FileIsDirectory(arg)) {
  1112. std::string path = cmSystemTools::CollapseFullPath(arg);
  1113. cmSystemTools::ConvertToUnixSlashes(path);
  1114. std::string cacheFile = cmStrCat(path, "/CMakeCache.txt");
  1115. std::string listFile = cmStrCat(path, "/CMakeLists.txt");
  1116. if (cmSystemTools::FileExists(cacheFile)) {
  1117. cachePath = path;
  1118. }
  1119. if (cmSystemTools::FileExists(listFile)) {
  1120. listPath = path;
  1121. }
  1122. } else if (cmSystemTools::FileExists(arg)) {
  1123. argIsFile = true;
  1124. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  1125. std::string name = cmSystemTools::GetFilenameName(fullPath);
  1126. name = cmSystemTools::LowerCase(name);
  1127. if (name == "cmakecache.txt"_s) {
  1128. cachePath = cmSystemTools::GetFilenamePath(fullPath);
  1129. } else if (name == "cmakelists.txt"_s) {
  1130. listPath = cmSystemTools::GetFilenamePath(fullPath);
  1131. }
  1132. } else {
  1133. // Specified file or directory does not exist. Try to set things
  1134. // up to produce a meaningful error message.
  1135. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  1136. std::string name = cmSystemTools::GetFilenameName(fullPath);
  1137. name = cmSystemTools::LowerCase(name);
  1138. if (name == "cmakecache.txt"_s || name == "cmakelists.txt"_s) {
  1139. argIsFile = true;
  1140. listPath = cmSystemTools::GetFilenamePath(fullPath);
  1141. } else {
  1142. listPath = fullPath;
  1143. }
  1144. }
  1145. // If there is a CMakeCache.txt file, use its settings.
  1146. if (!cachePath.empty()) {
  1147. if (this->LoadCache(cachePath)) {
  1148. cmProp existingValue =
  1149. this->State->GetCacheEntryValue("CMAKE_HOME_DIRECTORY");
  1150. if (existingValue) {
  1151. this->SetHomeOutputDirectory(cachePath);
  1152. this->SetHomeDirectory(*existingValue);
  1153. return;
  1154. }
  1155. }
  1156. }
  1157. // If there is a CMakeLists.txt file, use it as the source tree.
  1158. if (!listPath.empty()) {
  1159. this->SetHomeDirectory(listPath);
  1160. if (argIsFile) {
  1161. // Source CMakeLists.txt file given. It was probably dropped
  1162. // onto the executable in a GUI. Default to an in-source build.
  1163. this->SetHomeOutputDirectory(listPath);
  1164. } else {
  1165. // Source directory given on command line. Use current working
  1166. // directory as build tree if -B hasn't been given already
  1167. if (this->GetHomeOutputDirectory().empty()) {
  1168. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1169. this->SetHomeOutputDirectory(cwd);
  1170. }
  1171. }
  1172. return;
  1173. }
  1174. if (this->GetHomeDirectory().empty()) {
  1175. // We didn't find a CMakeLists.txt and it wasn't specified
  1176. // with -S. Assume it is the path to the source tree
  1177. std::string full = cmSystemTools::CollapseFullPath(arg);
  1178. this->SetHomeDirectory(full);
  1179. }
  1180. if (this->GetHomeOutputDirectory().empty()) {
  1181. // We didn't find a CMakeCache.txt and it wasn't specified
  1182. // with -B. Assume the current working directory as the build tree.
  1183. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1184. this->SetHomeOutputDirectory(cwd);
  1185. }
  1186. }
  1187. // at the end of this CMAKE_ROOT and CMAKE_COMMAND should be added to the
  1188. // cache
  1189. int cmake::AddCMakePaths()
  1190. {
  1191. // Save the value in the cache
  1192. this->AddCacheEntry("CMAKE_COMMAND",
  1193. cmSystemTools::GetCMakeCommand().c_str(),
  1194. "Path to CMake executable.", cmStateEnums::INTERNAL);
  1195. #ifndef CMAKE_BOOTSTRAP
  1196. this->AddCacheEntry(
  1197. "CMAKE_CTEST_COMMAND", cmSystemTools::GetCTestCommand().c_str(),
  1198. "Path to ctest program executable.", cmStateEnums::INTERNAL);
  1199. this->AddCacheEntry(
  1200. "CMAKE_CPACK_COMMAND", cmSystemTools::GetCPackCommand().c_str(),
  1201. "Path to cpack program executable.", cmStateEnums::INTERNAL);
  1202. #endif
  1203. if (!cmSystemTools::FileExists(
  1204. (cmSystemTools::GetCMakeRoot() + "/Modules/CMake.cmake"))) {
  1205. // couldn't find modules
  1206. cmSystemTools::Error(
  1207. "Could not find CMAKE_ROOT !!!\n"
  1208. "CMake has most likely not been installed correctly.\n"
  1209. "Modules directory not found in\n" +
  1210. cmSystemTools::GetCMakeRoot());
  1211. return 0;
  1212. }
  1213. this->AddCacheEntry("CMAKE_ROOT", cmSystemTools::GetCMakeRoot().c_str(),
  1214. "Path to CMake installation.", cmStateEnums::INTERNAL);
  1215. return 1;
  1216. }
  1217. void cmake::AddDefaultExtraGenerators()
  1218. {
  1219. #if !defined(CMAKE_BOOTSTRAP)
  1220. this->ExtraGenerators.push_back(cmExtraCodeBlocksGenerator::GetFactory());
  1221. this->ExtraGenerators.push_back(cmExtraCodeLiteGenerator::GetFactory());
  1222. this->ExtraGenerators.push_back(cmExtraEclipseCDT4Generator::GetFactory());
  1223. this->ExtraGenerators.push_back(cmExtraKateGenerator::GetFactory());
  1224. this->ExtraGenerators.push_back(cmExtraSublimeTextGenerator::GetFactory());
  1225. #endif
  1226. }
  1227. void cmake::GetRegisteredGenerators(std::vector<GeneratorInfo>& generators,
  1228. bool includeNamesWithPlatform) const
  1229. {
  1230. for (const auto& gen : this->Generators) {
  1231. std::vector<std::string> names = gen->GetGeneratorNames();
  1232. if (includeNamesWithPlatform) {
  1233. cm::append(names, gen->GetGeneratorNamesWithPlatform());
  1234. }
  1235. for (std::string const& name : names) {
  1236. GeneratorInfo info;
  1237. info.supportsToolset = gen->SupportsToolset();
  1238. info.supportsPlatform = gen->SupportsPlatform();
  1239. info.supportedPlatforms = gen->GetKnownPlatforms();
  1240. info.defaultPlatform = gen->GetDefaultPlatformName();
  1241. info.name = name;
  1242. info.baseName = name;
  1243. info.isAlias = false;
  1244. generators.push_back(std::move(info));
  1245. }
  1246. }
  1247. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  1248. const std::vector<std::string> genList =
  1249. eg->GetSupportedGlobalGenerators();
  1250. for (std::string const& gen : genList) {
  1251. GeneratorInfo info;
  1252. info.name = cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1253. gen, eg->GetName());
  1254. info.baseName = gen;
  1255. info.extraName = eg->GetName();
  1256. info.supportsPlatform = false;
  1257. info.supportsToolset = false;
  1258. info.isAlias = false;
  1259. generators.push_back(std::move(info));
  1260. }
  1261. for (std::string const& a : eg->Aliases) {
  1262. GeneratorInfo info;
  1263. info.name = a;
  1264. if (!genList.empty()) {
  1265. info.baseName = genList.at(0);
  1266. }
  1267. info.extraName = eg->GetName();
  1268. info.supportsPlatform = false;
  1269. info.supportsToolset = false;
  1270. info.isAlias = true;
  1271. generators.push_back(std::move(info));
  1272. }
  1273. }
  1274. }
  1275. static std::pair<std::unique_ptr<cmExternalMakefileProjectGenerator>,
  1276. std::string>
  1277. createExtraGenerator(
  1278. const std::vector<cmExternalMakefileProjectGeneratorFactory*>& in,
  1279. const std::string& name)
  1280. {
  1281. for (cmExternalMakefileProjectGeneratorFactory* i : in) {
  1282. const std::vector<std::string> generators =
  1283. i->GetSupportedGlobalGenerators();
  1284. if (i->GetName() == name) { // Match aliases
  1285. return { i->CreateExternalMakefileProjectGenerator(), generators.at(0) };
  1286. }
  1287. for (std::string const& g : generators) {
  1288. const std::string fullName =
  1289. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1290. g, i->GetName());
  1291. if (fullName == name) {
  1292. return { i->CreateExternalMakefileProjectGenerator(), g };
  1293. }
  1294. }
  1295. }
  1296. return { nullptr, name };
  1297. }
  1298. std::unique_ptr<cmGlobalGenerator> cmake::CreateGlobalGenerator(
  1299. const std::string& gname, bool allowArch)
  1300. {
  1301. std::pair<std::unique_ptr<cmExternalMakefileProjectGenerator>, std::string>
  1302. extra = createExtraGenerator(this->ExtraGenerators, gname);
  1303. std::unique_ptr<cmExternalMakefileProjectGenerator>& extraGenerator =
  1304. extra.first;
  1305. const std::string& name = extra.second;
  1306. std::unique_ptr<cmGlobalGenerator> generator;
  1307. for (const auto& g : this->Generators) {
  1308. generator = g->CreateGlobalGenerator(name, allowArch, this);
  1309. if (generator) {
  1310. break;
  1311. }
  1312. }
  1313. if (generator) {
  1314. generator->SetExternalMakefileProjectGenerator(std::move(extraGenerator));
  1315. }
  1316. return generator;
  1317. }
  1318. bool cmake::CreateAndSetGlobalGenerator(const std::string& name,
  1319. bool allowArch)
  1320. {
  1321. auto gen = this->CreateGlobalGenerator(name, allowArch);
  1322. if (!gen) {
  1323. std::string kdevError;
  1324. std::string vsError;
  1325. if (name.find("KDevelop3", 0) != std::string::npos) {
  1326. kdevError = "\nThe KDevelop3 generator is not supported anymore.";
  1327. }
  1328. if (!allowArch && cmHasLiteralPrefix(name, "Visual Studio ") &&
  1329. name.length() >= cmStrLen("Visual Studio xx xxxx ")) {
  1330. vsError = "\nUsing platforms in Visual Studio generator names is not "
  1331. "supported in CMakePresets.json.";
  1332. }
  1333. cmSystemTools::Error(
  1334. cmStrCat("Could not create named generator ", name, kdevError, vsError));
  1335. this->PrintGeneratorList();
  1336. return false;
  1337. }
  1338. this->SetGlobalGenerator(std::move(gen));
  1339. return true;
  1340. }
  1341. #ifndef CMAKE_BOOTSTRAP
  1342. void cmake::PrintPresetList(const cmCMakePresetsFile& file) const
  1343. {
  1344. std::vector<GeneratorInfo> generators;
  1345. this->GetRegisteredGenerators(generators, false);
  1346. std::vector<cmCMakePresetsFile::UnexpandedPreset> presets;
  1347. for (auto const& p : file.PresetOrder) {
  1348. auto const& preset = file.Presets.at(p);
  1349. if (!preset.Unexpanded.Hidden && preset.Expanded &&
  1350. std::find_if(generators.begin(), generators.end(),
  1351. [&preset](const GeneratorInfo& info) {
  1352. return info.name == preset.Unexpanded.Generator;
  1353. }) != generators.end()) {
  1354. presets.push_back(preset.Unexpanded);
  1355. }
  1356. }
  1357. if (presets.empty()) {
  1358. return;
  1359. }
  1360. std::cout << "Available presets:\n\n";
  1361. auto longestPresetName =
  1362. std::max_element(presets.begin(), presets.end(),
  1363. [](const cmCMakePresetsFile::UnexpandedPreset& a,
  1364. const cmCMakePresetsFile::UnexpandedPreset& b) {
  1365. return a.Name.length() < b.Name.length();
  1366. });
  1367. auto longestLength = longestPresetName->Name.length();
  1368. for (auto const& preset : presets) {
  1369. std::cout << " \"" << preset.Name << '"';
  1370. auto const& description = preset.DisplayName;
  1371. if (!description.empty()) {
  1372. for (std::size_t i = 0; i < longestLength - preset.Name.length(); ++i) {
  1373. std::cout << ' ';
  1374. }
  1375. std::cout << " - " << description;
  1376. }
  1377. std::cout << '\n';
  1378. }
  1379. }
  1380. #endif
  1381. void cmake::SetHomeDirectory(const std::string& dir)
  1382. {
  1383. this->State->SetSourceDirectory(dir);
  1384. if (this->CurrentSnapshot.IsValid()) {
  1385. this->CurrentSnapshot.SetDefinition("CMAKE_SOURCE_DIR", dir);
  1386. }
  1387. }
  1388. std::string const& cmake::GetHomeDirectory() const
  1389. {
  1390. return this->State->GetSourceDirectory();
  1391. }
  1392. void cmake::SetHomeOutputDirectory(const std::string& dir)
  1393. {
  1394. this->State->SetBinaryDirectory(dir);
  1395. if (this->CurrentSnapshot.IsValid()) {
  1396. this->CurrentSnapshot.SetDefinition("CMAKE_BINARY_DIR", dir);
  1397. }
  1398. }
  1399. std::string const& cmake::GetHomeOutputDirectory() const
  1400. {
  1401. return this->State->GetBinaryDirectory();
  1402. }
  1403. std::string cmake::FindCacheFile(const std::string& binaryDir)
  1404. {
  1405. std::string cachePath = binaryDir;
  1406. cmSystemTools::ConvertToUnixSlashes(cachePath);
  1407. std::string cacheFile = cmStrCat(cachePath, "/CMakeCache.txt");
  1408. if (!cmSystemTools::FileExists(cacheFile)) {
  1409. // search in parent directories for cache
  1410. std::string cmakeFiles = cmStrCat(cachePath, "/CMakeFiles");
  1411. if (cmSystemTools::FileExists(cmakeFiles)) {
  1412. std::string cachePathFound =
  1413. cmSystemTools::FileExistsInParentDirectories("CMakeCache.txt",
  1414. cachePath, "/");
  1415. if (!cachePathFound.empty()) {
  1416. cachePath = cmSystemTools::GetFilenamePath(cachePathFound);
  1417. }
  1418. }
  1419. }
  1420. return cachePath;
  1421. }
  1422. void cmake::SetGlobalGenerator(std::unique_ptr<cmGlobalGenerator> gg)
  1423. {
  1424. if (!gg) {
  1425. cmSystemTools::Error("Error SetGlobalGenerator called with null");
  1426. return;
  1427. }
  1428. if (this->GlobalGenerator) {
  1429. // restore the original environment variables CXX and CC
  1430. // Restore CC
  1431. std::string env = "CC=";
  1432. if (!this->CCEnvironment.empty()) {
  1433. env += this->CCEnvironment;
  1434. }
  1435. cmSystemTools::PutEnv(env);
  1436. env = "CXX=";
  1437. if (!this->CXXEnvironment.empty()) {
  1438. env += this->CXXEnvironment;
  1439. }
  1440. cmSystemTools::PutEnv(env);
  1441. }
  1442. // set the new
  1443. this->GlobalGenerator = std::move(gg);
  1444. // set the global flag for unix style paths on cmSystemTools as soon as
  1445. // the generator is set. This allows gmake to be used on windows.
  1446. cmSystemTools::SetForceUnixPaths(this->GlobalGenerator->GetForceUnixPaths());
  1447. // Save the environment variables CXX and CC
  1448. if (!cmSystemTools::GetEnv("CXX", this->CXXEnvironment)) {
  1449. this->CXXEnvironment.clear();
  1450. }
  1451. if (!cmSystemTools::GetEnv("CC", this->CCEnvironment)) {
  1452. this->CCEnvironment.clear();
  1453. }
  1454. }
  1455. int cmake::DoPreConfigureChecks()
  1456. {
  1457. // Make sure the Source directory contains a CMakeLists.txt file.
  1458. std::string srcList = cmStrCat(this->GetHomeDirectory(), "/CMakeLists.txt");
  1459. if (!cmSystemTools::FileExists(srcList)) {
  1460. std::ostringstream err;
  1461. if (cmSystemTools::FileIsDirectory(this->GetHomeDirectory())) {
  1462. err << "The source directory \"" << this->GetHomeDirectory()
  1463. << "\" does not appear to contain CMakeLists.txt.\n";
  1464. } else if (cmSystemTools::FileExists(this->GetHomeDirectory())) {
  1465. err << "The source directory \"" << this->GetHomeDirectory()
  1466. << "\" is a file, not a directory.\n";
  1467. } else {
  1468. err << "The source directory \"" << this->GetHomeDirectory()
  1469. << "\" does not exist.\n";
  1470. }
  1471. err << "Specify --help for usage, or press the help button on the CMake "
  1472. "GUI.";
  1473. cmSystemTools::Error(err.str());
  1474. return -2;
  1475. }
  1476. // do a sanity check on some values
  1477. if (this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY")) {
  1478. std::string cacheStart =
  1479. cmStrCat(*this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY"),
  1480. "/CMakeLists.txt");
  1481. std::string currentStart =
  1482. cmStrCat(this->GetHomeDirectory(), "/CMakeLists.txt");
  1483. if (!cmSystemTools::SameFile(cacheStart, currentStart)) {
  1484. std::string message =
  1485. cmStrCat("The source \"", currentStart,
  1486. "\" does not match the source \"", cacheStart,
  1487. "\" used to generate cache. Re-run cmake with a different "
  1488. "source directory.");
  1489. cmSystemTools::Error(message);
  1490. return -2;
  1491. }
  1492. } else {
  1493. return 0;
  1494. }
  1495. return 1;
  1496. }
  1497. struct SaveCacheEntry
  1498. {
  1499. std::string key;
  1500. std::string value;
  1501. std::string help;
  1502. cmStateEnums::CacheEntryType type;
  1503. };
  1504. int cmake::HandleDeleteCacheVariables(const std::string& var)
  1505. {
  1506. std::vector<std::string> argsSplit = cmExpandedList(var, true);
  1507. // erase the property to avoid infinite recursion
  1508. this->State->SetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_", "");
  1509. if (this->State->GetIsInTryCompile()) {
  1510. return 0;
  1511. }
  1512. std::vector<SaveCacheEntry> saved;
  1513. std::ostringstream warning;
  1514. /* clang-format off */
  1515. warning
  1516. << "You have changed variables that require your cache to be deleted.\n"
  1517. << "Configure will be re-run and you may have to reset some variables.\n"
  1518. << "The following variables have changed:\n";
  1519. /* clang-format on */
  1520. for (auto i = argsSplit.begin(); i != argsSplit.end(); ++i) {
  1521. SaveCacheEntry save;
  1522. save.key = *i;
  1523. warning << *i << "= ";
  1524. i++;
  1525. if (i != argsSplit.end()) {
  1526. save.value = *i;
  1527. warning << *i << "\n";
  1528. } else {
  1529. warning << "\n";
  1530. i -= 1;
  1531. }
  1532. cmProp existingValue = this->State->GetCacheEntryValue(save.key);
  1533. if (existingValue) {
  1534. save.type = this->State->GetCacheEntryType(save.key);
  1535. if (cmProp help =
  1536. this->State->GetCacheEntryProperty(save.key, "HELPSTRING")) {
  1537. save.help = *help;
  1538. }
  1539. } else {
  1540. save.type = cmStateEnums::CacheEntryType::UNINITIALIZED;
  1541. }
  1542. saved.push_back(std::move(save));
  1543. }
  1544. // remove the cache
  1545. this->DeleteCache(this->GetHomeOutputDirectory());
  1546. // load the empty cache
  1547. this->LoadCache();
  1548. // restore the changed compilers
  1549. for (SaveCacheEntry const& i : saved) {
  1550. this->AddCacheEntry(i.key, i.value.c_str(), i.help.c_str(), i.type);
  1551. }
  1552. cmSystemTools::Message(warning.str());
  1553. // avoid reconfigure if there were errors
  1554. if (!cmSystemTools::GetErrorOccuredFlag()) {
  1555. // re-run configure
  1556. return this->Configure();
  1557. }
  1558. return 0;
  1559. }
  1560. int cmake::Configure()
  1561. {
  1562. DiagLevel diagLevel;
  1563. if (this->DiagLevels.count("deprecated") == 1) {
  1564. diagLevel = this->DiagLevels["deprecated"];
  1565. if (diagLevel == DIAG_IGNORE) {
  1566. this->SetSuppressDeprecatedWarnings(true);
  1567. this->SetDeprecatedWarningsAsErrors(false);
  1568. } else if (diagLevel == DIAG_WARN) {
  1569. this->SetSuppressDeprecatedWarnings(false);
  1570. this->SetDeprecatedWarningsAsErrors(false);
  1571. } else if (diagLevel == DIAG_ERROR) {
  1572. this->SetSuppressDeprecatedWarnings(false);
  1573. this->SetDeprecatedWarningsAsErrors(true);
  1574. }
  1575. }
  1576. if (this->DiagLevels.count("dev") == 1) {
  1577. bool setDeprecatedVariables = false;
  1578. cmProp cachedWarnDeprecated =
  1579. this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1580. cmProp cachedErrorDeprecated =
  1581. this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1582. // don't overwrite deprecated warning setting from a previous invocation
  1583. if (!cachedWarnDeprecated && !cachedErrorDeprecated) {
  1584. setDeprecatedVariables = true;
  1585. }
  1586. diagLevel = this->DiagLevels["dev"];
  1587. if (diagLevel == DIAG_IGNORE) {
  1588. this->SetSuppressDevWarnings(true);
  1589. this->SetDevWarningsAsErrors(false);
  1590. if (setDeprecatedVariables) {
  1591. this->SetSuppressDeprecatedWarnings(true);
  1592. this->SetDeprecatedWarningsAsErrors(false);
  1593. }
  1594. } else if (diagLevel == DIAG_WARN) {
  1595. this->SetSuppressDevWarnings(false);
  1596. this->SetDevWarningsAsErrors(false);
  1597. if (setDeprecatedVariables) {
  1598. this->SetSuppressDeprecatedWarnings(false);
  1599. this->SetDeprecatedWarningsAsErrors(false);
  1600. }
  1601. } else if (diagLevel == DIAG_ERROR) {
  1602. this->SetSuppressDevWarnings(false);
  1603. this->SetDevWarningsAsErrors(true);
  1604. if (setDeprecatedVariables) {
  1605. this->SetSuppressDeprecatedWarnings(false);
  1606. this->SetDeprecatedWarningsAsErrors(true);
  1607. }
  1608. }
  1609. }
  1610. // Cache variables may have already been set by a previous invocation,
  1611. // so we cannot rely on command line options alone. Always ensure our
  1612. // messenger is in sync with the cache.
  1613. cmProp value = this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1614. this->Messenger->SetSuppressDeprecatedWarnings(value && cmIsOff(*value));
  1615. value = this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1616. this->Messenger->SetDeprecatedWarningsAsErrors(cmIsOn(value));
  1617. value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_WARNINGS");
  1618. this->Messenger->SetSuppressDevWarnings(cmIsOn(value));
  1619. value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_ERRORS");
  1620. this->Messenger->SetDevWarningsAsErrors(value && cmIsOff(*value));
  1621. int ret = this->ActualConfigure();
  1622. cmProp delCacheVars =
  1623. this->State->GetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_");
  1624. if (delCacheVars && !delCacheVars->empty()) {
  1625. return this->HandleDeleteCacheVariables(*delCacheVars);
  1626. }
  1627. return ret;
  1628. }
  1629. int cmake::ActualConfigure()
  1630. {
  1631. // Construct right now our path conversion table before it's too late:
  1632. this->UpdateConversionPathTable();
  1633. this->CleanupCommandsAndMacros();
  1634. int res = this->DoPreConfigureChecks();
  1635. if (res < 0) {
  1636. return -2;
  1637. }
  1638. if (!res) {
  1639. this->AddCacheEntry(
  1640. "CMAKE_HOME_DIRECTORY", this->GetHomeDirectory().c_str(),
  1641. "Source directory with the top level CMakeLists.txt file for this "
  1642. "project",
  1643. cmStateEnums::INTERNAL);
  1644. }
  1645. // no generator specified on the command line
  1646. if (!this->GlobalGenerator) {
  1647. cmProp genName = this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1648. cmProp extraGenName =
  1649. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  1650. if (genName) {
  1651. std::string fullName =
  1652. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1653. *genName, extraGenName ? *extraGenName : "");
  1654. this->GlobalGenerator = this->CreateGlobalGenerator(fullName);
  1655. }
  1656. if (this->GlobalGenerator) {
  1657. // set the global flag for unix style paths on cmSystemTools as
  1658. // soon as the generator is set. This allows gmake to be used
  1659. // on windows.
  1660. cmSystemTools::SetForceUnixPaths(
  1661. this->GlobalGenerator->GetForceUnixPaths());
  1662. } else {
  1663. this->CreateDefaultGlobalGenerator();
  1664. }
  1665. if (!this->GlobalGenerator) {
  1666. cmSystemTools::Error("Could not create generator");
  1667. return -1;
  1668. }
  1669. }
  1670. cmProp genName = this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1671. if (genName) {
  1672. if (!this->GlobalGenerator->MatchesGeneratorName(*genName)) {
  1673. std::string message =
  1674. cmStrCat("Error: generator : ", this->GlobalGenerator->GetName(),
  1675. "\nDoes not match the generator used previously: ", *genName,
  1676. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1677. "directory or choose a different binary directory.");
  1678. cmSystemTools::Error(message);
  1679. return -2;
  1680. }
  1681. }
  1682. if (!this->State->GetInitializedCacheValue("CMAKE_GENERATOR")) {
  1683. this->AddCacheEntry("CMAKE_GENERATOR",
  1684. this->GlobalGenerator->GetName().c_str(),
  1685. "Name of generator.", cmStateEnums::INTERNAL);
  1686. this->AddCacheEntry("CMAKE_EXTRA_GENERATOR",
  1687. this->GlobalGenerator->GetExtraGeneratorName().c_str(),
  1688. "Name of external makefile project generator.",
  1689. cmStateEnums::INTERNAL);
  1690. }
  1691. if (cmProp instance =
  1692. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_INSTANCE")) {
  1693. if (this->GeneratorInstanceSet && this->GeneratorInstance != *instance) {
  1694. std::string message =
  1695. cmStrCat("Error: generator instance: ", this->GeneratorInstance,
  1696. "\nDoes not match the instance used previously: ", *instance,
  1697. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1698. "directory or choose a different binary directory.");
  1699. cmSystemTools::Error(message);
  1700. return -2;
  1701. }
  1702. } else {
  1703. this->AddCacheEntry(
  1704. "CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance.c_str(),
  1705. "Generator instance identifier.", cmStateEnums::INTERNAL);
  1706. }
  1707. if (cmProp platformName =
  1708. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_PLATFORM")) {
  1709. if (this->GeneratorPlatformSet &&
  1710. this->GeneratorPlatform != *platformName) {
  1711. std::string message = cmStrCat(
  1712. "Error: generator platform: ", this->GeneratorPlatform,
  1713. "\nDoes not match the platform used previously: ", *platformName,
  1714. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1715. "directory or choose a different binary directory.");
  1716. cmSystemTools::Error(message);
  1717. return -2;
  1718. }
  1719. } else {
  1720. this->AddCacheEntry("CMAKE_GENERATOR_PLATFORM",
  1721. this->GeneratorPlatform.c_str(),
  1722. "Name of generator platform.", cmStateEnums::INTERNAL);
  1723. }
  1724. if (cmProp tsName =
  1725. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_TOOLSET")) {
  1726. if (this->GeneratorToolsetSet && this->GeneratorToolset != *tsName) {
  1727. std::string message =
  1728. cmStrCat("Error: generator toolset: ", this->GeneratorToolset,
  1729. "\nDoes not match the toolset used previously: ", *tsName,
  1730. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1731. "directory or choose a different binary directory.");
  1732. cmSystemTools::Error(message);
  1733. return -2;
  1734. }
  1735. } else {
  1736. this->AddCacheEntry("CMAKE_GENERATOR_TOOLSET",
  1737. this->GeneratorToolset.c_str(),
  1738. "Name of generator toolset.", cmStateEnums::INTERNAL);
  1739. }
  1740. // reset any system configuration information, except for when we are
  1741. // InTryCompile. With TryCompile the system info is taken from the parent's
  1742. // info to save time
  1743. if (!this->State->GetIsInTryCompile()) {
  1744. this->GlobalGenerator->ClearEnabledLanguages();
  1745. this->TruncateOutputLog("CMakeOutput.log");
  1746. this->TruncateOutputLog("CMakeError.log");
  1747. }
  1748. #if !defined(CMAKE_BOOTSTRAP)
  1749. this->FileAPI = cm::make_unique<cmFileAPI>(this);
  1750. this->FileAPI->ReadQueries();
  1751. #endif
  1752. // actually do the configure
  1753. this->GlobalGenerator->Configure();
  1754. // Before saving the cache
  1755. // if the project did not define one of the entries below, add them now
  1756. // so users can edit the values in the cache:
  1757. // We used to always present LIBRARY_OUTPUT_PATH and
  1758. // EXECUTABLE_OUTPUT_PATH. They are now documented as old-style and
  1759. // should no longer be used. Therefore we present them only if the
  1760. // project requires compatibility with CMake 2.4. We detect this
  1761. // here by looking for the old CMAKE_BACKWARDS_COMPATIBILITY
  1762. // variable created when CMP0001 is not set to NEW.
  1763. if (this->State->GetInitializedCacheValue("CMAKE_BACKWARDS_COMPATIBILITY")) {
  1764. if (!this->State->GetInitializedCacheValue("LIBRARY_OUTPUT_PATH")) {
  1765. this->AddCacheEntry(
  1766. "LIBRARY_OUTPUT_PATH", "",
  1767. "Single output directory for building all libraries.",
  1768. cmStateEnums::PATH);
  1769. }
  1770. if (!this->State->GetInitializedCacheValue("EXECUTABLE_OUTPUT_PATH")) {
  1771. this->AddCacheEntry(
  1772. "EXECUTABLE_OUTPUT_PATH", "",
  1773. "Single output directory for building all executables.",
  1774. cmStateEnums::PATH);
  1775. }
  1776. }
  1777. auto& mf = this->GlobalGenerator->GetMakefiles()[0];
  1778. if (mf->IsOn("CTEST_USE_LAUNCHERS") &&
  1779. !this->State->GetGlobalProperty("RULE_LAUNCH_COMPILE")) {
  1780. cmSystemTools::Error(
  1781. "CTEST_USE_LAUNCHERS is enabled, but the "
  1782. "RULE_LAUNCH_COMPILE global property is not defined.\n"
  1783. "Did you forget to include(CTest) in the toplevel "
  1784. "CMakeLists.txt ?");
  1785. }
  1786. this->State->SaveVerificationScript(this->GetHomeOutputDirectory());
  1787. this->SaveCache(this->GetHomeOutputDirectory());
  1788. if (cmSystemTools::GetErrorOccuredFlag()) {
  1789. return -1;
  1790. }
  1791. return 0;
  1792. }
  1793. std::unique_ptr<cmGlobalGenerator> cmake::EvaluateDefaultGlobalGenerator()
  1794. {
  1795. if (!this->EnvironmentGenerator.empty()) {
  1796. auto gen = this->CreateGlobalGenerator(this->EnvironmentGenerator);
  1797. if (!gen) {
  1798. cmSystemTools::Error("CMAKE_GENERATOR was set but the specified "
  1799. "generator doesn't exist. Using CMake default.");
  1800. } else {
  1801. return gen;
  1802. }
  1803. }
  1804. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  1805. std::string found;
  1806. // Try to find the newest VS installed on the computer and
  1807. // use that as a default if -G is not specified
  1808. const std::string vsregBase = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\";
  1809. static const char* const vsVariants[] = {
  1810. /* clang-format needs this comment to break after the opening brace */
  1811. "VisualStudio\\", "VCExpress\\", "WDExpress\\"
  1812. };
  1813. struct VSVersionedGenerator
  1814. {
  1815. const char* MSVersion;
  1816. const char* GeneratorName;
  1817. };
  1818. static VSVersionedGenerator const vsGenerators[] = {
  1819. { "14.0", "Visual Studio 14 2015" }, //
  1820. { "12.0", "Visual Studio 12 2013" }, //
  1821. { "11.0", "Visual Studio 11 2012" }, //
  1822. { "10.0", "Visual Studio 10 2010" }, //
  1823. { "9.0", "Visual Studio 9 2008" }
  1824. };
  1825. static const char* const vsEntries[] = {
  1826. "\\Setup\\VC;ProductDir", //
  1827. ";InstallDir" //
  1828. };
  1829. if (cmVSSetupAPIHelper(16).IsVSInstalled()) {
  1830. found = "Visual Studio 16 2019";
  1831. } else if (cmVSSetupAPIHelper(15).IsVSInstalled()) {
  1832. found = "Visual Studio 15 2017";
  1833. } else {
  1834. for (VSVersionedGenerator const* g = cm::cbegin(vsGenerators);
  1835. found.empty() && g != cm::cend(vsGenerators); ++g) {
  1836. for (const char* const* v = cm::cbegin(vsVariants);
  1837. found.empty() && v != cm::cend(vsVariants); ++v) {
  1838. for (const char* const* e = cm::cbegin(vsEntries);
  1839. found.empty() && e != cm::cend(vsEntries); ++e) {
  1840. std::string const reg = vsregBase + *v + g->MSVersion + *e;
  1841. std::string dir;
  1842. if (cmSystemTools::ReadRegistryValue(reg, dir,
  1843. cmSystemTools::KeyWOW64_32) &&
  1844. cmSystemTools::PathExists(dir)) {
  1845. found = g->GeneratorName;
  1846. }
  1847. }
  1848. }
  1849. }
  1850. }
  1851. auto gen = this->CreateGlobalGenerator(found);
  1852. if (!gen) {
  1853. gen = cm::make_unique<cmGlobalNMakeMakefileGenerator>(this);
  1854. }
  1855. return std::unique_ptr<cmGlobalGenerator>(std::move(gen));
  1856. #elif defined(CMAKE_BOOTSTRAP_NINJA)
  1857. return std::unique_ptr<cmGlobalGenerator>(
  1858. cm::make_unique<cmGlobalNinjaGenerator>(this));
  1859. #else
  1860. return std::unique_ptr<cmGlobalGenerator>(
  1861. cm::make_unique<cmGlobalUnixMakefileGenerator3>(this));
  1862. #endif
  1863. }
  1864. void cmake::CreateDefaultGlobalGenerator()
  1865. {
  1866. auto gen = this->EvaluateDefaultGlobalGenerator();
  1867. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  1868. // This print could be unified for all platforms
  1869. std::cout << "-- Building for: " << gen->GetName() << "\n";
  1870. #endif
  1871. this->SetGlobalGenerator(std::move(gen));
  1872. }
  1873. void cmake::PreLoadCMakeFiles()
  1874. {
  1875. std::vector<std::string> args;
  1876. std::string pre_load = this->GetHomeDirectory();
  1877. if (!pre_load.empty()) {
  1878. pre_load += "/PreLoad.cmake";
  1879. if (cmSystemTools::FileExists(pre_load)) {
  1880. this->ReadListFile(args, pre_load);
  1881. }
  1882. }
  1883. pre_load = this->GetHomeOutputDirectory();
  1884. if (!pre_load.empty()) {
  1885. pre_load += "/PreLoad.cmake";
  1886. if (cmSystemTools::FileExists(pre_load)) {
  1887. this->ReadListFile(args, pre_load);
  1888. }
  1889. }
  1890. }
  1891. // handle a command line invocation
  1892. int cmake::Run(const std::vector<std::string>& args, bool noconfigure)
  1893. {
  1894. // Process the arguments
  1895. this->SetArgs(args);
  1896. if (cmSystemTools::GetErrorOccuredFlag()) {
  1897. return -1;
  1898. }
  1899. if (this->GetWorkingMode() == HELP_MODE) {
  1900. return 0;
  1901. }
  1902. // Log the trace format version to the desired output
  1903. if (this->GetTrace()) {
  1904. this->PrintTraceFormatVersion();
  1905. }
  1906. // If we are given a stamp list file check if it is really out of date.
  1907. if (!this->CheckStampList.empty() &&
  1908. cmakeCheckStampList(this->CheckStampList)) {
  1909. return 0;
  1910. }
  1911. // If we are given a stamp file check if it is really out of date.
  1912. if (!this->CheckStampFile.empty() &&
  1913. cmakeCheckStampFile(this->CheckStampFile)) {
  1914. return 0;
  1915. }
  1916. if (this->GetWorkingMode() == NORMAL_MODE) {
  1917. // load the cache
  1918. if (this->LoadCache() < 0) {
  1919. cmSystemTools::Error("Error executing cmake::LoadCache(). Aborting.\n");
  1920. return -1;
  1921. }
  1922. } else {
  1923. this->AddCMakePaths();
  1924. }
  1925. #ifndef CMAKE_BOOTSTRAP
  1926. this->ProcessPresetVariables();
  1927. this->ProcessPresetEnvironment();
  1928. #endif
  1929. // Add any cache args
  1930. if (!this->SetCacheArgs(args)) {
  1931. cmSystemTools::Error("Problem processing arguments. Aborting.\n");
  1932. return -1;
  1933. }
  1934. #ifndef CMAKE_BOOTSTRAP
  1935. this->PrintPresetVariables();
  1936. this->PrintPresetEnvironment();
  1937. #endif
  1938. // In script mode we terminate after running the script.
  1939. if (this->GetWorkingMode() != NORMAL_MODE) {
  1940. if (cmSystemTools::GetErrorOccuredFlag()) {
  1941. return -1;
  1942. }
  1943. return 0;
  1944. }
  1945. // If MAKEFLAGS are given in the environment, remove the environment
  1946. // variable. This will prevent try-compile from succeeding when it
  1947. // should fail (if "-i" is an option). We cannot simply test
  1948. // whether "-i" is given and remove it because some make programs
  1949. // encode the MAKEFLAGS variable in a strange way.
  1950. if (cmSystemTools::HasEnv("MAKEFLAGS")) {
  1951. cmSystemTools::PutEnv("MAKEFLAGS=");
  1952. }
  1953. this->PreLoadCMakeFiles();
  1954. if (noconfigure) {
  1955. return 0;
  1956. }
  1957. // now run the global generate
  1958. // Check the state of the build system to see if we need to regenerate.
  1959. if (!this->CheckBuildSystem()) {
  1960. return 0;
  1961. }
  1962. int ret = this->Configure();
  1963. if (ret) {
  1964. #if defined(CMAKE_HAVE_VS_GENERATORS)
  1965. if (!this->VSSolutionFile.empty() && this->GlobalGenerator) {
  1966. // CMake is running to regenerate a Visual Studio build tree
  1967. // during a build from the VS IDE. The build files cannot be
  1968. // regenerated, so we should stop the build.
  1969. cmSystemTools::Message("CMake Configure step failed. "
  1970. "Build files cannot be regenerated correctly. "
  1971. "Attempting to stop IDE build.");
  1972. cmGlobalVisualStudioGenerator& gg =
  1973. cm::static_reference_cast<cmGlobalVisualStudioGenerator>(
  1974. this->GlobalGenerator);
  1975. gg.CallVisualStudioMacro(cmGlobalVisualStudioGenerator::MacroStop,
  1976. this->VSSolutionFile);
  1977. }
  1978. #endif
  1979. return ret;
  1980. }
  1981. ret = this->Generate();
  1982. if (ret) {
  1983. cmSystemTools::Message("CMake Generate step failed. "
  1984. "Build files cannot be regenerated correctly.");
  1985. return ret;
  1986. }
  1987. std::string message = cmStrCat("Build files have been written to: ",
  1988. this->GetHomeOutputDirectory());
  1989. this->UpdateProgress(message, -1);
  1990. return ret;
  1991. }
  1992. int cmake::Generate()
  1993. {
  1994. if (!this->GlobalGenerator) {
  1995. return -1;
  1996. }
  1997. if (!this->GlobalGenerator->Compute()) {
  1998. return -1;
  1999. }
  2000. this->GlobalGenerator->Generate();
  2001. if (!this->GraphVizFile.empty()) {
  2002. std::cout << "Generate graphviz: " << this->GraphVizFile << std::endl;
  2003. this->GenerateGraphViz(this->GraphVizFile);
  2004. }
  2005. if (this->WarnUnusedCli) {
  2006. this->RunCheckForUnusedVariables();
  2007. }
  2008. if (cmSystemTools::GetErrorOccuredFlag()) {
  2009. return -1;
  2010. }
  2011. // Save the cache again after a successful Generate so that any internal
  2012. // variables created during Generate are saved. (Specifically target GUIDs
  2013. // for the Visual Studio and Xcode generators.)
  2014. this->SaveCache(this->GetHomeOutputDirectory());
  2015. #if !defined(CMAKE_BOOTSTRAP)
  2016. this->FileAPI->WriteReplies();
  2017. #endif
  2018. return 0;
  2019. }
  2020. void cmake::AddCacheEntry(const std::string& key, const char* value,
  2021. const char* helpString, int type)
  2022. {
  2023. this->State->AddCacheEntry(key, value, helpString,
  2024. cmStateEnums::CacheEntryType(type));
  2025. this->UnwatchUnusedCli(key);
  2026. if (key == "CMAKE_WARN_DEPRECATED"_s) {
  2027. this->Messenger->SetSuppressDeprecatedWarnings(value && cmIsOff(value));
  2028. } else if (key == "CMAKE_ERROR_DEPRECATED"_s) {
  2029. this->Messenger->SetDeprecatedWarningsAsErrors(cmIsOn(value));
  2030. } else if (key == "CMAKE_SUPPRESS_DEVELOPER_WARNINGS"_s) {
  2031. this->Messenger->SetSuppressDevWarnings(cmIsOn(value));
  2032. } else if (key == "CMAKE_SUPPRESS_DEVELOPER_ERRORS"_s) {
  2033. this->Messenger->SetDevWarningsAsErrors(value && cmIsOff(value));
  2034. }
  2035. }
  2036. bool cmake::DoWriteGlobVerifyTarget() const
  2037. {
  2038. return this->State->DoWriteGlobVerifyTarget();
  2039. }
  2040. std::string const& cmake::GetGlobVerifyScript() const
  2041. {
  2042. return this->State->GetGlobVerifyScript();
  2043. }
  2044. std::string const& cmake::GetGlobVerifyStamp() const
  2045. {
  2046. return this->State->GetGlobVerifyStamp();
  2047. }
  2048. void cmake::AddGlobCacheEntry(bool recurse, bool listDirectories,
  2049. bool followSymlinks, const std::string& relative,
  2050. const std::string& expression,
  2051. const std::vector<std::string>& files,
  2052. const std::string& variable,
  2053. cmListFileBacktrace const& backtrace)
  2054. {
  2055. this->State->AddGlobCacheEntry(recurse, listDirectories, followSymlinks,
  2056. relative, expression, files, variable,
  2057. backtrace);
  2058. }
  2059. std::vector<std::string> cmake::GetAllExtensions() const
  2060. {
  2061. std::vector<std::string> allExt = this->CLikeSourceFileExtensions.ordered;
  2062. allExt.insert(allExt.end(), this->HeaderFileExtensions.ordered.begin(),
  2063. this->HeaderFileExtensions.ordered.end());
  2064. // cuda extensions are also in SourceFileExtensions so we ignore it here
  2065. allExt.insert(allExt.end(), this->FortranFileExtensions.ordered.begin(),
  2066. this->FortranFileExtensions.ordered.end());
  2067. allExt.insert(allExt.end(), this->ISPCFileExtensions.ordered.begin(),
  2068. this->ISPCFileExtensions.ordered.end());
  2069. return allExt;
  2070. }
  2071. std::string cmake::StripExtension(const std::string& file) const
  2072. {
  2073. auto dotpos = file.rfind('.');
  2074. if (dotpos != std::string::npos) {
  2075. #if defined(_WIN32) || defined(__APPLE__)
  2076. auto ext = cmSystemTools::LowerCase(file.substr(dotpos + 1));
  2077. #else
  2078. auto ext = cm::string_view(file).substr(dotpos + 1);
  2079. #endif
  2080. if (this->IsAKnownExtension(ext)) {
  2081. return file.substr(0, dotpos);
  2082. }
  2083. }
  2084. return file;
  2085. }
  2086. cmProp cmake::GetCacheDefinition(const std::string& name) const
  2087. {
  2088. return this->State->GetInitializedCacheValue(name);
  2089. }
  2090. void cmake::AddScriptingCommands()
  2091. {
  2092. GetScriptingCommands(this->GetState());
  2093. }
  2094. void cmake::AddProjectCommands()
  2095. {
  2096. GetProjectCommands(this->GetState());
  2097. }
  2098. void cmake::AddDefaultGenerators()
  2099. {
  2100. #if defined(_WIN32) && !defined(__CYGWIN__)
  2101. # if !defined(CMAKE_BOOT_MINGW)
  2102. this->Generators.push_back(
  2103. cmGlobalVisualStudioVersionedGenerator::NewFactory16());
  2104. this->Generators.push_back(
  2105. cmGlobalVisualStudioVersionedGenerator::NewFactory15());
  2106. this->Generators.push_back(cmGlobalVisualStudio14Generator::NewFactory());
  2107. this->Generators.push_back(cmGlobalVisualStudio12Generator::NewFactory());
  2108. this->Generators.push_back(cmGlobalVisualStudio11Generator::NewFactory());
  2109. this->Generators.push_back(cmGlobalVisualStudio10Generator::NewFactory());
  2110. this->Generators.push_back(cmGlobalVisualStudio9Generator::NewFactory());
  2111. this->Generators.push_back(cmGlobalBorlandMakefileGenerator::NewFactory());
  2112. this->Generators.push_back(cmGlobalNMakeMakefileGenerator::NewFactory());
  2113. this->Generators.push_back(cmGlobalJOMMakefileGenerator::NewFactory());
  2114. # endif
  2115. this->Generators.push_back(cmGlobalMSYSMakefileGenerator::NewFactory());
  2116. this->Generators.push_back(cmGlobalMinGWMakefileGenerator::NewFactory());
  2117. #endif
  2118. #if !defined(CMAKE_BOOTSTRAP)
  2119. # if defined(__linux__) || defined(_WIN32)
  2120. this->Generators.push_back(cmGlobalGhsMultiGenerator::NewFactory());
  2121. # endif
  2122. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  2123. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  2124. this->Generators.push_back(cmGlobalNinjaMultiGenerator::NewFactory());
  2125. #elif defined(CMAKE_BOOTSTRAP_NINJA)
  2126. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  2127. #elif defined(CMAKE_BOOTSTRAP_MAKEFILES)
  2128. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  2129. #endif
  2130. #if defined(CMAKE_USE_WMAKE)
  2131. this->Generators.push_back(cmGlobalWatcomWMakeGenerator::NewFactory());
  2132. #endif
  2133. #ifdef CMAKE_USE_XCODE
  2134. this->Generators.push_back(cmGlobalXCodeGenerator::NewFactory());
  2135. #endif
  2136. }
  2137. bool cmake::ParseCacheEntry(const std::string& entry, std::string& var,
  2138. std::string& value,
  2139. cmStateEnums::CacheEntryType& type)
  2140. {
  2141. return cmState::ParseCacheEntry(entry, var, value, type);
  2142. }
  2143. int cmake::LoadCache()
  2144. {
  2145. // could we not read the cache
  2146. if (!this->LoadCache(this->GetHomeOutputDirectory())) {
  2147. // if it does exist, but isn't readable then warn the user
  2148. std::string cacheFile =
  2149. cmStrCat(this->GetHomeOutputDirectory(), "/CMakeCache.txt");
  2150. if (cmSystemTools::FileExists(cacheFile)) {
  2151. cmSystemTools::Error(
  2152. "There is a CMakeCache.txt file for the current binary tree but "
  2153. "cmake does not have permission to read it. Please check the "
  2154. "permissions of the directory you are trying to run CMake on.");
  2155. return -1;
  2156. }
  2157. }
  2158. // setup CMAKE_ROOT and CMAKE_COMMAND
  2159. if (!this->AddCMakePaths()) {
  2160. return -3;
  2161. }
  2162. return 0;
  2163. }
  2164. bool cmake::LoadCache(const std::string& path)
  2165. {
  2166. std::set<std::string> emptySet;
  2167. return this->LoadCache(path, true, emptySet, emptySet);
  2168. }
  2169. bool cmake::LoadCache(const std::string& path, bool internal,
  2170. std::set<std::string>& excludes,
  2171. std::set<std::string>& includes)
  2172. {
  2173. bool result = this->State->LoadCache(path, internal, excludes, includes);
  2174. static const auto entries = { "CMAKE_CACHE_MAJOR_VERSION",
  2175. "CMAKE_CACHE_MINOR_VERSION" };
  2176. for (auto const& entry : entries) {
  2177. this->UnwatchUnusedCli(entry);
  2178. }
  2179. return result;
  2180. }
  2181. bool cmake::SaveCache(const std::string& path)
  2182. {
  2183. bool result = this->State->SaveCache(path, this->GetMessenger());
  2184. static const auto entries = { "CMAKE_CACHE_MAJOR_VERSION",
  2185. "CMAKE_CACHE_MINOR_VERSION",
  2186. "CMAKE_CACHE_PATCH_VERSION",
  2187. "CMAKE_CACHEFILE_DIR" };
  2188. for (auto const& entry : entries) {
  2189. this->UnwatchUnusedCli(entry);
  2190. }
  2191. return result;
  2192. }
  2193. bool cmake::DeleteCache(const std::string& path)
  2194. {
  2195. return this->State->DeleteCache(path);
  2196. }
  2197. void cmake::SetProgressCallback(ProgressCallbackType f)
  2198. {
  2199. this->ProgressCallback = std::move(f);
  2200. }
  2201. void cmake::UpdateProgress(const std::string& msg, float prog)
  2202. {
  2203. if (this->ProgressCallback && !this->State->GetIsInTryCompile()) {
  2204. this->ProgressCallback(msg, prog);
  2205. }
  2206. }
  2207. bool cmake::GetIsInTryCompile() const
  2208. {
  2209. return this->State->GetIsInTryCompile();
  2210. }
  2211. void cmake::SetIsInTryCompile(bool b)
  2212. {
  2213. this->State->SetIsInTryCompile(b);
  2214. }
  2215. void cmake::AppendGlobalGeneratorsDocumentation(
  2216. std::vector<cmDocumentationEntry>& v)
  2217. {
  2218. const auto defaultGenerator = this->EvaluateDefaultGlobalGenerator();
  2219. const std::string defaultName = defaultGenerator->GetName();
  2220. bool foundDefaultOne = false;
  2221. for (const auto& g : this->Generators) {
  2222. cmDocumentationEntry e;
  2223. g->GetDocumentation(e);
  2224. if (!foundDefaultOne && cmHasPrefix(e.Name, defaultName)) {
  2225. e.CustomNamePrefix = '*';
  2226. foundDefaultOne = true;
  2227. }
  2228. v.push_back(std::move(e));
  2229. }
  2230. }
  2231. void cmake::AppendExtraGeneratorsDocumentation(
  2232. std::vector<cmDocumentationEntry>& v)
  2233. {
  2234. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  2235. const std::string doc = eg->GetDocumentation();
  2236. const std::string name = eg->GetName();
  2237. // Aliases:
  2238. for (std::string const& a : eg->Aliases) {
  2239. cmDocumentationEntry e;
  2240. e.Name = a;
  2241. e.Brief = doc;
  2242. v.push_back(std::move(e));
  2243. }
  2244. // Full names:
  2245. const std::vector<std::string> generators =
  2246. eg->GetSupportedGlobalGenerators();
  2247. for (std::string const& g : generators) {
  2248. cmDocumentationEntry e;
  2249. e.Name =
  2250. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(g, name);
  2251. e.Brief = doc;
  2252. v.push_back(std::move(e));
  2253. }
  2254. }
  2255. }
  2256. std::vector<cmDocumentationEntry> cmake::GetGeneratorsDocumentation()
  2257. {
  2258. std::vector<cmDocumentationEntry> v;
  2259. this->AppendGlobalGeneratorsDocumentation(v);
  2260. this->AppendExtraGeneratorsDocumentation(v);
  2261. return v;
  2262. }
  2263. void cmake::PrintGeneratorList()
  2264. {
  2265. #ifndef CMAKE_BOOTSTRAP
  2266. cmDocumentation doc;
  2267. auto generators = this->GetGeneratorsDocumentation();
  2268. doc.AppendSection("Generators", generators);
  2269. std::cerr << "\n";
  2270. doc.PrintDocumentation(cmDocumentation::ListGenerators, std::cerr);
  2271. #endif
  2272. }
  2273. void cmake::UpdateConversionPathTable()
  2274. {
  2275. // Update the path conversion table with any specified file:
  2276. cmProp tablepath =
  2277. this->State->GetInitializedCacheValue("CMAKE_PATH_TRANSLATION_FILE");
  2278. if (tablepath) {
  2279. cmsys::ifstream table(tablepath->c_str());
  2280. if (!table) {
  2281. cmSystemTools::Error("CMAKE_PATH_TRANSLATION_FILE set to " + *tablepath +
  2282. ". CMake can not open file.");
  2283. cmSystemTools::ReportLastSystemError("CMake can not open file.");
  2284. } else {
  2285. std::string a;
  2286. std::string b;
  2287. while (!table.eof()) {
  2288. // two entries per line
  2289. table >> a;
  2290. table >> b;
  2291. cmSystemTools::AddTranslationPath(a, b);
  2292. }
  2293. }
  2294. }
  2295. }
  2296. int cmake::CheckBuildSystem()
  2297. {
  2298. // We do not need to rerun CMake. Check dependency integrity.
  2299. const bool verbose = isCMakeVerbose();
  2300. // This method will check the integrity of the build system if the
  2301. // option was given on the command line. It reads the given file to
  2302. // determine whether CMake should rerun.
  2303. // If no file is provided for the check, we have to rerun.
  2304. if (this->CheckBuildSystemArgument.empty()) {
  2305. if (verbose) {
  2306. cmSystemTools::Stdout("Re-run cmake no build system arguments\n");
  2307. }
  2308. return 1;
  2309. }
  2310. // If the file provided does not exist, we have to rerun.
  2311. if (!cmSystemTools::FileExists(this->CheckBuildSystemArgument)) {
  2312. if (verbose) {
  2313. std::ostringstream msg;
  2314. msg << "Re-run cmake missing file: " << this->CheckBuildSystemArgument
  2315. << "\n";
  2316. cmSystemTools::Stdout(msg.str());
  2317. }
  2318. return 1;
  2319. }
  2320. // Read the rerun check file and use it to decide whether to do the
  2321. // global generate.
  2322. // Actually, all we need is the `set` command.
  2323. cmake cm(RoleScript, cmState::Unknown);
  2324. cm.SetHomeDirectory("");
  2325. cm.SetHomeOutputDirectory("");
  2326. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  2327. cmGlobalGenerator gg(&cm);
  2328. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  2329. if (!mf.ReadListFile(this->CheckBuildSystemArgument) ||
  2330. cmSystemTools::GetErrorOccuredFlag()) {
  2331. if (verbose) {
  2332. std::ostringstream msg;
  2333. msg << "Re-run cmake error reading : " << this->CheckBuildSystemArgument
  2334. << "\n";
  2335. cmSystemTools::Stdout(msg.str());
  2336. }
  2337. // There was an error reading the file. Just rerun.
  2338. return 1;
  2339. }
  2340. if (this->ClearBuildSystem) {
  2341. // Get the generator used for this build system.
  2342. const char* genName =
  2343. cmToCStr(mf.GetDefinition("CMAKE_DEPENDS_GENERATOR"));
  2344. if (!cmNonempty(genName)) {
  2345. genName = "Unix Makefiles";
  2346. }
  2347. // Create the generator and use it to clear the dependencies.
  2348. std::unique_ptr<cmGlobalGenerator> ggd =
  2349. this->CreateGlobalGenerator(genName);
  2350. if (ggd) {
  2351. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  2352. cmMakefile mfd(ggd.get(), cm.GetCurrentSnapshot());
  2353. auto lgd = ggd->CreateLocalGenerator(&mfd);
  2354. lgd->ClearDependencies(&mfd, verbose);
  2355. }
  2356. }
  2357. // If any byproduct of makefile generation is missing we must re-run.
  2358. std::vector<std::string> products;
  2359. mf.GetDefExpandList("CMAKE_MAKEFILE_PRODUCTS", products);
  2360. for (std::string const& p : products) {
  2361. if (!(cmSystemTools::FileExists(p) || cmSystemTools::FileIsSymlink(p))) {
  2362. if (verbose) {
  2363. std::ostringstream msg;
  2364. msg << "Re-run cmake, missing byproduct: " << p << "\n";
  2365. cmSystemTools::Stdout(msg.str());
  2366. }
  2367. return 1;
  2368. }
  2369. }
  2370. // Get the set of dependencies and outputs.
  2371. std::vector<std::string> depends;
  2372. std::vector<std::string> outputs;
  2373. if (mf.GetDefExpandList("CMAKE_MAKEFILE_DEPENDS", depends)) {
  2374. mf.GetDefExpandList("CMAKE_MAKEFILE_OUTPUTS", outputs);
  2375. }
  2376. if (depends.empty() || outputs.empty()) {
  2377. // Not enough information was provided to do the test. Just rerun.
  2378. if (verbose) {
  2379. cmSystemTools::Stdout("Re-run cmake no CMAKE_MAKEFILE_DEPENDS "
  2380. "or CMAKE_MAKEFILE_OUTPUTS :\n");
  2381. }
  2382. return 1;
  2383. }
  2384. // Find the newest dependency.
  2385. auto dep = depends.begin();
  2386. std::string dep_newest = *dep++;
  2387. for (; dep != depends.end(); ++dep) {
  2388. int result = 0;
  2389. if (this->FileTimeCache->Compare(dep_newest, *dep, &result)) {
  2390. if (result < 0) {
  2391. dep_newest = *dep;
  2392. }
  2393. } else {
  2394. if (verbose) {
  2395. cmSystemTools::Stdout(
  2396. "Re-run cmake: build system dependency is missing\n");
  2397. }
  2398. return 1;
  2399. }
  2400. }
  2401. // Find the oldest output.
  2402. auto out = outputs.begin();
  2403. std::string out_oldest = *out++;
  2404. for (; out != outputs.end(); ++out) {
  2405. int result = 0;
  2406. if (this->FileTimeCache->Compare(out_oldest, *out, &result)) {
  2407. if (result > 0) {
  2408. out_oldest = *out;
  2409. }
  2410. } else {
  2411. if (verbose) {
  2412. cmSystemTools::Stdout(
  2413. "Re-run cmake: build system output is missing\n");
  2414. }
  2415. return 1;
  2416. }
  2417. }
  2418. // If any output is older than any dependency then rerun.
  2419. {
  2420. int result = 0;
  2421. if (!this->FileTimeCache->Compare(out_oldest, dep_newest, &result) ||
  2422. result < 0) {
  2423. if (verbose) {
  2424. std::ostringstream msg;
  2425. msg << "Re-run cmake file: " << out_oldest
  2426. << " older than: " << dep_newest << "\n";
  2427. cmSystemTools::Stdout(msg.str());
  2428. }
  2429. return 1;
  2430. }
  2431. }
  2432. // No need to rerun.
  2433. return 0;
  2434. }
  2435. void cmake::TruncateOutputLog(const char* fname)
  2436. {
  2437. std::string fullPath = cmStrCat(this->GetHomeOutputDirectory(), '/', fname);
  2438. struct stat st;
  2439. if (::stat(fullPath.c_str(), &st)) {
  2440. return;
  2441. }
  2442. if (!this->State->GetInitializedCacheValue("CMAKE_CACHEFILE_DIR")) {
  2443. cmSystemTools::RemoveFile(fullPath);
  2444. return;
  2445. }
  2446. off_t fsize = st.st_size;
  2447. const off_t maxFileSize = 50 * 1024;
  2448. if (fsize < maxFileSize) {
  2449. // TODO: truncate file
  2450. return;
  2451. }
  2452. }
  2453. void cmake::MarkCliAsUsed(const std::string& variable)
  2454. {
  2455. this->UsedCliVariables[variable] = true;
  2456. }
  2457. void cmake::GenerateGraphViz(const std::string& fileName) const
  2458. {
  2459. #ifndef CMAKE_BOOTSTRAP
  2460. cmGraphVizWriter gvWriter(fileName, this->GetGlobalGenerator());
  2461. std::string settingsFile =
  2462. cmStrCat(this->GetHomeOutputDirectory(), "/CMakeGraphVizOptions.cmake");
  2463. std::string fallbackSettingsFile =
  2464. cmStrCat(this->GetHomeDirectory(), "/CMakeGraphVizOptions.cmake");
  2465. gvWriter.ReadSettings(settingsFile, fallbackSettingsFile);
  2466. gvWriter.Write();
  2467. #endif
  2468. }
  2469. void cmake::SetProperty(const std::string& prop, const char* value)
  2470. {
  2471. this->State->SetGlobalProperty(prop, value);
  2472. }
  2473. void cmake::AppendProperty(const std::string& prop, const std::string& value,
  2474. bool asString)
  2475. {
  2476. this->State->AppendGlobalProperty(prop, value, asString);
  2477. }
  2478. cmProp cmake::GetProperty(const std::string& prop)
  2479. {
  2480. return this->State->GetGlobalProperty(prop);
  2481. }
  2482. bool cmake::GetPropertyAsBool(const std::string& prop)
  2483. {
  2484. return this->State->GetGlobalPropertyAsBool(prop);
  2485. }
  2486. cmInstalledFile* cmake::GetOrCreateInstalledFile(cmMakefile* mf,
  2487. const std::string& name)
  2488. {
  2489. auto i = this->InstalledFiles.find(name);
  2490. if (i != this->InstalledFiles.end()) {
  2491. cmInstalledFile& file = i->second;
  2492. return &file;
  2493. }
  2494. cmInstalledFile& file = this->InstalledFiles[name];
  2495. file.SetName(mf, name);
  2496. return &file;
  2497. }
  2498. cmInstalledFile const* cmake::GetInstalledFile(const std::string& name) const
  2499. {
  2500. auto i = this->InstalledFiles.find(name);
  2501. if (i != this->InstalledFiles.end()) {
  2502. cmInstalledFile const& file = i->second;
  2503. return &file;
  2504. }
  2505. return nullptr;
  2506. }
  2507. int cmake::GetSystemInformation(std::vector<std::string>& args)
  2508. {
  2509. // so create the directory
  2510. std::string resultFile;
  2511. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  2512. std::string destPath = cwd + "/__cmake_systeminformation";
  2513. cmSystemTools::RemoveADirectory(destPath);
  2514. if (!cmSystemTools::MakeDirectory(destPath)) {
  2515. std::cerr << "Error: --system-information must be run from a "
  2516. "writable directory!\n";
  2517. return 1;
  2518. }
  2519. // process the arguments
  2520. bool writeToStdout = true;
  2521. for (unsigned int i = 1; i < args.size(); ++i) {
  2522. std::string const& arg = args[i];
  2523. if (cmHasLiteralPrefix(arg, "-G")) {
  2524. std::string value = arg.substr(2);
  2525. if (value.empty()) {
  2526. ++i;
  2527. if (i >= args.size()) {
  2528. cmSystemTools::Error("No generator specified for -G");
  2529. this->PrintGeneratorList();
  2530. return -1;
  2531. }
  2532. value = args[i];
  2533. }
  2534. auto gen = this->CreateGlobalGenerator(value);
  2535. if (!gen) {
  2536. cmSystemTools::Error("Could not create named generator " + value);
  2537. this->PrintGeneratorList();
  2538. } else {
  2539. this->SetGlobalGenerator(std::move(gen));
  2540. }
  2541. }
  2542. // no option assume it is the output file
  2543. else {
  2544. if (!cmSystemTools::FileIsFullPath(arg)) {
  2545. resultFile = cmStrCat(cwd, '/');
  2546. }
  2547. resultFile += arg;
  2548. writeToStdout = false;
  2549. }
  2550. }
  2551. // we have to find the module directory, so we can copy the files
  2552. this->AddCMakePaths();
  2553. std::string modulesPath =
  2554. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules");
  2555. std::string inFile = cmStrCat(modulesPath, "/SystemInformation.cmake");
  2556. std::string outFile = cmStrCat(destPath, "/CMakeLists.txt");
  2557. // Copy file
  2558. if (!cmsys::SystemTools::CopyFileAlways(inFile, outFile)) {
  2559. std::cerr << "Error copying file \"" << inFile << "\" to \"" << outFile
  2560. << "\".\n";
  2561. return 1;
  2562. }
  2563. // do we write to a file or to stdout?
  2564. if (resultFile.empty()) {
  2565. resultFile = cmStrCat(cwd, "/__cmake_systeminformation/results.txt");
  2566. }
  2567. {
  2568. // now run cmake on the CMakeLists file
  2569. cmWorkingDirectory workdir(destPath);
  2570. if (workdir.Failed()) {
  2571. // We created the directory and we were able to copy the CMakeLists.txt
  2572. // file to it, so we wouldn't expect to get here unless the default
  2573. // permissions are questionable or some other process has deleted the
  2574. // directory
  2575. std::cerr << "Failed to change to directory " << destPath << " : "
  2576. << std::strerror(workdir.GetLastResult()) << std::endl;
  2577. return 1;
  2578. }
  2579. std::vector<std::string> args2;
  2580. args2.push_back(args[0]);
  2581. args2.push_back(destPath);
  2582. args2.push_back("-DRESULT_FILE=" + resultFile);
  2583. int res = this->Run(args2, false);
  2584. if (res != 0) {
  2585. std::cerr << "Error: --system-information failed on internal CMake!\n";
  2586. return res;
  2587. }
  2588. }
  2589. // echo results to stdout if needed
  2590. if (writeToStdout) {
  2591. FILE* fin = cmsys::SystemTools::Fopen(resultFile, "r");
  2592. if (fin) {
  2593. const int bufferSize = 4096;
  2594. char buffer[bufferSize];
  2595. size_t n;
  2596. while ((n = fread(buffer, 1, bufferSize, fin)) > 0) {
  2597. for (char* c = buffer; c < buffer + n; ++c) {
  2598. putc(*c, stdout);
  2599. }
  2600. fflush(stdout);
  2601. }
  2602. fclose(fin);
  2603. }
  2604. }
  2605. // clean up the directory
  2606. cmSystemTools::RemoveADirectory(destPath);
  2607. return 0;
  2608. }
  2609. static bool cmakeCheckStampFile(const std::string& stampName)
  2610. {
  2611. // The stamp file does not exist. Use the stamp dependencies to
  2612. // determine whether it is really out of date. This works in
  2613. // conjunction with cmLocalVisualStudio7Generator to avoid
  2614. // repeatedly re-running CMake when the user rebuilds the entire
  2615. // solution.
  2616. std::string stampDepends = cmStrCat(stampName, ".depend");
  2617. #if defined(_WIN32) || defined(__CYGWIN__)
  2618. cmsys::ifstream fin(stampDepends.c_str(), std::ios::in | std::ios::binary);
  2619. #else
  2620. cmsys::ifstream fin(stampDepends.c_str());
  2621. #endif
  2622. if (!fin) {
  2623. // The stamp dependencies file cannot be read. Just assume the
  2624. // build system is really out of date.
  2625. std::cout << "CMake is re-running because " << stampName
  2626. << " dependency file is missing.\n";
  2627. return false;
  2628. }
  2629. // Compare the stamp dependencies against the dependency file itself.
  2630. {
  2631. cmFileTimeCache ftc;
  2632. std::string dep;
  2633. while (cmSystemTools::GetLineFromStream(fin, dep)) {
  2634. int result;
  2635. if (!dep.empty() && dep[0] != '#' &&
  2636. (!ftc.Compare(stampDepends, dep, &result) || result < 0)) {
  2637. // The stamp depends file is older than this dependency. The
  2638. // build system is really out of date.
  2639. std::cout << "CMake is re-running because " << stampName
  2640. << " is out-of-date.\n";
  2641. std::cout << " the file '" << dep << "'\n";
  2642. std::cout << " is newer than '" << stampDepends << "'\n";
  2643. std::cout << " result='" << result << "'\n";
  2644. return false;
  2645. }
  2646. }
  2647. }
  2648. // The build system is up to date. The stamp file has been removed
  2649. // by the VS IDE due to a "rebuild" request. Restore it atomically.
  2650. std::ostringstream stampTempStream;
  2651. stampTempStream << stampName << ".tmp" << cmSystemTools::RandomSeed();
  2652. std::string stampTemp = stampTempStream.str();
  2653. {
  2654. // TODO: Teach cmGeneratedFileStream to use a random temp file (with
  2655. // multiple tries in unlikely case of conflict) and use that here.
  2656. cmsys::ofstream stamp(stampTemp.c_str());
  2657. stamp << "# CMake generation timestamp file for this directory.\n";
  2658. }
  2659. if (cmSystemTools::RenameFile(stampTemp, stampName)) {
  2660. // CMake does not need to re-run because the stamp file is up-to-date.
  2661. return true;
  2662. }
  2663. cmSystemTools::RemoveFile(stampTemp);
  2664. cmSystemTools::Error("Cannot restore timestamp " + stampName);
  2665. return false;
  2666. }
  2667. static bool cmakeCheckStampList(const std::string& stampList)
  2668. {
  2669. // If the stamp list does not exist CMake must rerun to generate it.
  2670. if (!cmSystemTools::FileExists(stampList)) {
  2671. std::cout << "CMake is re-running because generate.stamp.list "
  2672. << "is missing.\n";
  2673. return false;
  2674. }
  2675. cmsys::ifstream fin(stampList.c_str());
  2676. if (!fin) {
  2677. std::cout << "CMake is re-running because generate.stamp.list "
  2678. << "could not be read.\n";
  2679. return false;
  2680. }
  2681. // Check each stamp.
  2682. std::string stampName;
  2683. while (cmSystemTools::GetLineFromStream(fin, stampName)) {
  2684. if (!cmakeCheckStampFile(stampName)) {
  2685. return false;
  2686. }
  2687. }
  2688. return true;
  2689. }
  2690. void cmake::IssueMessage(MessageType t, std::string const& text,
  2691. cmListFileBacktrace const& backtrace) const
  2692. {
  2693. this->Messenger->IssueMessage(t, text, backtrace);
  2694. }
  2695. std::vector<std::string> cmake::GetDebugConfigs()
  2696. {
  2697. std::vector<std::string> configs;
  2698. if (cmProp config_list =
  2699. this->State->GetGlobalProperty("DEBUG_CONFIGURATIONS")) {
  2700. // Expand the specified list and convert to upper-case.
  2701. cmExpandList(*config_list, configs);
  2702. std::transform(configs.begin(), configs.end(), configs.begin(),
  2703. cmSystemTools::UpperCase);
  2704. }
  2705. // If no configurations were specified, use a default list.
  2706. if (configs.empty()) {
  2707. configs.emplace_back("DEBUG");
  2708. }
  2709. return configs;
  2710. }
  2711. int cmake::Build(int jobs, const std::string& dir,
  2712. const std::vector<std::string>& targets,
  2713. const std::string& config,
  2714. const std::vector<std::string>& nativeOptions, bool clean,
  2715. bool verbose)
  2716. {
  2717. this->SetHomeDirectory("");
  2718. this->SetHomeOutputDirectory("");
  2719. if (!cmSystemTools::FileIsDirectory(dir)) {
  2720. std::cerr << "Error: " << dir << " is not a directory\n";
  2721. return 1;
  2722. }
  2723. std::string cachePath = FindCacheFile(dir);
  2724. if (!this->LoadCache(cachePath)) {
  2725. std::cerr << "Error: could not load cache\n";
  2726. return 1;
  2727. }
  2728. cmProp cachedGenerator = this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  2729. if (!cachedGenerator) {
  2730. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  2731. return 1;
  2732. }
  2733. auto gen = this->CreateGlobalGenerator(*cachedGenerator);
  2734. if (!gen) {
  2735. std::cerr << "Error: could create CMAKE_GENERATOR \"" << *cachedGenerator
  2736. << "\"\n";
  2737. return 1;
  2738. }
  2739. this->SetGlobalGenerator(std::move(gen));
  2740. cmProp cachedGeneratorInstance =
  2741. this->State->GetCacheEntryValue("CMAKE_GENERATOR_INSTANCE");
  2742. if (cachedGeneratorInstance) {
  2743. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  2744. if (!this->GlobalGenerator->SetGeneratorInstance(*cachedGeneratorInstance,
  2745. &mf)) {
  2746. return 1;
  2747. }
  2748. }
  2749. cmProp cachedGeneratorPlatform =
  2750. this->State->GetCacheEntryValue("CMAKE_GENERATOR_PLATFORM");
  2751. if (cachedGeneratorPlatform) {
  2752. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  2753. if (!this->GlobalGenerator->SetGeneratorPlatform(*cachedGeneratorPlatform,
  2754. &mf)) {
  2755. return 1;
  2756. }
  2757. }
  2758. cmProp cachedGeneratorToolset =
  2759. this->State->GetCacheEntryValue("CMAKE_GENERATOR_TOOLSET");
  2760. if (cachedGeneratorToolset) {
  2761. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  2762. if (!this->GlobalGenerator->SetGeneratorToolset(*cachedGeneratorToolset,
  2763. true, &mf)) {
  2764. return 1;
  2765. }
  2766. }
  2767. std::string output;
  2768. std::string projName;
  2769. cmProp cachedProjectName =
  2770. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  2771. if (!cachedProjectName) {
  2772. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  2773. return 1;
  2774. }
  2775. projName = *cachedProjectName;
  2776. if (cmIsOn(this->State->GetCacheEntryValue("CMAKE_VERBOSE_MAKEFILE"))) {
  2777. verbose = true;
  2778. }
  2779. #ifdef CMAKE_HAVE_VS_GENERATORS
  2780. // For VS generators, explicitly check if regeneration is necessary before
  2781. // actually starting the build. If not done separately from the build
  2782. // itself, there is the risk of building an out-of-date solution file due
  2783. // to limitations of the underlying build system.
  2784. std::string const stampList = cachePath + "/" + "CMakeFiles/" +
  2785. cmGlobalVisualStudio9Generator::GetGenerateStampList();
  2786. // Note that the stampList file only exists for VS generators.
  2787. if (cmSystemTools::FileExists(stampList)) {
  2788. // Check if running for Visual Studio 9 - we need to explicitly run
  2789. // the glob verification script before starting the build
  2790. this->AddScriptingCommands();
  2791. if (this->GlobalGenerator->MatchesGeneratorName("Visual Studio 9 2008")) {
  2792. std::string const globVerifyScript =
  2793. cachePath + "/" + "CMakeFiles/" + "VerifyGlobs.cmake";
  2794. if (cmSystemTools::FileExists(globVerifyScript)) {
  2795. std::vector<std::string> args;
  2796. this->ReadListFile(args, globVerifyScript);
  2797. }
  2798. }
  2799. if (!cmakeCheckStampList(stampList)) {
  2800. // Correctly initialize the home (=source) and home output (=binary)
  2801. // directories, which is required for running the generation step.
  2802. std::string homeOrig = this->GetHomeDirectory();
  2803. std::string homeOutputOrig = this->GetHomeOutputDirectory();
  2804. this->SetDirectoriesFromFile(cachePath);
  2805. this->AddProjectCommands();
  2806. int ret = this->Configure();
  2807. if (ret) {
  2808. cmSystemTools::Message("CMake Configure step failed. "
  2809. "Build files cannot be regenerated correctly.");
  2810. return ret;
  2811. }
  2812. ret = this->Generate();
  2813. if (ret) {
  2814. cmSystemTools::Message("CMake Generate step failed. "
  2815. "Build files cannot be regenerated correctly.");
  2816. return ret;
  2817. }
  2818. std::string message = cmStrCat("Build files have been written to: ",
  2819. this->GetHomeOutputDirectory());
  2820. this->UpdateProgress(message, -1);
  2821. // Restore the previously set directories to their original value.
  2822. this->SetHomeDirectory(homeOrig);
  2823. this->SetHomeOutputDirectory(homeOutputOrig);
  2824. }
  2825. }
  2826. #endif
  2827. if (!this->GlobalGenerator->ReadCacheEntriesForBuild(*this->State)) {
  2828. return 1;
  2829. }
  2830. this->GlobalGenerator->PrintBuildCommandAdvice(std::cerr, jobs);
  2831. return this->GlobalGenerator->Build(
  2832. jobs, "", dir, projName, targets, output, "", config, clean, false,
  2833. verbose, cmDuration::zero(), cmSystemTools::OUTPUT_PASSTHROUGH,
  2834. nativeOptions);
  2835. }
  2836. bool cmake::Open(const std::string& dir, bool dryRun)
  2837. {
  2838. this->SetHomeDirectory("");
  2839. this->SetHomeOutputDirectory("");
  2840. if (!cmSystemTools::FileIsDirectory(dir)) {
  2841. std::cerr << "Error: " << dir << " is not a directory\n";
  2842. return false;
  2843. }
  2844. std::string cachePath = FindCacheFile(dir);
  2845. if (!this->LoadCache(cachePath)) {
  2846. std::cerr << "Error: could not load cache\n";
  2847. return false;
  2848. }
  2849. cmProp genName = this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  2850. if (!genName) {
  2851. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  2852. return false;
  2853. }
  2854. cmProp extraGenName =
  2855. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  2856. std::string fullName =
  2857. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  2858. *genName, extraGenName ? *extraGenName : "");
  2859. std::unique_ptr<cmGlobalGenerator> gen =
  2860. this->CreateGlobalGenerator(fullName);
  2861. if (!gen) {
  2862. std::cerr << "Error: could create CMAKE_GENERATOR \"" << fullName
  2863. << "\"\n";
  2864. return false;
  2865. }
  2866. cmProp cachedProjectName =
  2867. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  2868. if (!cachedProjectName) {
  2869. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  2870. return false;
  2871. }
  2872. return gen->Open(dir, *cachedProjectName, dryRun);
  2873. }
  2874. void cmake::WatchUnusedCli(const std::string& var)
  2875. {
  2876. #ifndef CMAKE_BOOTSTRAP
  2877. this->VariableWatch->AddWatch(var, cmWarnUnusedCliWarning, this);
  2878. if (!cm::contains(this->UsedCliVariables, var)) {
  2879. this->UsedCliVariables[var] = false;
  2880. }
  2881. #endif
  2882. }
  2883. void cmake::UnwatchUnusedCli(const std::string& var)
  2884. {
  2885. #ifndef CMAKE_BOOTSTRAP
  2886. this->VariableWatch->RemoveWatch(var, cmWarnUnusedCliWarning);
  2887. this->UsedCliVariables.erase(var);
  2888. #endif
  2889. }
  2890. void cmake::RunCheckForUnusedVariables()
  2891. {
  2892. #ifndef CMAKE_BOOTSTRAP
  2893. bool haveUnused = false;
  2894. std::ostringstream msg;
  2895. msg << "Manually-specified variables were not used by the project:";
  2896. for (auto const& it : this->UsedCliVariables) {
  2897. if (!it.second) {
  2898. haveUnused = true;
  2899. msg << "\n " << it.first;
  2900. }
  2901. }
  2902. if (haveUnused) {
  2903. this->IssueMessage(MessageType::WARNING, msg.str());
  2904. }
  2905. #endif
  2906. }
  2907. bool cmake::GetSuppressDevWarnings() const
  2908. {
  2909. return this->Messenger->GetSuppressDevWarnings();
  2910. }
  2911. void cmake::SetSuppressDevWarnings(bool b)
  2912. {
  2913. std::string value;
  2914. // equivalent to -Wno-dev
  2915. if (b) {
  2916. value = "TRUE";
  2917. }
  2918. // equivalent to -Wdev
  2919. else {
  2920. value = "FALSE";
  2921. }
  2922. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", value.c_str(),
  2923. "Suppress Warnings that are meant for"
  2924. " the author of the CMakeLists.txt files.",
  2925. cmStateEnums::INTERNAL);
  2926. }
  2927. bool cmake::GetSuppressDeprecatedWarnings() const
  2928. {
  2929. return this->Messenger->GetSuppressDeprecatedWarnings();
  2930. }
  2931. void cmake::SetSuppressDeprecatedWarnings(bool b)
  2932. {
  2933. std::string value;
  2934. // equivalent to -Wno-deprecated
  2935. if (b) {
  2936. value = "FALSE";
  2937. }
  2938. // equivalent to -Wdeprecated
  2939. else {
  2940. value = "TRUE";
  2941. }
  2942. this->AddCacheEntry("CMAKE_WARN_DEPRECATED", value.c_str(),
  2943. "Whether to issue warnings for deprecated "
  2944. "functionality.",
  2945. cmStateEnums::INTERNAL);
  2946. }
  2947. bool cmake::GetDevWarningsAsErrors() const
  2948. {
  2949. return this->Messenger->GetDevWarningsAsErrors();
  2950. }
  2951. void cmake::SetDevWarningsAsErrors(bool b)
  2952. {
  2953. std::string value;
  2954. // equivalent to -Werror=dev
  2955. if (b) {
  2956. value = "FALSE";
  2957. }
  2958. // equivalent to -Wno-error=dev
  2959. else {
  2960. value = "TRUE";
  2961. }
  2962. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_ERRORS", value.c_str(),
  2963. "Suppress errors that are meant for"
  2964. " the author of the CMakeLists.txt files.",
  2965. cmStateEnums::INTERNAL);
  2966. }
  2967. bool cmake::GetDeprecatedWarningsAsErrors() const
  2968. {
  2969. return this->Messenger->GetDeprecatedWarningsAsErrors();
  2970. }
  2971. void cmake::SetDeprecatedWarningsAsErrors(bool b)
  2972. {
  2973. std::string value;
  2974. // equivalent to -Werror=deprecated
  2975. if (b) {
  2976. value = "TRUE";
  2977. }
  2978. // equivalent to -Wno-error=deprecated
  2979. else {
  2980. value = "FALSE";
  2981. }
  2982. this->AddCacheEntry("CMAKE_ERROR_DEPRECATED", value.c_str(),
  2983. "Whether to issue deprecation errors for macros"
  2984. " and functions.",
  2985. cmStateEnums::INTERNAL);
  2986. }
  2987. #if !defined(CMAKE_BOOTSTRAP)
  2988. cmMakefileProfilingData& cmake::GetProfilingOutput()
  2989. {
  2990. return *(this->ProfilingOutput);
  2991. }
  2992. bool cmake::IsProfilingEnabled() const
  2993. {
  2994. return static_cast<bool>(this->ProfilingOutput);
  2995. }
  2996. #endif