cmFindPackageCommand.cxx 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267
  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 "cmFindPackageCommand.h"
  4. #include "cmSystemTools.h"
  5. #include "cmsys/Directory.hxx"
  6. #include "cmsys/FStream.hxx"
  7. #include "cmsys/Glob.hxx"
  8. #include "cmsys/RegularExpression.hxx"
  9. #include "cmsys/String.h"
  10. #include <algorithm>
  11. #include <assert.h>
  12. #include <deque>
  13. #include <functional>
  14. #include <iterator>
  15. #include <memory> // IWYU pragma: keep
  16. #include <sstream>
  17. #include <stdio.h>
  18. #include <string.h>
  19. #include <utility>
  20. #include "cmAlgorithms.h"
  21. #include "cmMakefile.h"
  22. #include "cmPolicies.h"
  23. #include "cmSearchPath.h"
  24. #include "cmState.h"
  25. #include "cmStateTypes.h"
  26. #include "cmVersion.h"
  27. #include "cmake.h"
  28. #if defined(__HAIKU__)
  29. # include <FindDirectory.h>
  30. # include <StorageDefs.h>
  31. #endif
  32. class cmExecutionStatus;
  33. class cmFileList;
  34. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::UserRegistry(
  35. "PACKAGE_REGISTRY");
  36. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::Builds(
  37. "BUILDS");
  38. cmFindPackageCommand::PathLabel
  39. cmFindPackageCommand::PathLabel::SystemRegistry("SYSTEM_PACKAGE_REGISTRY");
  40. struct StrverscmpGreater
  41. {
  42. bool operator()(const std::string& lhs, const std::string& rhs) const
  43. {
  44. return cmSystemTools::strverscmp(lhs, rhs) > 0;
  45. }
  46. };
  47. struct StrverscmpLesser
  48. {
  49. bool operator()(const std::string& lhs, const std::string& rhs) const
  50. {
  51. return cmSystemTools::strverscmp(lhs, rhs) < 0;
  52. }
  53. };
  54. void cmFindPackageCommand::Sort(std::vector<std::string>::iterator begin,
  55. std::vector<std::string>::iterator end,
  56. SortOrderType order, SortDirectionType dir)
  57. {
  58. if (order == Name_order) {
  59. if (dir == Dec) {
  60. std::sort(begin, end, std::greater<std::string>());
  61. } else {
  62. std::sort(begin, end);
  63. }
  64. } else if (order == Natural)
  65. // natural order uses letters and numbers (contiguous numbers digit are
  66. // compared such that e.g. 000 00 < 01 < 010 < 09 < 0 < 1 < 9 < 10
  67. {
  68. if (dir == Dec) {
  69. std::sort(begin, end, StrverscmpGreater());
  70. } else {
  71. std::sort(begin, end, StrverscmpLesser());
  72. }
  73. }
  74. // else do not sort
  75. }
  76. cmFindPackageCommand::cmFindPackageCommand()
  77. {
  78. this->CMakePathName = "PACKAGE";
  79. this->Quiet = false;
  80. this->Required = false;
  81. this->NoUserRegistry = false;
  82. this->NoSystemRegistry = false;
  83. this->UseConfigFiles = true;
  84. this->UseFindModules = true;
  85. this->DebugMode = false;
  86. this->UseLib32Paths = false;
  87. this->UseLib64Paths = false;
  88. this->UseLibx32Paths = false;
  89. this->PolicyScope = true;
  90. this->VersionMajor = 0;
  91. this->VersionMinor = 0;
  92. this->VersionPatch = 0;
  93. this->VersionTweak = 0;
  94. this->VersionCount = 0;
  95. this->VersionExact = false;
  96. this->VersionFoundMajor = 0;
  97. this->VersionFoundMinor = 0;
  98. this->VersionFoundPatch = 0;
  99. this->VersionFoundTweak = 0;
  100. this->VersionFoundCount = 0;
  101. this->RequiredCMakeVersion = 0;
  102. this->SortOrder = None;
  103. this->SortDirection = Asc;
  104. this->AppendSearchPathGroups();
  105. this->DeprecatedFindModules["Qt"] = cmPolicies::CMP0084;
  106. }
  107. void cmFindPackageCommand::AppendSearchPathGroups()
  108. {
  109. std::vector<cmFindCommon::PathLabel>* labels;
  110. // Update the All group with new paths
  111. labels = &this->PathGroupLabelMap[PathGroup::All];
  112. labels->insert(
  113. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  114. PathLabel::UserRegistry);
  115. labels->insert(
  116. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  117. PathLabel::Builds);
  118. labels->insert(std::find(labels->begin(), labels->end(), PathLabel::Guess),
  119. PathLabel::SystemRegistry);
  120. // Create the new path objects
  121. this->LabeledPaths.insert(
  122. std::make_pair(PathLabel::UserRegistry, cmSearchPath(this)));
  123. this->LabeledPaths.insert(
  124. std::make_pair(PathLabel::Builds, cmSearchPath(this)));
  125. this->LabeledPaths.insert(
  126. std::make_pair(PathLabel::SystemRegistry, cmSearchPath(this)));
  127. }
  128. bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args,
  129. cmExecutionStatus&)
  130. {
  131. if (args.empty()) {
  132. this->SetError("called with incorrect number of arguments");
  133. return false;
  134. }
  135. // Lookup required version of CMake.
  136. if (const char* rv =
  137. this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
  138. unsigned int v[3] = { 0, 0, 0 };
  139. sscanf(rv, "%u.%u.%u", &v[0], &v[1], &v[2]);
  140. this->RequiredCMakeVersion = CMake_VERSION_ENCODE(v[0], v[1], v[2]);
  141. }
  142. // Check for debug mode.
  143. this->DebugMode = this->Makefile->IsOn("CMAKE_FIND_DEBUG_MODE");
  144. // Lookup target architecture, if any.
  145. if (const char* arch =
  146. this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) {
  147. this->LibraryArchitecture = arch;
  148. }
  149. // Lookup whether lib32 paths should be used.
  150. if (this->Makefile->PlatformIs32Bit() &&
  151. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  152. "FIND_LIBRARY_USE_LIB32_PATHS")) {
  153. this->UseLib32Paths = true;
  154. }
  155. // Lookup whether lib64 paths should be used.
  156. if (this->Makefile->PlatformIs64Bit() &&
  157. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  158. "FIND_LIBRARY_USE_LIB64_PATHS")) {
  159. this->UseLib64Paths = true;
  160. }
  161. // Lookup whether libx32 paths should be used.
  162. if (this->Makefile->PlatformIsx32() &&
  163. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  164. "FIND_LIBRARY_USE_LIBX32_PATHS")) {
  165. this->UseLibx32Paths = true;
  166. }
  167. // Check if User Package Registry should be disabled
  168. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY")) {
  169. this->NoUserRegistry = true;
  170. }
  171. // Check if System Package Registry should be disabled
  172. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY")) {
  173. this->NoSystemRegistry = true;
  174. }
  175. // Check if Sorting should be enabled
  176. if (const char* so =
  177. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_ORDER")) {
  178. if (strcmp(so, "NAME") == 0) {
  179. this->SortOrder = Name_order;
  180. } else if (strcmp(so, "NATURAL") == 0) {
  181. this->SortOrder = Natural;
  182. } else {
  183. this->SortOrder = None;
  184. }
  185. }
  186. if (const char* sd =
  187. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_DIRECTION")) {
  188. this->SortDirection = strcmp(sd, "ASC") == 0 ? Asc : Dec;
  189. }
  190. // Find the current root path mode.
  191. this->SelectDefaultRootPathMode();
  192. // Find the current bundle/framework search policy.
  193. this->SelectDefaultMacMode();
  194. // Record options.
  195. this->Name = args[0];
  196. std::string components;
  197. const char* components_sep = "";
  198. std::set<std::string> requiredComponents;
  199. std::set<std::string> optionalComponents;
  200. // Always search directly in a generated path.
  201. this->SearchPathSuffixes.emplace_back();
  202. // Parse the arguments.
  203. enum Doing
  204. {
  205. DoingNone,
  206. DoingComponents,
  207. DoingOptionalComponents,
  208. DoingNames,
  209. DoingPaths,
  210. DoingPathSuffixes,
  211. DoingConfigs,
  212. DoingHints
  213. };
  214. Doing doing = DoingNone;
  215. cmsys::RegularExpression version("^[0-9.]+$");
  216. bool haveVersion = false;
  217. std::set<unsigned int> configArgs;
  218. std::set<unsigned int> moduleArgs;
  219. for (unsigned int i = 1; i < args.size(); ++i) {
  220. if (args[i] == "QUIET") {
  221. this->Quiet = true;
  222. doing = DoingNone;
  223. } else if (args[i] == "EXACT") {
  224. this->VersionExact = true;
  225. doing = DoingNone;
  226. } else if (args[i] == "MODULE") {
  227. moduleArgs.insert(i);
  228. doing = DoingNone;
  229. } else if (args[i] == "CONFIG") {
  230. configArgs.insert(i);
  231. doing = DoingNone;
  232. } else if (args[i] == "NO_MODULE") {
  233. configArgs.insert(i);
  234. doing = DoingNone;
  235. } else if (args[i] == "REQUIRED") {
  236. this->Required = true;
  237. doing = DoingComponents;
  238. } else if (args[i] == "COMPONENTS") {
  239. doing = DoingComponents;
  240. } else if (args[i] == "OPTIONAL_COMPONENTS") {
  241. doing = DoingOptionalComponents;
  242. } else if (args[i] == "NAMES") {
  243. configArgs.insert(i);
  244. doing = DoingNames;
  245. } else if (args[i] == "PATHS") {
  246. configArgs.insert(i);
  247. doing = DoingPaths;
  248. } else if (args[i] == "HINTS") {
  249. configArgs.insert(i);
  250. doing = DoingHints;
  251. } else if (args[i] == "PATH_SUFFIXES") {
  252. configArgs.insert(i);
  253. doing = DoingPathSuffixes;
  254. } else if (args[i] == "CONFIGS") {
  255. configArgs.insert(i);
  256. doing = DoingConfigs;
  257. } else if (args[i] == "NO_POLICY_SCOPE") {
  258. this->PolicyScope = false;
  259. doing = DoingNone;
  260. } else if (args[i] == "NO_CMAKE_PACKAGE_REGISTRY") {
  261. this->NoUserRegistry = true;
  262. configArgs.insert(i);
  263. doing = DoingNone;
  264. } else if (args[i] == "NO_CMAKE_SYSTEM_PACKAGE_REGISTRY") {
  265. this->NoSystemRegistry = true;
  266. configArgs.insert(i);
  267. doing = DoingNone;
  268. } else if (args[i] == "NO_CMAKE_BUILDS_PATH") {
  269. // Ignore legacy option.
  270. configArgs.insert(i);
  271. doing = DoingNone;
  272. } else if (this->CheckCommonArgument(args[i])) {
  273. configArgs.insert(i);
  274. doing = DoingNone;
  275. } else if ((doing == DoingComponents) ||
  276. (doing == DoingOptionalComponents)) {
  277. // Set a variable telling the find script whether this component
  278. // is required.
  279. const char* isRequired = "1";
  280. if (doing == DoingOptionalComponents) {
  281. isRequired = "0";
  282. optionalComponents.insert(args[i]);
  283. } else {
  284. requiredComponents.insert(args[i]);
  285. }
  286. std::string req_var = this->Name + "_FIND_REQUIRED_" + args[i];
  287. this->AddFindDefinition(req_var, isRequired);
  288. // Append to the list of required components.
  289. components += components_sep;
  290. components += args[i];
  291. components_sep = ";";
  292. } else if (doing == DoingNames) {
  293. this->Names.push_back(args[i]);
  294. } else if (doing == DoingPaths) {
  295. this->UserGuessArgs.push_back(args[i]);
  296. } else if (doing == DoingHints) {
  297. this->UserHintsArgs.push_back(args[i]);
  298. } else if (doing == DoingPathSuffixes) {
  299. this->AddPathSuffix(args[i]);
  300. } else if (doing == DoingConfigs) {
  301. if (args[i].find_first_of(":/\\") != std::string::npos ||
  302. cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake") {
  303. std::ostringstream e;
  304. e << "given CONFIGS option followed by invalid file name \"" << args[i]
  305. << "\". The names given must be file names without "
  306. << "a path and with a \".cmake\" extension.";
  307. this->SetError(e.str());
  308. return false;
  309. }
  310. this->Configs.push_back(args[i]);
  311. } else if (!haveVersion && version.find(args[i])) {
  312. haveVersion = true;
  313. this->Version = args[i];
  314. } else {
  315. std::ostringstream e;
  316. e << "called with invalid argument \"" << args[i] << "\"";
  317. this->SetError(e.str());
  318. return false;
  319. }
  320. }
  321. std::vector<std::string> doubledComponents;
  322. std::set_intersection(requiredComponents.begin(), requiredComponents.end(),
  323. optionalComponents.begin(), optionalComponents.end(),
  324. std::back_inserter(doubledComponents));
  325. if (!doubledComponents.empty()) {
  326. std::ostringstream e;
  327. e << "called with components that are both required and optional:\n";
  328. e << cmWrap(" ", doubledComponents, "", "\n") << "\n";
  329. this->SetError(e.str());
  330. return false;
  331. }
  332. // Maybe choose one mode exclusively.
  333. this->UseFindModules = configArgs.empty();
  334. this->UseConfigFiles = moduleArgs.empty();
  335. if (!this->UseFindModules && !this->UseConfigFiles) {
  336. std::ostringstream e;
  337. e << "given options exclusive to Module mode:\n";
  338. for (unsigned int si : moduleArgs) {
  339. e << " " << args[si] << "\n";
  340. }
  341. e << "and options exclusive to Config mode:\n";
  342. for (unsigned int si : configArgs) {
  343. e << " " << args[si] << "\n";
  344. }
  345. e << "The options are incompatible.";
  346. this->SetError(e.str());
  347. return false;
  348. }
  349. // Ignore EXACT with no version.
  350. if (this->Version.empty() && this->VersionExact) {
  351. this->VersionExact = false;
  352. this->Makefile->IssueMessage(
  353. cmake::AUTHOR_WARNING, "Ignoring EXACT since no version is requested.");
  354. }
  355. if (this->Version.empty() || components.empty()) {
  356. // Check whether we are recursing inside "Find<name>.cmake" within
  357. // another find_package(<name>) call.
  358. std::string mod = this->Name;
  359. mod += "_FIND_MODULE";
  360. if (this->Makefile->IsOn(mod)) {
  361. if (this->Version.empty()) {
  362. // Get version information from the outer call if necessary.
  363. // Requested version string.
  364. std::string ver = this->Name;
  365. ver += "_FIND_VERSION";
  366. this->Version = this->Makefile->GetSafeDefinition(ver);
  367. // Whether an exact version is required.
  368. std::string exact = this->Name;
  369. exact += "_FIND_VERSION_EXACT";
  370. this->VersionExact = this->Makefile->IsOn(exact);
  371. }
  372. if (components.empty()) {
  373. std::string components_var = this->Name + "_FIND_COMPONENTS";
  374. components = this->Makefile->GetSafeDefinition(components_var);
  375. }
  376. }
  377. }
  378. if (!this->Version.empty()) {
  379. // Try to parse the version number and store the results that were
  380. // successfully parsed.
  381. unsigned int parsed_major;
  382. unsigned int parsed_minor;
  383. unsigned int parsed_patch;
  384. unsigned int parsed_tweak;
  385. this->VersionCount =
  386. sscanf(this->Version.c_str(), "%u.%u.%u.%u", &parsed_major,
  387. &parsed_minor, &parsed_patch, &parsed_tweak);
  388. switch (this->VersionCount) {
  389. case 4:
  390. this->VersionTweak = parsed_tweak;
  391. CM_FALLTHROUGH;
  392. case 3:
  393. this->VersionPatch = parsed_patch;
  394. CM_FALLTHROUGH;
  395. case 2:
  396. this->VersionMinor = parsed_minor;
  397. CM_FALLTHROUGH;
  398. case 1:
  399. this->VersionMajor = parsed_major;
  400. CM_FALLTHROUGH;
  401. default:
  402. break;
  403. }
  404. }
  405. std::string disableFindPackageVar = "CMAKE_DISABLE_FIND_PACKAGE_";
  406. disableFindPackageVar += this->Name;
  407. if (this->Makefile->IsOn(disableFindPackageVar)) {
  408. if (this->Required) {
  409. std::ostringstream e;
  410. e << "for module " << this->Name << " called with REQUIRED, but "
  411. << disableFindPackageVar
  412. << " is enabled. A REQUIRED package cannot be disabled.";
  413. this->SetError(e.str());
  414. return false;
  415. }
  416. return true;
  417. }
  418. {
  419. // Allocate a PACKAGE_ROOT_PATH for the current find_package call.
  420. this->Makefile->FindPackageRootPathStack.emplace_back();
  421. std::vector<std::string>& rootPaths =
  422. *this->Makefile->FindPackageRootPathStack.rbegin();
  423. // Add root paths from <PackageName>_ROOT CMake and environment variables,
  424. // subject to CMP0074.
  425. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0074)) {
  426. case cmPolicies::WARN:
  427. this->Makefile->MaybeWarnCMP0074(this->Name);
  428. CM_FALLTHROUGH;
  429. case cmPolicies::OLD:
  430. // OLD behavior is to ignore the <pkg>_ROOT variables.
  431. break;
  432. case cmPolicies::REQUIRED_IF_USED:
  433. case cmPolicies::REQUIRED_ALWAYS:
  434. this->Makefile->IssueMessage(
  435. cmake::FATAL_ERROR,
  436. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0074));
  437. break;
  438. case cmPolicies::NEW: {
  439. // NEW behavior is to honor the <pkg>_ROOT variables.
  440. std::string const rootVar = this->Name + "_ROOT";
  441. if (const char* pkgRoot = this->Makefile->GetDefinition(rootVar)) {
  442. cmSystemTools::ExpandListArgument(pkgRoot, rootPaths, false);
  443. }
  444. cmSystemTools::GetPath(rootPaths, rootVar.c_str());
  445. } break;
  446. }
  447. }
  448. this->SetModuleVariables(components);
  449. // See if there is a Find<PackageName>.cmake module.
  450. if (this->UseFindModules) {
  451. bool foundModule = false;
  452. if (!this->FindModule(foundModule)) {
  453. this->AppendSuccessInformation();
  454. return false;
  455. }
  456. if (foundModule) {
  457. this->AppendSuccessInformation();
  458. return true;
  459. }
  460. }
  461. if (this->UseFindModules && this->UseConfigFiles &&
  462. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_WARN_NO_MODULE")) {
  463. std::ostringstream aw;
  464. if (this->RequiredCMakeVersion >= CMake_VERSION_ENCODE(2, 8, 8)) {
  465. aw << "find_package called without either MODULE or CONFIG option and "
  466. "no Find"
  467. << this->Name
  468. << ".cmake module is in CMAKE_MODULE_PATH. "
  469. "Add MODULE to exclusively request Module mode and fail if "
  470. "Find"
  471. << this->Name
  472. << ".cmake is missing. "
  473. "Add CONFIG to exclusively request Config mode and search for a "
  474. "package configuration file provided by "
  475. << this->Name << " (" << this->Name << "Config.cmake or "
  476. << cmSystemTools::LowerCase(this->Name) << "-config.cmake). ";
  477. } else {
  478. aw
  479. << "find_package called without NO_MODULE option and no "
  480. "Find"
  481. << this->Name
  482. << ".cmake module is in CMAKE_MODULE_PATH. "
  483. "Add NO_MODULE to exclusively request Config mode and search for a "
  484. "package configuration file provided by "
  485. << this->Name << " (" << this->Name << "Config.cmake or "
  486. << cmSystemTools::LowerCase(this->Name)
  487. << "-config.cmake). "
  488. "Otherwise make Find"
  489. << this->Name
  490. << ".cmake available in "
  491. "CMAKE_MODULE_PATH.";
  492. }
  493. aw << "\n"
  494. "(Variable CMAKE_FIND_PACKAGE_WARN_NO_MODULE enabled this warning.)";
  495. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, aw.str());
  496. }
  497. // No find module. Assume the project has a CMake config file. Use
  498. // a <PackageName>_DIR cache variable to locate it.
  499. this->Variable = this->Name;
  500. this->Variable += "_DIR";
  501. // Add the default name.
  502. if (this->Names.empty()) {
  503. this->Names.push_back(this->Name);
  504. }
  505. // Add the default configs.
  506. if (this->Configs.empty()) {
  507. for (std::string const& n : this->Names) {
  508. std::string config = n;
  509. config += "Config.cmake";
  510. this->Configs.push_back(config);
  511. config = cmSystemTools::LowerCase(n);
  512. config += "-config.cmake";
  513. this->Configs.push_back(std::move(config));
  514. }
  515. }
  516. // get igonored paths from vars and reroot them.
  517. std::vector<std::string> ignored;
  518. this->GetIgnoredPaths(ignored);
  519. this->RerootPaths(ignored);
  520. // Construct a set of ignored paths
  521. this->IgnoredPaths.clear();
  522. this->IgnoredPaths.insert(ignored.begin(), ignored.end());
  523. // Find and load the package.
  524. bool result = this->HandlePackageMode();
  525. this->AppendSuccessInformation();
  526. return result;
  527. }
  528. void cmFindPackageCommand::SetModuleVariables(const std::string& components)
  529. {
  530. this->AddFindDefinition("CMAKE_FIND_PACKAGE_NAME", this->Name.c_str());
  531. // Store the list of components.
  532. std::string components_var = this->Name + "_FIND_COMPONENTS";
  533. this->AddFindDefinition(components_var, components.c_str());
  534. if (this->Quiet) {
  535. // Tell the module that is about to be read that it should find
  536. // quietly.
  537. std::string quietly = this->Name;
  538. quietly += "_FIND_QUIETLY";
  539. this->AddFindDefinition(quietly, "1");
  540. }
  541. if (this->Required) {
  542. // Tell the module that is about to be read that it should report
  543. // a fatal error if the package is not found.
  544. std::string req = this->Name;
  545. req += "_FIND_REQUIRED";
  546. this->AddFindDefinition(req, "1");
  547. }
  548. if (!this->Version.empty()) {
  549. // Tell the module that is about to be read what version of the
  550. // package has been requested.
  551. std::string ver = this->Name;
  552. ver += "_FIND_VERSION";
  553. this->AddFindDefinition(ver, this->Version.c_str());
  554. char buf[64];
  555. sprintf(buf, "%u", this->VersionMajor);
  556. this->AddFindDefinition(ver + "_MAJOR", buf);
  557. sprintf(buf, "%u", this->VersionMinor);
  558. this->AddFindDefinition(ver + "_MINOR", buf);
  559. sprintf(buf, "%u", this->VersionPatch);
  560. this->AddFindDefinition(ver + "_PATCH", buf);
  561. sprintf(buf, "%u", this->VersionTweak);
  562. this->AddFindDefinition(ver + "_TWEAK", buf);
  563. sprintf(buf, "%u", this->VersionCount);
  564. this->AddFindDefinition(ver + "_COUNT", buf);
  565. // Tell the module whether an exact version has been requested.
  566. std::string exact = this->Name;
  567. exact += "_FIND_VERSION_EXACT";
  568. this->AddFindDefinition(exact, this->VersionExact ? "1" : "0");
  569. }
  570. }
  571. void cmFindPackageCommand::AddFindDefinition(const std::string& var,
  572. const char* val)
  573. {
  574. if (const char* old = this->Makefile->GetDefinition(var)) {
  575. this->OriginalDefs[var].exists = true;
  576. this->OriginalDefs[var].value = old;
  577. } else {
  578. this->OriginalDefs[var].exists = false;
  579. }
  580. this->Makefile->AddDefinition(var, val);
  581. }
  582. void cmFindPackageCommand::RestoreFindDefinitions()
  583. {
  584. for (auto const& i : this->OriginalDefs) {
  585. OriginalDef const& od = i.second;
  586. if (od.exists) {
  587. this->Makefile->AddDefinition(i.first, od.value.c_str());
  588. } else {
  589. this->Makefile->RemoveDefinition(i.first);
  590. }
  591. }
  592. }
  593. bool cmFindPackageCommand::FindModule(bool& found)
  594. {
  595. std::string module = "Find";
  596. module += this->Name;
  597. module += ".cmake";
  598. bool system = false;
  599. std::string mfile = this->Makefile->GetModulesFile(module.c_str(), system);
  600. if (!mfile.empty()) {
  601. if (system) {
  602. auto it = this->DeprecatedFindModules.find(this->Name);
  603. if (it != this->DeprecatedFindModules.end()) {
  604. cmPolicies::PolicyStatus status =
  605. this->Makefile->GetPolicyStatus(it->second);
  606. switch (status) {
  607. case cmPolicies::WARN: {
  608. std::ostringstream e;
  609. e << cmPolicies::GetPolicyWarning(it->second) << "\n";
  610. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, e.str());
  611. CM_FALLTHROUGH;
  612. }
  613. case cmPolicies::OLD:
  614. break;
  615. case cmPolicies::REQUIRED_IF_USED:
  616. case cmPolicies::REQUIRED_ALWAYS:
  617. case cmPolicies::NEW:
  618. return true;
  619. }
  620. }
  621. }
  622. // Load the module we found, and set "<name>_FIND_MODULE" to true
  623. // while inside it.
  624. found = true;
  625. std::string var = this->Name;
  626. var += "_FIND_MODULE";
  627. this->Makefile->AddDefinition(var, "1");
  628. bool result = this->ReadListFile(mfile.c_str(), DoPolicyScope);
  629. this->Makefile->RemoveDefinition(var);
  630. return result;
  631. }
  632. return true;
  633. }
  634. bool cmFindPackageCommand::HandlePackageMode()
  635. {
  636. this->ConsideredConfigs.clear();
  637. // Support old capitalization behavior.
  638. std::string upperDir = cmSystemTools::UpperCase(this->Name);
  639. std::string upperFound = cmSystemTools::UpperCase(this->Name);
  640. upperDir += "_DIR";
  641. upperFound += "_FOUND";
  642. // Try to find the config file.
  643. const char* def = this->Makefile->GetDefinition(this->Variable);
  644. // Try to load the config file if the directory is known
  645. bool fileFound = false;
  646. if (this->UseConfigFiles) {
  647. if (!cmSystemTools::IsOff(def)) {
  648. // Get the directory from the variable value.
  649. std::string dir = def;
  650. cmSystemTools::ConvertToUnixSlashes(dir);
  651. // Treat relative paths with respect to the current source dir.
  652. if (!cmSystemTools::FileIsFullPath(dir)) {
  653. dir = "/" + dir;
  654. dir = this->Makefile->GetCurrentSourceDirectory() + dir;
  655. }
  656. // The file location was cached. Look for the correct file.
  657. std::string file;
  658. if (this->FindConfigFile(dir, file)) {
  659. this->FileFound = file;
  660. fileFound = true;
  661. }
  662. def = this->Makefile->GetDefinition(this->Variable);
  663. }
  664. // Search for the config file if it is not already found.
  665. if (cmSystemTools::IsOff(def) || !fileFound) {
  666. fileFound = this->FindConfig();
  667. }
  668. // Sanity check.
  669. if (fileFound && this->FileFound.empty()) {
  670. this->Makefile->IssueMessage(
  671. cmake::INTERNAL_ERROR, "fileFound is true but FileFound is empty!");
  672. fileFound = false;
  673. }
  674. }
  675. std::string foundVar = this->Name;
  676. foundVar += "_FOUND";
  677. std::string notFoundMessageVar = this->Name;
  678. notFoundMessageVar += "_NOT_FOUND_MESSAGE";
  679. std::string notFoundMessage;
  680. // If the directory for the config file was found, try to read the file.
  681. bool result = true;
  682. bool found = false;
  683. bool configFileSetFOUNDFalse = false;
  684. if (fileFound) {
  685. if (this->Makefile->IsDefinitionSet(foundVar) &&
  686. !this->Makefile->IsOn(foundVar)) {
  687. // by removing Foo_FOUND here if it is FALSE, we don't really change
  688. // the situation for the Config file which is about to be included,
  689. // but we make it possible to detect later on whether the Config file
  690. // has set Foo_FOUND to FALSE itself:
  691. this->Makefile->RemoveDefinition(foundVar);
  692. }
  693. this->Makefile->RemoveDefinition(notFoundMessageVar);
  694. // Set the version variables before loading the config file.
  695. // It may override them.
  696. this->StoreVersionFound();
  697. // Parse the configuration file.
  698. if (this->ReadListFile(this->FileFound.c_str(), DoPolicyScope)) {
  699. // The package has been found.
  700. found = true;
  701. // Check whether the Config file has set Foo_FOUND to FALSE:
  702. if (this->Makefile->IsDefinitionSet(foundVar) &&
  703. !this->Makefile->IsOn(foundVar)) {
  704. // we get here if the Config file has set Foo_FOUND actively to FALSE
  705. found = false;
  706. configFileSetFOUNDFalse = true;
  707. notFoundMessage =
  708. this->Makefile->GetSafeDefinition(notFoundMessageVar);
  709. }
  710. } else {
  711. // The configuration file is invalid.
  712. result = false;
  713. }
  714. }
  715. // package not found
  716. if (result && !found) {
  717. // warn if package required or neither quiet nor in config mode
  718. if (this->Required ||
  719. !(this->Quiet ||
  720. (this->UseConfigFiles && !this->UseFindModules &&
  721. this->ConsideredConfigs.empty()))) {
  722. // The variable is not set.
  723. std::ostringstream e;
  724. std::ostringstream aw;
  725. if (configFileSetFOUNDFalse) {
  726. /* clang-format off */
  727. e << "Found package configuration file:\n"
  728. " " << this->FileFound << "\n"
  729. "but it set " << foundVar << " to FALSE so package \"" <<
  730. this->Name << "\" is considered to be NOT FOUND.";
  731. /* clang-format on */
  732. if (!notFoundMessage.empty()) {
  733. e << " Reason given by package: \n" << notFoundMessage << "\n";
  734. }
  735. }
  736. // If there are files in ConsideredConfigs, it means that FooConfig.cmake
  737. // have been found, but they didn't have appropriate versions.
  738. else if (!this->ConsideredConfigs.empty()) {
  739. std::vector<ConfigFileInfo>::const_iterator duplicate_end =
  740. cmRemoveDuplicates(this->ConsideredConfigs);
  741. e << "Could not find a configuration file for package \"" << this->Name
  742. << "\" that "
  743. << (this->VersionExact ? "exactly matches" : "is compatible with")
  744. << " requested version \"" << this->Version << "\".\n"
  745. << "The following configuration files were considered but not "
  746. "accepted:\n";
  747. for (std::vector<ConfigFileInfo>::const_iterator i =
  748. this->ConsideredConfigs.begin();
  749. i != duplicate_end; ++i) {
  750. e << " " << i->filename << ", version: " << i->version << "\n";
  751. }
  752. } else {
  753. std::string requestedVersionString;
  754. if (!this->Version.empty()) {
  755. requestedVersionString = " (requested version ";
  756. requestedVersionString += this->Version;
  757. requestedVersionString += ")";
  758. }
  759. if (this->UseConfigFiles) {
  760. if (this->UseFindModules) {
  761. e << "By not providing \"Find" << this->Name
  762. << ".cmake\" in "
  763. "CMAKE_MODULE_PATH this project has asked CMake to find a "
  764. "package configuration file provided by \""
  765. << this->Name
  766. << "\", "
  767. "but CMake did not find one.\n";
  768. }
  769. if (this->Configs.size() == 1) {
  770. e << "Could not find a package configuration file named \""
  771. << this->Configs[0] << "\" provided by package \"" << this->Name
  772. << "\"" << requestedVersionString << ".\n";
  773. } else {
  774. e << "Could not find a package configuration file provided by \""
  775. << this->Name << "\"" << requestedVersionString
  776. << " with any of the following names:\n"
  777. << cmWrap(" ", this->Configs, "", "\n") << "\n";
  778. }
  779. e << "Add the installation prefix of \"" << this->Name
  780. << "\" to "
  781. "CMAKE_PREFIX_PATH or set \""
  782. << this->Variable
  783. << "\" to a "
  784. "directory containing one of the above files. "
  785. "If \""
  786. << this->Name
  787. << "\" provides a separate development "
  788. "package or SDK, be sure it has been installed.";
  789. } else // if(!this->UseFindModules && !this->UseConfigFiles)
  790. {
  791. e << "No \"Find" << this->Name << ".cmake\" found in "
  792. << "CMAKE_MODULE_PATH.";
  793. aw
  794. << "Find" << this->Name
  795. << ".cmake must either be part of this "
  796. "project itself, in this case adjust CMAKE_MODULE_PATH so that "
  797. "it points to the correct location inside its source tree.\n"
  798. "Or it must be installed by a package which has already been "
  799. "found via find_package(). In this case make sure that "
  800. "package has indeed been found and adjust CMAKE_MODULE_PATH to "
  801. "contain the location where that package has installed "
  802. "Find"
  803. << this->Name
  804. << ".cmake. This must be a location "
  805. "provided by that package. This error in general means that "
  806. "the buildsystem of this project is relying on a Find-module "
  807. "without ensuring that it is actually available.\n";
  808. }
  809. }
  810. this->Makefile->IssueMessage(
  811. this->Required ? cmake::FATAL_ERROR : cmake::WARNING, e.str());
  812. if (this->Required) {
  813. cmSystemTools::SetFatalErrorOccured();
  814. }
  815. if (!aw.str().empty()) {
  816. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, aw.str());
  817. }
  818. }
  819. // output result if in config mode but not in quiet mode
  820. else if (!this->Quiet) {
  821. std::ostringstream aw;
  822. aw << "Could NOT find " << this->Name << " (missing: " << this->Name
  823. << "_DIR)";
  824. this->Makefile->DisplayStatus(aw.str().c_str(), -1);
  825. }
  826. }
  827. // Set a variable marking whether the package was found.
  828. this->Makefile->AddDefinition(foundVar, found ? "1" : "0");
  829. // Set a variable naming the configuration file that was found.
  830. std::string fileVar = this->Name;
  831. fileVar += "_CONFIG";
  832. if (found) {
  833. this->Makefile->AddDefinition(fileVar, this->FileFound.c_str());
  834. } else {
  835. this->Makefile->RemoveDefinition(fileVar);
  836. }
  837. std::string consideredConfigsVar = this->Name;
  838. consideredConfigsVar += "_CONSIDERED_CONFIGS";
  839. std::string consideredVersionsVar = this->Name;
  840. consideredVersionsVar += "_CONSIDERED_VERSIONS";
  841. std::string consideredConfigFiles;
  842. std::string consideredVersions;
  843. const char* sep = "";
  844. for (ConfigFileInfo const& i : this->ConsideredConfigs) {
  845. consideredConfigFiles += sep;
  846. consideredVersions += sep;
  847. consideredConfigFiles += i.filename;
  848. consideredVersions += i.version;
  849. sep = ";";
  850. }
  851. this->Makefile->AddDefinition(consideredConfigsVar,
  852. consideredConfigFiles.c_str());
  853. this->Makefile->AddDefinition(consideredVersionsVar,
  854. consideredVersions.c_str());
  855. return result;
  856. }
  857. bool cmFindPackageCommand::FindConfig()
  858. {
  859. // Compute the set of search prefixes.
  860. this->ComputePrefixes();
  861. // Look for the project's configuration file.
  862. bool found = false;
  863. // Search for frameworks.
  864. if (!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly)) {
  865. found = this->FindFrameworkConfig();
  866. }
  867. // Search for apps.
  868. if (!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly)) {
  869. found = this->FindAppBundleConfig();
  870. }
  871. // Search prefixes.
  872. if (!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly)) {
  873. found = this->FindPrefixedConfig();
  874. }
  875. // Search for frameworks.
  876. if (!found && this->SearchFrameworkLast) {
  877. found = this->FindFrameworkConfig();
  878. }
  879. // Search for apps.
  880. if (!found && this->SearchAppBundleLast) {
  881. found = this->FindAppBundleConfig();
  882. }
  883. // Store the entry in the cache so it can be set by the user.
  884. std::string init;
  885. if (found) {
  886. init = cmSystemTools::GetFilenamePath(this->FileFound);
  887. } else {
  888. init = this->Variable + "-NOTFOUND";
  889. }
  890. std::string help =
  891. "The directory containing a CMake configuration file for ";
  892. help += this->Name;
  893. help += ".";
  894. // We force the value since we do not get here if it was already set.
  895. this->Makefile->AddCacheDefinition(this->Variable, init.c_str(),
  896. help.c_str(), cmStateEnums::PATH, true);
  897. return found;
  898. }
  899. bool cmFindPackageCommand::FindPrefixedConfig()
  900. {
  901. std::vector<std::string> const& prefixes = this->SearchPaths;
  902. for (std::string const& p : prefixes) {
  903. if (this->SearchPrefix(p)) {
  904. return true;
  905. }
  906. }
  907. return false;
  908. }
  909. bool cmFindPackageCommand::FindFrameworkConfig()
  910. {
  911. std::vector<std::string> const& prefixes = this->SearchPaths;
  912. for (std::string const& p : prefixes) {
  913. if (this->SearchFrameworkPrefix(p)) {
  914. return true;
  915. }
  916. }
  917. return false;
  918. }
  919. bool cmFindPackageCommand::FindAppBundleConfig()
  920. {
  921. std::vector<std::string> const& prefixes = this->SearchPaths;
  922. for (std::string const& p : prefixes) {
  923. if (this->SearchAppBundlePrefix(p)) {
  924. return true;
  925. }
  926. }
  927. return false;
  928. }
  929. bool cmFindPackageCommand::ReadListFile(const char* f, PolicyScopeRule psr)
  930. {
  931. const bool noPolicyScope = !this->PolicyScope || psr == NoPolicyScope;
  932. if (this->Makefile->ReadDependentFile(f, noPolicyScope)) {
  933. return true;
  934. }
  935. std::string e = "Error reading CMake code from \"";
  936. e += f;
  937. e += "\".";
  938. this->SetError(e);
  939. return false;
  940. }
  941. void cmFindPackageCommand::AppendToFoundProperty(bool found)
  942. {
  943. std::vector<std::string> foundContents;
  944. const char* foundProp =
  945. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_FOUND");
  946. if (foundProp && *foundProp) {
  947. std::string tmp = foundProp;
  948. cmSystemTools::ExpandListArgument(tmp, foundContents, false);
  949. std::vector<std::string>::iterator nameIt =
  950. std::find(foundContents.begin(), foundContents.end(), this->Name);
  951. if (nameIt != foundContents.end()) {
  952. foundContents.erase(nameIt);
  953. }
  954. }
  955. std::vector<std::string> notFoundContents;
  956. const char* notFoundProp =
  957. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_NOT_FOUND");
  958. if (notFoundProp && *notFoundProp) {
  959. std::string tmp = notFoundProp;
  960. cmSystemTools::ExpandListArgument(tmp, notFoundContents, false);
  961. std::vector<std::string>::iterator nameIt =
  962. std::find(notFoundContents.begin(), notFoundContents.end(), this->Name);
  963. if (nameIt != notFoundContents.end()) {
  964. notFoundContents.erase(nameIt);
  965. }
  966. }
  967. if (found) {
  968. foundContents.push_back(this->Name);
  969. } else {
  970. notFoundContents.push_back(this->Name);
  971. }
  972. std::string tmp = cmJoin(foundContents, ";");
  973. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_FOUND", tmp.c_str());
  974. tmp = cmJoin(notFoundContents, ";");
  975. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_NOT_FOUND",
  976. tmp.c_str());
  977. }
  978. void cmFindPackageCommand::AppendSuccessInformation()
  979. {
  980. {
  981. std::string transitivePropName = "_CMAKE_";
  982. transitivePropName += this->Name + "_TRANSITIVE_DEPENDENCY";
  983. this->Makefile->GetState()->SetGlobalProperty(transitivePropName, "False");
  984. }
  985. std::string found = this->Name;
  986. found += "_FOUND";
  987. std::string upperFound = cmSystemTools::UpperCase(found);
  988. const char* upperResult = this->Makefile->GetDefinition(upperFound);
  989. const char* result = this->Makefile->GetDefinition(found);
  990. bool packageFound =
  991. ((cmSystemTools::IsOn(result)) || (cmSystemTools::IsOn(upperResult)));
  992. this->AppendToFoundProperty(packageFound);
  993. // Record whether the find was quiet or not, so this can be used
  994. // e.g. in FeatureSummary.cmake
  995. std::string quietInfoPropName = "_CMAKE_";
  996. quietInfoPropName += this->Name;
  997. quietInfoPropName += "_QUIET";
  998. this->Makefile->GetState()->SetGlobalProperty(
  999. quietInfoPropName, this->Quiet ? "TRUE" : "FALSE");
  1000. // set a global property to record the required version of this package
  1001. std::string versionInfoPropName = "_CMAKE_";
  1002. versionInfoPropName += this->Name;
  1003. versionInfoPropName += "_REQUIRED_VERSION";
  1004. std::string versionInfo;
  1005. if (!this->Version.empty()) {
  1006. versionInfo = this->VersionExact ? "==" : ">=";
  1007. versionInfo += " ";
  1008. versionInfo += this->Version;
  1009. }
  1010. this->Makefile->GetState()->SetGlobalProperty(versionInfoPropName,
  1011. versionInfo.c_str());
  1012. if (this->Required) {
  1013. std::string requiredInfoPropName = "_CMAKE_";
  1014. requiredInfoPropName += this->Name;
  1015. requiredInfoPropName += "_TYPE";
  1016. this->Makefile->GetState()->SetGlobalProperty(requiredInfoPropName,
  1017. "REQUIRED");
  1018. }
  1019. // Restore original state of "_FIND_" variables we set.
  1020. this->RestoreFindDefinitions();
  1021. // Pop the package stack
  1022. this->Makefile->FindPackageRootPathStack.pop_back();
  1023. }
  1024. void cmFindPackageCommand::ComputePrefixes()
  1025. {
  1026. if (!this->NoDefaultPath) {
  1027. if (!this->NoPackageRootPath) {
  1028. this->FillPrefixesPackageRoot();
  1029. }
  1030. if (!this->NoCMakePath) {
  1031. this->FillPrefixesCMakeVariable();
  1032. }
  1033. if (!this->NoCMakeEnvironmentPath) {
  1034. this->FillPrefixesCMakeEnvironment();
  1035. }
  1036. }
  1037. this->FillPrefixesUserHints();
  1038. if (!this->NoDefaultPath) {
  1039. if (!this->NoSystemEnvironmentPath) {
  1040. this->FillPrefixesSystemEnvironment();
  1041. }
  1042. if (!this->NoUserRegistry) {
  1043. this->FillPrefixesUserRegistry();
  1044. }
  1045. if (!this->NoCMakeSystemPath) {
  1046. this->FillPrefixesCMakeSystemVariable();
  1047. }
  1048. if (!this->NoSystemRegistry) {
  1049. this->FillPrefixesSystemRegistry();
  1050. }
  1051. }
  1052. this->FillPrefixesUserGuess();
  1053. this->ComputeFinalPaths();
  1054. }
  1055. void cmFindPackageCommand::FillPrefixesPackageRoot()
  1056. {
  1057. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot];
  1058. // Add the PACKAGE_ROOT_PATH from each enclosing find_package call.
  1059. for (std::deque<std::vector<std::string>>::const_reverse_iterator pkgPaths =
  1060. this->Makefile->FindPackageRootPathStack.rbegin();
  1061. pkgPaths != this->Makefile->FindPackageRootPathStack.rend();
  1062. ++pkgPaths) {
  1063. for (std::string const& path : *pkgPaths) {
  1064. paths.AddPath(path);
  1065. }
  1066. }
  1067. }
  1068. void cmFindPackageCommand::FillPrefixesCMakeEnvironment()
  1069. {
  1070. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment];
  1071. // Check the environment variable with the same name as the cache
  1072. // entry.
  1073. paths.AddEnvPath(this->Variable);
  1074. // And now the general CMake environment variables
  1075. paths.AddEnvPath("CMAKE_PREFIX_PATH");
  1076. paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
  1077. paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
  1078. }
  1079. void cmFindPackageCommand::FillPrefixesCMakeVariable()
  1080. {
  1081. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake];
  1082. paths.AddCMakePath("CMAKE_PREFIX_PATH");
  1083. paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
  1084. paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
  1085. }
  1086. void cmFindPackageCommand::FillPrefixesSystemEnvironment()
  1087. {
  1088. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemEnvironment];
  1089. // Use the system search path to generate prefixes.
  1090. // Relative paths are interpreted with respect to the current
  1091. // working directory.
  1092. std::vector<std::string> tmp;
  1093. cmSystemTools::GetPath(tmp);
  1094. for (std::string const& i : tmp) {
  1095. // If the path is a PREFIX/bin case then add its parent instead.
  1096. if ((cmHasLiteralSuffix(i, "/bin")) || (cmHasLiteralSuffix(i, "/sbin"))) {
  1097. paths.AddPath(cmSystemTools::GetFilenamePath(i));
  1098. } else {
  1099. paths.AddPath(i);
  1100. }
  1101. }
  1102. }
  1103. void cmFindPackageCommand::FillPrefixesUserRegistry()
  1104. {
  1105. #if defined(_WIN32) && !defined(__CYGWIN__)
  1106. this->LoadPackageRegistryWinUser();
  1107. #elif defined(__HAIKU__)
  1108. char dir[B_PATH_NAME_LENGTH];
  1109. if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  1110. B_OK) {
  1111. std::string fname = dir;
  1112. fname += "/cmake/packages/";
  1113. fname += Name;
  1114. this->LoadPackageRegistryDir(fname,
  1115. this->LabeledPaths[PathLabel::UserRegistry]);
  1116. }
  1117. #else
  1118. std::string dir;
  1119. if (cmSystemTools::GetEnv("HOME", dir)) {
  1120. dir += "/.cmake/packages/";
  1121. dir += this->Name;
  1122. this->LoadPackageRegistryDir(dir,
  1123. this->LabeledPaths[PathLabel::UserRegistry]);
  1124. }
  1125. #endif
  1126. }
  1127. void cmFindPackageCommand::FillPrefixesSystemRegistry()
  1128. {
  1129. if (this->NoSystemRegistry || this->NoDefaultPath) {
  1130. return;
  1131. }
  1132. #if defined(_WIN32) && !defined(__CYGWIN__)
  1133. this->LoadPackageRegistryWinSystem();
  1134. #endif
  1135. }
  1136. #if defined(_WIN32) && !defined(__CYGWIN__)
  1137. # include <windows.h>
  1138. // http://msdn.microsoft.com/en-us/library/aa384253%28v=vs.85%29.aspx
  1139. # if !defined(KEY_WOW64_32KEY)
  1140. # define KEY_WOW64_32KEY 0x0200
  1141. # endif
  1142. # if !defined(KEY_WOW64_64KEY)
  1143. # define KEY_WOW64_64KEY 0x0100
  1144. # endif
  1145. void cmFindPackageCommand::LoadPackageRegistryWinUser()
  1146. {
  1147. // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
  1148. this->LoadPackageRegistryWin(true, 0,
  1149. this->LabeledPaths[PathLabel::UserRegistry]);
  1150. }
  1151. void cmFindPackageCommand::LoadPackageRegistryWinSystem()
  1152. {
  1153. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemRegistry];
  1154. // HKEY_LOCAL_MACHINE\\SOFTWARE has separate 32-bit and 64-bit views.
  1155. // Prefer the target platform view first.
  1156. if (this->Makefile->PlatformIs64Bit()) {
  1157. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1158. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1159. } else {
  1160. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1161. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1162. }
  1163. }
  1164. void cmFindPackageCommand::LoadPackageRegistryWin(bool user, unsigned int view,
  1165. cmSearchPath& outPaths)
  1166. {
  1167. std::wstring key = L"Software\\Kitware\\CMake\\Packages\\";
  1168. key += cmsys::Encoding::ToWide(this->Name);
  1169. std::set<std::wstring> bad;
  1170. HKEY hKey;
  1171. if (RegOpenKeyExW(user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, key.c_str(),
  1172. 0, KEY_QUERY_VALUE | view, &hKey) == ERROR_SUCCESS) {
  1173. DWORD valueType = REG_NONE;
  1174. wchar_t name[16383]; // RegEnumValue docs limit name to 32767 _bytes_
  1175. std::vector<wchar_t> data(512);
  1176. bool done = false;
  1177. DWORD index = 0;
  1178. while (!done) {
  1179. DWORD nameSize = static_cast<DWORD>(sizeof(name));
  1180. DWORD dataSize = static_cast<DWORD>(data.size() * sizeof(data[0]));
  1181. switch (RegEnumValueW(hKey, index, name, &nameSize, 0, &valueType,
  1182. (BYTE*)&data[0], &dataSize)) {
  1183. case ERROR_SUCCESS:
  1184. ++index;
  1185. if (valueType == REG_SZ) {
  1186. data[dataSize] = 0;
  1187. if (!this->CheckPackageRegistryEntry(
  1188. cmsys::Encoding::ToNarrow(&data[0]), outPaths)) {
  1189. // The entry is invalid.
  1190. bad.insert(name);
  1191. }
  1192. }
  1193. break;
  1194. case ERROR_MORE_DATA:
  1195. data.resize((dataSize + sizeof(data[0]) - 1) / sizeof(data[0]));
  1196. break;
  1197. case ERROR_NO_MORE_ITEMS:
  1198. default:
  1199. done = true;
  1200. break;
  1201. }
  1202. }
  1203. RegCloseKey(hKey);
  1204. }
  1205. // Remove bad values if possible.
  1206. if (user && !bad.empty() &&
  1207. RegOpenKeyExW(HKEY_CURRENT_USER, key.c_str(), 0, KEY_SET_VALUE | view,
  1208. &hKey) == ERROR_SUCCESS) {
  1209. for (std::wstring const& v : bad) {
  1210. RegDeleteValueW(hKey, v.c_str());
  1211. }
  1212. RegCloseKey(hKey);
  1213. }
  1214. }
  1215. #else
  1216. class cmFindPackageCommandHoldFile
  1217. {
  1218. const char* File;
  1219. public:
  1220. cmFindPackageCommandHoldFile(const char* f)
  1221. : File(f)
  1222. {
  1223. }
  1224. ~cmFindPackageCommandHoldFile()
  1225. {
  1226. if (this->File) {
  1227. cmSystemTools::RemoveFile(this->File);
  1228. }
  1229. }
  1230. void Release() { this->File = nullptr; }
  1231. };
  1232. void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
  1233. cmSearchPath& outPaths)
  1234. {
  1235. cmsys::Directory files;
  1236. if (!files.Load(dir)) {
  1237. return;
  1238. }
  1239. std::string fname;
  1240. for (unsigned long i = 0; i < files.GetNumberOfFiles(); ++i) {
  1241. fname = dir;
  1242. fname += "/";
  1243. fname += files.GetFile(i);
  1244. if (!cmSystemTools::FileIsDirectory(fname)) {
  1245. // Hold this file hostage until it behaves.
  1246. cmFindPackageCommandHoldFile holdFile(fname.c_str());
  1247. // Load the file.
  1248. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  1249. std::string fentry;
  1250. if (fin && cmSystemTools::GetLineFromStream(fin, fentry) &&
  1251. this->CheckPackageRegistryEntry(fentry, outPaths)) {
  1252. // The file references an existing package, so release it.
  1253. holdFile.Release();
  1254. }
  1255. }
  1256. }
  1257. // TODO: Wipe out the directory if it is empty.
  1258. }
  1259. #endif
  1260. bool cmFindPackageCommand::CheckPackageRegistryEntry(const std::string& fname,
  1261. cmSearchPath& outPaths)
  1262. {
  1263. // Parse the content of one package registry entry.
  1264. if (cmSystemTools::FileIsFullPath(fname)) {
  1265. // The first line in the stream is the full path to a file or
  1266. // directory containing the package.
  1267. if (cmSystemTools::FileExists(fname)) {
  1268. // The path exists. Look for the package here.
  1269. if (!cmSystemTools::FileIsDirectory(fname)) {
  1270. outPaths.AddPath(cmSystemTools::GetFilenamePath(fname));
  1271. } else {
  1272. outPaths.AddPath(fname);
  1273. }
  1274. return true;
  1275. }
  1276. // The path does not exist. Assume the stream content is
  1277. // associated with an old package that no longer exists, and
  1278. // delete it to keep the package registry clean.
  1279. return false;
  1280. }
  1281. // The first line in the stream is not the full path to a file or
  1282. // directory. Assume the stream content was created by a future
  1283. // version of CMake that uses a different format, and leave it.
  1284. return true;
  1285. }
  1286. void cmFindPackageCommand::FillPrefixesCMakeSystemVariable()
  1287. {
  1288. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem];
  1289. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  1290. paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
  1291. paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
  1292. }
  1293. void cmFindPackageCommand::FillPrefixesUserGuess()
  1294. {
  1295. cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
  1296. for (std::string const& p : this->UserGuessArgs) {
  1297. paths.AddUserPath(p);
  1298. }
  1299. }
  1300. void cmFindPackageCommand::FillPrefixesUserHints()
  1301. {
  1302. cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
  1303. for (std::string const& p : this->UserHintsArgs) {
  1304. paths.AddUserPath(p);
  1305. }
  1306. }
  1307. bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
  1308. {
  1309. assert(!dir.empty() && dir.back() == '/');
  1310. // Check each path suffix on this directory.
  1311. for (std::string const& s : this->SearchPathSuffixes) {
  1312. std::string d = dir;
  1313. if (!s.empty()) {
  1314. d += s;
  1315. d += "/";
  1316. }
  1317. if (this->CheckDirectory(d)) {
  1318. return true;
  1319. }
  1320. }
  1321. return false;
  1322. }
  1323. bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
  1324. {
  1325. assert(!dir.empty() && dir.back() == '/');
  1326. // Look for the file in this directory.
  1327. std::string d = dir.substr(0, dir.size() - 1);
  1328. if (this->FindConfigFile(d, this->FileFound)) {
  1329. // Remove duplicate slashes.
  1330. cmSystemTools::ConvertToUnixSlashes(this->FileFound);
  1331. return true;
  1332. }
  1333. return false;
  1334. }
  1335. bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
  1336. std::string& file)
  1337. {
  1338. if (this->IgnoredPaths.count(dir)) {
  1339. return false;
  1340. }
  1341. for (std::string const& c : this->Configs) {
  1342. file = dir;
  1343. file += "/";
  1344. file += c;
  1345. if (this->DebugMode) {
  1346. fprintf(stderr, "Checking file [%s]\n", file.c_str());
  1347. }
  1348. if (cmSystemTools::FileExists(file, true) && this->CheckVersion(file)) {
  1349. return true;
  1350. }
  1351. }
  1352. return false;
  1353. }
  1354. bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
  1355. {
  1356. bool result = false; // by default, assume the version is not ok.
  1357. bool haveResult = false;
  1358. std::string version = "unknown";
  1359. // Get the filename without the .cmake extension.
  1360. std::string::size_type pos = config_file.rfind('.');
  1361. std::string version_file_base = config_file.substr(0, pos);
  1362. // Look for foo-config-version.cmake
  1363. std::string version_file = version_file_base;
  1364. version_file += "-version.cmake";
  1365. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1366. result = this->CheckVersionFile(version_file, version);
  1367. haveResult = true;
  1368. }
  1369. // Look for fooConfigVersion.cmake
  1370. version_file = version_file_base;
  1371. version_file += "Version.cmake";
  1372. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1373. result = this->CheckVersionFile(version_file, version);
  1374. haveResult = true;
  1375. }
  1376. // If no version was requested a versionless package is acceptable.
  1377. if (!haveResult && this->Version.empty()) {
  1378. result = true;
  1379. }
  1380. ConfigFileInfo configFileInfo;
  1381. configFileInfo.filename = config_file;
  1382. configFileInfo.version = version;
  1383. this->ConsideredConfigs.push_back(std::move(configFileInfo));
  1384. return result;
  1385. }
  1386. bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
  1387. std::string& result_version)
  1388. {
  1389. // The version file will be loaded in an isolated scope.
  1390. cmMakefile::ScopePushPop varScope(this->Makefile);
  1391. cmMakefile::PolicyPushPop polScope(this->Makefile);
  1392. static_cast<void>(varScope);
  1393. static_cast<void>(polScope);
  1394. // Clear the output variables.
  1395. this->Makefile->RemoveDefinition("PACKAGE_VERSION");
  1396. this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
  1397. this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
  1398. this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
  1399. // Set the input variables.
  1400. this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name.c_str());
  1401. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION", this->Version.c_str());
  1402. char buf[64];
  1403. sprintf(buf, "%u", this->VersionMajor);
  1404. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MAJOR", buf);
  1405. sprintf(buf, "%u", this->VersionMinor);
  1406. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MINOR", buf);
  1407. sprintf(buf, "%u", this->VersionPatch);
  1408. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_PATCH", buf);
  1409. sprintf(buf, "%u", this->VersionTweak);
  1410. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_TWEAK", buf);
  1411. sprintf(buf, "%u", this->VersionCount);
  1412. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COUNT", buf);
  1413. // Load the version check file. Pass NoPolicyScope because we do
  1414. // our own policy push/pop independent of CMP0011.
  1415. bool suitable = false;
  1416. if (this->ReadListFile(version_file.c_str(), NoPolicyScope)) {
  1417. // Check the output variables.
  1418. bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
  1419. bool unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
  1420. if (!okay && !this->VersionExact) {
  1421. okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
  1422. }
  1423. // The package is suitable if the version is okay and not
  1424. // explicitly unsuitable.
  1425. suitable = !unsuitable && (okay || this->Version.empty());
  1426. if (suitable) {
  1427. // Get the version found.
  1428. this->VersionFound =
  1429. this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1430. // Try to parse the version number and store the results that were
  1431. // successfully parsed.
  1432. unsigned int parsed_major;
  1433. unsigned int parsed_minor;
  1434. unsigned int parsed_patch;
  1435. unsigned int parsed_tweak;
  1436. this->VersionFoundCount =
  1437. sscanf(this->VersionFound.c_str(), "%u.%u.%u.%u", &parsed_major,
  1438. &parsed_minor, &parsed_patch, &parsed_tweak);
  1439. switch (this->VersionFoundCount) {
  1440. case 4:
  1441. this->VersionFoundTweak = parsed_tweak;
  1442. CM_FALLTHROUGH;
  1443. case 3:
  1444. this->VersionFoundPatch = parsed_patch;
  1445. CM_FALLTHROUGH;
  1446. case 2:
  1447. this->VersionFoundMinor = parsed_minor;
  1448. CM_FALLTHROUGH;
  1449. case 1:
  1450. this->VersionFoundMajor = parsed_major;
  1451. CM_FALLTHROUGH;
  1452. default:
  1453. break;
  1454. }
  1455. }
  1456. }
  1457. result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1458. if (result_version.empty()) {
  1459. result_version = "unknown";
  1460. }
  1461. // Succeed if the version is suitable.
  1462. return suitable;
  1463. }
  1464. void cmFindPackageCommand::StoreVersionFound()
  1465. {
  1466. // Store the whole version string.
  1467. std::string ver = this->Name;
  1468. ver += "_VERSION";
  1469. if (this->VersionFound.empty()) {
  1470. this->Makefile->RemoveDefinition(ver);
  1471. } else {
  1472. this->Makefile->AddDefinition(ver, this->VersionFound.c_str());
  1473. }
  1474. // Store the version components.
  1475. char buf[64];
  1476. sprintf(buf, "%u", this->VersionFoundMajor);
  1477. this->Makefile->AddDefinition(ver + "_MAJOR", buf);
  1478. sprintf(buf, "%u", this->VersionFoundMinor);
  1479. this->Makefile->AddDefinition(ver + "_MINOR", buf);
  1480. sprintf(buf, "%u", this->VersionFoundPatch);
  1481. this->Makefile->AddDefinition(ver + "_PATCH", buf);
  1482. sprintf(buf, "%u", this->VersionFoundTweak);
  1483. this->Makefile->AddDefinition(ver + "_TWEAK", buf);
  1484. sprintf(buf, "%u", this->VersionFoundCount);
  1485. this->Makefile->AddDefinition(ver + "_COUNT", buf);
  1486. }
  1487. class cmFileListGeneratorBase
  1488. {
  1489. public:
  1490. virtual ~cmFileListGeneratorBase() {}
  1491. protected:
  1492. bool Consider(std::string const& fullPath, cmFileList& listing);
  1493. private:
  1494. bool Search(cmFileList&);
  1495. virtual bool Search(std::string const& parent, cmFileList&) = 0;
  1496. virtual std::unique_ptr<cmFileListGeneratorBase> Clone() const = 0;
  1497. friend class cmFileList;
  1498. cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next);
  1499. std::unique_ptr<cmFileListGeneratorBase> Next;
  1500. };
  1501. class cmFileList
  1502. {
  1503. public:
  1504. cmFileList()
  1505. : Last(nullptr)
  1506. {
  1507. }
  1508. virtual ~cmFileList() {}
  1509. cmFileList& operator/(cmFileListGeneratorBase const& rhs)
  1510. {
  1511. if (this->Last) {
  1512. this->Last = this->Last->SetNext(rhs);
  1513. } else {
  1514. this->First = rhs.Clone();
  1515. this->Last = this->First.get();
  1516. }
  1517. return *this;
  1518. }
  1519. bool Search()
  1520. {
  1521. if (this->First) {
  1522. return this->First->Search(*this);
  1523. }
  1524. return false;
  1525. }
  1526. private:
  1527. virtual bool Visit(std::string const& fullPath) = 0;
  1528. friend class cmFileListGeneratorBase;
  1529. std::unique_ptr<cmFileListGeneratorBase> First;
  1530. cmFileListGeneratorBase* Last;
  1531. };
  1532. class cmFindPackageFileList : public cmFileList
  1533. {
  1534. public:
  1535. cmFindPackageFileList(cmFindPackageCommand* fpc, bool use_suffixes = true)
  1536. : FPC(fpc)
  1537. , UseSuffixes(use_suffixes)
  1538. {
  1539. }
  1540. private:
  1541. bool Visit(std::string const& fullPath) override
  1542. {
  1543. if (this->UseSuffixes) {
  1544. return this->FPC->SearchDirectory(fullPath);
  1545. }
  1546. return this->FPC->CheckDirectory(fullPath);
  1547. }
  1548. cmFindPackageCommand* FPC;
  1549. bool UseSuffixes;
  1550. };
  1551. bool cmFileListGeneratorBase::Search(cmFileList& listing)
  1552. {
  1553. return this->Search("", listing);
  1554. }
  1555. cmFileListGeneratorBase* cmFileListGeneratorBase::SetNext(
  1556. cmFileListGeneratorBase const& next)
  1557. {
  1558. this->Next = next.Clone();
  1559. return this->Next.get();
  1560. }
  1561. bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
  1562. cmFileList& listing)
  1563. {
  1564. if (this->Next) {
  1565. return this->Next->Search(fullPath + "/", listing);
  1566. }
  1567. return listing.Visit(fullPath + "/");
  1568. }
  1569. class cmFileListGeneratorFixed : public cmFileListGeneratorBase
  1570. {
  1571. public:
  1572. cmFileListGeneratorFixed(std::string const& str)
  1573. : String(str)
  1574. {
  1575. }
  1576. cmFileListGeneratorFixed(cmFileListGeneratorFixed const& r)
  1577. : String(r.String)
  1578. {
  1579. }
  1580. private:
  1581. std::string String;
  1582. bool Search(std::string const& parent, cmFileList& lister) override
  1583. {
  1584. std::string fullPath = parent + this->String;
  1585. return this->Consider(fullPath, lister);
  1586. }
  1587. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1588. {
  1589. std::unique_ptr<cmFileListGeneratorBase> g(
  1590. new cmFileListGeneratorFixed(*this));
  1591. return g;
  1592. }
  1593. };
  1594. class cmFileListGeneratorEnumerate : public cmFileListGeneratorBase
  1595. {
  1596. public:
  1597. cmFileListGeneratorEnumerate(std::vector<std::string> const& v)
  1598. : Vector(v)
  1599. {
  1600. }
  1601. cmFileListGeneratorEnumerate(cmFileListGeneratorEnumerate const& r)
  1602. : Vector(r.Vector)
  1603. {
  1604. }
  1605. private:
  1606. std::vector<std::string> const& Vector;
  1607. bool Search(std::string const& parent, cmFileList& lister) override
  1608. {
  1609. for (std::string const& i : this->Vector) {
  1610. if (this->Consider(parent + i, lister)) {
  1611. return true;
  1612. }
  1613. }
  1614. return false;
  1615. }
  1616. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1617. {
  1618. std::unique_ptr<cmFileListGeneratorBase> g(
  1619. new cmFileListGeneratorEnumerate(*this));
  1620. return g;
  1621. }
  1622. };
  1623. class cmFileListGeneratorProject : public cmFileListGeneratorBase
  1624. {
  1625. public:
  1626. cmFileListGeneratorProject(std::vector<std::string> const& names,
  1627. cmFindPackageCommand::SortOrderType so,
  1628. cmFindPackageCommand::SortDirectionType sd)
  1629. : Names(names)
  1630. {
  1631. this->SetSort(so, sd);
  1632. }
  1633. cmFileListGeneratorProject(cmFileListGeneratorProject const& r)
  1634. : Names(r.Names)
  1635. {
  1636. this->SetSort(r.SortOrder, r.SortDirection);
  1637. }
  1638. void SetSort(cmFindPackageCommand::SortOrderType o,
  1639. cmFindPackageCommand::SortDirectionType d)
  1640. {
  1641. SortOrder = o;
  1642. SortDirection = d;
  1643. }
  1644. protected:
  1645. // sort parameters
  1646. cmFindPackageCommand::SortOrderType SortOrder;
  1647. cmFindPackageCommand::SortDirectionType SortDirection;
  1648. private:
  1649. std::vector<std::string> const& Names;
  1650. bool Search(std::string const& parent, cmFileList& lister) override
  1651. {
  1652. // Construct a list of matches.
  1653. std::vector<std::string> matches;
  1654. cmsys::Directory d;
  1655. d.Load(parent);
  1656. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1657. const char* fname = d.GetFile(i);
  1658. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1659. continue;
  1660. }
  1661. for (std::string const& n : this->Names) {
  1662. if (cmsysString_strncasecmp(fname, n.c_str(), n.length()) == 0) {
  1663. matches.push_back(fname);
  1664. }
  1665. }
  1666. }
  1667. // before testing the matches check if there is a specific sorting order to
  1668. // perform
  1669. if (this->SortOrder != cmFindPackageCommand::None) {
  1670. cmFindPackageCommand::Sort(matches.begin(), matches.end(), SortOrder,
  1671. SortDirection);
  1672. }
  1673. for (std::string const& i : matches) {
  1674. if (this->Consider(parent + i, lister)) {
  1675. return true;
  1676. }
  1677. }
  1678. return false;
  1679. }
  1680. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1681. {
  1682. std::unique_ptr<cmFileListGeneratorBase> g(
  1683. new cmFileListGeneratorProject(*this));
  1684. return g;
  1685. }
  1686. };
  1687. class cmFileListGeneratorMacProject : public cmFileListGeneratorBase
  1688. {
  1689. public:
  1690. cmFileListGeneratorMacProject(std::vector<std::string> const& names,
  1691. const char* ext)
  1692. : Names(names)
  1693. , Extension(ext)
  1694. {
  1695. }
  1696. cmFileListGeneratorMacProject(cmFileListGeneratorMacProject const& r)
  1697. : Names(r.Names)
  1698. , Extension(r.Extension)
  1699. {
  1700. }
  1701. private:
  1702. std::vector<std::string> const& Names;
  1703. std::string Extension;
  1704. bool Search(std::string const& parent, cmFileList& lister) override
  1705. {
  1706. // Construct a list of matches.
  1707. std::vector<std::string> matches;
  1708. cmsys::Directory d;
  1709. d.Load(parent);
  1710. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1711. const char* fname = d.GetFile(i);
  1712. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1713. continue;
  1714. }
  1715. for (std::string name : this->Names) {
  1716. name += this->Extension;
  1717. if (cmsysString_strcasecmp(fname, name.c_str()) == 0) {
  1718. matches.push_back(fname);
  1719. }
  1720. }
  1721. }
  1722. for (std::string const& i : matches) {
  1723. if (this->Consider(parent + i, lister)) {
  1724. return true;
  1725. }
  1726. }
  1727. return false;
  1728. }
  1729. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1730. {
  1731. std::unique_ptr<cmFileListGeneratorBase> g(
  1732. new cmFileListGeneratorMacProject(*this));
  1733. return g;
  1734. }
  1735. };
  1736. class cmFileListGeneratorCaseInsensitive : public cmFileListGeneratorBase
  1737. {
  1738. public:
  1739. cmFileListGeneratorCaseInsensitive(std::string const& str)
  1740. : String(str)
  1741. {
  1742. }
  1743. cmFileListGeneratorCaseInsensitive(
  1744. cmFileListGeneratorCaseInsensitive const& r)
  1745. : String(r.String)
  1746. {
  1747. }
  1748. private:
  1749. std::string String;
  1750. bool Search(std::string const& parent, cmFileList& lister) override
  1751. {
  1752. // Look for matching files.
  1753. std::vector<std::string> matches;
  1754. cmsys::Directory d;
  1755. d.Load(parent);
  1756. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1757. const char* fname = d.GetFile(i);
  1758. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1759. continue;
  1760. }
  1761. if (cmsysString_strcasecmp(fname, this->String.c_str()) == 0) {
  1762. if (this->Consider(parent + fname, lister)) {
  1763. return true;
  1764. }
  1765. }
  1766. }
  1767. return false;
  1768. }
  1769. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1770. {
  1771. std::unique_ptr<cmFileListGeneratorBase> g(
  1772. new cmFileListGeneratorCaseInsensitive(*this));
  1773. return g;
  1774. }
  1775. };
  1776. class cmFileListGeneratorGlob : public cmFileListGeneratorBase
  1777. {
  1778. public:
  1779. cmFileListGeneratorGlob(std::string const& str)
  1780. : Pattern(str)
  1781. {
  1782. }
  1783. cmFileListGeneratorGlob(cmFileListGeneratorGlob const& r)
  1784. : Pattern(r.Pattern)
  1785. {
  1786. }
  1787. private:
  1788. std::string Pattern;
  1789. bool Search(std::string const& parent, cmFileList& lister) override
  1790. {
  1791. // Glob the set of matching files.
  1792. std::string expr = parent;
  1793. expr += this->Pattern;
  1794. cmsys::Glob g;
  1795. if (!g.FindFiles(expr)) {
  1796. return false;
  1797. }
  1798. std::vector<std::string> const& files = g.GetFiles();
  1799. // Look for directories among the matches.
  1800. for (std::string const& f : files) {
  1801. if (cmSystemTools::FileIsDirectory(f)) {
  1802. if (this->Consider(f, lister)) {
  1803. return true;
  1804. }
  1805. }
  1806. }
  1807. return false;
  1808. }
  1809. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1810. {
  1811. return cm::make_unique<cmFileListGeneratorGlob>(*this);
  1812. }
  1813. };
  1814. bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
  1815. {
  1816. assert(!prefix_in.empty() && prefix_in.back() == '/');
  1817. if (this->DebugMode) {
  1818. fprintf(stderr, "Checking prefix [%s]\n", prefix_in.c_str());
  1819. }
  1820. // Skip this if the prefix does not exist.
  1821. if (!cmSystemTools::FileIsDirectory(prefix_in)) {
  1822. return false;
  1823. }
  1824. // PREFIX/ (useful on windows or in build trees)
  1825. if (this->SearchDirectory(prefix_in)) {
  1826. return true;
  1827. }
  1828. // Strip the trailing slash because the path generator is about to
  1829. // add one.
  1830. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  1831. // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
  1832. {
  1833. cmFindPackageFileList lister(this);
  1834. lister / cmFileListGeneratorFixed(prefix) /
  1835. cmFileListGeneratorCaseInsensitive("cmake");
  1836. if (lister.Search()) {
  1837. return true;
  1838. }
  1839. }
  1840. // PREFIX/(Foo|foo|FOO).*/
  1841. {
  1842. cmFindPackageFileList lister(this);
  1843. lister / cmFileListGeneratorFixed(prefix) /
  1844. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1845. this->SortDirection);
  1846. if (lister.Search()) {
  1847. return true;
  1848. }
  1849. }
  1850. // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
  1851. {
  1852. cmFindPackageFileList lister(this);
  1853. lister / cmFileListGeneratorFixed(prefix) /
  1854. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1855. this->SortDirection) /
  1856. cmFileListGeneratorCaseInsensitive("cmake");
  1857. if (lister.Search()) {
  1858. return true;
  1859. }
  1860. }
  1861. // Construct list of common install locations (lib and share).
  1862. std::vector<std::string> common;
  1863. if (!this->LibraryArchitecture.empty()) {
  1864. common.push_back("lib/" + this->LibraryArchitecture);
  1865. }
  1866. if (this->UseLib32Paths) {
  1867. common.push_back("lib32");
  1868. }
  1869. if (this->UseLib64Paths) {
  1870. common.push_back("lib64");
  1871. }
  1872. if (this->UseLibx32Paths) {
  1873. common.push_back("libx32");
  1874. }
  1875. common.push_back("lib");
  1876. common.push_back("share");
  1877. // PREFIX/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  1878. {
  1879. cmFindPackageFileList lister(this);
  1880. lister / cmFileListGeneratorFixed(prefix) /
  1881. cmFileListGeneratorEnumerate(common) /
  1882. cmFileListGeneratorFixed("cmake") /
  1883. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1884. this->SortDirection);
  1885. if (lister.Search()) {
  1886. return true;
  1887. }
  1888. }
  1889. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  1890. {
  1891. cmFindPackageFileList lister(this);
  1892. lister / cmFileListGeneratorFixed(prefix) /
  1893. cmFileListGeneratorEnumerate(common) /
  1894. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1895. this->SortDirection);
  1896. if (lister.Search()) {
  1897. return true;
  1898. }
  1899. }
  1900. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  1901. {
  1902. cmFindPackageFileList lister(this);
  1903. lister / cmFileListGeneratorFixed(prefix) /
  1904. cmFileListGeneratorEnumerate(common) /
  1905. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1906. this->SortDirection) /
  1907. cmFileListGeneratorCaseInsensitive("cmake");
  1908. if (lister.Search()) {
  1909. return true;
  1910. }
  1911. }
  1912. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  1913. {
  1914. cmFindPackageFileList lister(this);
  1915. lister / cmFileListGeneratorFixed(prefix) /
  1916. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1917. this->SortDirection) /
  1918. cmFileListGeneratorEnumerate(common) /
  1919. cmFileListGeneratorFixed("cmake") /
  1920. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1921. this->SortDirection);
  1922. if (lister.Search()) {
  1923. return true;
  1924. }
  1925. }
  1926. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  1927. {
  1928. cmFindPackageFileList lister(this);
  1929. lister / cmFileListGeneratorFixed(prefix) /
  1930. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1931. this->SortDirection) /
  1932. cmFileListGeneratorEnumerate(common) /
  1933. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1934. this->SortDirection);
  1935. if (lister.Search()) {
  1936. return true;
  1937. }
  1938. }
  1939. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  1940. {
  1941. cmFindPackageFileList lister(this);
  1942. lister / cmFileListGeneratorFixed(prefix) /
  1943. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1944. this->SortDirection) /
  1945. cmFileListGeneratorEnumerate(common) /
  1946. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1947. this->SortDirection) /
  1948. cmFileListGeneratorCaseInsensitive("cmake");
  1949. if (lister.Search()) {
  1950. return true;
  1951. }
  1952. }
  1953. return false;
  1954. }
  1955. bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
  1956. {
  1957. assert(!prefix_in.empty() && prefix_in.back() == '/');
  1958. if (this->DebugMode) {
  1959. fprintf(stderr, "Checking framework prefix [%s]\n", prefix_in.c_str());
  1960. }
  1961. // Strip the trailing slash because the path generator is about to
  1962. // add one.
  1963. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  1964. // <prefix>/Foo.framework/Resources/
  1965. {
  1966. cmFindPackageFileList lister(this);
  1967. lister / cmFileListGeneratorFixed(prefix) /
  1968. cmFileListGeneratorMacProject(this->Names, ".framework") /
  1969. cmFileListGeneratorFixed("Resources");
  1970. if (lister.Search()) {
  1971. return true;
  1972. }
  1973. }
  1974. // <prefix>/Foo.framework/Resources/CMake/
  1975. {
  1976. cmFindPackageFileList lister(this);
  1977. lister / cmFileListGeneratorFixed(prefix) /
  1978. cmFileListGeneratorMacProject(this->Names, ".framework") /
  1979. cmFileListGeneratorFixed("Resources") /
  1980. cmFileListGeneratorCaseInsensitive("cmake");
  1981. if (lister.Search()) {
  1982. return true;
  1983. }
  1984. }
  1985. // <prefix>/Foo.framework/Versions/*/Resources/
  1986. {
  1987. cmFindPackageFileList lister(this);
  1988. lister / cmFileListGeneratorFixed(prefix) /
  1989. cmFileListGeneratorMacProject(this->Names, ".framework") /
  1990. cmFileListGeneratorFixed("Versions") /
  1991. cmFileListGeneratorGlob("*/Resources");
  1992. if (lister.Search()) {
  1993. return true;
  1994. }
  1995. }
  1996. // <prefix>/Foo.framework/Versions/*/Resources/CMake/
  1997. {
  1998. cmFindPackageFileList lister(this);
  1999. lister / cmFileListGeneratorFixed(prefix) /
  2000. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2001. cmFileListGeneratorFixed("Versions") /
  2002. cmFileListGeneratorGlob("*/Resources") /
  2003. cmFileListGeneratorCaseInsensitive("cmake");
  2004. if (lister.Search()) {
  2005. return true;
  2006. }
  2007. }
  2008. return false;
  2009. }
  2010. bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
  2011. {
  2012. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2013. if (this->DebugMode) {
  2014. fprintf(stderr, "Checking bundle prefix [%s]\n", prefix_in.c_str());
  2015. }
  2016. // Strip the trailing slash because the path generator is about to
  2017. // add one.
  2018. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2019. // <prefix>/Foo.app/Contents/Resources
  2020. {
  2021. cmFindPackageFileList lister(this);
  2022. lister / cmFileListGeneratorFixed(prefix) /
  2023. cmFileListGeneratorMacProject(this->Names, ".app") /
  2024. cmFileListGeneratorFixed("Contents/Resources");
  2025. if (lister.Search()) {
  2026. return true;
  2027. }
  2028. }
  2029. // <prefix>/Foo.app/Contents/Resources/CMake
  2030. {
  2031. cmFindPackageFileList lister(this);
  2032. lister / cmFileListGeneratorFixed(prefix) /
  2033. cmFileListGeneratorMacProject(this->Names, ".app") /
  2034. cmFileListGeneratorFixed("Contents/Resources") /
  2035. cmFileListGeneratorCaseInsensitive("cmake");
  2036. if (lister.Search()) {
  2037. return true;
  2038. }
  2039. }
  2040. return false;
  2041. }
  2042. // TODO: Debug cmsys::Glob double slash problem.