cmServerProtocol.cxx 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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 "cmServerProtocol.h"
  4. #include "cmExternalMakefileProjectGenerator.h"
  5. #include "cmFileMonitor.h"
  6. #include "cmGeneratorTarget.h"
  7. #include "cmGlobalGenerator.h"
  8. #include "cmLinkLineComputer.h"
  9. #include "cmListFileCache.h"
  10. #include "cmLocalGenerator.h"
  11. #include "cmMakefile.h"
  12. #include "cmServer.h"
  13. #include "cmServerDictionary.h"
  14. #include "cmSourceFile.h"
  15. #include "cmSystemTools.h"
  16. #include "cmake.h"
  17. #include "cmServerDictionary.h"
  18. #if defined(CMAKE_BUILD_WITH_CMAKE)
  19. #include "cm_jsoncpp_reader.h"
  20. #include "cm_jsoncpp_value.h"
  21. #endif
  22. #include <algorithm>
  23. #include <string>
  24. #include <vector>
  25. // Get rid of some windows macros:
  26. #undef max
  27. namespace {
  28. std::vector<std::string> getConfigurations(const cmake* cm)
  29. {
  30. std::vector<std::string> configurations;
  31. auto makefiles = cm->GetGlobalGenerator()->GetMakefiles();
  32. if (makefiles.empty()) {
  33. return configurations;
  34. }
  35. makefiles[0]->GetConfigurations(configurations);
  36. if (configurations.empty()) {
  37. configurations.push_back("");
  38. }
  39. return configurations;
  40. }
  41. bool hasString(const Json::Value& v, const std::string& s)
  42. {
  43. return !v.isNull() &&
  44. std::find_if(v.begin(), v.end(), [s](const Json::Value& i) {
  45. return i.asString() == s;
  46. }) != v.end();
  47. }
  48. template <class T>
  49. Json::Value fromStringList(const T& in)
  50. {
  51. Json::Value result = Json::arrayValue;
  52. for (const std::string& i : in) {
  53. result.append(i);
  54. }
  55. return result;
  56. }
  57. std::vector<std::string> toStringList(const Json::Value& in)
  58. {
  59. std::vector<std::string> result;
  60. for (const auto& it : in) {
  61. result.push_back(it.asString());
  62. }
  63. return result;
  64. }
  65. void getCMakeInputs(const cmGlobalGenerator* gg, const std::string& sourceDir,
  66. const std::string& buildDir,
  67. std::vector<std::string>* internalFiles,
  68. std::vector<std::string>* explicitFiles,
  69. std::vector<std::string>* tmpFiles)
  70. {
  71. const std::string cmakeRootDir = cmSystemTools::GetCMakeRoot() + '/';
  72. std::vector<cmMakefile*> const& makefiles = gg->GetMakefiles();
  73. for (auto it = makefiles.begin(); it != makefiles.end(); ++it) {
  74. const std::vector<std::string> listFiles = (*it)->GetListFiles();
  75. for (auto jt = listFiles.begin(); jt != listFiles.end(); ++jt) {
  76. const std::string startOfFile = jt->substr(0, cmakeRootDir.size());
  77. const bool isInternal = (startOfFile == cmakeRootDir);
  78. const bool isTemporary = !isInternal && (jt->find(buildDir + '/') == 0);
  79. std::string toAdd = *jt;
  80. if (!sourceDir.empty()) {
  81. const std::string& relative =
  82. cmSystemTools::RelativePath(sourceDir.c_str(), jt->c_str());
  83. if (toAdd.size() > relative.size()) {
  84. toAdd = relative;
  85. }
  86. }
  87. if (isInternal) {
  88. if (internalFiles) {
  89. internalFiles->push_back(toAdd);
  90. }
  91. } else {
  92. if (isTemporary) {
  93. if (tmpFiles) {
  94. tmpFiles->push_back(toAdd);
  95. }
  96. } else {
  97. if (explicitFiles) {
  98. explicitFiles->push_back(toAdd);
  99. }
  100. }
  101. }
  102. }
  103. }
  104. }
  105. } // namespace
  106. cmServerRequest::cmServerRequest(cmServer* server, const std::string& t,
  107. const std::string& c, const Json::Value& d)
  108. : Type(t)
  109. , Cookie(c)
  110. , Data(d)
  111. , m_Server(server)
  112. {
  113. }
  114. void cmServerRequest::ReportProgress(int min, int current, int max,
  115. const std::string& message) const
  116. {
  117. this->m_Server->WriteProgress(*this, min, current, max, message);
  118. }
  119. void cmServerRequest::ReportMessage(const std::string& message,
  120. const std::string& title) const
  121. {
  122. m_Server->WriteMessage(*this, message, title);
  123. }
  124. cmServerResponse cmServerRequest::Reply(const Json::Value& data) const
  125. {
  126. cmServerResponse response(*this);
  127. response.SetData(data);
  128. return response;
  129. }
  130. cmServerResponse cmServerRequest::ReportError(const std::string& message) const
  131. {
  132. cmServerResponse response(*this);
  133. response.SetError(message);
  134. return response;
  135. }
  136. cmServerResponse::cmServerResponse(const cmServerRequest& request)
  137. : Type(request.Type)
  138. , Cookie(request.Cookie)
  139. {
  140. }
  141. void cmServerResponse::SetData(const Json::Value& data)
  142. {
  143. assert(this->m_Payload == PAYLOAD_UNKNOWN);
  144. if (!data[kCOOKIE_KEY].isNull() || !data[kTYPE_KEY].isNull()) {
  145. this->SetError("Response contains cookie or type field.");
  146. return;
  147. }
  148. this->m_Payload = PAYLOAD_DATA;
  149. this->m_Data = data;
  150. }
  151. void cmServerResponse::SetError(const std::string& message)
  152. {
  153. assert(this->m_Payload == PAYLOAD_UNKNOWN);
  154. this->m_Payload = PAYLOAD_ERROR;
  155. this->m_ErrorMessage = message;
  156. }
  157. bool cmServerResponse::IsComplete() const
  158. {
  159. return this->m_Payload != PAYLOAD_UNKNOWN;
  160. }
  161. bool cmServerResponse::IsError() const
  162. {
  163. assert(this->m_Payload != PAYLOAD_UNKNOWN);
  164. return this->m_Payload == PAYLOAD_ERROR;
  165. }
  166. std::string cmServerResponse::ErrorMessage() const
  167. {
  168. if (this->m_Payload == PAYLOAD_ERROR) {
  169. return this->m_ErrorMessage;
  170. }
  171. return std::string();
  172. }
  173. Json::Value cmServerResponse::Data() const
  174. {
  175. assert(this->m_Payload != PAYLOAD_UNKNOWN);
  176. return this->m_Data;
  177. }
  178. bool cmServerProtocol::Activate(cmServer* server,
  179. const cmServerRequest& request,
  180. std::string* errorMessage)
  181. {
  182. assert(server);
  183. this->m_Server = server;
  184. this->m_CMakeInstance = std::make_unique<cmake>();
  185. const bool result = this->DoActivate(request, errorMessage);
  186. if (!result) {
  187. this->m_CMakeInstance = CM_NULLPTR;
  188. }
  189. return result;
  190. }
  191. cmFileMonitor* cmServerProtocol::FileMonitor() const
  192. {
  193. return this->m_Server ? this->m_Server->FileMonitor() : nullptr;
  194. }
  195. void cmServerProtocol::SendSignal(const std::string& name,
  196. const Json::Value& data) const
  197. {
  198. if (this->m_Server) {
  199. this->m_Server->WriteSignal(name, data);
  200. }
  201. }
  202. cmake* cmServerProtocol::CMakeInstance() const
  203. {
  204. return this->m_CMakeInstance.get();
  205. }
  206. bool cmServerProtocol::DoActivate(const cmServerRequest& /*request*/,
  207. std::string* /*errorMessage*/)
  208. {
  209. return true;
  210. }
  211. std::pair<int, int> cmServerProtocol1_0::ProtocolVersion() const
  212. {
  213. return std::make_pair(1, 0);
  214. }
  215. static void setErrorMessage(std::string* errorMessage, const std::string& text)
  216. {
  217. if (errorMessage) {
  218. *errorMessage = text;
  219. }
  220. }
  221. static bool testValue(cmState* state, const std::string& key,
  222. std::string& value, const std::string& keyDescription,
  223. std::string* errorMessage)
  224. {
  225. const std::string cachedValue = std::string(state->GetCacheEntryValue(key));
  226. if (!cachedValue.empty() && !value.empty() && cachedValue != value) {
  227. setErrorMessage(errorMessage, std::string("\"") + key +
  228. "\" is set but incompatible with configured " +
  229. keyDescription + " value.");
  230. return false;
  231. }
  232. if (value.empty()) {
  233. value = cachedValue;
  234. }
  235. return true;
  236. }
  237. bool cmServerProtocol1_0::DoActivate(const cmServerRequest& request,
  238. std::string* errorMessage)
  239. {
  240. std::string sourceDirectory = request.Data[kSOURCE_DIRECTORY_KEY].asString();
  241. const std::string buildDirectory =
  242. request.Data[kBUILD_DIRECTORY_KEY].asString();
  243. std::string generator = request.Data[kGENERATOR_KEY].asString();
  244. std::string extraGenerator = request.Data[kEXTRA_GENERATOR_KEY].asString();
  245. std::string toolset = request.Data[kTOOLSET_KEY].asString();
  246. std::string platform = request.Data[kPLATFORM_KEY].asString();
  247. if (buildDirectory.empty()) {
  248. setErrorMessage(errorMessage, std::string("\"") + kBUILD_DIRECTORY_KEY +
  249. "\" is missing.");
  250. return false;
  251. }
  252. cmake* cm = CMakeInstance();
  253. if (cmSystemTools::PathExists(buildDirectory)) {
  254. if (!cmSystemTools::FileIsDirectory(buildDirectory)) {
  255. setErrorMessage(errorMessage, std::string("\"") + kBUILD_DIRECTORY_KEY +
  256. "\" exists but is not a directory.");
  257. return false;
  258. }
  259. const std::string cachePath = cm->FindCacheFile(buildDirectory);
  260. if (cm->LoadCache(cachePath)) {
  261. cmState* state = cm->GetState();
  262. // Check generator:
  263. if (!testValue(state, "CMAKE_GENERATOR", generator, "generator",
  264. errorMessage)) {
  265. return false;
  266. }
  267. // check extra generator:
  268. if (!testValue(state, "CMAKE_EXTRA_GENERATOR", extraGenerator,
  269. "extra generator", errorMessage)) {
  270. return false;
  271. }
  272. // check sourcedir:
  273. if (!testValue(state, "CMAKE_HOME_DIRECTORY", sourceDirectory,
  274. "source directory", errorMessage)) {
  275. return false;
  276. }
  277. // check toolset:
  278. if (!testValue(state, "CMAKE_GENERATOR_TOOLSET", toolset, "toolset",
  279. errorMessage)) {
  280. return false;
  281. }
  282. // check platform:
  283. if (!testValue(state, "CMAKE_GENERATOR_PLATFORM", platform, "platform",
  284. errorMessage)) {
  285. return false;
  286. }
  287. }
  288. }
  289. if (sourceDirectory.empty()) {
  290. setErrorMessage(errorMessage, std::string("\"") + kSOURCE_DIRECTORY_KEY +
  291. "\" is unset but required.");
  292. return false;
  293. }
  294. if (!cmSystemTools::FileIsDirectory(sourceDirectory)) {
  295. setErrorMessage(errorMessage, std::string("\"") + kSOURCE_DIRECTORY_KEY +
  296. "\" is not a directory.");
  297. return false;
  298. }
  299. if (generator.empty()) {
  300. setErrorMessage(errorMessage, std::string("\"") + kGENERATOR_KEY +
  301. "\" is unset but required.");
  302. return false;
  303. }
  304. std::vector<cmake::GeneratorInfo> generators;
  305. cm->GetRegisteredGenerators(generators);
  306. auto baseIt = std::find_if(generators.begin(), generators.end(),
  307. [&generator](const cmake::GeneratorInfo& info) {
  308. return info.name == generator;
  309. });
  310. if (baseIt == generators.end()) {
  311. setErrorMessage(errorMessage, std::string("Generator \"") + generator +
  312. "\" not supported.");
  313. return false;
  314. }
  315. auto extraIt = std::find_if(
  316. generators.begin(), generators.end(),
  317. [&generator, &extraGenerator](const cmake::GeneratorInfo& info) {
  318. return info.baseName == generator && info.extraName == extraGenerator;
  319. });
  320. if (extraIt == generators.end()) {
  321. setErrorMessage(errorMessage,
  322. std::string("The combination of generator \"" + generator +
  323. "\" and extra generator \"" + extraGenerator +
  324. "\" is not supported."));
  325. return false;
  326. }
  327. if (!extraIt->supportsToolset && !toolset.empty()) {
  328. setErrorMessage(errorMessage,
  329. std::string("Toolset was provided but is not supported by "
  330. "the requested generator."));
  331. return false;
  332. }
  333. if (!extraIt->supportsPlatform && !platform.empty()) {
  334. setErrorMessage(errorMessage,
  335. std::string("Platform was provided but is not supported "
  336. "by the requested generator."));
  337. return false;
  338. }
  339. this->GeneratorInfo =
  340. GeneratorInformation(generator, extraGenerator, toolset, platform,
  341. sourceDirectory, buildDirectory);
  342. this->m_State = STATE_ACTIVE;
  343. return true;
  344. }
  345. void cmServerProtocol1_0::HandleCMakeFileChanges(const std::string& path,
  346. int event, int status)
  347. {
  348. assert(status == 0);
  349. static_cast<void>(status);
  350. if (!m_isDirty) {
  351. m_isDirty = true;
  352. SendSignal(kDIRTY_SIGNAL, Json::objectValue);
  353. }
  354. Json::Value obj = Json::objectValue;
  355. obj[kPATH_KEY] = path;
  356. Json::Value properties = Json::arrayValue;
  357. if (event & UV_RENAME) {
  358. properties.append(kRENAME_PROPERTY_VALUE);
  359. }
  360. if (event & UV_CHANGE) {
  361. properties.append(kCHANGE_PROPERTY_VALUE);
  362. }
  363. obj[kPROPERTIES_KEY] = properties;
  364. SendSignal(kFILE_CHANGE_SIGNAL, obj);
  365. }
  366. const cmServerResponse cmServerProtocol1_0::Process(
  367. const cmServerRequest& request)
  368. {
  369. assert(this->m_State >= STATE_ACTIVE);
  370. if (request.Type == kCACHE_TYPE) {
  371. return this->ProcessCache(request);
  372. }
  373. if (request.Type == kCMAKE_INPUTS_TYPE) {
  374. return this->ProcessCMakeInputs(request);
  375. }
  376. if (request.Type == kCODE_MODEL_TYPE) {
  377. return this->ProcessCodeModel(request);
  378. }
  379. if (request.Type == kCOMPUTE_TYPE) {
  380. return this->ProcessCompute(request);
  381. }
  382. if (request.Type == kCONFIGURE_TYPE) {
  383. return this->ProcessConfigure(request);
  384. }
  385. if (request.Type == kFILESYSTEM_WATCHERS_TYPE) {
  386. return this->ProcessFileSystemWatchers(request);
  387. }
  388. if (request.Type == kGLOBAL_SETTINGS_TYPE) {
  389. return this->ProcessGlobalSettings(request);
  390. }
  391. if (request.Type == kSET_GLOBAL_SETTINGS_TYPE) {
  392. return this->ProcessSetGlobalSettings(request);
  393. }
  394. return request.ReportError("Unknown command!");
  395. }
  396. bool cmServerProtocol1_0::IsExperimental() const
  397. {
  398. return true;
  399. }
  400. cmServerResponse cmServerProtocol1_0::ProcessCache(
  401. const cmServerRequest& request)
  402. {
  403. if (this->m_State < STATE_CONFIGURED) {
  404. return request.ReportError("This project was not configured yet.");
  405. }
  406. cmState* state = this->CMakeInstance()->GetState();
  407. Json::Value result = Json::objectValue;
  408. std::vector<std::string> allKeys = state->GetCacheEntryKeys();
  409. Json::Value list = Json::arrayValue;
  410. std::vector<std::string> keys = toStringList(request.Data[kKEYS_KEY]);
  411. if (keys.empty()) {
  412. keys = allKeys;
  413. } else {
  414. for (auto i : keys) {
  415. if (std::find_if(allKeys.begin(), allKeys.end(),
  416. [i](const std::string& j) { return i == j; }) ==
  417. allKeys.end()) {
  418. return request.ReportError("Key \"" + i + "\" not found in cache.");
  419. }
  420. }
  421. }
  422. std::sort(keys.begin(), keys.end());
  423. for (auto key : keys) {
  424. Json::Value entry = Json::objectValue;
  425. entry[kKEY_KEY] = key;
  426. entry[kTYPE_KEY] =
  427. cmState::CacheEntryTypeToString(state->GetCacheEntryType(key));
  428. entry[kVALUE_KEY] = state->GetCacheEntryValue(key);
  429. Json::Value props = Json::objectValue;
  430. bool haveProperties = false;
  431. for (auto prop : state->GetCacheEntryPropertyList(key)) {
  432. haveProperties = true;
  433. props[prop] = state->GetCacheEntryProperty(key, prop);
  434. }
  435. if (haveProperties) {
  436. entry[kPROPERTIES_KEY] = props;
  437. }
  438. list.append(entry);
  439. }
  440. result[kCACHE_KEY] = list;
  441. return request.Reply(result);
  442. }
  443. cmServerResponse cmServerProtocol1_0::ProcessCMakeInputs(
  444. const cmServerRequest& request)
  445. {
  446. if (this->m_State < STATE_CONFIGURED) {
  447. return request.ReportError("This instance was not yet configured.");
  448. }
  449. const cmake* cm = this->CMakeInstance();
  450. const cmGlobalGenerator* gg = cm->GetGlobalGenerator();
  451. const std::string cmakeRootDir = cmSystemTools::GetCMakeRoot();
  452. const std::string buildDir = cm->GetHomeOutputDirectory();
  453. const std::string sourceDir = cm->GetHomeDirectory();
  454. Json::Value result = Json::objectValue;
  455. result[kSOURCE_DIRECTORY_KEY] = sourceDir;
  456. result[kCMAKE_ROOT_DIRECTORY_KEY] = cmakeRootDir;
  457. std::vector<std::string> internalFiles;
  458. std::vector<std::string> explicitFiles;
  459. std::vector<std::string> tmpFiles;
  460. getCMakeInputs(gg, sourceDir, buildDir, &internalFiles, &explicitFiles,
  461. &tmpFiles);
  462. Json::Value array = Json::arrayValue;
  463. Json::Value tmp = Json::objectValue;
  464. tmp[kIS_CMAKE_KEY] = true;
  465. tmp[kIS_TEMPORARY_KEY] = false;
  466. tmp[kSOURCES_KEY] = fromStringList(internalFiles);
  467. array.append(tmp);
  468. tmp = Json::objectValue;
  469. tmp[kIS_CMAKE_KEY] = false;
  470. tmp[kIS_TEMPORARY_KEY] = false;
  471. tmp[kSOURCES_KEY] = fromStringList(explicitFiles);
  472. array.append(tmp);
  473. tmp = Json::objectValue;
  474. tmp[kIS_CMAKE_KEY] = false;
  475. tmp[kIS_TEMPORARY_KEY] = true;
  476. tmp[kSOURCES_KEY] = fromStringList(tmpFiles);
  477. array.append(tmp);
  478. result[kBUILD_FILES_KEY] = array;
  479. return request.Reply(result);
  480. }
  481. class LanguageData
  482. {
  483. public:
  484. bool operator==(const LanguageData& other) const;
  485. void SetDefines(const std::set<std::string>& defines);
  486. bool IsGenerated = false;
  487. std::string Language;
  488. std::string Flags;
  489. std::vector<std::string> Defines;
  490. std::vector<std::pair<std::string, bool> > IncludePathList;
  491. };
  492. bool LanguageData::operator==(const LanguageData& other) const
  493. {
  494. return Language == other.Language && Defines == other.Defines &&
  495. Flags == other.Flags && IncludePathList == other.IncludePathList &&
  496. IsGenerated == other.IsGenerated;
  497. }
  498. void LanguageData::SetDefines(const std::set<std::string>& defines)
  499. {
  500. std::vector<std::string> result;
  501. for (auto i : defines) {
  502. result.push_back(i);
  503. }
  504. std::sort(result.begin(), result.end());
  505. Defines = result;
  506. }
  507. namespace std {
  508. template <>
  509. struct hash<LanguageData>
  510. {
  511. std::size_t operator()(const LanguageData& in) const
  512. {
  513. using std::hash;
  514. size_t result =
  515. hash<std::string>()(in.Language) ^ hash<std::string>()(in.Flags);
  516. for (auto i : in.IncludePathList) {
  517. result = result ^ (hash<std::string>()(i.first) ^
  518. (i.second ? std::numeric_limits<size_t>::max() : 0));
  519. }
  520. for (auto i : in.Defines) {
  521. result = result ^ hash<std::string>()(i);
  522. }
  523. result =
  524. result ^ (in.IsGenerated ? std::numeric_limits<size_t>::max() : 0);
  525. return result;
  526. }
  527. };
  528. } // namespace std
  529. static Json::Value DumpSourceFileGroup(const LanguageData& data,
  530. const std::vector<std::string>& files,
  531. const std::string& baseDir)
  532. {
  533. Json::Value result = Json::objectValue;
  534. if (!data.Language.empty()) {
  535. result[kLANGUAGE_KEY] = data.Language;
  536. if (!data.Flags.empty()) {
  537. result[kCOMPILE_FLAGS_KEY] = data.Flags;
  538. }
  539. if (!data.IncludePathList.empty()) {
  540. Json::Value includes = Json::arrayValue;
  541. for (auto i : data.IncludePathList) {
  542. Json::Value tmp = Json::objectValue;
  543. tmp[kPATH_KEY] = i.first;
  544. if (i.second) {
  545. tmp[kIS_SYSTEM_KEY] = i.second;
  546. }
  547. includes.append(tmp);
  548. }
  549. result[kINCLUDE_PATH_KEY] = includes;
  550. }
  551. if (!data.Defines.empty()) {
  552. result[kDEFINES_KEY] = fromStringList(data.Defines);
  553. }
  554. }
  555. result[kIS_GENERATED_KEY] = data.IsGenerated;
  556. Json::Value sourcesValue = Json::arrayValue;
  557. for (auto i : files) {
  558. const std::string relPath =
  559. cmSystemTools::RelativePath(baseDir.c_str(), i.c_str());
  560. sourcesValue.append(relPath.size() < i.size() ? relPath : i);
  561. }
  562. result[kSOURCES_KEY] = sourcesValue;
  563. return result;
  564. }
  565. static Json::Value DumpSourceFilesList(
  566. cmGeneratorTarget* target, const std::string& config,
  567. const std::map<std::string, LanguageData>& languageDataMap)
  568. {
  569. // Collect sourcefile groups:
  570. std::vector<cmSourceFile*> files;
  571. target->GetSourceFiles(files, config);
  572. std::unordered_map<LanguageData, std::vector<std::string> > fileGroups;
  573. for (cmSourceFile* file : files) {
  574. LanguageData fileData;
  575. fileData.Language = file->GetLanguage();
  576. if (!fileData.Language.empty()) {
  577. const LanguageData& ld = languageDataMap.at(fileData.Language);
  578. cmLocalGenerator* lg = target->GetLocalGenerator();
  579. std::string compileFlags = ld.Flags;
  580. if (const char* cflags = file->GetProperty("COMPILE_FLAGS")) {
  581. cmGeneratorExpression ge;
  582. auto cge = ge.Parse(cflags);
  583. const char* processed =
  584. cge->Evaluate(target->GetLocalGenerator(), config);
  585. lg->AppendFlags(compileFlags, processed);
  586. }
  587. fileData.Flags = compileFlags;
  588. fileData.IncludePathList = ld.IncludePathList;
  589. std::set<std::string> defines;
  590. lg->AppendDefines(defines, file->GetProperty("COMPILE_DEFINITIONS"));
  591. const std::string defPropName =
  592. "COMPILE_DEFINITIONS_" + cmSystemTools::UpperCase(config);
  593. lg->AppendDefines(defines, file->GetProperty(defPropName));
  594. defines.insert(ld.Defines.begin(), ld.Defines.end());
  595. fileData.SetDefines(defines);
  596. }
  597. fileData.IsGenerated = file->GetPropertyAsBool("GENERATED");
  598. std::vector<std::string>& groupFileList = fileGroups[fileData];
  599. groupFileList.push_back(file->GetFullPath());
  600. }
  601. const std::string baseDir = target->Makefile->GetCurrentSourceDirectory();
  602. Json::Value result = Json::arrayValue;
  603. for (auto it = fileGroups.begin(); it != fileGroups.end(); ++it) {
  604. Json::Value group = DumpSourceFileGroup(it->first, it->second, baseDir);
  605. if (!group.isNull()) {
  606. result.append(group);
  607. }
  608. }
  609. return result;
  610. }
  611. static Json::Value DumpTarget(cmGeneratorTarget* target,
  612. const std::string& config)
  613. {
  614. cmLocalGenerator* lg = target->GetLocalGenerator();
  615. const cmState* state = lg->GetState();
  616. const cmStateEnums::TargetType type = target->GetType();
  617. const std::string typeName = state->GetTargetTypeName(type);
  618. Json::Value ttl = Json::arrayValue;
  619. ttl.append("EXECUTABLE");
  620. ttl.append("STATIC_LIBRARY");
  621. ttl.append("SHARED_LIBRARY");
  622. ttl.append("MODULE_LIBRARY");
  623. ttl.append("OBJECT_LIBRARY");
  624. ttl.append("UTILITY");
  625. ttl.append("INTERFACE_LIBRARY");
  626. if (!hasString(ttl, typeName) || target->IsImported()) {
  627. return Json::Value();
  628. }
  629. Json::Value result = Json::objectValue;
  630. result[kNAME_KEY] = target->GetName();
  631. result[kTYPE_KEY] = typeName;
  632. result[kSOURCE_DIRECTORY_KEY] = lg->GetCurrentSourceDirectory();
  633. result[kBUILD_DIRECTORY_KEY] = lg->GetCurrentBinaryDirectory();
  634. if (type == cmStateEnums::INTERFACE_LIBRARY) {
  635. return result;
  636. }
  637. result[kFULL_NAME_KEY] = target->GetFullName(config);
  638. if (target->HaveWellDefinedOutputFiles()) {
  639. Json::Value artifacts = Json::arrayValue;
  640. artifacts.append(target->GetFullPath(config, false));
  641. if (target->IsDLLPlatform()) {
  642. artifacts.append(target->GetFullPath(config, true));
  643. const cmGeneratorTarget::OutputInfo* output =
  644. target->GetOutputInfo(config);
  645. if (output && !output->PdbDir.empty()) {
  646. artifacts.append(output->PdbDir + '/' + target->GetPDBName(config));
  647. }
  648. }
  649. result[kARTIFACTS_KEY] = artifacts;
  650. result[kLINKER_LANGUAGE_KEY] = target->GetLinkerLanguage(config);
  651. std::string linkLibs;
  652. std::string linkFlags;
  653. std::string linkLanguageFlags;
  654. std::string frameworkPath;
  655. std::string linkPath;
  656. cmLinkLineComputer linkLineComputer(lg,
  657. lg->GetStateSnapshot().GetDirectory());
  658. lg->GetTargetFlags(&linkLineComputer, config, linkLibs, linkLanguageFlags,
  659. linkFlags, frameworkPath, linkPath, target);
  660. linkLibs = cmSystemTools::TrimWhitespace(linkLibs);
  661. linkFlags = cmSystemTools::TrimWhitespace(linkFlags);
  662. linkLanguageFlags = cmSystemTools::TrimWhitespace(linkLanguageFlags);
  663. frameworkPath = cmSystemTools::TrimWhitespace(frameworkPath);
  664. linkPath = cmSystemTools::TrimWhitespace(linkPath);
  665. if (!cmSystemTools::TrimWhitespace(linkLibs).empty()) {
  666. result[kLINK_LIBRARIES_KEY] = linkLibs;
  667. }
  668. if (!cmSystemTools::TrimWhitespace(linkFlags).empty()) {
  669. result[kLINK_FLAGS_KEY] = linkFlags;
  670. }
  671. if (!cmSystemTools::TrimWhitespace(linkLanguageFlags).empty()) {
  672. result[kLINK_LANGUAGE_FLAGS_KEY] = linkLanguageFlags;
  673. }
  674. if (!frameworkPath.empty()) {
  675. result[kFRAMEWORK_PATH_KEY] = frameworkPath;
  676. }
  677. if (!linkPath.empty()) {
  678. result[kLINK_PATH_KEY] = linkPath;
  679. }
  680. const std::string sysroot =
  681. lg->GetMakefile()->GetSafeDefinition("CMAKE_SYSROOT");
  682. if (!sysroot.empty()) {
  683. result[kSYSROOT_KEY] = sysroot;
  684. }
  685. }
  686. std::set<std::string> languages;
  687. target->GetLanguages(languages, config);
  688. std::map<std::string, LanguageData> languageDataMap;
  689. for (auto lang : languages) {
  690. LanguageData& ld = languageDataMap[lang];
  691. ld.Language = lang;
  692. lg->GetTargetCompileFlags(target, config, lang, ld.Flags);
  693. std::set<std::string> defines;
  694. lg->GetTargetDefines(target, config, lang, defines);
  695. ld.SetDefines(defines);
  696. std::vector<std::string> includePathList;
  697. lg->GetIncludeDirectories(includePathList, target, lang, config, true);
  698. for (auto i : includePathList) {
  699. ld.IncludePathList.push_back(
  700. std::make_pair(i, target->IsSystemIncludeDirectory(i, config)));
  701. }
  702. }
  703. Json::Value sourceGroupsValue =
  704. DumpSourceFilesList(target, config, languageDataMap);
  705. if (!sourceGroupsValue.empty()) {
  706. result[kFILE_GROUPS_KEY] = sourceGroupsValue;
  707. }
  708. return result;
  709. }
  710. static Json::Value DumpTargetsList(
  711. const std::vector<cmLocalGenerator*>& generators, const std::string& config)
  712. {
  713. Json::Value result = Json::arrayValue;
  714. std::vector<cmGeneratorTarget*> targetList;
  715. for (const auto& lgIt : generators) {
  716. auto list = lgIt->GetGeneratorTargets();
  717. targetList.insert(targetList.end(), list.begin(), list.end());
  718. }
  719. std::sort(targetList.begin(), targetList.end());
  720. for (cmGeneratorTarget* target : targetList) {
  721. Json::Value tmp = DumpTarget(target, config);
  722. if (!tmp.isNull()) {
  723. result.append(tmp);
  724. }
  725. }
  726. return result;
  727. }
  728. static Json::Value DumpProjectList(const cmake* cm, std::string const& config)
  729. {
  730. Json::Value result = Json::arrayValue;
  731. auto globalGen = cm->GetGlobalGenerator();
  732. for (const auto& projectIt : globalGen->GetProjectMap()) {
  733. Json::Value pObj = Json::objectValue;
  734. pObj[kNAME_KEY] = projectIt.first;
  735. // All Projects must have at least one local generator
  736. assert(!projectIt.second.empty());
  737. const cmLocalGenerator* lg = projectIt.second.at(0);
  738. // Project structure information:
  739. const cmMakefile* mf = lg->GetMakefile();
  740. pObj[kSOURCE_DIRECTORY_KEY] = mf->GetCurrentSourceDirectory();
  741. pObj[kBUILD_DIRECTORY_KEY] = mf->GetCurrentBinaryDirectory();
  742. pObj[kTARGETS_KEY] = DumpTargetsList(projectIt.second, config);
  743. result.append(pObj);
  744. }
  745. return result;
  746. }
  747. static Json::Value DumpConfiguration(const cmake* cm,
  748. const std::string& config)
  749. {
  750. Json::Value result = Json::objectValue;
  751. result[kNAME_KEY] = config;
  752. result[kPROJECTS_KEY] = DumpProjectList(cm, config);
  753. return result;
  754. }
  755. static Json::Value DumpConfigurationsList(const cmake* cm)
  756. {
  757. Json::Value result = Json::arrayValue;
  758. for (const std::string& c : getConfigurations(cm)) {
  759. result.append(DumpConfiguration(cm, c));
  760. }
  761. return result;
  762. }
  763. cmServerResponse cmServerProtocol1_0::ProcessCodeModel(
  764. const cmServerRequest& request)
  765. {
  766. if (this->m_State != STATE_COMPUTED) {
  767. return request.ReportError("No build system was generated yet.");
  768. }
  769. Json::Value result = Json::objectValue;
  770. result[kCONFIGURATIONS_KEY] = DumpConfigurationsList(this->CMakeInstance());
  771. return request.Reply(result);
  772. }
  773. cmServerResponse cmServerProtocol1_0::ProcessCompute(
  774. const cmServerRequest& request)
  775. {
  776. if (this->m_State > STATE_CONFIGURED) {
  777. return request.ReportError("This build system was already generated.");
  778. }
  779. if (this->m_State < STATE_CONFIGURED) {
  780. return request.ReportError("This project was not configured yet.");
  781. }
  782. cmake* cm = this->CMakeInstance();
  783. int ret = cm->Generate();
  784. if (ret < 0) {
  785. return request.ReportError("Failed to compute build system.");
  786. }
  787. m_State = STATE_COMPUTED;
  788. return request.Reply(Json::Value());
  789. }
  790. cmServerResponse cmServerProtocol1_0::ProcessConfigure(
  791. const cmServerRequest& request)
  792. {
  793. if (this->m_State == STATE_INACTIVE) {
  794. return request.ReportError("This instance is inactive.");
  795. }
  796. FileMonitor()->StopMonitoring();
  797. std::string errorMessage;
  798. cmake* cm = this->CMakeInstance();
  799. this->GeneratorInfo.SetupGenerator(cm, &errorMessage);
  800. if (!errorMessage.empty()) {
  801. return request.ReportError(errorMessage);
  802. }
  803. // Make sure the types of cacheArguments matches (if given):
  804. std::vector<std::string> cacheArgs = { "unused" };
  805. bool cacheArgumentsError = false;
  806. const Json::Value passedArgs = request.Data[kCACHE_ARGUMENTS_KEY];
  807. if (!passedArgs.isNull()) {
  808. if (passedArgs.isString()) {
  809. cacheArgs.push_back(passedArgs.asString());
  810. } else if (passedArgs.isArray()) {
  811. for (auto i = passedArgs.begin(); i != passedArgs.end(); ++i) {
  812. if (!i->isString()) {
  813. cacheArgumentsError = true;
  814. break;
  815. }
  816. cacheArgs.push_back(i->asString());
  817. }
  818. } else {
  819. cacheArgumentsError = true;
  820. }
  821. }
  822. if (cacheArgumentsError) {
  823. request.ReportError(
  824. "cacheArguments must be unset, a string or an array of strings.");
  825. }
  826. std::string sourceDir = cm->GetHomeDirectory();
  827. const std::string buildDir = cm->GetHomeOutputDirectory();
  828. cmGlobalGenerator* gg = cm->GetGlobalGenerator();
  829. if (buildDir.empty()) {
  830. return request.ReportError("No build directory set via Handshake.");
  831. }
  832. if (cm->LoadCache(buildDir)) {
  833. // build directory has been set up before
  834. const char* cachedSourceDir =
  835. cm->GetState()->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY");
  836. if (!cachedSourceDir) {
  837. return request.ReportError("No CMAKE_HOME_DIRECTORY found in cache.");
  838. }
  839. if (sourceDir.empty()) {
  840. sourceDir = std::string(cachedSourceDir);
  841. cm->SetHomeDirectory(sourceDir);
  842. }
  843. const char* cachedGenerator =
  844. cm->GetState()->GetInitializedCacheValue("CMAKE_GENERATOR");
  845. if (cachedGenerator) {
  846. if (gg && gg->GetName() != cachedGenerator) {
  847. return request.ReportError("Configured generator does not match with "
  848. "CMAKE_GENERATOR found in cache.");
  849. }
  850. }
  851. } else {
  852. // build directory has not been set up before
  853. if (sourceDir.empty()) {
  854. return request.ReportError("No sourceDirectory set via "
  855. "setGlobalSettings and no cache found in "
  856. "buildDirectory.");
  857. }
  858. }
  859. cmSystemTools::ResetErrorOccuredFlag(); // Reset error state
  860. if (cm->AddCMakePaths() != 1) {
  861. return request.ReportError("Failed to set CMake paths.");
  862. }
  863. if (!cm->SetCacheArgs(cacheArgs)) {
  864. return request.ReportError("cacheArguments could not be set.");
  865. }
  866. int ret = cm->Configure();
  867. if (ret < 0) {
  868. return request.ReportError("Configuration failed.");
  869. }
  870. std::vector<std::string> toWatchList;
  871. getCMakeInputs(gg, std::string(), buildDir, nullptr, &toWatchList, nullptr);
  872. FileMonitor()->MonitorPaths(toWatchList,
  873. [this](const std::string& p, int e, int s) {
  874. this->HandleCMakeFileChanges(p, e, s);
  875. });
  876. m_State = STATE_CONFIGURED;
  877. m_isDirty = false;
  878. return request.Reply(Json::Value());
  879. }
  880. cmServerResponse cmServerProtocol1_0::ProcessGlobalSettings(
  881. const cmServerRequest& request)
  882. {
  883. cmake* cm = this->CMakeInstance();
  884. Json::Value obj = Json::objectValue;
  885. // Capabilities information:
  886. obj[kCAPABILITIES_KEY] = cm->ReportCapabilitiesJson(true);
  887. obj[kDEBUG_OUTPUT_KEY] = cm->GetDebugOutput();
  888. obj[kTRACE_KEY] = cm->GetTrace();
  889. obj[kTRACE_EXPAND_KEY] = cm->GetTraceExpand();
  890. obj[kWARN_UNINITIALIZED_KEY] = cm->GetWarnUninitialized();
  891. obj[kWARN_UNUSED_KEY] = cm->GetWarnUnused();
  892. obj[kWARN_UNUSED_CLI_KEY] = cm->GetWarnUnusedCli();
  893. obj[kCHECK_SYSTEM_VARS_KEY] = cm->GetCheckSystemVars();
  894. obj[kSOURCE_DIRECTORY_KEY] = this->GeneratorInfo.SourceDirectory;
  895. obj[kBUILD_DIRECTORY_KEY] = this->GeneratorInfo.BuildDirectory;
  896. // Currently used generator:
  897. obj[kGENERATOR_KEY] = this->GeneratorInfo.GeneratorName;
  898. obj[kEXTRA_GENERATOR_KEY] = this->GeneratorInfo.ExtraGeneratorName;
  899. return request.Reply(obj);
  900. }
  901. static void setBool(const cmServerRequest& request, const std::string& key,
  902. std::function<void(bool)> const& setter)
  903. {
  904. if (request.Data[key].isNull()) {
  905. return;
  906. }
  907. setter(request.Data[key].asBool());
  908. }
  909. cmServerResponse cmServerProtocol1_0::ProcessSetGlobalSettings(
  910. const cmServerRequest& request)
  911. {
  912. const std::vector<std::string> boolValues = {
  913. kDEBUG_OUTPUT_KEY, kTRACE_KEY, kTRACE_EXPAND_KEY,
  914. kWARN_UNINITIALIZED_KEY, kWARN_UNUSED_KEY, kWARN_UNUSED_CLI_KEY,
  915. kCHECK_SYSTEM_VARS_KEY
  916. };
  917. for (auto i : boolValues) {
  918. if (!request.Data[i].isNull() && !request.Data[i].isBool()) {
  919. return request.ReportError("\"" + i +
  920. "\" must be unset or a bool value.");
  921. }
  922. }
  923. cmake* cm = this->CMakeInstance();
  924. setBool(request, kDEBUG_OUTPUT_KEY,
  925. [cm](bool e) { cm->SetDebugOutputOn(e); });
  926. setBool(request, kTRACE_KEY, [cm](bool e) { cm->SetTrace(e); });
  927. setBool(request, kTRACE_EXPAND_KEY, [cm](bool e) { cm->SetTraceExpand(e); });
  928. setBool(request, kWARN_UNINITIALIZED_KEY,
  929. [cm](bool e) { cm->SetWarnUninitialized(e); });
  930. setBool(request, kWARN_UNUSED_KEY, [cm](bool e) { cm->SetWarnUnused(e); });
  931. setBool(request, kWARN_UNUSED_CLI_KEY,
  932. [cm](bool e) { cm->SetWarnUnusedCli(e); });
  933. setBool(request, kCHECK_SYSTEM_VARS_KEY,
  934. [cm](bool e) { cm->SetCheckSystemVars(e); });
  935. return request.Reply(Json::Value());
  936. }
  937. cmServerResponse cmServerProtocol1_0::ProcessFileSystemWatchers(
  938. const cmServerRequest& request)
  939. {
  940. const cmFileMonitor* const fm = FileMonitor();
  941. Json::Value result = Json::objectValue;
  942. Json::Value files = Json::arrayValue;
  943. for (const auto& f : fm->WatchedFiles()) {
  944. files.append(f);
  945. }
  946. Json::Value directories = Json::arrayValue;
  947. for (const auto& d : fm->WatchedDirectories()) {
  948. directories.append(d);
  949. }
  950. result[kWATCHED_FILES_KEY] = files;
  951. result[kWATCHED_DIRECTORIES_KEY] = directories;
  952. return request.Reply(result);
  953. }
  954. cmServerProtocol1_0::GeneratorInformation::GeneratorInformation(
  955. const std::string& generatorName, const std::string& extraGeneratorName,
  956. const std::string& toolset, const std::string& platform,
  957. const std::string& sourceDirectory, const std::string& buildDirectory)
  958. : GeneratorName(generatorName)
  959. , ExtraGeneratorName(extraGeneratorName)
  960. , Toolset(toolset)
  961. , Platform(platform)
  962. , SourceDirectory(sourceDirectory)
  963. , BuildDirectory(buildDirectory)
  964. {
  965. }
  966. void cmServerProtocol1_0::GeneratorInformation::SetupGenerator(
  967. cmake* cm, std::string* errorMessage)
  968. {
  969. const std::string fullGeneratorName =
  970. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  971. GeneratorName, ExtraGeneratorName);
  972. cm->SetHomeDirectory(SourceDirectory);
  973. cm->SetHomeOutputDirectory(BuildDirectory);
  974. cmGlobalGenerator* gg = cm->CreateGlobalGenerator(fullGeneratorName);
  975. if (!gg) {
  976. setErrorMessage(
  977. errorMessage,
  978. std::string("Could not set up the requested combination of \"") +
  979. kGENERATOR_KEY + "\" and \"" + kEXTRA_GENERATOR_KEY + "\"");
  980. return;
  981. }
  982. cm->SetGlobalGenerator(gg);
  983. cm->SetGeneratorToolset(Toolset);
  984. cm->SetGeneratorPlatform(Platform);
  985. }