cmake.cxx 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590
  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 "cmAlgorithms.h"
  5. #include "cmCommands.h"
  6. #include "cmDocumentation.h"
  7. #include "cmDocumentationEntry.h"
  8. #include "cmDocumentationFormatter.h"
  9. #include "cmExternalMakefileProjectGenerator.h"
  10. #include "cmFileTimeComparison.h"
  11. #include "cmGeneratorTarget.h"
  12. #include "cmGlobalGenerator.h"
  13. #include "cmGlobalGeneratorFactory.h"
  14. #include "cmLinkLineComputer.h"
  15. #include "cmLocalGenerator.h"
  16. #include "cmMakefile.h"
  17. #include "cmMessenger.h"
  18. #include "cmState.h"
  19. #include "cmStateDirectory.h"
  20. #include "cmSystemTools.h"
  21. #include "cmTarget.h"
  22. #include "cmTargetLinkLibraryType.h"
  23. #include "cmUtils.hxx"
  24. #include "cmVersionConfig.h"
  25. #include "cmWorkingDirectory.h"
  26. #include "cm_auto_ptr.hxx"
  27. #include "cm_sys_stat.h"
  28. #if defined(CMAKE_BUILD_WITH_CMAKE)
  29. #include "cm_jsoncpp_writer.h"
  30. #include "cmGraphVizWriter.h"
  31. #include "cmVariableWatch.h"
  32. #include "cm_unordered_map.hxx"
  33. #endif
  34. // only build kdevelop generator on non-windows platforms
  35. // when not bootstrapping cmake
  36. #if !defined(_WIN32)
  37. #if defined(CMAKE_BUILD_WITH_CMAKE)
  38. #define CMAKE_USE_KDEVELOP
  39. #endif
  40. #endif
  41. #if defined(CMAKE_BUILD_WITH_CMAKE)
  42. #define CMAKE_USE_ECLIPSE
  43. #endif
  44. #if defined(__MINGW32__) && !defined(CMAKE_BUILD_WITH_CMAKE)
  45. #define CMAKE_BOOT_MINGW
  46. #endif
  47. // include the generator
  48. #if defined(_WIN32) && !defined(__CYGWIN__)
  49. #if !defined(CMAKE_BOOT_MINGW)
  50. #include "cmGlobalBorlandMakefileGenerator.h"
  51. #include "cmGlobalGhsMultiGenerator.h"
  52. #include "cmGlobalJOMMakefileGenerator.h"
  53. #include "cmGlobalNMakeMakefileGenerator.h"
  54. #include "cmGlobalVisualStudio10Generator.h"
  55. #include "cmGlobalVisualStudio11Generator.h"
  56. #include "cmGlobalVisualStudio12Generator.h"
  57. #include "cmGlobalVisualStudio14Generator.h"
  58. #include "cmGlobalVisualStudio15Generator.h"
  59. #include "cmGlobalVisualStudio8Generator.h"
  60. #include "cmGlobalVisualStudio9Generator.h"
  61. #include "cmVSSetupHelper.h"
  62. #define CMAKE_HAVE_VS_GENERATORS
  63. #endif
  64. #include "cmGlobalMSYSMakefileGenerator.h"
  65. #include "cmGlobalMinGWMakefileGenerator.h"
  66. #else
  67. #endif
  68. #if defined(CMAKE_USE_WMAKE)
  69. #include "cmGlobalWatcomWMakeGenerator.h"
  70. #endif
  71. #include "cmGlobalUnixMakefileGenerator3.h"
  72. #if defined(CMAKE_BUILD_WITH_CMAKE)
  73. #include "cmGlobalNinjaGenerator.h"
  74. #endif
  75. #include "cmExtraCodeLiteGenerator.h"
  76. #if !defined(CMAKE_BOOT_MINGW)
  77. #include "cmExtraCodeBlocksGenerator.h"
  78. #endif
  79. #include "cmExtraKateGenerator.h"
  80. #include "cmExtraSublimeTextGenerator.h"
  81. #ifdef CMAKE_USE_KDEVELOP
  82. #include "cmGlobalKdevelopGenerator.h"
  83. #endif
  84. #ifdef CMAKE_USE_ECLIPSE
  85. #include "cmExtraEclipseCDT4Generator.h"
  86. #endif
  87. #if defined(__APPLE__)
  88. #if defined(CMAKE_BUILD_WITH_CMAKE)
  89. #include "cmGlobalXCodeGenerator.h"
  90. #define CMAKE_USE_XCODE 1
  91. #endif
  92. #include <sys/resource.h>
  93. #include <sys/time.h>
  94. #endif
  95. #include "cmsys/FStream.hxx"
  96. #include "cmsys/Glob.hxx"
  97. #include "cmsys/RegularExpression.hxx"
  98. #include <algorithm>
  99. #include <iostream>
  100. #include <sstream>
  101. #include <stdio.h>
  102. #include <stdlib.h>
  103. #include <string.h>
  104. #include <utility>
  105. namespace {
  106. #if defined(CMAKE_BUILD_WITH_CMAKE)
  107. typedef CM_UNORDERED_MAP<std::string, Json::Value> JsonValueMapType;
  108. #endif
  109. } // namespace
  110. static bool cmakeCheckStampFile(const char* stampName, bool verbose = true);
  111. static bool cmakeCheckStampList(const char* stampList, bool verbose = true);
  112. void cmWarnUnusedCliWarning(const std::string& variable, int /*unused*/,
  113. void* ctx, const char* /*unused*/,
  114. const cmMakefile* /*unused*/)
  115. {
  116. cmake* cm = reinterpret_cast<cmake*>(ctx);
  117. cm->MarkCliAsUsed(variable);
  118. }
  119. cmake::cmake(Role role)
  120. {
  121. this->Trace = false;
  122. this->TraceExpand = false;
  123. this->WarnUninitialized = false;
  124. this->WarnUnused = false;
  125. this->WarnUnusedCli = true;
  126. this->CheckSystemVars = false;
  127. this->DebugOutput = false;
  128. this->DebugTryCompile = false;
  129. this->ClearBuildSystem = false;
  130. this->FileComparison = new cmFileTimeComparison;
  131. this->State = new cmState;
  132. this->CurrentSnapshot = this->State->CreateBaseSnapshot();
  133. this->Messenger = new cmMessenger(this->State);
  134. #ifdef __APPLE__
  135. struct rlimit rlp;
  136. if (!getrlimit(RLIMIT_STACK, &rlp)) {
  137. if (rlp.rlim_cur != rlp.rlim_max) {
  138. rlp.rlim_cur = rlp.rlim_max;
  139. setrlimit(RLIMIT_STACK, &rlp);
  140. }
  141. }
  142. #endif
  143. this->GlobalGenerator = CM_NULLPTR;
  144. this->ProgressCallback = CM_NULLPTR;
  145. this->ProgressCallbackClientData = CM_NULLPTR;
  146. this->CurrentWorkingMode = NORMAL_MODE;
  147. #ifdef CMAKE_BUILD_WITH_CMAKE
  148. this->VariableWatch = new cmVariableWatch;
  149. #endif
  150. this->AddDefaultGenerators();
  151. this->AddDefaultExtraGenerators();
  152. if (role == RoleScript || role == RoleProject) {
  153. this->AddScriptingCommands();
  154. }
  155. if (role == RoleProject) {
  156. this->AddProjectCommands();
  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
  162. // is not given
  163. // The "c" extension MUST precede the "C" extension.
  164. this->SourceFileExtensions.push_back("c");
  165. this->SourceFileExtensions.push_back("C");
  166. this->SourceFileExtensions.push_back("c++");
  167. this->SourceFileExtensions.push_back("cc");
  168. this->SourceFileExtensions.push_back("cpp");
  169. this->SourceFileExtensions.push_back("cxx");
  170. this->SourceFileExtensions.push_back("m");
  171. this->SourceFileExtensions.push_back("M");
  172. this->SourceFileExtensions.push_back("mm");
  173. this->HeaderFileExtensions.push_back("h");
  174. this->HeaderFileExtensions.push_back("hh");
  175. this->HeaderFileExtensions.push_back("h++");
  176. this->HeaderFileExtensions.push_back("hm");
  177. this->HeaderFileExtensions.push_back("hpp");
  178. this->HeaderFileExtensions.push_back("hxx");
  179. this->HeaderFileExtensions.push_back("in");
  180. this->HeaderFileExtensions.push_back("txx");
  181. }
  182. cmake::~cmake()
  183. {
  184. delete this->State;
  185. delete this->Messenger;
  186. if (this->GlobalGenerator) {
  187. delete this->GlobalGenerator;
  188. this->GlobalGenerator = CM_NULLPTR;
  189. }
  190. cmDeleteAll(this->Generators);
  191. #ifdef CMAKE_BUILD_WITH_CMAKE
  192. delete this->VariableWatch;
  193. #endif
  194. delete this->FileComparison;
  195. }
  196. #if defined(CMAKE_BUILD_WITH_CMAKE)
  197. Json::Value cmake::ReportCapabilitiesJson(bool haveServerMode) const
  198. {
  199. Json::Value obj = Json::objectValue;
  200. // Version information:
  201. Json::Value version = Json::objectValue;
  202. version["string"] = CMake_VERSION;
  203. version["major"] = CMake_VERSION_MAJOR;
  204. version["minor"] = CMake_VERSION_MINOR;
  205. version["suffix"] = CMake_VERSION_SUFFIX;
  206. version["isDirty"] = (CMake_VERSION_IS_DIRTY == 1);
  207. version["patch"] = CMake_VERSION_PATCH;
  208. obj["version"] = version;
  209. // Generators:
  210. std::vector<cmake::GeneratorInfo> generatorInfoList;
  211. this->GetRegisteredGenerators(generatorInfoList);
  212. JsonValueMapType generatorMap;
  213. for (std::vector<cmake::GeneratorInfo>::const_iterator i =
  214. generatorInfoList.begin();
  215. i != generatorInfoList.end(); ++i) {
  216. if (i->isAlias) { // skip aliases, they are there for compatibility reasons
  217. // only
  218. continue;
  219. }
  220. if (i->extraName.empty()) {
  221. Json::Value gen = Json::objectValue;
  222. gen["name"] = i->name;
  223. gen["toolsetSupport"] = i->supportsToolset;
  224. gen["platformSupport"] = i->supportsPlatform;
  225. gen["extraGenerators"] = Json::arrayValue;
  226. generatorMap[i->name] = gen;
  227. } else {
  228. Json::Value& gen = generatorMap[i->baseName];
  229. gen["extraGenerators"].append(i->extraName);
  230. }
  231. }
  232. Json::Value generators = Json::arrayValue;
  233. for (JsonValueMapType::const_iterator i = generatorMap.begin();
  234. i != generatorMap.end(); ++i) {
  235. generators.append(i->second);
  236. }
  237. obj["generators"] = generators;
  238. obj["serverMode"] = haveServerMode;
  239. return obj;
  240. }
  241. #endif
  242. std::string cmake::ReportCapabilities(bool haveServerMode) const
  243. {
  244. std::string result;
  245. #if defined(CMAKE_BUILD_WITH_CMAKE)
  246. Json::FastWriter writer;
  247. result = writer.write(this->ReportCapabilitiesJson(haveServerMode));
  248. #else
  249. result = "Not supported";
  250. #endif
  251. return result;
  252. }
  253. void cmake::CleanupCommandsAndMacros()
  254. {
  255. this->CurrentSnapshot = this->State->Reset();
  256. this->State->RemoveUserDefinedCommands();
  257. this->CurrentSnapshot.SetDefaultDefinitions();
  258. }
  259. // Parse the args
  260. bool cmake::SetCacheArgs(const std::vector<std::string>& args)
  261. {
  262. bool findPackageMode = false;
  263. for (unsigned int i = 1; i < args.size(); ++i) {
  264. std::string const& arg = args[i];
  265. if (arg.find("-D", 0) == 0) {
  266. std::string entry = arg.substr(2);
  267. if (entry.empty()) {
  268. ++i;
  269. if (i < args.size()) {
  270. entry = args[i];
  271. } else {
  272. cmSystemTools::Error("-D must be followed with VAR=VALUE.");
  273. return false;
  274. }
  275. }
  276. std::string var, value;
  277. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  278. if (cmState::ParseCacheEntry(entry, var, value, type)) {
  279. // The value is transformed if it is a filepath for example, so
  280. // we can't compare whether the value is already in the cache until
  281. // after we call AddCacheEntry.
  282. bool haveValue = false;
  283. std::string cachedValue;
  284. if (this->WarnUnusedCli) {
  285. if (const char* v = this->State->GetInitializedCacheValue(var)) {
  286. haveValue = true;
  287. cachedValue = v;
  288. }
  289. }
  290. this->AddCacheEntry(var, value.c_str(),
  291. "No help, variable specified on the command line.",
  292. type);
  293. if (this->WarnUnusedCli) {
  294. if (!haveValue ||
  295. cachedValue != this->State->GetInitializedCacheValue(var)) {
  296. this->WatchUnusedCli(var);
  297. }
  298. }
  299. } else {
  300. std::cerr << "Parse error in command line argument: " << arg << "\n"
  301. << "Should be: VAR:type=value\n";
  302. cmSystemTools::Error("No cmake script provided.");
  303. return false;
  304. }
  305. } else if (cmHasLiteralPrefix(arg, "-W")) {
  306. std::string entry = arg.substr(2);
  307. if (entry.empty()) {
  308. ++i;
  309. if (i < args.size()) {
  310. entry = args[i];
  311. } else {
  312. cmSystemTools::Error("-W must be followed with [no-]<name>.");
  313. return false;
  314. }
  315. }
  316. std::string name;
  317. bool foundNo = false;
  318. bool foundError = false;
  319. unsigned int nameStartPosition = 0;
  320. if (entry.find("no-", nameStartPosition) == 0) {
  321. foundNo = true;
  322. nameStartPosition += 3;
  323. }
  324. if (entry.find("error=", nameStartPosition) == 0) {
  325. foundError = true;
  326. nameStartPosition += 6;
  327. }
  328. name = entry.substr(nameStartPosition);
  329. if (name.empty()) {
  330. cmSystemTools::Error("No warning name provided.");
  331. return false;
  332. }
  333. if (!foundNo && !foundError) {
  334. // -W<name>
  335. this->DiagLevels[name] = std::max(this->DiagLevels[name], DIAG_WARN);
  336. } else if (foundNo && !foundError) {
  337. // -Wno<name>
  338. this->DiagLevels[name] = DIAG_IGNORE;
  339. } else if (!foundNo && foundError) {
  340. // -Werror=<name>
  341. this->DiagLevels[name] = DIAG_ERROR;
  342. } else {
  343. // -Wno-error=<name>
  344. this->DiagLevels[name] = std::min(this->DiagLevels[name], DIAG_WARN);
  345. }
  346. } else if (arg.find("-U", 0) == 0) {
  347. std::string entryPattern = arg.substr(2);
  348. if (entryPattern.empty()) {
  349. ++i;
  350. if (i < args.size()) {
  351. entryPattern = args[i];
  352. } else {
  353. cmSystemTools::Error("-U must be followed with VAR.");
  354. return false;
  355. }
  356. }
  357. cmsys::RegularExpression regex(
  358. cmsys::Glob::PatternToRegex(entryPattern, true, true).c_str());
  359. // go through all cache entries and collect the vars which will be
  360. // removed
  361. std::vector<std::string> entriesToDelete;
  362. std::vector<std::string> cacheKeys = this->State->GetCacheEntryKeys();
  363. for (std::vector<std::string>::const_iterator it = cacheKeys.begin();
  364. it != cacheKeys.end(); ++it) {
  365. cmStateEnums::CacheEntryType t = this->State->GetCacheEntryType(*it);
  366. if (t != cmStateEnums::STATIC) {
  367. if (regex.find(it->c_str())) {
  368. entriesToDelete.push_back(*it);
  369. }
  370. }
  371. }
  372. // now remove them from the cache
  373. for (std::vector<std::string>::const_iterator currentEntry =
  374. entriesToDelete.begin();
  375. currentEntry != entriesToDelete.end(); ++currentEntry) {
  376. this->State->RemoveCacheEntry(*currentEntry);
  377. }
  378. } else if (arg.find("-C", 0) == 0) {
  379. std::string path = arg.substr(2);
  380. if (path.empty()) {
  381. ++i;
  382. if (i < args.size()) {
  383. path = args[i];
  384. } else {
  385. cmSystemTools::Error("-C must be followed by a file name.");
  386. return false;
  387. }
  388. }
  389. std::cout << "loading initial cache file " << path << "\n";
  390. this->ReadListFile(args, path.c_str());
  391. } else if (arg.find("-P", 0) == 0) {
  392. i++;
  393. if (i >= args.size()) {
  394. cmSystemTools::Error("-P must be followed by a file name.");
  395. return false;
  396. }
  397. std::string path = args[i];
  398. if (path.empty()) {
  399. cmSystemTools::Error("No cmake script provided.");
  400. return false;
  401. }
  402. // Register fake project commands that hint misuse in script mode.
  403. GetProjectCommandsInScriptMode(this->State);
  404. this->ReadListFile(args, path.c_str());
  405. } else if (arg.find("--find-package", 0) == 0) {
  406. findPackageMode = true;
  407. }
  408. }
  409. if (findPackageMode) {
  410. return this->FindPackage(args);
  411. }
  412. return true;
  413. }
  414. void cmake::ReadListFile(const std::vector<std::string>& args,
  415. const char* path)
  416. {
  417. // if a generator was not yet created, temporarily create one
  418. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  419. bool created = false;
  420. // if a generator was not specified use a generic one
  421. if (!gg) {
  422. gg = new cmGlobalGenerator(this);
  423. created = true;
  424. }
  425. // read in the list file to fill the cache
  426. if (path) {
  427. this->CurrentSnapshot = this->State->Reset();
  428. std::string homeDir = this->GetHomeDirectory();
  429. std::string homeOutputDir = this->GetHomeOutputDirectory();
  430. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  431. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  432. cmStateSnapshot snapshot = this->GetCurrentSnapshot();
  433. snapshot.GetDirectory().SetCurrentBinary(
  434. cmSystemTools::GetCurrentWorkingDirectory());
  435. snapshot.GetDirectory().SetCurrentSource(
  436. cmSystemTools::GetCurrentWorkingDirectory());
  437. snapshot.SetDefaultDefinitions();
  438. CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(gg, snapshot));
  439. if (this->GetWorkingMode() != NORMAL_MODE) {
  440. std::string file(cmSystemTools::CollapseFullPath(path));
  441. cmSystemTools::ConvertToUnixSlashes(file);
  442. mf->SetScriptModeFile(file.c_str());
  443. mf->SetArgcArgv(args);
  444. }
  445. if (!mf->ReadListFile(path)) {
  446. cmSystemTools::Error("Error processing file: ", path);
  447. }
  448. this->SetHomeDirectory(homeDir);
  449. this->SetHomeOutputDirectory(homeOutputDir);
  450. }
  451. // free generic one if generated
  452. if (created) {
  453. delete gg;
  454. }
  455. }
  456. bool cmake::FindPackage(const std::vector<std::string>& args)
  457. {
  458. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  459. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  460. // if a generator was not yet created, temporarily create one
  461. cmGlobalGenerator* gg = new cmGlobalGenerator(this);
  462. this->SetGlobalGenerator(gg);
  463. cmStateSnapshot snapshot = this->GetCurrentSnapshot();
  464. snapshot.GetDirectory().SetCurrentBinary(
  465. cmSystemTools::GetCurrentWorkingDirectory());
  466. snapshot.GetDirectory().SetCurrentSource(
  467. cmSystemTools::GetCurrentWorkingDirectory());
  468. // read in the list file to fill the cache
  469. snapshot.SetDefaultDefinitions();
  470. cmMakefile* mf = new cmMakefile(gg, snapshot);
  471. gg->AddMakefile(mf);
  472. mf->SetArgcArgv(args);
  473. std::string systemFile = mf->GetModulesFile("CMakeFindPackageMode.cmake");
  474. mf->ReadListFile(systemFile.c_str());
  475. std::string language = mf->GetSafeDefinition("LANGUAGE");
  476. std::string mode = mf->GetSafeDefinition("MODE");
  477. std::string packageName = mf->GetSafeDefinition("NAME");
  478. bool packageFound = mf->IsOn("PACKAGE_FOUND");
  479. bool quiet = mf->IsOn("PACKAGE_QUIET");
  480. if (!packageFound) {
  481. if (!quiet) {
  482. printf("%s not found.\n", packageName.c_str());
  483. }
  484. } else if (mode == "EXIST") {
  485. if (!quiet) {
  486. printf("%s found.\n", packageName.c_str());
  487. }
  488. } else if (mode == "COMPILE") {
  489. std::string includes = mf->GetSafeDefinition("PACKAGE_INCLUDE_DIRS");
  490. std::vector<std::string> includeDirs;
  491. cmSystemTools::ExpandListArgument(includes, includeDirs);
  492. gg->CreateGenerationObjects();
  493. cmLocalGenerator* lg = gg->LocalGenerators[0];
  494. std::string includeFlags =
  495. lg->GetIncludeFlags(includeDirs, CM_NULLPTR, language);
  496. std::string definitions = mf->GetSafeDefinition("PACKAGE_DEFINITIONS");
  497. printf("%s %s\n", includeFlags.c_str(), definitions.c_str());
  498. } else if (mode == "LINK") {
  499. const char* targetName = "dummy";
  500. std::vector<std::string> srcs;
  501. cmTarget* tgt = mf->AddExecutable(targetName, srcs, true);
  502. tgt->SetProperty("LINKER_LANGUAGE", language.c_str());
  503. std::string libs = mf->GetSafeDefinition("PACKAGE_LIBRARIES");
  504. std::vector<std::string> libList;
  505. cmSystemTools::ExpandListArgument(libs, libList);
  506. for (std::vector<std::string>::const_iterator libIt = libList.begin();
  507. libIt != libList.end(); ++libIt) {
  508. tgt->AddLinkLibrary(*mf, *libIt, GENERAL_LibraryType);
  509. }
  510. std::string buildType = mf->GetSafeDefinition("CMAKE_BUILD_TYPE");
  511. buildType = cmSystemTools::UpperCase(buildType);
  512. std::string linkLibs;
  513. std::string frameworkPath;
  514. std::string linkPath;
  515. std::string flags;
  516. std::string linkFlags;
  517. gg->CreateGenerationObjects();
  518. cmGeneratorTarget* gtgt = gg->FindGeneratorTarget(tgt->GetName());
  519. cmLocalGenerator* lg = gtgt->GetLocalGenerator();
  520. cmLinkLineComputer linkLineComputer(lg,
  521. lg->GetStateSnapshot().GetDirectory());
  522. lg->GetTargetFlags(&linkLineComputer, buildType, linkLibs, flags,
  523. linkFlags, frameworkPath, linkPath, gtgt);
  524. linkLibs = frameworkPath + linkPath + linkLibs;
  525. printf("%s\n", linkLibs.c_str());
  526. /* if ( use_win32 )
  527. {
  528. tgt->SetProperty("WIN32_EXECUTABLE", "ON");
  529. }
  530. if ( use_macbundle)
  531. {
  532. tgt->SetProperty("MACOSX_BUNDLE", "ON");
  533. }*/
  534. }
  535. // free generic one if generated
  536. // this->SetGlobalGenerator(0); // setting 0-pointer is not possible
  537. // delete gg; // this crashes inside the cmake instance
  538. return packageFound;
  539. }
  540. // Parse the args
  541. void cmake::SetArgs(const std::vector<std::string>& args,
  542. bool directoriesSetBefore)
  543. {
  544. bool directoriesSet = directoriesSetBefore;
  545. bool haveToolset = false;
  546. bool havePlatform = false;
  547. for (unsigned int i = 1; i < args.size(); ++i) {
  548. std::string const& arg = args[i];
  549. if (arg.find("-H", 0) == 0) {
  550. directoriesSet = true;
  551. std::string path = arg.substr(2);
  552. path = cmSystemTools::CollapseFullPath(path);
  553. cmSystemTools::ConvertToUnixSlashes(path);
  554. this->SetHomeDirectory(path);
  555. } else if (arg.find("-S", 0) == 0) {
  556. // There is no local generate anymore. Ignore -S option.
  557. } else if (arg.find("-O", 0) == 0) {
  558. // There is no local generate anymore. Ignore -O option.
  559. } else if (arg.find("-B", 0) == 0) {
  560. directoriesSet = true;
  561. std::string path = arg.substr(2);
  562. path = cmSystemTools::CollapseFullPath(path);
  563. cmSystemTools::ConvertToUnixSlashes(path);
  564. this->SetHomeOutputDirectory(path);
  565. } else if ((i < args.size() - 2) &&
  566. (arg.find("--check-build-system", 0) == 0)) {
  567. this->CheckBuildSystemArgument = args[++i];
  568. this->ClearBuildSystem = (atoi(args[++i].c_str()) > 0);
  569. } else if ((i < args.size() - 1) &&
  570. (arg.find("--check-stamp-file", 0) == 0)) {
  571. this->CheckStampFile = args[++i];
  572. } else if ((i < args.size() - 1) &&
  573. (arg.find("--check-stamp-list", 0) == 0)) {
  574. this->CheckStampList = args[++i];
  575. }
  576. #if defined(CMAKE_HAVE_VS_GENERATORS)
  577. else if ((i < args.size() - 1) &&
  578. (arg.find("--vs-solution-file", 0) == 0)) {
  579. this->VSSolutionFile = args[++i];
  580. }
  581. #endif
  582. else if (arg.find("-D", 0) == 0) {
  583. // skip for now
  584. } else if (arg.find("-U", 0) == 0) {
  585. // skip for now
  586. } else if (arg.find("-C", 0) == 0) {
  587. // skip for now
  588. } else if (arg.find("-P", 0) == 0) {
  589. // skip for now
  590. i++;
  591. } else if (arg.find("--find-package", 0) == 0) {
  592. // skip for now
  593. i++;
  594. } else if (arg.find("-W", 0) == 0) {
  595. // skip for now
  596. } else if (arg.find("--graphviz=", 0) == 0) {
  597. std::string path = arg.substr(strlen("--graphviz="));
  598. path = cmSystemTools::CollapseFullPath(path);
  599. cmSystemTools::ConvertToUnixSlashes(path);
  600. this->GraphVizFile = path;
  601. if (this->GraphVizFile.empty()) {
  602. cmSystemTools::Error("No file specified for --graphviz");
  603. }
  604. } else if (arg.find("--debug-trycompile", 0) == 0) {
  605. std::cout << "debug trycompile on\n";
  606. this->DebugTryCompileOn();
  607. } else if (arg.find("--debug-output", 0) == 0) {
  608. std::cout << "Running with debug output on.\n";
  609. this->SetDebugOutputOn(true);
  610. } else if (arg.find("--trace-expand", 0) == 0) {
  611. std::cout << "Running with expanded trace output on.\n";
  612. this->SetTrace(true);
  613. this->SetTraceExpand(true);
  614. } else if (arg.find("--trace-source=", 0) == 0) {
  615. std::string file = arg.substr(strlen("--trace-source="));
  616. cmSystemTools::ConvertToUnixSlashes(file);
  617. this->AddTraceSource(file);
  618. this->SetTrace(true);
  619. } else if (arg.find("--trace", 0) == 0) {
  620. std::cout << "Running with trace output on.\n";
  621. this->SetTrace(true);
  622. this->SetTraceExpand(false);
  623. } else if (arg.find("--warn-uninitialized", 0) == 0) {
  624. std::cout << "Warn about uninitialized values.\n";
  625. this->SetWarnUninitialized(true);
  626. } else if (arg.find("--warn-unused-vars", 0) == 0) {
  627. std::cout << "Finding unused variables.\n";
  628. this->SetWarnUnused(true);
  629. } else if (arg.find("--no-warn-unused-cli", 0) == 0) {
  630. std::cout << "Not searching for unused variables given on the "
  631. << "command line.\n";
  632. this->SetWarnUnusedCli(false);
  633. } else if (arg.find("--check-system-vars", 0) == 0) {
  634. std::cout << "Also check system files when warning about unused and "
  635. << "uninitialized variables.\n";
  636. this->SetCheckSystemVars(true);
  637. } else if (arg.find("-A", 0) == 0) {
  638. std::string value = arg.substr(2);
  639. if (value.empty()) {
  640. ++i;
  641. if (i >= args.size()) {
  642. cmSystemTools::Error("No platform specified for -A");
  643. return;
  644. }
  645. value = args[i];
  646. }
  647. if (havePlatform) {
  648. cmSystemTools::Error("Multiple -A options not allowed");
  649. return;
  650. }
  651. this->GeneratorPlatform = value;
  652. havePlatform = true;
  653. } else if (arg.find("-T", 0) == 0) {
  654. std::string value = arg.substr(2);
  655. if (value.empty()) {
  656. ++i;
  657. if (i >= args.size()) {
  658. cmSystemTools::Error("No toolset specified for -T");
  659. return;
  660. }
  661. value = args[i];
  662. }
  663. if (haveToolset) {
  664. cmSystemTools::Error("Multiple -T options not allowed");
  665. return;
  666. }
  667. this->GeneratorToolset = value;
  668. haveToolset = true;
  669. } else if (arg.find("-G", 0) == 0) {
  670. std::string value = arg.substr(2);
  671. if (value.empty()) {
  672. ++i;
  673. if (i >= args.size()) {
  674. cmSystemTools::Error("No generator specified for -G");
  675. this->PrintGeneratorList();
  676. return;
  677. }
  678. value = args[i];
  679. }
  680. cmGlobalGenerator* gen = this->CreateGlobalGenerator(value);
  681. if (!gen) {
  682. cmSystemTools::Error("Could not create named generator ",
  683. value.c_str());
  684. this->PrintGeneratorList();
  685. } else {
  686. this->SetGlobalGenerator(gen);
  687. }
  688. }
  689. // no option assume it is the path to the source
  690. else {
  691. directoriesSet = true;
  692. this->SetDirectoriesFromFile(arg.c_str());
  693. }
  694. }
  695. if (!directoriesSet) {
  696. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  697. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  698. }
  699. }
  700. void cmake::SetDirectoriesFromFile(const char* arg)
  701. {
  702. // Check if the argument refers to a CMakeCache.txt or
  703. // CMakeLists.txt file.
  704. std::string listPath;
  705. std::string cachePath;
  706. bool argIsFile = false;
  707. if (cmSystemTools::FileIsDirectory(arg)) {
  708. std::string path = cmSystemTools::CollapseFullPath(arg);
  709. cmSystemTools::ConvertToUnixSlashes(path);
  710. std::string cacheFile = path;
  711. cacheFile += "/CMakeCache.txt";
  712. std::string listFile = path;
  713. listFile += "/CMakeLists.txt";
  714. if (cmSystemTools::FileExists(cacheFile.c_str())) {
  715. cachePath = path;
  716. }
  717. if (cmSystemTools::FileExists(listFile.c_str())) {
  718. listPath = path;
  719. }
  720. } else if (cmSystemTools::FileExists(arg)) {
  721. argIsFile = true;
  722. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  723. std::string name = cmSystemTools::GetFilenameName(fullPath);
  724. name = cmSystemTools::LowerCase(name);
  725. if (name == "cmakecache.txt") {
  726. cachePath = cmSystemTools::GetFilenamePath(fullPath);
  727. } else if (name == "cmakelists.txt") {
  728. listPath = cmSystemTools::GetFilenamePath(fullPath);
  729. }
  730. } else {
  731. // Specified file or directory does not exist. Try to set things
  732. // up to produce a meaningful error message.
  733. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  734. std::string name = cmSystemTools::GetFilenameName(fullPath);
  735. name = cmSystemTools::LowerCase(name);
  736. if (name == "cmakecache.txt" || name == "cmakelists.txt") {
  737. argIsFile = true;
  738. listPath = cmSystemTools::GetFilenamePath(fullPath);
  739. } else {
  740. listPath = fullPath;
  741. }
  742. }
  743. // If there is a CMakeCache.txt file, use its settings.
  744. if (!cachePath.empty()) {
  745. if (this->LoadCache(cachePath)) {
  746. const char* existingValue =
  747. this->State->GetCacheEntryValue("CMAKE_HOME_DIRECTORY");
  748. if (existingValue) {
  749. this->SetHomeOutputDirectory(cachePath);
  750. this->SetHomeDirectory(existingValue);
  751. return;
  752. }
  753. }
  754. }
  755. // If there is a CMakeLists.txt file, use it as the source tree.
  756. if (!listPath.empty()) {
  757. this->SetHomeDirectory(listPath);
  758. if (argIsFile) {
  759. // Source CMakeLists.txt file given. It was probably dropped
  760. // onto the executable in a GUI. Default to an in-source build.
  761. this->SetHomeOutputDirectory(listPath);
  762. } else {
  763. // Source directory given on command line. Use current working
  764. // directory as build tree.
  765. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  766. this->SetHomeOutputDirectory(cwd);
  767. }
  768. return;
  769. }
  770. // We didn't find a CMakeLists.txt or CMakeCache.txt file from the
  771. // argument. Assume it is the path to the source tree, and use the
  772. // current working directory as the build tree.
  773. std::string full = cmSystemTools::CollapseFullPath(arg);
  774. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  775. this->SetHomeDirectory(full);
  776. this->SetHomeOutputDirectory(cwd);
  777. }
  778. // at the end of this CMAKE_ROOT and CMAKE_COMMAND should be added to the
  779. // cache
  780. int cmake::AddCMakePaths()
  781. {
  782. // Save the value in the cache
  783. this->AddCacheEntry("CMAKE_COMMAND",
  784. cmSystemTools::GetCMakeCommand().c_str(),
  785. "Path to CMake executable.", cmStateEnums::INTERNAL);
  786. #ifdef CMAKE_BUILD_WITH_CMAKE
  787. this->AddCacheEntry(
  788. "CMAKE_CTEST_COMMAND", cmSystemTools::GetCTestCommand().c_str(),
  789. "Path to ctest program executable.", cmStateEnums::INTERNAL);
  790. this->AddCacheEntry(
  791. "CMAKE_CPACK_COMMAND", cmSystemTools::GetCPackCommand().c_str(),
  792. "Path to cpack program executable.", cmStateEnums::INTERNAL);
  793. #endif
  794. if (!cmSystemTools::FileExists(
  795. (cmSystemTools::GetCMakeRoot() + "/Modules/CMake.cmake").c_str())) {
  796. // couldn't find modules
  797. cmSystemTools::Error(
  798. "Could not find CMAKE_ROOT !!!\n"
  799. "CMake has most likely not been installed correctly.\n"
  800. "Modules directory not found in\n",
  801. cmSystemTools::GetCMakeRoot().c_str());
  802. return 0;
  803. }
  804. this->AddCacheEntry("CMAKE_ROOT", cmSystemTools::GetCMakeRoot().c_str(),
  805. "Path to CMake installation.", cmStateEnums::INTERNAL);
  806. return 1;
  807. }
  808. void cmake::AddDefaultExtraGenerators()
  809. {
  810. #if defined(CMAKE_BUILD_WITH_CMAKE)
  811. this->ExtraGenerators.push_back(cmExtraCodeBlocksGenerator::GetFactory());
  812. this->ExtraGenerators.push_back(cmExtraCodeLiteGenerator::GetFactory());
  813. this->ExtraGenerators.push_back(cmExtraSublimeTextGenerator::GetFactory());
  814. this->ExtraGenerators.push_back(cmExtraKateGenerator::GetFactory());
  815. #ifdef CMAKE_USE_ECLIPSE
  816. this->ExtraGenerators.push_back(cmExtraEclipseCDT4Generator::GetFactory());
  817. #endif
  818. #ifdef CMAKE_USE_KDEVELOP
  819. this->ExtraGenerators.push_back(cmGlobalKdevelopGenerator::GetFactory());
  820. #endif
  821. #endif
  822. }
  823. void cmake::GetRegisteredGenerators(
  824. std::vector<GeneratorInfo>& generators) const
  825. {
  826. for (RegisteredGeneratorsVector::const_iterator i = this->Generators.begin(),
  827. e = this->Generators.end();
  828. i != e; ++i) {
  829. std::vector<std::string> names;
  830. (*i)->GetGenerators(names);
  831. for (size_t j = 0; j < names.size(); ++j) {
  832. GeneratorInfo info;
  833. info.supportsToolset = (*i)->SupportsToolset();
  834. info.supportsPlatform = (*i)->SupportsPlatform();
  835. info.name = names[j];
  836. info.baseName = names[j];
  837. info.isAlias = false;
  838. generators.push_back(info);
  839. }
  840. }
  841. for (RegisteredExtraGeneratorsVector::const_iterator
  842. i = this->ExtraGenerators.begin(),
  843. e = this->ExtraGenerators.end();
  844. i != e; ++i) {
  845. const std::vector<std::string> genList =
  846. (*i)->GetSupportedGlobalGenerators();
  847. for (std::vector<std::string>::const_iterator gen = genList.begin();
  848. gen != genList.end(); ++gen) {
  849. GeneratorInfo info;
  850. info.name = cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  851. *gen, (*i)->GetName());
  852. info.baseName = *gen;
  853. info.extraName = (*i)->GetName();
  854. info.supportsPlatform = false;
  855. info.supportsToolset = false;
  856. info.isAlias = false;
  857. generators.push_back(info);
  858. }
  859. for (std::vector<std::string>::const_iterator a = (*i)->Aliases.begin();
  860. a != (*i)->Aliases.end(); ++a) {
  861. GeneratorInfo info;
  862. info.name = *a;
  863. if (!genList.empty()) {
  864. info.baseName = genList.at(0);
  865. }
  866. info.extraName = (*i)->GetName();
  867. info.supportsPlatform = false;
  868. info.supportsToolset = false;
  869. info.isAlias = true;
  870. generators.push_back(info);
  871. }
  872. }
  873. }
  874. static std::pair<cmExternalMakefileProjectGenerator*, std::string>
  875. createExtraGenerator(
  876. const std::vector<cmExternalMakefileProjectGeneratorFactory*>& in,
  877. const std::string& name)
  878. {
  879. for (std::vector<cmExternalMakefileProjectGeneratorFactory*>::const_iterator
  880. i = in.begin();
  881. i != in.end(); ++i) {
  882. const std::vector<std::string> generators =
  883. (*i)->GetSupportedGlobalGenerators();
  884. if ((*i)->GetName() == name) { // Match aliases
  885. return std::make_pair((*i)->CreateExternalMakefileProjectGenerator(),
  886. generators.at(0));
  887. }
  888. for (std::vector<std::string>::const_iterator g = generators.begin();
  889. g != generators.end(); ++g) {
  890. const std::string fullName =
  891. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  892. *g, (*i)->GetName());
  893. if (fullName == name) {
  894. return std::make_pair((*i)->CreateExternalMakefileProjectGenerator(),
  895. *g);
  896. }
  897. }
  898. }
  899. return std::make_pair(
  900. static_cast<cmExternalMakefileProjectGenerator*>(CM_NULLPTR), name);
  901. }
  902. cmGlobalGenerator* cmake::CreateGlobalGenerator(const std::string& gname)
  903. {
  904. std::pair<cmExternalMakefileProjectGenerator*, std::string> extra =
  905. createExtraGenerator(this->ExtraGenerators, gname);
  906. cmExternalMakefileProjectGenerator* extraGenerator = extra.first;
  907. const std::string name = extra.second;
  908. cmGlobalGenerator* generator = CM_NULLPTR;
  909. for (RegisteredGeneratorsVector::const_iterator i = this->Generators.begin();
  910. i != this->Generators.end(); ++i) {
  911. generator = (*i)->CreateGlobalGenerator(name, this);
  912. if (generator) {
  913. break;
  914. }
  915. }
  916. if (generator) {
  917. generator->SetExternalMakefileProjectGenerator(extraGenerator);
  918. } else {
  919. delete extraGenerator;
  920. }
  921. return generator;
  922. }
  923. void cmake::SetHomeDirectory(const std::string& dir)
  924. {
  925. this->State->SetSourceDirectory(dir);
  926. if (this->CurrentSnapshot.IsValid()) {
  927. this->CurrentSnapshot.SetDefinition("CMAKE_SOURCE_DIR", dir);
  928. }
  929. }
  930. const char* cmake::GetHomeDirectory() const
  931. {
  932. return this->State->GetSourceDirectory();
  933. }
  934. void cmake::SetHomeOutputDirectory(const std::string& dir)
  935. {
  936. this->State->SetBinaryDirectory(dir);
  937. if (this->CurrentSnapshot.IsValid()) {
  938. this->CurrentSnapshot.SetDefinition("CMAKE_BINARY_DIR", dir);
  939. }
  940. }
  941. const char* cmake::GetHomeOutputDirectory() const
  942. {
  943. return this->State->GetBinaryDirectory();
  944. }
  945. std::string cmake::FindCacheFile(const std::string& binaryDir)
  946. {
  947. std::string cachePath = binaryDir;
  948. cmSystemTools::ConvertToUnixSlashes(cachePath);
  949. std::string cacheFile = cachePath;
  950. cacheFile += "/CMakeCache.txt";
  951. if (!cmSystemTools::FileExists(cacheFile.c_str())) {
  952. // search in parent directories for cache
  953. std::string cmakeFiles = cachePath;
  954. cmakeFiles += "/CMakeFiles";
  955. if (cmSystemTools::FileExists(cmakeFiles.c_str())) {
  956. std::string cachePathFound =
  957. cmSystemTools::FileExistsInParentDirectories("CMakeCache.txt",
  958. cachePath.c_str(), "/");
  959. if (!cachePathFound.empty()) {
  960. cachePath = cmSystemTools::GetFilenamePath(cachePathFound);
  961. }
  962. }
  963. }
  964. return cachePath;
  965. }
  966. void cmake::SetGlobalGenerator(cmGlobalGenerator* gg)
  967. {
  968. if (!gg) {
  969. cmSystemTools::Error("Error SetGlobalGenerator called with null");
  970. return;
  971. }
  972. // delete the old generator
  973. if (this->GlobalGenerator) {
  974. delete this->GlobalGenerator;
  975. // restore the original environment variables CXX and CC
  976. // Restore CC
  977. std::string env = "CC=";
  978. if (!this->CCEnvironment.empty()) {
  979. env += this->CCEnvironment;
  980. }
  981. cmSystemTools::PutEnv(env);
  982. env = "CXX=";
  983. if (!this->CXXEnvironment.empty()) {
  984. env += this->CXXEnvironment;
  985. }
  986. cmSystemTools::PutEnv(env);
  987. }
  988. // set the new
  989. this->GlobalGenerator = gg;
  990. // set the global flag for unix style paths on cmSystemTools as soon as
  991. // the generator is set. This allows gmake to be used on windows.
  992. cmSystemTools::SetForceUnixPaths(this->GlobalGenerator->GetForceUnixPaths());
  993. // Save the environment variables CXX and CC
  994. if (!cmSystemTools::GetEnv("CXX", this->CXXEnvironment)) {
  995. this->CXXEnvironment = "";
  996. }
  997. if (!cmSystemTools::GetEnv("CC", this->CCEnvironment)) {
  998. this->CCEnvironment = "";
  999. }
  1000. }
  1001. int cmake::DoPreConfigureChecks()
  1002. {
  1003. // Make sure the Source directory contains a CMakeLists.txt file.
  1004. std::string srcList = this->GetHomeDirectory();
  1005. srcList += "/CMakeLists.txt";
  1006. if (!cmSystemTools::FileExists(srcList.c_str())) {
  1007. std::ostringstream err;
  1008. if (cmSystemTools::FileIsDirectory(this->GetHomeDirectory())) {
  1009. err << "The source directory \"" << this->GetHomeDirectory()
  1010. << "\" does not appear to contain CMakeLists.txt.\n";
  1011. } else if (cmSystemTools::FileExists(this->GetHomeDirectory())) {
  1012. err << "The source directory \"" << this->GetHomeDirectory()
  1013. << "\" is a file, not a directory.\n";
  1014. } else {
  1015. err << "The source directory \"" << this->GetHomeDirectory()
  1016. << "\" does not exist.\n";
  1017. }
  1018. err << "Specify --help for usage, or press the help button on the CMake "
  1019. "GUI.";
  1020. cmSystemTools::Error(err.str().c_str());
  1021. return -2;
  1022. }
  1023. // do a sanity check on some values
  1024. if (this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY")) {
  1025. std::string cacheStart =
  1026. this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY");
  1027. cacheStart += "/CMakeLists.txt";
  1028. std::string currentStart = this->GetHomeDirectory();
  1029. currentStart += "/CMakeLists.txt";
  1030. if (!cmSystemTools::SameFile(cacheStart, currentStart)) {
  1031. std::string message = "The source \"";
  1032. message += currentStart;
  1033. message += "\" does not match the source \"";
  1034. message += cacheStart;
  1035. message += "\" used to generate cache. ";
  1036. message += "Re-run cmake with a different source directory.";
  1037. cmSystemTools::Error(message.c_str());
  1038. return -2;
  1039. }
  1040. } else {
  1041. return 0;
  1042. }
  1043. return 1;
  1044. }
  1045. struct SaveCacheEntry
  1046. {
  1047. std::string key;
  1048. std::string value;
  1049. std::string help;
  1050. cmStateEnums::CacheEntryType type;
  1051. };
  1052. int cmake::HandleDeleteCacheVariables(const std::string& var)
  1053. {
  1054. std::vector<std::string> argsSplit;
  1055. cmSystemTools::ExpandListArgument(std::string(var), argsSplit, true);
  1056. // erase the property to avoid infinite recursion
  1057. this->State->SetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_", "");
  1058. if (this->State->GetIsInTryCompile()) {
  1059. return 0;
  1060. }
  1061. std::vector<SaveCacheEntry> saved;
  1062. std::ostringstream warning;
  1063. /* clang-format off */
  1064. warning
  1065. << "You have changed variables that require your cache to be deleted.\n"
  1066. << "Configure will be re-run and you may have to reset some variables.\n"
  1067. << "The following variables have changed:\n";
  1068. /* clang-format on */
  1069. for (std::vector<std::string>::iterator i = argsSplit.begin();
  1070. i != argsSplit.end(); ++i) {
  1071. SaveCacheEntry save;
  1072. save.key = *i;
  1073. warning << *i << "= ";
  1074. i++;
  1075. save.value = *i;
  1076. warning << *i << "\n";
  1077. const char* existingValue = this->State->GetCacheEntryValue(save.key);
  1078. if (existingValue) {
  1079. save.type = this->State->GetCacheEntryType(save.key);
  1080. if (const char* help =
  1081. this->State->GetCacheEntryProperty(save.key, "HELPSTRING")) {
  1082. save.help = help;
  1083. }
  1084. }
  1085. saved.push_back(save);
  1086. }
  1087. // remove the cache
  1088. this->DeleteCache(this->GetHomeOutputDirectory());
  1089. // load the empty cache
  1090. this->LoadCache();
  1091. // restore the changed compilers
  1092. for (std::vector<SaveCacheEntry>::iterator i = saved.begin();
  1093. i != saved.end(); ++i) {
  1094. this->AddCacheEntry(i->key, i->value.c_str(), i->help.c_str(), i->type);
  1095. }
  1096. cmSystemTools::Message(warning.str().c_str());
  1097. // avoid reconfigure if there were errors
  1098. if (!cmSystemTools::GetErrorOccuredFlag()) {
  1099. // re-run configure
  1100. return this->Configure();
  1101. }
  1102. return 0;
  1103. }
  1104. int cmake::Configure()
  1105. {
  1106. DiagLevel diagLevel;
  1107. if (this->DiagLevels.count("deprecated") == 1) {
  1108. diagLevel = this->DiagLevels["deprecated"];
  1109. if (diagLevel == DIAG_IGNORE) {
  1110. this->SetSuppressDeprecatedWarnings(true);
  1111. this->SetDeprecatedWarningsAsErrors(false);
  1112. } else if (diagLevel == DIAG_WARN) {
  1113. this->SetSuppressDeprecatedWarnings(false);
  1114. this->SetDeprecatedWarningsAsErrors(false);
  1115. } else if (diagLevel == DIAG_ERROR) {
  1116. this->SetSuppressDeprecatedWarnings(false);
  1117. this->SetDeprecatedWarningsAsErrors(true);
  1118. }
  1119. }
  1120. if (this->DiagLevels.count("dev") == 1) {
  1121. bool setDeprecatedVariables = false;
  1122. const char* cachedWarnDeprecated =
  1123. this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1124. const char* cachedErrorDeprecated =
  1125. this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1126. // don't overwrite deprecated warning setting from a previous invocation
  1127. if (!cachedWarnDeprecated && !cachedErrorDeprecated) {
  1128. setDeprecatedVariables = true;
  1129. }
  1130. diagLevel = this->DiagLevels["dev"];
  1131. if (diagLevel == DIAG_IGNORE) {
  1132. this->SetSuppressDevWarnings(true);
  1133. this->SetDevWarningsAsErrors(false);
  1134. if (setDeprecatedVariables) {
  1135. this->SetSuppressDeprecatedWarnings(true);
  1136. this->SetDeprecatedWarningsAsErrors(false);
  1137. }
  1138. } else if (diagLevel == DIAG_WARN) {
  1139. this->SetSuppressDevWarnings(false);
  1140. this->SetDevWarningsAsErrors(false);
  1141. if (setDeprecatedVariables) {
  1142. this->SetSuppressDeprecatedWarnings(false);
  1143. this->SetDeprecatedWarningsAsErrors(false);
  1144. }
  1145. } else if (diagLevel == DIAG_ERROR) {
  1146. this->SetSuppressDevWarnings(false);
  1147. this->SetDevWarningsAsErrors(true);
  1148. if (setDeprecatedVariables) {
  1149. this->SetSuppressDeprecatedWarnings(false);
  1150. this->SetDeprecatedWarningsAsErrors(true);
  1151. }
  1152. }
  1153. }
  1154. int ret = this->ActualConfigure();
  1155. const char* delCacheVars =
  1156. this->State->GetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_");
  1157. if (delCacheVars && delCacheVars[0] != 0) {
  1158. return this->HandleDeleteCacheVariables(delCacheVars);
  1159. }
  1160. return ret;
  1161. }
  1162. int cmake::ActualConfigure()
  1163. {
  1164. // Construct right now our path conversion table before it's too late:
  1165. this->UpdateConversionPathTable();
  1166. this->CleanupCommandsAndMacros();
  1167. int res = 0;
  1168. if (this->GetWorkingMode() == NORMAL_MODE) {
  1169. res = this->DoPreConfigureChecks();
  1170. }
  1171. if (res < 0) {
  1172. return -2;
  1173. }
  1174. if (!res) {
  1175. this->AddCacheEntry(
  1176. "CMAKE_HOME_DIRECTORY", this->GetHomeDirectory(),
  1177. "Source directory with the top level CMakeLists.txt file for this "
  1178. "project",
  1179. cmStateEnums::INTERNAL);
  1180. }
  1181. // no generator specified on the command line
  1182. if (!this->GlobalGenerator) {
  1183. const char* genName =
  1184. this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1185. const char* extraGenName =
  1186. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  1187. if (genName) {
  1188. std::string fullName =
  1189. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1190. genName, extraGenName ? extraGenName : "");
  1191. this->GlobalGenerator = this->CreateGlobalGenerator(fullName);
  1192. }
  1193. if (this->GlobalGenerator) {
  1194. // set the global flag for unix style paths on cmSystemTools as
  1195. // soon as the generator is set. This allows gmake to be used
  1196. // on windows.
  1197. cmSystemTools::SetForceUnixPaths(
  1198. this->GlobalGenerator->GetForceUnixPaths());
  1199. } else {
  1200. this->CreateDefaultGlobalGenerator();
  1201. }
  1202. if (!this->GlobalGenerator) {
  1203. cmSystemTools::Error("Could not create generator");
  1204. return -1;
  1205. }
  1206. }
  1207. const char* genName =
  1208. this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1209. if (genName) {
  1210. if (!this->GlobalGenerator->MatchesGeneratorName(genName)) {
  1211. std::string message = "Error: generator : ";
  1212. message += this->GlobalGenerator->GetName();
  1213. message += "\nDoes not match the generator used previously: ";
  1214. message += genName;
  1215. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1216. "directory or choose a different binary directory.";
  1217. cmSystemTools::Error(message.c_str());
  1218. return -2;
  1219. }
  1220. }
  1221. if (!this->State->GetInitializedCacheValue("CMAKE_GENERATOR")) {
  1222. this->AddCacheEntry("CMAKE_GENERATOR",
  1223. this->GlobalGenerator->GetName().c_str(),
  1224. "Name of generator.", cmStateEnums::INTERNAL);
  1225. this->AddCacheEntry("CMAKE_EXTRA_GENERATOR",
  1226. this->GlobalGenerator->GetExtraGeneratorName().c_str(),
  1227. "Name of external makefile project generator.",
  1228. cmStateEnums::INTERNAL);
  1229. }
  1230. if (const char* platformName =
  1231. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_PLATFORM")) {
  1232. if (this->GeneratorPlatform.empty()) {
  1233. this->GeneratorPlatform = platformName;
  1234. } else if (this->GeneratorPlatform != platformName) {
  1235. std::string message = "Error: generator platform: ";
  1236. message += this->GeneratorPlatform;
  1237. message += "\nDoes not match the platform used previously: ";
  1238. message += platformName;
  1239. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1240. "directory or choose a different binary directory.";
  1241. cmSystemTools::Error(message.c_str());
  1242. return -2;
  1243. }
  1244. } else {
  1245. this->AddCacheEntry("CMAKE_GENERATOR_PLATFORM",
  1246. this->GeneratorPlatform.c_str(),
  1247. "Name of generator platform.", cmStateEnums::INTERNAL);
  1248. }
  1249. if (const char* tsName =
  1250. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_TOOLSET")) {
  1251. if (this->GeneratorToolset.empty()) {
  1252. this->GeneratorToolset = tsName;
  1253. } else if (this->GeneratorToolset != tsName) {
  1254. std::string message = "Error: generator toolset: ";
  1255. message += this->GeneratorToolset;
  1256. message += "\nDoes not match the toolset used previously: ";
  1257. message += tsName;
  1258. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1259. "directory or choose a different binary directory.";
  1260. cmSystemTools::Error(message.c_str());
  1261. return -2;
  1262. }
  1263. } else {
  1264. this->AddCacheEntry("CMAKE_GENERATOR_TOOLSET",
  1265. this->GeneratorToolset.c_str(),
  1266. "Name of generator toolset.", cmStateEnums::INTERNAL);
  1267. }
  1268. // reset any system configuration information, except for when we are
  1269. // InTryCompile. With TryCompile the system info is taken from the parent's
  1270. // info to save time
  1271. if (!this->State->GetIsInTryCompile()) {
  1272. this->GlobalGenerator->ClearEnabledLanguages();
  1273. this->TruncateOutputLog("CMakeOutput.log");
  1274. this->TruncateOutputLog("CMakeError.log");
  1275. }
  1276. // actually do the configure
  1277. this->GlobalGenerator->Configure();
  1278. // Before saving the cache
  1279. // if the project did not define one of the entries below, add them now
  1280. // so users can edit the values in the cache:
  1281. // We used to always present LIBRARY_OUTPUT_PATH and
  1282. // EXECUTABLE_OUTPUT_PATH. They are now documented as old-style and
  1283. // should no longer be used. Therefore we present them only if the
  1284. // project requires compatibility with CMake 2.4. We detect this
  1285. // here by looking for the old CMAKE_BACKWARDS_COMPATIBILITY
  1286. // variable created when CMP0001 is not set to NEW.
  1287. if (this->State->GetInitializedCacheValue("CMAKE_BACKWARDS_COMPATIBILITY")) {
  1288. if (!this->State->GetInitializedCacheValue("LIBRARY_OUTPUT_PATH")) {
  1289. this->AddCacheEntry(
  1290. "LIBRARY_OUTPUT_PATH", "",
  1291. "Single output directory for building all libraries.",
  1292. cmStateEnums::PATH);
  1293. }
  1294. if (!this->State->GetInitializedCacheValue("EXECUTABLE_OUTPUT_PATH")) {
  1295. this->AddCacheEntry(
  1296. "EXECUTABLE_OUTPUT_PATH", "",
  1297. "Single output directory for building all executables.",
  1298. cmStateEnums::PATH);
  1299. }
  1300. }
  1301. cmMakefile* mf = this->GlobalGenerator->GetMakefiles()[0];
  1302. if (mf->IsOn("CTEST_USE_LAUNCHERS") &&
  1303. !this->State->GetGlobalProperty("RULE_LAUNCH_COMPILE")) {
  1304. cmSystemTools::Error(
  1305. "CTEST_USE_LAUNCHERS is enabled, but the "
  1306. "RULE_LAUNCH_COMPILE global property is not defined.\n"
  1307. "Did you forget to include(CTest) in the toplevel "
  1308. "CMakeLists.txt ?");
  1309. }
  1310. // only save the cache if there were no fatal errors
  1311. if (this->GetWorkingMode() == NORMAL_MODE) {
  1312. this->SaveCache(this->GetHomeOutputDirectory());
  1313. }
  1314. if (cmSystemTools::GetErrorOccuredFlag()) {
  1315. return -1;
  1316. }
  1317. return 0;
  1318. }
  1319. void cmake::CreateDefaultGlobalGenerator()
  1320. {
  1321. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  1322. std::string found;
  1323. // Try to find the newest VS installed on the computer and
  1324. // use that as a default if -G is not specified
  1325. const std::string vsregBase = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\";
  1326. static const char* const vsVariants[] = {
  1327. /* clang-format needs this comment to break after the opening brace */
  1328. "VisualStudio\\", "VCExpress\\", "WDExpress\\"
  1329. };
  1330. struct VSVersionedGenerator
  1331. {
  1332. const char* MSVersion;
  1333. const char* GeneratorName;
  1334. };
  1335. static VSVersionedGenerator const vsGenerators[] = {
  1336. { "15.0", "Visual Studio 15 2017" }, //
  1337. { "14.0", "Visual Studio 14 2015" }, //
  1338. { "12.0", "Visual Studio 12 2013" }, //
  1339. { "11.0", "Visual Studio 11 2012" }, //
  1340. { "10.0", "Visual Studio 10 2010" }, //
  1341. { "9.0", "Visual Studio 9 2008" }, //
  1342. { "8.0", "Visual Studio 8 2005" }
  1343. };
  1344. static const char* const vsEntries[] = {
  1345. "\\Setup\\VC;ProductDir", //
  1346. ";InstallDir" //
  1347. };
  1348. cmVSSetupAPIHelper vsSetupAPIHelper;
  1349. if (vsSetupAPIHelper.IsVS2017Installed()) {
  1350. found = "Visual Studio 15 2017";
  1351. } else {
  1352. for (VSVersionedGenerator const* g = cmArrayBegin(vsGenerators);
  1353. found.empty() && g != cmArrayEnd(vsGenerators); ++g) {
  1354. for (const char* const* v = cmArrayBegin(vsVariants);
  1355. found.empty() && v != cmArrayEnd(vsVariants); ++v) {
  1356. for (const char* const* e = cmArrayBegin(vsEntries);
  1357. found.empty() && e != cmArrayEnd(vsEntries); ++e) {
  1358. std::string const reg = vsregBase + *v + g->MSVersion + *e;
  1359. std::string dir;
  1360. if (cmSystemTools::ReadRegistryValue(reg, dir,
  1361. cmSystemTools::KeyWOW64_32) &&
  1362. cmSystemTools::PathExists(dir)) {
  1363. found = g->GeneratorName;
  1364. }
  1365. }
  1366. }
  1367. }
  1368. }
  1369. cmGlobalGenerator* gen = this->CreateGlobalGenerator(found);
  1370. if (!gen) {
  1371. gen = new cmGlobalNMakeMakefileGenerator(this);
  1372. }
  1373. this->SetGlobalGenerator(gen);
  1374. std::cout << "-- Building for: " << gen->GetName() << "\n";
  1375. #else
  1376. this->SetGlobalGenerator(new cmGlobalUnixMakefileGenerator3(this));
  1377. #endif
  1378. }
  1379. void cmake::PreLoadCMakeFiles()
  1380. {
  1381. std::vector<std::string> args;
  1382. std::string pre_load = this->GetHomeDirectory();
  1383. if (!pre_load.empty()) {
  1384. pre_load += "/PreLoad.cmake";
  1385. if (cmSystemTools::FileExists(pre_load.c_str())) {
  1386. this->ReadListFile(args, pre_load.c_str());
  1387. }
  1388. }
  1389. pre_load = this->GetHomeOutputDirectory();
  1390. if (!pre_load.empty()) {
  1391. pre_load += "/PreLoad.cmake";
  1392. if (cmSystemTools::FileExists(pre_load.c_str())) {
  1393. this->ReadListFile(args, pre_load.c_str());
  1394. }
  1395. }
  1396. }
  1397. // handle a command line invocation
  1398. int cmake::Run(const std::vector<std::string>& args, bool noconfigure)
  1399. {
  1400. // Process the arguments
  1401. this->SetArgs(args);
  1402. if (cmSystemTools::GetErrorOccuredFlag()) {
  1403. return -1;
  1404. }
  1405. // If we are given a stamp list file check if it is really out of date.
  1406. if (!this->CheckStampList.empty() &&
  1407. cmakeCheckStampList(this->CheckStampList.c_str())) {
  1408. return 0;
  1409. }
  1410. // If we are given a stamp file check if it is really out of date.
  1411. if (!this->CheckStampFile.empty() &&
  1412. cmakeCheckStampFile(this->CheckStampFile.c_str())) {
  1413. return 0;
  1414. }
  1415. if (this->GetWorkingMode() == NORMAL_MODE) {
  1416. // load the cache
  1417. if (this->LoadCache() < 0) {
  1418. cmSystemTools::Error("Error executing cmake::LoadCache(). Aborting.\n");
  1419. return -1;
  1420. }
  1421. } else {
  1422. this->AddCMakePaths();
  1423. }
  1424. // Add any cache args
  1425. if (!this->SetCacheArgs(args)) {
  1426. cmSystemTools::Error("Problem processing arguments. Aborting.\n");
  1427. return -1;
  1428. }
  1429. // In script mode we terminate after running the script.
  1430. if (this->GetWorkingMode() != NORMAL_MODE) {
  1431. if (cmSystemTools::GetErrorOccuredFlag()) {
  1432. return -1;
  1433. }
  1434. return 0;
  1435. }
  1436. // If MAKEFLAGS are given in the environment, remove the environment
  1437. // variable. This will prevent try-compile from succeeding when it
  1438. // should fail (if "-i" is an option). We cannot simply test
  1439. // whether "-i" is given and remove it because some make programs
  1440. // encode the MAKEFLAGS variable in a strange way.
  1441. if (cmSystemTools::HasEnv("MAKEFLAGS")) {
  1442. cmSystemTools::PutEnv("MAKEFLAGS=");
  1443. }
  1444. this->PreLoadCMakeFiles();
  1445. if (noconfigure) {
  1446. return 0;
  1447. }
  1448. // now run the global generate
  1449. // Check the state of the build system to see if we need to regenerate.
  1450. if (!this->CheckBuildSystem()) {
  1451. return 0;
  1452. }
  1453. int ret = this->Configure();
  1454. if (ret || this->GetWorkingMode() != NORMAL_MODE) {
  1455. #if defined(CMAKE_HAVE_VS_GENERATORS)
  1456. if (!this->VSSolutionFile.empty() && this->GlobalGenerator) {
  1457. // CMake is running to regenerate a Visual Studio build tree
  1458. // during a build from the VS IDE. The build files cannot be
  1459. // regenerated, so we should stop the build.
  1460. cmSystemTools::Message("CMake Configure step failed. "
  1461. "Build files cannot be regenerated correctly. "
  1462. "Attempting to stop IDE build.");
  1463. cmGlobalVisualStudioGenerator* gg =
  1464. static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator);
  1465. gg->CallVisualStudioMacro(cmGlobalVisualStudioGenerator::MacroStop,
  1466. this->VSSolutionFile.c_str());
  1467. }
  1468. #endif
  1469. return ret;
  1470. }
  1471. ret = this->Generate();
  1472. std::string message = "Build files have been written to: ";
  1473. message += this->GetHomeOutputDirectory();
  1474. this->UpdateProgress(message.c_str(), -1);
  1475. return ret;
  1476. }
  1477. int cmake::Generate()
  1478. {
  1479. if (!this->GlobalGenerator) {
  1480. return -1;
  1481. }
  1482. if (!this->GlobalGenerator->Compute()) {
  1483. return -1;
  1484. }
  1485. this->GlobalGenerator->Generate();
  1486. if (!this->GraphVizFile.empty()) {
  1487. std::cout << "Generate graphviz: " << this->GraphVizFile << std::endl;
  1488. this->GenerateGraphViz(this->GraphVizFile.c_str());
  1489. }
  1490. if (this->WarnUnusedCli) {
  1491. this->RunCheckForUnusedVariables();
  1492. }
  1493. if (cmSystemTools::GetErrorOccuredFlag()) {
  1494. return -1;
  1495. }
  1496. // Save the cache again after a successful Generate so that any internal
  1497. // variables created during Generate are saved. (Specifically target GUIDs
  1498. // for the Visual Studio and Xcode generators.)
  1499. if (this->GetWorkingMode() == NORMAL_MODE) {
  1500. this->SaveCache(this->GetHomeOutputDirectory());
  1501. }
  1502. return 0;
  1503. }
  1504. void cmake::AddCacheEntry(const std::string& key, const char* value,
  1505. const char* helpString, int type)
  1506. {
  1507. this->State->AddCacheEntry(key, value, helpString,
  1508. cmStateEnums::CacheEntryType(type));
  1509. this->UnwatchUnusedCli(key);
  1510. }
  1511. const char* cmake::GetCacheDefinition(const std::string& name) const
  1512. {
  1513. return this->State->GetInitializedCacheValue(name);
  1514. }
  1515. void cmake::AddScriptingCommands()
  1516. {
  1517. GetScriptingCommands(this->State);
  1518. }
  1519. void cmake::AddProjectCommands()
  1520. {
  1521. GetProjectCommands(this->State);
  1522. }
  1523. void cmake::AddDefaultGenerators()
  1524. {
  1525. #if defined(_WIN32) && !defined(__CYGWIN__)
  1526. #if !defined(CMAKE_BOOT_MINGW)
  1527. this->Generators.push_back(cmGlobalVisualStudio15Generator::NewFactory());
  1528. this->Generators.push_back(cmGlobalVisualStudio14Generator::NewFactory());
  1529. this->Generators.push_back(cmGlobalVisualStudio12Generator::NewFactory());
  1530. this->Generators.push_back(cmGlobalVisualStudio11Generator::NewFactory());
  1531. this->Generators.push_back(cmGlobalVisualStudio10Generator::NewFactory());
  1532. this->Generators.push_back(cmGlobalVisualStudio9Generator::NewFactory());
  1533. this->Generators.push_back(cmGlobalVisualStudio8Generator::NewFactory());
  1534. this->Generators.push_back(cmGlobalBorlandMakefileGenerator::NewFactory());
  1535. this->Generators.push_back(cmGlobalNMakeMakefileGenerator::NewFactory());
  1536. this->Generators.push_back(cmGlobalJOMMakefileGenerator::NewFactory());
  1537. this->Generators.push_back(cmGlobalGhsMultiGenerator::NewFactory());
  1538. #endif
  1539. this->Generators.push_back(cmGlobalMSYSMakefileGenerator::NewFactory());
  1540. this->Generators.push_back(cmGlobalMinGWMakefileGenerator::NewFactory());
  1541. #endif
  1542. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  1543. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1544. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  1545. #endif
  1546. #if defined(CMAKE_USE_WMAKE)
  1547. this->Generators.push_back(cmGlobalWatcomWMakeGenerator::NewFactory());
  1548. #endif
  1549. #ifdef CMAKE_USE_XCODE
  1550. this->Generators.push_back(cmGlobalXCodeGenerator::NewFactory());
  1551. #endif
  1552. }
  1553. bool cmake::ParseCacheEntry(const std::string& entry, std::string& var,
  1554. std::string& value,
  1555. cmStateEnums::CacheEntryType& type)
  1556. {
  1557. return cmState::ParseCacheEntry(entry, var, value, type);
  1558. }
  1559. int cmake::LoadCache()
  1560. {
  1561. // could we not read the cache
  1562. if (!this->LoadCache(this->GetHomeOutputDirectory())) {
  1563. // if it does exist, but isn't readable then warn the user
  1564. std::string cacheFile = this->GetHomeOutputDirectory();
  1565. cacheFile += "/CMakeCache.txt";
  1566. if (cmSystemTools::FileExists(cacheFile.c_str())) {
  1567. cmSystemTools::Error(
  1568. "There is a CMakeCache.txt file for the current binary tree but "
  1569. "cmake does not have permission to read it. Please check the "
  1570. "permissions of the directory you are trying to run CMake on.");
  1571. return -1;
  1572. }
  1573. }
  1574. // setup CMAKE_ROOT and CMAKE_COMMAND
  1575. if (!this->AddCMakePaths()) {
  1576. return -3;
  1577. }
  1578. return 0;
  1579. }
  1580. bool cmake::LoadCache(const std::string& path)
  1581. {
  1582. std::set<std::string> emptySet;
  1583. return this->LoadCache(path, true, emptySet, emptySet);
  1584. }
  1585. bool cmake::LoadCache(const std::string& path, bool internal,
  1586. std::set<std::string>& excludes,
  1587. std::set<std::string>& includes)
  1588. {
  1589. bool result = this->State->LoadCache(path, internal, excludes, includes);
  1590. static const char* entries[] = { "CMAKE_CACHE_MAJOR_VERSION",
  1591. "CMAKE_CACHE_MINOR_VERSION" };
  1592. for (const char* const* nameIt = cmArrayBegin(entries);
  1593. nameIt != cmArrayEnd(entries); ++nameIt) {
  1594. this->UnwatchUnusedCli(*nameIt);
  1595. }
  1596. return result;
  1597. }
  1598. bool cmake::SaveCache(const std::string& path)
  1599. {
  1600. bool result = this->State->SaveCache(path);
  1601. static const char* entries[] = { "CMAKE_CACHE_MAJOR_VERSION",
  1602. "CMAKE_CACHE_MINOR_VERSION",
  1603. "CMAKE_CACHE_PATCH_VERSION",
  1604. "CMAKE_CACHEFILE_DIR" };
  1605. for (const char* const* nameIt = cmArrayBegin(entries);
  1606. nameIt != cmArrayEnd(entries); ++nameIt) {
  1607. this->UnwatchUnusedCli(*nameIt);
  1608. }
  1609. return result;
  1610. }
  1611. bool cmake::DeleteCache(const std::string& path)
  1612. {
  1613. return this->State->DeleteCache(path);
  1614. }
  1615. void cmake::SetProgressCallback(ProgressCallbackType f, void* cd)
  1616. {
  1617. this->ProgressCallback = f;
  1618. this->ProgressCallbackClientData = cd;
  1619. }
  1620. void cmake::UpdateProgress(const char* msg, float prog)
  1621. {
  1622. if (this->ProgressCallback && !this->State->GetIsInTryCompile()) {
  1623. (*this->ProgressCallback)(msg, prog, this->ProgressCallbackClientData);
  1624. return;
  1625. }
  1626. }
  1627. bool cmake::GetIsInTryCompile() const
  1628. {
  1629. return this->State->GetIsInTryCompile();
  1630. }
  1631. void cmake::SetIsInTryCompile(bool b)
  1632. {
  1633. this->State->SetIsInTryCompile(b);
  1634. }
  1635. void cmake::GetGeneratorDocumentation(std::vector<cmDocumentationEntry>& v)
  1636. {
  1637. for (RegisteredGeneratorsVector::const_iterator i = this->Generators.begin();
  1638. i != this->Generators.end(); ++i) {
  1639. cmDocumentationEntry e;
  1640. (*i)->GetDocumentation(e);
  1641. v.push_back(e);
  1642. }
  1643. for (RegisteredExtraGeneratorsVector::const_iterator i =
  1644. this->ExtraGenerators.begin();
  1645. i != this->ExtraGenerators.end(); ++i) {
  1646. const std::string doc = (*i)->GetDocumentation();
  1647. const std::string name = (*i)->GetName();
  1648. // Aliases:
  1649. for (std::vector<std::string>::const_iterator a = (*i)->Aliases.begin();
  1650. a != (*i)->Aliases.end(); ++a) {
  1651. cmDocumentationEntry e;
  1652. e.Name = *a;
  1653. e.Brief = doc;
  1654. v.push_back(e);
  1655. }
  1656. // Full names:
  1657. const std::vector<std::string> generators =
  1658. (*i)->GetSupportedGlobalGenerators();
  1659. for (std::vector<std::string>::const_iterator g = generators.begin();
  1660. g != generators.end(); ++g) {
  1661. cmDocumentationEntry e;
  1662. e.Name =
  1663. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(*g, name);
  1664. e.Brief = doc;
  1665. v.push_back(e);
  1666. }
  1667. }
  1668. }
  1669. void cmake::PrintGeneratorList()
  1670. {
  1671. #ifdef CMAKE_BUILD_WITH_CMAKE
  1672. cmDocumentation doc;
  1673. std::vector<cmDocumentationEntry> generators;
  1674. this->GetGeneratorDocumentation(generators);
  1675. doc.AppendSection("Generators", generators);
  1676. std::cerr << "\n";
  1677. doc.PrintDocumentation(cmDocumentation::ListGenerators, std::cerr);
  1678. #endif
  1679. }
  1680. void cmake::UpdateConversionPathTable()
  1681. {
  1682. // Update the path conversion table with any specified file:
  1683. const char* tablepath =
  1684. this->State->GetInitializedCacheValue("CMAKE_PATH_TRANSLATION_FILE");
  1685. if (tablepath) {
  1686. cmsys::ifstream table(tablepath);
  1687. if (!table) {
  1688. cmSystemTools::Error("CMAKE_PATH_TRANSLATION_FILE set to ", tablepath,
  1689. ". CMake can not open file.");
  1690. cmSystemTools::ReportLastSystemError("CMake can not open file.");
  1691. } else {
  1692. std::string a, b;
  1693. while (!table.eof()) {
  1694. // two entries per line
  1695. table >> a;
  1696. table >> b;
  1697. cmSystemTools::AddTranslationPath(a, b);
  1698. }
  1699. }
  1700. }
  1701. }
  1702. int cmake::CheckBuildSystem()
  1703. {
  1704. // We do not need to rerun CMake. Check dependency integrity.
  1705. const bool verbose = isCMakeVerbose();
  1706. // This method will check the integrity of the build system if the
  1707. // option was given on the command line. It reads the given file to
  1708. // determine whether CMake should rerun.
  1709. // If no file is provided for the check, we have to rerun.
  1710. if (this->CheckBuildSystemArgument.empty()) {
  1711. if (verbose) {
  1712. std::ostringstream msg;
  1713. msg << "Re-run cmake no build system arguments\n";
  1714. cmSystemTools::Stdout(msg.str().c_str());
  1715. }
  1716. return 1;
  1717. }
  1718. // If the file provided does not exist, we have to rerun.
  1719. if (!cmSystemTools::FileExists(this->CheckBuildSystemArgument.c_str())) {
  1720. if (verbose) {
  1721. std::ostringstream msg;
  1722. msg << "Re-run cmake missing file: " << this->CheckBuildSystemArgument
  1723. << "\n";
  1724. cmSystemTools::Stdout(msg.str().c_str());
  1725. }
  1726. return 1;
  1727. }
  1728. // Read the rerun check file and use it to decide whether to do the
  1729. // global generate.
  1730. cmake cm(RoleScript); // Actually, all we need is the `set` command.
  1731. cm.SetHomeDirectory("");
  1732. cm.SetHomeOutputDirectory("");
  1733. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1734. cmGlobalGenerator gg(&cm);
  1735. CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
  1736. if (!mf->ReadListFile(this->CheckBuildSystemArgument.c_str()) ||
  1737. cmSystemTools::GetErrorOccuredFlag()) {
  1738. if (verbose) {
  1739. std::ostringstream msg;
  1740. msg << "Re-run cmake error reading : " << this->CheckBuildSystemArgument
  1741. << "\n";
  1742. cmSystemTools::Stdout(msg.str().c_str());
  1743. }
  1744. // There was an error reading the file. Just rerun.
  1745. return 1;
  1746. }
  1747. if (this->ClearBuildSystem) {
  1748. // Get the generator used for this build system.
  1749. const char* genName = mf->GetDefinition("CMAKE_DEPENDS_GENERATOR");
  1750. if (!genName || genName[0] == '\0') {
  1751. genName = "Unix Makefiles";
  1752. }
  1753. // Create the generator and use it to clear the dependencies.
  1754. CM_AUTO_PTR<cmGlobalGenerator> ggd(this->CreateGlobalGenerator(genName));
  1755. if (ggd.get()) {
  1756. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1757. CM_AUTO_PTR<cmMakefile> mfd(
  1758. new cmMakefile(ggd.get(), cm.GetCurrentSnapshot()));
  1759. CM_AUTO_PTR<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(mfd.get()));
  1760. lgd->ClearDependencies(mfd.get(), verbose);
  1761. }
  1762. }
  1763. // If any byproduct of makefile generation is missing we must re-run.
  1764. std::vector<std::string> products;
  1765. if (const char* productStr = mf->GetDefinition("CMAKE_MAKEFILE_PRODUCTS")) {
  1766. cmSystemTools::ExpandListArgument(productStr, products);
  1767. }
  1768. for (std::vector<std::string>::const_iterator pi = products.begin();
  1769. pi != products.end(); ++pi) {
  1770. if (!(cmSystemTools::FileExists(pi->c_str()) ||
  1771. cmSystemTools::FileIsSymlink(*pi))) {
  1772. if (verbose) {
  1773. std::ostringstream msg;
  1774. msg << "Re-run cmake, missing byproduct: " << *pi << "\n";
  1775. cmSystemTools::Stdout(msg.str().c_str());
  1776. }
  1777. return 1;
  1778. }
  1779. }
  1780. // Get the set of dependencies and outputs.
  1781. std::vector<std::string> depends;
  1782. std::vector<std::string> outputs;
  1783. const char* dependsStr = mf->GetDefinition("CMAKE_MAKEFILE_DEPENDS");
  1784. const char* outputsStr = mf->GetDefinition("CMAKE_MAKEFILE_OUTPUTS");
  1785. if (dependsStr && outputsStr) {
  1786. cmSystemTools::ExpandListArgument(dependsStr, depends);
  1787. cmSystemTools::ExpandListArgument(outputsStr, outputs);
  1788. }
  1789. if (depends.empty() || outputs.empty()) {
  1790. // Not enough information was provided to do the test. Just rerun.
  1791. if (verbose) {
  1792. std::ostringstream msg;
  1793. msg << "Re-run cmake no CMAKE_MAKEFILE_DEPENDS "
  1794. "or CMAKE_MAKEFILE_OUTPUTS :\n";
  1795. cmSystemTools::Stdout(msg.str().c_str());
  1796. }
  1797. return 1;
  1798. }
  1799. // Find the newest dependency.
  1800. std::vector<std::string>::iterator dep = depends.begin();
  1801. std::string dep_newest = *dep++;
  1802. for (; dep != depends.end(); ++dep) {
  1803. int result = 0;
  1804. if (this->FileComparison->FileTimeCompare(dep_newest.c_str(), dep->c_str(),
  1805. &result)) {
  1806. if (result < 0) {
  1807. dep_newest = *dep;
  1808. }
  1809. } else {
  1810. if (verbose) {
  1811. std::ostringstream msg;
  1812. msg << "Re-run cmake: build system dependency is missing\n";
  1813. cmSystemTools::Stdout(msg.str().c_str());
  1814. }
  1815. return 1;
  1816. }
  1817. }
  1818. // Find the oldest output.
  1819. std::vector<std::string>::iterator out = outputs.begin();
  1820. std::string out_oldest = *out++;
  1821. for (; out != outputs.end(); ++out) {
  1822. int result = 0;
  1823. if (this->FileComparison->FileTimeCompare(out_oldest.c_str(), out->c_str(),
  1824. &result)) {
  1825. if (result > 0) {
  1826. out_oldest = *out;
  1827. }
  1828. } else {
  1829. if (verbose) {
  1830. std::ostringstream msg;
  1831. msg << "Re-run cmake: build system output is missing\n";
  1832. cmSystemTools::Stdout(msg.str().c_str());
  1833. }
  1834. return 1;
  1835. }
  1836. }
  1837. // If any output is older than any dependency then rerun.
  1838. {
  1839. int result = 0;
  1840. if (!this->FileComparison->FileTimeCompare(out_oldest.c_str(),
  1841. dep_newest.c_str(), &result) ||
  1842. result < 0) {
  1843. if (verbose) {
  1844. std::ostringstream msg;
  1845. msg << "Re-run cmake file: " << out_oldest
  1846. << " older than: " << dep_newest << "\n";
  1847. cmSystemTools::Stdout(msg.str().c_str());
  1848. }
  1849. return 1;
  1850. }
  1851. }
  1852. // No need to rerun.
  1853. return 0;
  1854. }
  1855. void cmake::TruncateOutputLog(const char* fname)
  1856. {
  1857. std::string fullPath = this->GetHomeOutputDirectory();
  1858. fullPath += "/";
  1859. fullPath += fname;
  1860. struct stat st;
  1861. if (::stat(fullPath.c_str(), &st)) {
  1862. return;
  1863. }
  1864. if (!this->State->GetInitializedCacheValue("CMAKE_CACHEFILE_DIR")) {
  1865. cmSystemTools::RemoveFile(fullPath);
  1866. return;
  1867. }
  1868. off_t fsize = st.st_size;
  1869. const off_t maxFileSize = 50 * 1024;
  1870. if (fsize < maxFileSize) {
  1871. // TODO: truncate file
  1872. return;
  1873. }
  1874. }
  1875. inline std::string removeQuotes(const std::string& s)
  1876. {
  1877. if (s[0] == '\"' && s[s.size() - 1] == '\"') {
  1878. return s.substr(1, s.size() - 2);
  1879. }
  1880. return s;
  1881. }
  1882. void cmake::MarkCliAsUsed(const std::string& variable)
  1883. {
  1884. this->UsedCliVariables[variable] = true;
  1885. }
  1886. void cmake::GenerateGraphViz(const char* fileName) const
  1887. {
  1888. #ifdef CMAKE_BUILD_WITH_CMAKE
  1889. CM_AUTO_PTR<cmGraphVizWriter> gvWriter(
  1890. new cmGraphVizWriter(this->GetGlobalGenerator()->GetLocalGenerators()));
  1891. std::string settingsFile = this->GetHomeOutputDirectory();
  1892. settingsFile += "/CMakeGraphVizOptions.cmake";
  1893. std::string fallbackSettingsFile = this->GetHomeDirectory();
  1894. fallbackSettingsFile += "/CMakeGraphVizOptions.cmake";
  1895. gvWriter->ReadSettings(settingsFile.c_str(), fallbackSettingsFile.c_str());
  1896. gvWriter->WritePerTargetFiles(fileName);
  1897. gvWriter->WriteTargetDependersFiles(fileName);
  1898. gvWriter->WriteGlobalFile(fileName);
  1899. #endif
  1900. }
  1901. void cmake::SetProperty(const std::string& prop, const char* value)
  1902. {
  1903. this->State->SetGlobalProperty(prop, value);
  1904. }
  1905. void cmake::AppendProperty(const std::string& prop, const char* value,
  1906. bool asString)
  1907. {
  1908. this->State->AppendGlobalProperty(prop, value, asString);
  1909. }
  1910. const char* cmake::GetProperty(const std::string& prop)
  1911. {
  1912. return this->State->GetGlobalProperty(prop);
  1913. }
  1914. bool cmake::GetPropertyAsBool(const std::string& prop)
  1915. {
  1916. return this->State->GetGlobalPropertyAsBool(prop);
  1917. }
  1918. cmInstalledFile* cmake::GetOrCreateInstalledFile(cmMakefile* mf,
  1919. const std::string& name)
  1920. {
  1921. std::map<std::string, cmInstalledFile>::iterator i =
  1922. this->InstalledFiles.find(name);
  1923. if (i != this->InstalledFiles.end()) {
  1924. cmInstalledFile& file = i->second;
  1925. return &file;
  1926. }
  1927. cmInstalledFile& file = this->InstalledFiles[name];
  1928. file.SetName(mf, name);
  1929. return &file;
  1930. }
  1931. cmInstalledFile const* cmake::GetInstalledFile(const std::string& name) const
  1932. {
  1933. std::map<std::string, cmInstalledFile>::const_iterator i =
  1934. this->InstalledFiles.find(name);
  1935. if (i != this->InstalledFiles.end()) {
  1936. cmInstalledFile const& file = i->second;
  1937. return &file;
  1938. }
  1939. return CM_NULLPTR;
  1940. }
  1941. int cmake::GetSystemInformation(std::vector<std::string>& args)
  1942. {
  1943. // so create the directory
  1944. std::string resultFile;
  1945. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1946. std::string destPath = cwd + "/__cmake_systeminformation";
  1947. cmSystemTools::RemoveADirectory(destPath);
  1948. if (!cmSystemTools::MakeDirectory(destPath.c_str())) {
  1949. std::cerr << "Error: --system-information must be run from a "
  1950. "writable directory!\n";
  1951. return 1;
  1952. }
  1953. // process the arguments
  1954. bool writeToStdout = true;
  1955. for (unsigned int i = 1; i < args.size(); ++i) {
  1956. std::string const& arg = args[i];
  1957. if (arg.find("-G", 0) == 0) {
  1958. std::string value = arg.substr(2);
  1959. if (value.empty()) {
  1960. ++i;
  1961. if (i >= args.size()) {
  1962. cmSystemTools::Error("No generator specified for -G");
  1963. this->PrintGeneratorList();
  1964. return -1;
  1965. }
  1966. value = args[i];
  1967. }
  1968. cmGlobalGenerator* gen = this->CreateGlobalGenerator(value);
  1969. if (!gen) {
  1970. cmSystemTools::Error("Could not create named generator ",
  1971. value.c_str());
  1972. this->PrintGeneratorList();
  1973. } else {
  1974. this->SetGlobalGenerator(gen);
  1975. }
  1976. }
  1977. // no option assume it is the output file
  1978. else {
  1979. if (!cmSystemTools::FileIsFullPath(arg.c_str())) {
  1980. resultFile = cwd;
  1981. resultFile += "/";
  1982. }
  1983. resultFile += arg;
  1984. writeToStdout = false;
  1985. }
  1986. }
  1987. // we have to find the module directory, so we can copy the files
  1988. this->AddCMakePaths();
  1989. std::string modulesPath = cmSystemTools::GetCMakeRoot();
  1990. modulesPath += "/Modules";
  1991. std::string inFile = modulesPath;
  1992. inFile += "/SystemInformation.cmake";
  1993. std::string outFile = destPath;
  1994. outFile += "/CMakeLists.txt";
  1995. // Copy file
  1996. if (!cmSystemTools::cmCopyFile(inFile.c_str(), outFile.c_str())) {
  1997. std::cerr << "Error copying file \"" << inFile << "\" to \"" << outFile
  1998. << "\".\n";
  1999. return 1;
  2000. }
  2001. // do we write to a file or to stdout?
  2002. if (resultFile.empty()) {
  2003. resultFile = cwd;
  2004. resultFile += "/__cmake_systeminformation/results.txt";
  2005. }
  2006. {
  2007. // now run cmake on the CMakeLists file
  2008. cmWorkingDirectory workdir(destPath);
  2009. std::vector<std::string> args2;
  2010. args2.push_back(args[0]);
  2011. args2.push_back(destPath);
  2012. std::string resultArg = "-DRESULT_FILE=";
  2013. resultArg += resultFile;
  2014. args2.push_back(resultArg);
  2015. int res = this->Run(args2, false);
  2016. if (res != 0) {
  2017. std::cerr << "Error: --system-information failed on internal CMake!\n";
  2018. return res;
  2019. }
  2020. }
  2021. // echo results to stdout if needed
  2022. if (writeToStdout) {
  2023. FILE* fin = cmsys::SystemTools::Fopen(resultFile, "r");
  2024. if (fin) {
  2025. const int bufferSize = 4096;
  2026. char buffer[bufferSize];
  2027. size_t n;
  2028. while ((n = fread(buffer, 1, bufferSize, fin)) > 0) {
  2029. for (char* c = buffer; c < buffer + n; ++c) {
  2030. putc(*c, stdout);
  2031. }
  2032. fflush(stdout);
  2033. }
  2034. fclose(fin);
  2035. }
  2036. }
  2037. // clean up the directory
  2038. cmSystemTools::RemoveADirectory(destPath);
  2039. return 0;
  2040. }
  2041. static bool cmakeCheckStampFile(const char* stampName, bool verbose)
  2042. {
  2043. // The stamp file does not exist. Use the stamp dependencies to
  2044. // determine whether it is really out of date. This works in
  2045. // conjunction with cmLocalVisualStudio7Generator to avoid
  2046. // repeatedly re-running CMake when the user rebuilds the entire
  2047. // solution.
  2048. std::string stampDepends = stampName;
  2049. stampDepends += ".depend";
  2050. #if defined(_WIN32) || defined(__CYGWIN__)
  2051. cmsys::ifstream fin(stampDepends.c_str(), std::ios::in | std::ios::binary);
  2052. #else
  2053. cmsys::ifstream fin(stampDepends.c_str());
  2054. #endif
  2055. if (!fin) {
  2056. // The stamp dependencies file cannot be read. Just assume the
  2057. // build system is really out of date.
  2058. std::cout << "CMake is re-running because " << stampName
  2059. << " dependency file is missing.\n";
  2060. return false;
  2061. }
  2062. // Compare the stamp dependencies against the dependency file itself.
  2063. cmFileTimeComparison ftc;
  2064. std::string dep;
  2065. while (cmSystemTools::GetLineFromStream(fin, dep)) {
  2066. int result;
  2067. if (!dep.empty() && dep[0] != '#' &&
  2068. (!ftc.FileTimeCompare(stampDepends.c_str(), dep.c_str(), &result) ||
  2069. result < 0)) {
  2070. // The stamp depends file is older than this dependency. The
  2071. // build system is really out of date.
  2072. std::cout << "CMake is re-running because " << stampName
  2073. << " is out-of-date.\n";
  2074. std::cout << " the file '" << dep << "'\n";
  2075. std::cout << " is newer than '" << stampDepends << "'\n";
  2076. std::cout << " result='" << result << "'\n";
  2077. return false;
  2078. }
  2079. }
  2080. // The build system is up to date. The stamp file has been removed
  2081. // by the VS IDE due to a "rebuild" request. Restore it atomically.
  2082. std::ostringstream stampTempStream;
  2083. stampTempStream << stampName << ".tmp" << cmSystemTools::RandomSeed();
  2084. std::string stampTempString = stampTempStream.str();
  2085. const char* stampTemp = stampTempString.c_str();
  2086. {
  2087. // TODO: Teach cmGeneratedFileStream to use a random temp file (with
  2088. // multiple tries in unlikely case of conflict) and use that here.
  2089. cmsys::ofstream stamp(stampTemp);
  2090. stamp << "# CMake generation timestamp file for this directory.\n";
  2091. }
  2092. if (cmSystemTools::RenameFile(stampTemp, stampName)) {
  2093. if (verbose) {
  2094. // Notify the user why CMake is not re-running. It is safe to
  2095. // just print to stdout here because this code is only reachable
  2096. // through an undocumented flag used by the VS generator.
  2097. std::cout << "CMake does not need to re-run because " << stampName
  2098. << " is up-to-date.\n";
  2099. }
  2100. return true;
  2101. }
  2102. cmSystemTools::RemoveFile(stampTemp);
  2103. cmSystemTools::Error("Cannot restore timestamp ", stampName);
  2104. return false;
  2105. }
  2106. static bool cmakeCheckStampList(const char* stampList, bool verbose)
  2107. {
  2108. // If the stamp list does not exist CMake must rerun to generate it.
  2109. if (!cmSystemTools::FileExists(stampList)) {
  2110. std::cout << "CMake is re-running because generate.stamp.list "
  2111. << "is missing.\n";
  2112. return false;
  2113. }
  2114. cmsys::ifstream fin(stampList);
  2115. if (!fin) {
  2116. std::cout << "CMake is re-running because generate.stamp.list "
  2117. << "could not be read.\n";
  2118. return false;
  2119. }
  2120. // Check each stamp.
  2121. std::string stampName;
  2122. while (cmSystemTools::GetLineFromStream(fin, stampName)) {
  2123. if (!cmakeCheckStampFile(stampName.c_str(), verbose)) {
  2124. return false;
  2125. }
  2126. }
  2127. return true;
  2128. }
  2129. void cmake::IssueMessage(cmake::MessageType t, std::string const& text,
  2130. cmListFileBacktrace const& backtrace) const
  2131. {
  2132. this->Messenger->IssueMessage(t, text, backtrace);
  2133. }
  2134. std::vector<std::string> cmake::GetDebugConfigs()
  2135. {
  2136. std::vector<std::string> configs;
  2137. if (const char* config_list =
  2138. this->State->GetGlobalProperty("DEBUG_CONFIGURATIONS")) {
  2139. // Expand the specified list and convert to upper-case.
  2140. cmSystemTools::ExpandListArgument(config_list, configs);
  2141. std::transform(configs.begin(), configs.end(), configs.begin(),
  2142. cmSystemTools::UpperCase);
  2143. }
  2144. // If no configurations were specified, use a default list.
  2145. if (configs.empty()) {
  2146. configs.push_back("DEBUG");
  2147. }
  2148. return configs;
  2149. }
  2150. cmMessenger* cmake::GetMessenger() const
  2151. {
  2152. return this->Messenger;
  2153. }
  2154. int cmake::Build(const std::string& dir, const std::string& target,
  2155. const std::string& config,
  2156. const std::vector<std::string>& nativeOptions, bool clean)
  2157. {
  2158. this->SetHomeDirectory("");
  2159. this->SetHomeOutputDirectory("");
  2160. if (!cmSystemTools::FileIsDirectory(dir)) {
  2161. std::cerr << "Error: " << dir << " is not a directory\n";
  2162. return 1;
  2163. }
  2164. std::string cachePath = FindCacheFile(dir);
  2165. if (!this->LoadCache(cachePath)) {
  2166. std::cerr << "Error: could not load cache\n";
  2167. return 1;
  2168. }
  2169. const char* cachedGenerator =
  2170. this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  2171. if (!cachedGenerator) {
  2172. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  2173. return 1;
  2174. }
  2175. CM_AUTO_PTR<cmGlobalGenerator> gen(
  2176. this->CreateGlobalGenerator(cachedGenerator));
  2177. if (!gen.get()) {
  2178. std::cerr << "Error: could create CMAKE_GENERATOR \"" << cachedGenerator
  2179. << "\"\n";
  2180. return 1;
  2181. }
  2182. std::string output;
  2183. std::string projName;
  2184. const char* cachedProjectName =
  2185. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  2186. if (!cachedProjectName) {
  2187. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  2188. return 1;
  2189. }
  2190. projName = cachedProjectName;
  2191. bool verbose = false;
  2192. const char* cachedVerbose =
  2193. this->State->GetCacheEntryValue("CMAKE_VERBOSE_MAKEFILE");
  2194. if (cachedVerbose) {
  2195. verbose = cmSystemTools::IsOn(cachedVerbose);
  2196. }
  2197. #ifdef CMAKE_HAVE_VS_GENERATORS
  2198. // For VS generators, explicitly check if regeneration is necessary before
  2199. // actually starting the build. If not done separately from the build
  2200. // itself, there is the risk of building an out-of-date solution file due
  2201. // to limitations of the underlying build system.
  2202. std::string const stampList = cachePath + "/" +
  2203. GetCMakeFilesDirectoryPostSlash() +
  2204. cmGlobalVisualStudio8Generator::GetGenerateStampList();
  2205. // Note that the stampList file only exists for VS generators.
  2206. if (cmSystemTools::FileExists(stampList.c_str()) &&
  2207. !cmakeCheckStampList(stampList.c_str(), false)) {
  2208. // Correctly initialize the home (=source) and home output (=binary)
  2209. // directories, which is required for running the generation step.
  2210. std::string homeOrig = this->GetHomeDirectory();
  2211. std::string homeOutputOrig = this->GetHomeOutputDirectory();
  2212. this->SetDirectoriesFromFile(cachePath.c_str());
  2213. this->AddScriptingCommands();
  2214. this->AddProjectCommands();
  2215. int ret = this->Configure();
  2216. if (ret) {
  2217. cmSystemTools::Message("CMake Configure step failed. "
  2218. "Build files cannot be regenerated correctly.");
  2219. return ret;
  2220. }
  2221. ret = this->Generate();
  2222. if (ret) {
  2223. cmSystemTools::Message("CMake Generate step failed. "
  2224. "Build files cannot be regenerated correctly.");
  2225. return ret;
  2226. }
  2227. std::string message = "Build files have been written to: ";
  2228. message += this->GetHomeOutputDirectory();
  2229. this->UpdateProgress(message.c_str(), -1);
  2230. // Restore the previously set directories to their original value.
  2231. this->SetHomeDirectory(homeOrig);
  2232. this->SetHomeOutputDirectory(homeOutputOrig);
  2233. }
  2234. #endif
  2235. return gen->Build("", dir, projName, target, output, "", config, clean,
  2236. false, verbose, 0, cmSystemTools::OUTPUT_PASSTHROUGH,
  2237. nativeOptions);
  2238. }
  2239. void cmake::WatchUnusedCli(const std::string& var)
  2240. {
  2241. #ifdef CMAKE_BUILD_WITH_CMAKE
  2242. this->VariableWatch->AddWatch(var, cmWarnUnusedCliWarning, this);
  2243. if (this->UsedCliVariables.find(var) == this->UsedCliVariables.end()) {
  2244. this->UsedCliVariables[var] = false;
  2245. }
  2246. #endif
  2247. }
  2248. void cmake::UnwatchUnusedCli(const std::string& var)
  2249. {
  2250. #ifdef CMAKE_BUILD_WITH_CMAKE
  2251. this->VariableWatch->RemoveWatch(var, cmWarnUnusedCliWarning);
  2252. this->UsedCliVariables.erase(var);
  2253. #endif
  2254. }
  2255. void cmake::RunCheckForUnusedVariables()
  2256. {
  2257. #ifdef CMAKE_BUILD_WITH_CMAKE
  2258. bool haveUnused = false;
  2259. std::ostringstream msg;
  2260. msg << "Manually-specified variables were not used by the project:";
  2261. for (std::map<std::string, bool>::const_iterator it =
  2262. this->UsedCliVariables.begin();
  2263. it != this->UsedCliVariables.end(); ++it) {
  2264. if (!it->second) {
  2265. haveUnused = true;
  2266. msg << "\n " << it->first;
  2267. }
  2268. }
  2269. if (haveUnused) {
  2270. this->IssueMessage(cmake::WARNING, msg.str());
  2271. }
  2272. #endif
  2273. }
  2274. bool cmake::GetSuppressDevWarnings() const
  2275. {
  2276. return this->Messenger->GetSuppressDevWarnings();
  2277. }
  2278. void cmake::SetSuppressDevWarnings(bool b)
  2279. {
  2280. std::string value;
  2281. // equivalent to -Wno-dev
  2282. if (b) {
  2283. value = "TRUE";
  2284. }
  2285. // equivalent to -Wdev
  2286. else {
  2287. value = "FALSE";
  2288. }
  2289. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", value.c_str(),
  2290. "Suppress Warnings that are meant for"
  2291. " the author of the CMakeLists.txt files.",
  2292. cmStateEnums::INTERNAL);
  2293. }
  2294. bool cmake::GetSuppressDeprecatedWarnings() const
  2295. {
  2296. return this->Messenger->GetSuppressDeprecatedWarnings();
  2297. }
  2298. void cmake::SetSuppressDeprecatedWarnings(bool b)
  2299. {
  2300. std::string value;
  2301. // equivalent to -Wno-deprecated
  2302. if (b) {
  2303. value = "FALSE";
  2304. }
  2305. // equivalent to -Wdeprecated
  2306. else {
  2307. value = "TRUE";
  2308. }
  2309. this->AddCacheEntry("CMAKE_WARN_DEPRECATED", value.c_str(),
  2310. "Whether to issue warnings for deprecated "
  2311. "functionality.",
  2312. cmStateEnums::INTERNAL);
  2313. }
  2314. bool cmake::GetDevWarningsAsErrors() const
  2315. {
  2316. return this->Messenger->GetDevWarningsAsErrors();
  2317. }
  2318. void cmake::SetDevWarningsAsErrors(bool b)
  2319. {
  2320. std::string value;
  2321. // equivalent to -Werror=dev
  2322. if (b) {
  2323. value = "FALSE";
  2324. }
  2325. // equivalent to -Wno-error=dev
  2326. else {
  2327. value = "TRUE";
  2328. }
  2329. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_ERRORS", value.c_str(),
  2330. "Suppress errors that are meant for"
  2331. " the author of the CMakeLists.txt files.",
  2332. cmStateEnums::INTERNAL);
  2333. }
  2334. bool cmake::GetDeprecatedWarningsAsErrors() const
  2335. {
  2336. return this->Messenger->GetDeprecatedWarningsAsErrors();
  2337. }
  2338. void cmake::SetDeprecatedWarningsAsErrors(bool b)
  2339. {
  2340. std::string value;
  2341. // equivalent to -Werror=deprecated
  2342. if (b) {
  2343. value = "TRUE";
  2344. }
  2345. // equivalent to -Wno-error=deprecated
  2346. else {
  2347. value = "FALSE";
  2348. }
  2349. this->AddCacheEntry("CMAKE_ERROR_DEPRECATED", value.c_str(),
  2350. "Whether to issue deprecation errors for macros"
  2351. " and functions.",
  2352. cmStateEnums::INTERNAL);
  2353. }