GetPrerequisites.cmake 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file LICENSE.rst or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. GetPrerequisites
  5. ----------------
  6. .. deprecated:: 3.16
  7. Use :command:`file(GET_RUNTIME_DEPENDENCIES)` instead.
  8. This module provides commands to analyze and list the dependencies
  9. (prerequisites) of executable or shared library files. These commands list
  10. the shared libraries (``.dll``, ``.dylib``, or ``.so`` files) required by an
  11. executable or shared library.
  12. Load this module in CMake with:
  13. .. code-block:: cmake
  14. include(GetPrerequisites)
  15. This module determines dependencies using the following platform-specific
  16. tools:
  17. * ``dumpbin`` (Windows)
  18. * ``objdump`` (MinGW on Windows)
  19. * ``ldd`` (Linux/Unix)
  20. * ``otool`` (Apple operating systems)
  21. .. versionchanged:: 3.16
  22. The tool specified by the :variable:`CMAKE_OBJDUMP` variable will be used, if
  23. set.
  24. Commands
  25. ^^^^^^^^
  26. This module provides the following commands:
  27. * :command:`get_prerequisites`
  28. * :command:`list_prerequisites`
  29. * :command:`list_prerequisites_by_glob`
  30. * :command:`gp_append_unique`
  31. * :command:`is_file_executable`
  32. * :command:`gp_item_default_embedded_path`
  33. (projects can override it with ``gp_item_default_embedded_path_override()``)
  34. * :command:`gp_resolve_item`
  35. (projects can override it with ``gp_resolve_item_override()``)
  36. * :command:`gp_resolved_file_type`
  37. (projects can override it with ``gp_resolved_file_type_override()``)
  38. * :command:`gp_file_type`
  39. .. command:: get_prerequisites
  40. Gets the list of shared library files required by specified target:
  41. .. code-block:: cmake
  42. get_prerequisites(<target> <prerequisites-var> <exclude-system> <recurse>
  43. <exepath> <dirs> [<rpaths>])
  44. The list in the variable named ``<prerequisites-var>`` should be empty on
  45. first entry to this command. On exit, ``<prerequisites-var>`` will contain
  46. the list of required shared library files.
  47. The arguments are:
  48. ``<target>``
  49. The full path to an executable or shared library file.
  50. ``<prerequisites-var>``
  51. The name of a CMake variable to contain the results.
  52. ``<exclude-system>``
  53. If set to 1 system prerequisites will be excluded, if set to 0 they will be
  54. included.
  55. ``<recurse>``
  56. If set to 1 all prerequisites will be found recursively, if set to 0 only
  57. direct prerequisites are listed.
  58. ``<exepath>``
  59. The path to the top level executable used for ``@executable_path``
  60. replacement on Apple operating systems.
  61. ``<dirs>``
  62. A list of paths where libraries might be found: these paths are searched
  63. first when a target without any path info is given. Then standard system
  64. locations are also searched: PATH, Framework locations, /usr/lib...
  65. ``<rpaths>``
  66. Optional run-time search paths for an executable file or library to help
  67. find files.
  68. .. versionadded:: 3.14
  69. The variable ``GET_PREREQUISITES_VERBOSE`` can be set to true before calling
  70. this command to enable verbose output.
  71. .. command:: list_prerequisites
  72. Prints a message listing the prerequisites of the specified target:
  73. .. code-block:: cmake
  74. list_prerequisites(<target> [<recurse> [<exclude-system> [<verbose>]]])
  75. The arguments are:
  76. ``<target>``
  77. The name of a shared library or executable target or the full path to a
  78. shared library or executable file.
  79. ``<recurse>``
  80. If set to 1 all prerequisites will be found recursively, if set to 0 only
  81. direct prerequisites are listed.
  82. ``<exclude-system>``
  83. If set to 1 system prerequisites will be excluded, if set to 0 they will be
  84. included.
  85. ``<verbose>``
  86. If set to 0 only the full path names of the prerequisites are printed. If
  87. set to 1 extra information will be displayed.
  88. .. command:: list_prerequisites_by_glob
  89. Prints the prerequisites of shared library and executable files matching a
  90. globbing pattern:
  91. .. code-block:: cmake
  92. list_prerequisites_by_glob(<GLOB|GLOB_RECURSE>
  93. <glob-exp>
  94. [<optional-args>...])
  95. The arguments are:
  96. ``GLOB`` or ``GLOB_RECURSE``
  97. The globbing mode, whether to traverse only the match or also its
  98. subdirectories recursively.
  99. ``<glob-exp>``
  100. A globbing expression used with :command:`file(GLOB)` or
  101. :command:`file(GLOB_RECURSE)` to retrieve a list of matching files. If a
  102. matching file is executable, its prerequisites are listed.
  103. ``<optional-args>...``
  104. Any additional (optional) arguments provided are passed along as the
  105. optional arguments to the ``list_prerequisite()`` calls.
  106. .. command:: gp_append_unique
  107. Appends the value to the list only if it is not already in the list:
  108. .. code-block:: cmake
  109. gp_append_unique(<list-var> <value>)
  110. The arguments are:
  111. ``<value>``
  112. The value to be appended to the list.
  113. ``<list-var>``
  114. The list variable name that will have the value appended only if it is
  115. not already in the list.
  116. .. command:: is_file_executable
  117. Checks if given file is a binary executable:
  118. .. code-block:: cmake
  119. is_file_executable(<file> <result-var>)
  120. This command sets the ``<result-var>`` to 1 if ``<file>`` is a binary
  121. executable; otherwise it sets it to 0.
  122. .. command:: gp_item_default_embedded_path
  123. Determines the reference path for the specified item:
  124. .. code-block:: cmake
  125. gp_item_default_embedded_path(<item> <default-embedded-path-var>)
  126. This command determines the reference path for ``<item>`` when it is
  127. embedded inside a bundle and stores it to a variable
  128. ``<default-embedded-path-var>``.
  129. Projects can override this command by defining a custom
  130. ``gp_item_default_embedded_path_override()`` command.
  131. .. command:: gp_resolve_item
  132. Resolves a given item into an existing full path file and stores it to a
  133. variable:
  134. .. code-block:: cmake
  135. gp_resolve_item(<context> <item> <exepath> <dirs> <resolved-item-var>
  136. [<rpaths>])
  137. The arguments are:
  138. ``<context>``
  139. The path to the top level loading path used for ``@loader_path`` replacement
  140. on Apple operating systems. When resolving item, ``@loader_path``
  141. references will be resolved relative to the directory of the given context
  142. value (presumably another library).
  143. ``<item>``
  144. The item to resolve.
  145. ``<exepath>``
  146. See the argument description in :command:`get_prerequisites`.
  147. ``<dirs>``
  148. See the argument description in :command:`get_prerequisites`.
  149. ``<resolved-item-var>``
  150. The result variable where the resolved item is stored into.
  151. ``<rpaths>``
  152. See the argument description in :command:`get_prerequisites`.
  153. Projects can override this command by defining a custom
  154. ``gp_resolve_item_override()`` command.
  155. .. command:: gp_resolved_file_type
  156. Determines the type of a given file:
  157. .. code-block:: cmake
  158. gp_resolved_file_type(<original-file> <file> <exepath> <dirs> <type-var>
  159. [<rpaths>])
  160. This command determines the type of ``<file>`` with respect to the
  161. ``<original-file>``. The resulting type of prerequisite is stored in the
  162. ``<type-var>`` variable.
  163. Use ``<exepath>`` and ``<dirs>`` if necessary to resolve non-absolute
  164. ``<file>`` values -- but only for non-embedded items.
  165. ``<rpaths>``
  166. See the argument description in :command:`get_prerequisites`.
  167. The ``<type-var>`` variable will be set to one of the following values:
  168. * ``system``
  169. * ``local``
  170. * ``embedded``
  171. * ``other``
  172. Projects can override this command by defining a custom
  173. ``gp_resolved_file_type_override()`` command.
  174. .. command:: gp_file_type
  175. Determines the type of a given file:
  176. .. code-block:: cmake
  177. gp_file_type(<original-file> <file> <type-var>)
  178. This command determines the type of ``<file>`` with respect to the
  179. ``<original-file>``. The resulting type of prerequisite is stored in the
  180. ``<type-var>`` variable.
  181. The ``<type-var>`` variable will be set to one of the following values:
  182. * ``system``
  183. * ``local``
  184. * ``embedded``
  185. * ``other``
  186. Examples
  187. ^^^^^^^^
  188. Example: Basic Usage
  189. """"""""""""""""""""
  190. Printing all dependencies of a shared library, including system libraries, with
  191. verbose output:
  192. .. code-block:: cmake
  193. include(GetPrerequisites)
  194. list_prerequisites("path/to/libfoo.dylib" 1 0 1)
  195. Example: Upgrading Code
  196. """""""""""""""""""""""
  197. For example:
  198. .. code-block:: cmake
  199. include(GetPrerequisites)
  200. # ...
  201. gp_append_unique(keys "${key}")
  202. the ``gp_append_unique()`` can be in new code replaced with:
  203. .. code-block:: cmake
  204. if(NOT key IN_LIST keys)
  205. list(APPEND keys "${key}")
  206. endif()
  207. #]=======================================================================]
  208. function(gp_append_unique list_var value)
  209. if(NOT value IN_LIST ${list_var})
  210. set(${list_var} ${${list_var}} "${value}" PARENT_SCOPE)
  211. endif()
  212. endfunction()
  213. function(is_file_executable file result_var)
  214. #
  215. # A file is not executable until proven otherwise:
  216. #
  217. set(${result_var} 0 PARENT_SCOPE)
  218. get_filename_component(file_full "${file}" ABSOLUTE)
  219. string(TOLOWER "${file_full}" file_full_lower)
  220. # If file name ends in .exe on Windows, *assume* executable:
  221. #
  222. if(WIN32 AND NOT UNIX)
  223. if("${file_full_lower}" MATCHES "\\.exe$")
  224. set(${result_var} 1 PARENT_SCOPE)
  225. return()
  226. endif()
  227. # A clause could be added here that uses output or return value of dumpbin
  228. # to determine ${result_var}. In 99%+? practical cases, the exe name
  229. # match will be sufficient...
  230. #
  231. endif()
  232. # Use the information returned from the Unix shell command "file" to
  233. # determine if ${file_full} should be considered an executable file...
  234. #
  235. # If the file command's output contains "executable" and does *not* contain
  236. # "text" then it is likely an executable suitable for prerequisite analysis
  237. # via the get_prerequisites macro.
  238. #
  239. if(UNIX)
  240. if(NOT file_cmd)
  241. find_program(file_cmd "file")
  242. mark_as_advanced(file_cmd)
  243. endif()
  244. if(file_cmd)
  245. execute_process(COMMAND "${file_cmd}" "${file_full}"
  246. RESULT_VARIABLE file_rv
  247. OUTPUT_VARIABLE file_ov
  248. ERROR_VARIABLE file_ev
  249. OUTPUT_STRIP_TRAILING_WHITESPACE
  250. )
  251. if(NOT file_rv STREQUAL "0")
  252. message(FATAL_ERROR "${file_cmd} failed: ${file_rv}\n${file_ev}")
  253. endif()
  254. # Replace the name of the file in the output with a placeholder token
  255. # (the string " _file_full_ ") so that just in case the path name of
  256. # the file contains the word "text" or "executable" we are not fooled
  257. # into thinking "the wrong thing" because the file name matches the
  258. # other 'file' command output we are looking for...
  259. #
  260. string(REPLACE "${file_full}" " _file_full_ " file_ov "${file_ov}")
  261. string(TOLOWER "${file_ov}" file_ov)
  262. #message(STATUS "file_ov='${file_ov}'")
  263. if("${file_ov}" MATCHES "executable")
  264. #message(STATUS "executable!")
  265. if("${file_ov}" MATCHES "text")
  266. #message(STATUS "but text, so *not* a binary executable!")
  267. else()
  268. set(${result_var} 1 PARENT_SCOPE)
  269. return()
  270. endif()
  271. endif()
  272. # Also detect position independent executables on Linux,
  273. # where "file" gives "shared object ... (uses shared libraries)"
  274. if("${file_ov}" MATCHES "shared object.*\(uses shared libs\)")
  275. set(${result_var} 1 PARENT_SCOPE)
  276. return()
  277. endif()
  278. # "file" version 5.22 does not print "(used shared libraries)"
  279. # but uses "interpreter"
  280. if("${file_ov}" MATCHES "shared object.*interpreter")
  281. set(${result_var} 1 PARENT_SCOPE)
  282. return()
  283. endif()
  284. else()
  285. message(STATUS "warning: No 'file' command, skipping execute_process...")
  286. endif()
  287. endif()
  288. endfunction()
  289. function(gp_item_default_embedded_path item default_embedded_path_var)
  290. # On Windows and Linux, "embed" prerequisites in the same directory
  291. # as the executable by default:
  292. #
  293. set(path "@executable_path")
  294. # On the Mac, relative to the executable depending on the type
  295. # of the thing we are embedding:
  296. #
  297. if(APPLE)
  298. #
  299. # The assumption here is that all executables in the bundle will be
  300. # in same-level-directories inside the bundle. The parent directory
  301. # of an executable inside the bundle should be MacOS or a sibling of
  302. # MacOS and all embedded paths returned from here will begin with
  303. # "@executable_path/../" and will work from all executables in all
  304. # such same-level-directories inside the bundle.
  305. #
  306. # By default, embed things right next to the main bundle executable:
  307. #
  308. set(path "@executable_path/../../Contents/MacOS")
  309. # Embed frameworks and .dylibs in the embedded "Frameworks" directory
  310. # (sibling of MacOS):
  311. #
  312. if(item MATCHES "[^/]+\\.framework/" OR item MATCHES "\\.dylib$")
  313. set(path "@executable_path/../Frameworks")
  314. endif()
  315. endif()
  316. # Provide a hook so that projects can override the default embedded location
  317. # of any given library by whatever logic they choose:
  318. #
  319. if(COMMAND gp_item_default_embedded_path_override)
  320. gp_item_default_embedded_path_override("${item}" path)
  321. endif()
  322. set(${default_embedded_path_var} "${path}" PARENT_SCOPE)
  323. endfunction()
  324. function(gp_resolve_item context item exepath dirs resolved_item_var)
  325. set(resolved 0)
  326. set(resolved_item "${item}")
  327. if(ARGC GREATER 5)
  328. set(rpaths "${ARGV5}")
  329. else()
  330. set(rpaths "")
  331. endif()
  332. # Is it already resolved?
  333. #
  334. if(IS_ABSOLUTE "${resolved_item}" AND EXISTS "${resolved_item}")
  335. set(resolved 1)
  336. endif()
  337. if(NOT resolved)
  338. if(item MATCHES "^@executable_path")
  339. #
  340. # @executable_path references are assumed relative to exepath
  341. #
  342. string(REPLACE "@executable_path" "${exepath}" ri "${item}")
  343. get_filename_component(ri "${ri}" ABSOLUTE)
  344. if(EXISTS "${ri}")
  345. #message(STATUS "info: embedded item exists (${ri})")
  346. set(resolved 1)
  347. set(resolved_item "${ri}")
  348. else()
  349. message(STATUS "warning: embedded item does not exist '${ri}'")
  350. endif()
  351. endif()
  352. endif()
  353. if(NOT resolved)
  354. if(item MATCHES "^@loader_path")
  355. #
  356. # @loader_path references are assumed relative to the
  357. # PATH of the given "context" (presumably another library)
  358. #
  359. get_filename_component(contextpath "${context}" PATH)
  360. string(REPLACE "@loader_path" "${contextpath}" ri "${item}")
  361. get_filename_component(ri "${ri}" ABSOLUTE)
  362. if(EXISTS "${ri}")
  363. #message(STATUS "info: embedded item exists (${ri})")
  364. set(resolved 1)
  365. set(resolved_item "${ri}")
  366. else()
  367. message(STATUS "warning: embedded item does not exist '${ri}'")
  368. endif()
  369. endif()
  370. endif()
  371. if(NOT resolved)
  372. if(item MATCHES "^@rpath")
  373. #
  374. # @rpath references are relative to the paths built into the binaries with -rpath
  375. # We handle this case like we do for other Unixes
  376. #
  377. string(REPLACE "@rpath/" "" norpath_item "${item}")
  378. set(ri "ri-NOTFOUND")
  379. find_file(ri "${norpath_item}" ${exepath} ${dirs} ${rpaths} NO_DEFAULT_PATH)
  380. if(ri)
  381. #message(STATUS "info: 'find_file' in exepath/dirs/rpaths (${ri})")
  382. set(resolved 1)
  383. set(resolved_item "${ri}")
  384. set(ri "ri-NOTFOUND")
  385. endif()
  386. endif()
  387. endif()
  388. if(NOT resolved)
  389. set(ri "ri-NOTFOUND")
  390. find_file(ri "${item}" ${exepath} ${dirs} NO_DEFAULT_PATH)
  391. find_file(ri "${item}" ${exepath} ${dirs} /usr/lib)
  392. get_filename_component(basename_item "${item}" NAME)
  393. find_file(ri "${basename_item}" PATHS ${exepath} ${dirs} NO_DEFAULT_PATH)
  394. find_file(ri "${basename_item}" PATHS /usr/lib)
  395. if(ri)
  396. #message(STATUS "info: 'find_file' in exepath/dirs (${ri})")
  397. set(resolved 1)
  398. set(resolved_item "${ri}")
  399. set(ri "ri-NOTFOUND")
  400. endif()
  401. endif()
  402. if(NOT resolved)
  403. if(item MATCHES "[^/]+\\.framework/")
  404. set(fw "fw-NOTFOUND")
  405. find_file(fw "${item}"
  406. "~/Library/Frameworks"
  407. "/Library/Frameworks"
  408. "/System/Library/Frameworks"
  409. )
  410. if(fw)
  411. #message(STATUS "info: 'find_file' found framework (${fw})")
  412. set(resolved 1)
  413. set(resolved_item "${fw}")
  414. set(fw "fw-NOTFOUND")
  415. endif()
  416. endif()
  417. endif()
  418. # Using find_program on Windows will find dll files that are in the PATH.
  419. # (Converting simple file names into full path names if found.)
  420. #
  421. if(WIN32 AND NOT UNIX)
  422. if(NOT resolved)
  423. set(ri "ri-NOTFOUND")
  424. find_program(ri "${item}" PATHS ${exepath} ${dirs} NO_DEFAULT_PATH)
  425. find_program(ri "${item}" PATHS ${exepath} ${dirs})
  426. if(ri)
  427. #message(STATUS "info: 'find_program' in exepath/dirs (${ri})")
  428. set(resolved 1)
  429. set(resolved_item "${ri}")
  430. set(ri "ri-NOTFOUND")
  431. endif()
  432. endif()
  433. endif()
  434. # Provide a hook so that projects can override item resolution
  435. # by whatever logic they choose:
  436. #
  437. if(COMMAND gp_resolve_item_override)
  438. gp_resolve_item_override("${context}" "${item}" "${exepath}" "${dirs}" resolved_item resolved)
  439. endif()
  440. if(NOT resolved)
  441. message(STATUS "
  442. warning: cannot resolve item '${item}'
  443. possible problems:
  444. need more directories?
  445. need to use InstallRequiredSystemLibraries?
  446. run in install tree instead of build tree?
  447. ")
  448. # message(STATUS "
  449. #******************************************************************************
  450. #warning: cannot resolve item '${item}'
  451. #
  452. # possible problems:
  453. # need more directories?
  454. # need to use InstallRequiredSystemLibraries?
  455. # run in install tree instead of build tree?
  456. #
  457. # context='${context}'
  458. # item='${item}'
  459. # exepath='${exepath}'
  460. # dirs='${dirs}'
  461. # resolved_item_var='${resolved_item_var}'
  462. #******************************************************************************
  463. #")
  464. endif()
  465. set(${resolved_item_var} "${resolved_item}" PARENT_SCOPE)
  466. endfunction()
  467. function(gp_resolved_file_type original_file file exepath dirs type_var)
  468. if(ARGC GREATER 5)
  469. set(rpaths "${ARGV5}")
  470. else()
  471. set(rpaths "")
  472. endif()
  473. #message(STATUS "**")
  474. if(NOT IS_ABSOLUTE "${original_file}")
  475. message(STATUS "warning: gp_resolved_file_type expects absolute full path for first arg original_file")
  476. endif()
  477. if(IS_ABSOLUTE "${original_file}")
  478. get_filename_component(original_file "${original_file}" ABSOLUTE) # canonicalize path
  479. endif()
  480. set(is_embedded 0)
  481. set(is_local 0)
  482. set(is_system 0)
  483. set(resolved_file "${file}")
  484. if("${file}" MATCHES "^@(executable|loader)_path")
  485. set(is_embedded 1)
  486. endif()
  487. if(NOT is_embedded)
  488. if(NOT IS_ABSOLUTE "${file}")
  489. gp_resolve_item("${original_file}" "${file}" "${exepath}" "${dirs}" resolved_file "${rpaths}")
  490. endif()
  491. if(IS_ABSOLUTE "${resolved_file}")
  492. get_filename_component(resolved_file "${resolved_file}" ABSOLUTE) # canonicalize path
  493. endif()
  494. string(TOLOWER "${original_file}" original_lower)
  495. string(TOLOWER "${resolved_file}" lower)
  496. if(UNIX)
  497. if(resolved_file MATCHES "^/*(/lib/|/lib32/|/libx32/|/lib64/|/usr/lib/|/usr/lib32/|/usr/libx32/|/usr/lib64/|/usr/X11R6/|/usr/bin/)" OR
  498. resolved_file MATCHES "/cce/.*/lib/lib[^/]+\.so\\.[0-9][^/]*$")
  499. set(is_system 1)
  500. endif()
  501. endif()
  502. if(APPLE)
  503. if(resolved_file MATCHES "^(/System/Library/|/usr/lib/)")
  504. set(is_system 1)
  505. endif()
  506. endif()
  507. if(WIN32)
  508. string(TOLOWER "$ENV{SystemRoot}" sysroot)
  509. file(TO_CMAKE_PATH "${sysroot}" sysroot)
  510. string(TOLOWER "$ENV{windir}" windir)
  511. file(TO_CMAKE_PATH "${windir}" windir)
  512. if(lower MATCHES "^(${sysroot}/sys(tem|wow)|${windir}/sys(tem|wow)|(.*/)*(msvc|api-ms-win-|vcruntime)[^/]+dll)")
  513. set(is_system 1)
  514. endif()
  515. if(UNIX)
  516. # if cygwin, we can get the properly formed windows paths from cygpath
  517. find_program(CYGPATH_EXECUTABLE cygpath)
  518. if(CYGPATH_EXECUTABLE)
  519. execute_process(COMMAND ${CYGPATH_EXECUTABLE} -W
  520. RESULT_VARIABLE env_rv
  521. OUTPUT_VARIABLE env_windir
  522. ERROR_VARIABLE env_ev
  523. OUTPUT_STRIP_TRAILING_WHITESPACE)
  524. if(NOT env_rv STREQUAL "0")
  525. message(FATAL_ERROR "${CYGPATH_EXECUTABLE} -W failed: ${env_rv}\n${env_ev}")
  526. endif()
  527. execute_process(COMMAND ${CYGPATH_EXECUTABLE} -S
  528. RESULT_VARIABLE env_rv
  529. OUTPUT_VARIABLE env_sysdir
  530. ERROR_VARIABLE env_ev
  531. OUTPUT_STRIP_TRAILING_WHITESPACE)
  532. if(NOT env_rv STREQUAL "0")
  533. message(FATAL_ERROR "${CYGPATH_EXECUTABLE} -S failed: ${env_rv}\n${env_ev}")
  534. endif()
  535. string(TOLOWER "${env_windir}" windir)
  536. string(TOLOWER "${env_sysdir}" sysroot)
  537. if(lower MATCHES "^(${sysroot}/sys(tem|wow)|${windir}/sys(tem|wow)|(.*/)*(msvc|api-ms-win-|vcruntime)[^/]+dll)")
  538. set(is_system 1)
  539. endif()
  540. endif()
  541. endif()
  542. endif()
  543. if(NOT is_system)
  544. get_filename_component(original_path "${original_lower}" PATH)
  545. get_filename_component(path "${lower}" PATH)
  546. if(original_path STREQUAL path)
  547. set(is_local 1)
  548. else()
  549. string(LENGTH "${original_path}/" original_length)
  550. string(LENGTH "${lower}" path_length)
  551. if(${path_length} GREATER ${original_length})
  552. string(SUBSTRING "${lower}" 0 ${original_length} path)
  553. if("${original_path}/" STREQUAL path)
  554. set(is_embedded 1)
  555. endif()
  556. endif()
  557. endif()
  558. endif()
  559. endif()
  560. # Return type string based on computed booleans:
  561. #
  562. set(type "other")
  563. if(is_system)
  564. set(type "system")
  565. elseif(is_embedded)
  566. set(type "embedded")
  567. elseif(is_local)
  568. set(type "local")
  569. endif()
  570. #message(STATUS "gp_resolved_file_type: '${file}' '${resolved_file}'")
  571. #message(STATUS " type: '${type}'")
  572. if(NOT is_embedded)
  573. if(NOT IS_ABSOLUTE "${resolved_file}")
  574. if(lower MATCHES "^(msvc|api-ms-win-|vcruntime)[^/]+dll" AND is_system)
  575. message(STATUS "info: non-absolute msvc file '${file}' returning type '${type}'")
  576. else()
  577. message(STATUS "warning: gp_resolved_file_type non-absolute file '${file}' returning type '${type}' -- possibly incorrect")
  578. endif()
  579. endif()
  580. endif()
  581. # Provide a hook so that projects can override the decision on whether a
  582. # library belongs to the system or not by whatever logic they choose:
  583. #
  584. if(COMMAND gp_resolved_file_type_override)
  585. gp_resolved_file_type_override("${resolved_file}" type)
  586. endif()
  587. set(${type_var} "${type}" PARENT_SCOPE)
  588. #message(STATUS "**")
  589. endfunction()
  590. function(gp_file_type original_file file type_var)
  591. if(NOT IS_ABSOLUTE "${original_file}")
  592. message(STATUS "warning: gp_file_type expects absolute full path for first arg original_file")
  593. endif()
  594. get_filename_component(exepath "${original_file}" PATH)
  595. set(type "")
  596. gp_resolved_file_type("${original_file}" "${file}" "${exepath}" "" type)
  597. set(${type_var} "${type}" PARENT_SCOPE)
  598. endfunction()
  599. function(get_prerequisites target prerequisites_var exclude_system recurse exepath dirs)
  600. set(verbose 0)
  601. set(eol_char "E")
  602. if(ARGC GREATER 6)
  603. set(rpaths "${ARGV6}")
  604. else()
  605. set(rpaths "")
  606. endif()
  607. if(GET_PREREQUISITES_VERBOSE)
  608. set(verbose 1)
  609. endif()
  610. if(NOT IS_ABSOLUTE "${target}")
  611. message("warning: target '${target}' is not absolute...")
  612. endif()
  613. if(NOT EXISTS "${target}")
  614. message("warning: target '${target}' does not exist...")
  615. return()
  616. endif()
  617. # Check for a script by extension (.bat,.sh,...) or if the file starts with "#!" (shebang)
  618. file(READ ${target} file_contents LIMIT 5)
  619. if(target MATCHES "\\.(bat|c?sh|bash|ksh|cmd)$" OR file_contents MATCHES "^#!")
  620. message(STATUS "GetPrerequisites(${target}) : ignoring script file")
  621. # Clear var
  622. set(${prerequisites_var} "" PARENT_SCOPE)
  623. return()
  624. endif()
  625. set(gp_cmd_paths ${gp_cmd_paths}
  626. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\14.0;InstallDir]/../../VC/bin"
  627. "$ENV{VS140COMNTOOLS}/../../VC/bin"
  628. "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin"
  629. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\12.0;InstallDir]/../../VC/bin"
  630. "$ENV{VS120COMNTOOLS}/../../VC/bin"
  631. "C:/Program Files (x86)/Microsoft Visual Studio 12.0/VC/bin"
  632. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\11.0;InstallDir]/../../VC/bin"
  633. "$ENV{VS110COMNTOOLS}/../../VC/bin"
  634. "C:/Program Files (x86)/Microsoft Visual Studio 11.0/VC/bin"
  635. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\10.0;InstallDir]/../../VC/bin"
  636. "$ENV{VS100COMNTOOLS}/../../VC/bin"
  637. "C:/Program Files (x86)/Microsoft Visual Studio 10.0/VC/bin"
  638. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\9.0;InstallDir]/../../VC/bin"
  639. "$ENV{VS90COMNTOOLS}/../../VC/bin"
  640. "C:/Program Files/Microsoft Visual Studio 9.0/VC/bin"
  641. "C:/Program Files (x86)/Microsoft Visual Studio 9.0/VC/bin"
  642. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\8.0;InstallDir]/../../VC/bin"
  643. "$ENV{VS80COMNTOOLS}/../../VC/bin"
  644. "C:/Program Files/Microsoft Visual Studio 8/VC/BIN"
  645. "C:/Program Files (x86)/Microsoft Visual Studio 8/VC/BIN"
  646. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\7.1;InstallDir]/../../VC7/bin"
  647. "$ENV{VS71COMNTOOLS}/../../VC7/bin"
  648. "C:/Program Files/Microsoft Visual Studio .NET 2003/VC7/BIN"
  649. "C:/Program Files (x86)/Microsoft Visual Studio .NET 2003/VC7/BIN"
  650. )
  651. # <setup-gp_tool-vars>
  652. #
  653. # Try to choose the right tool by default. Caller can set gp_tool prior to
  654. # calling this function to force using a different tool.
  655. #
  656. if(NOT gp_tool)
  657. set(gp_tool "ldd")
  658. if(APPLE)
  659. set(gp_tool "otool")
  660. endif()
  661. if(WIN32 AND NOT UNIX) # This is how to check for cygwin, har!
  662. find_program(gp_dumpbin "dumpbin" PATHS ${gp_cmd_paths})
  663. if(gp_dumpbin)
  664. set(gp_tool "dumpbin")
  665. elseif(CMAKE_OBJDUMP) # Try harder. Maybe we're on MinGW
  666. set(gp_tool "${CMAKE_OBJDUMP}")
  667. else()
  668. set(gp_tool "objdump")
  669. endif()
  670. endif()
  671. endif()
  672. find_program(gp_cmd ${gp_tool} PATHS ${gp_cmd_paths})
  673. if(NOT gp_cmd)
  674. message(STATUS "warning: could not find '${gp_tool}' - cannot analyze prerequisites...")
  675. return()
  676. endif()
  677. set(gp_cmd_maybe_filter) # optional command to pre-filter gp_tool results
  678. if(gp_tool MATCHES "ldd$")
  679. set(gp_cmd_args "")
  680. set(gp_regex "^[\t ]*[^\t ]+ =>[\t ]+([^\t\(]+)( \(.+\))?${eol_char}$")
  681. set(gp_regex_error "not found${eol_char}$")
  682. set(gp_regex_fallback "^[\t ]*([^\t ]+) => ([^\t ]+).*${eol_char}$")
  683. set(gp_regex_cmp_count 1)
  684. elseif(gp_tool MATCHES "otool$")
  685. set(gp_cmd_args "-L")
  686. set(gp_regex "^\t([^\t]+) \\(compatibility version ([0-9]+.[0-9]+.[0-9]+), current version ([0-9]+.[0-9]+.[0-9]+)(, weak)?\\)${eol_char}$")
  687. set(gp_regex_error "")
  688. set(gp_regex_fallback "")
  689. set(gp_regex_cmp_count 3)
  690. elseif(gp_tool MATCHES "dumpbin$")
  691. set(gp_cmd_args "/dependents")
  692. set(gp_regex "^ ([^ ].*[Dd][Ll][Ll])${eol_char}$")
  693. set(gp_regex_error "")
  694. set(gp_regex_fallback "")
  695. set(gp_regex_cmp_count 1)
  696. elseif(gp_tool MATCHES "objdump(\\.exe)?$")
  697. set(gp_cmd_args "-p")
  698. set(gp_regex "^[\t ]*DLL Name: (.*\\.[Dd][Ll][Ll])${eol_char}$")
  699. set(gp_regex_error "")
  700. set(gp_regex_fallback "")
  701. set(gp_regex_cmp_count 1)
  702. # objdump generates copious output so we create a grep filter to pre-filter results
  703. if(WIN32)
  704. find_program(gp_grep_cmd findstr)
  705. set(gp_grep_cmd_arg "")
  706. else()
  707. find_program(gp_grep_cmd grep)
  708. set(gp_grep_cmd_arg "-a")
  709. endif()
  710. if(gp_grep_cmd)
  711. set(gp_cmd_maybe_filter COMMAND ${gp_grep_cmd} "${gp_grep_cmd_arg}" "^[[:blank:]]*DLL Name: ")
  712. endif()
  713. else()
  714. message(STATUS "warning: gp_tool='${gp_tool}' is an unknown tool...")
  715. message(STATUS "CMake function get_prerequisites needs more code to handle '${gp_tool}'")
  716. message(STATUS "Valid gp_tool values are dumpbin, ldd, objdump and otool.")
  717. return()
  718. endif()
  719. if(gp_tool MATCHES "dumpbin$")
  720. # When running dumpbin, it also needs the "Common7/IDE" directory in the
  721. # PATH. It will already be in the PATH if being run from a Visual Studio
  722. # command prompt. Add it to the PATH here in case we are running from a
  723. # different command prompt.
  724. #
  725. get_filename_component(gp_cmd_dir "${gp_cmd}" PATH)
  726. get_filename_component(gp_cmd_dlls_dir "${gp_cmd_dir}/../../Common7/IDE" ABSOLUTE)
  727. # Use cmake paths as a user may have a PATH element ending with a backslash.
  728. # This will escape the list delimiter and create havoc!
  729. if(EXISTS "${gp_cmd_dlls_dir}")
  730. # only add to the path if it is not already in the path
  731. set(gp_found_cmd_dlls_dir 0)
  732. file(TO_CMAKE_PATH "$ENV{PATH}" env_path)
  733. foreach(gp_env_path_element ${env_path})
  734. if(gp_env_path_element STREQUAL gp_cmd_dlls_dir)
  735. set(gp_found_cmd_dlls_dir 1)
  736. endif()
  737. endforeach()
  738. if(NOT gp_found_cmd_dlls_dir)
  739. file(TO_NATIVE_PATH "${gp_cmd_dlls_dir}" gp_cmd_dlls_dir)
  740. set(ENV{PATH} "$ENV{PATH};${gp_cmd_dlls_dir}")
  741. endif()
  742. endif()
  743. endif()
  744. #
  745. # </setup-gp_tool-vars>
  746. if(gp_tool MATCHES "ldd$")
  747. set(old_ld_env "$ENV{LD_LIBRARY_PATH}")
  748. set(new_ld_env "${exepath}")
  749. foreach(dir ${dirs})
  750. string(APPEND new_ld_env ":${dir}")
  751. endforeach()
  752. set(ENV{LD_LIBRARY_PATH} "${new_ld_env}:$ENV{LD_LIBRARY_PATH}")
  753. endif()
  754. # Track new prerequisites at each new level of recursion. Start with an
  755. # empty list at each level:
  756. #
  757. set(unseen_prereqs)
  758. # Run gp_cmd on the target:
  759. #
  760. execute_process(
  761. COMMAND ${gp_cmd} ${gp_cmd_args} ${target}
  762. ${gp_cmd_maybe_filter}
  763. RESULT_VARIABLE gp_rv
  764. OUTPUT_VARIABLE gp_cmd_ov
  765. ERROR_VARIABLE gp_ev
  766. )
  767. if(gp_tool MATCHES "dumpbin$")
  768. # Exclude delay load dependencies under windows (they are listed in dumpbin output after the message below)
  769. string(FIND "${gp_cmd_ov}" "Image has the following delay load dependencies" gp_delayload_pos)
  770. if (${gp_delayload_pos} GREATER -1)
  771. string(SUBSTRING "${gp_cmd_ov}" 0 ${gp_delayload_pos} gp_cmd_ov_no_delayload_deps)
  772. string(SUBSTRING "${gp_cmd_ov}" ${gp_delayload_pos} -1 gp_cmd_ov_delayload_deps)
  773. if (verbose)
  774. message(STATUS "GetPrerequisites(${target}) : ignoring the following delay load dependencies :\n ${gp_cmd_ov_delayload_deps}")
  775. endif()
  776. set(gp_cmd_ov ${gp_cmd_ov_no_delayload_deps})
  777. endif()
  778. endif()
  779. if(NOT gp_rv STREQUAL "0")
  780. if(gp_tool MATCHES "dumpbin$")
  781. # dumpbin error messages seem to go to stdout
  782. message(FATAL_ERROR "${gp_cmd} failed: ${gp_rv}\n${gp_ev}\n${gp_cmd_ov}")
  783. else()
  784. message(FATAL_ERROR "${gp_cmd} failed: ${gp_rv}\n${gp_ev}")
  785. endif()
  786. endif()
  787. if(gp_tool MATCHES "ldd$")
  788. set(ENV{LD_LIBRARY_PATH} "${old_ld_env}")
  789. endif()
  790. if(verbose)
  791. message(STATUS "<RawOutput cmd='${gp_cmd} ${gp_cmd_args} ${target}'>")
  792. message(STATUS "gp_cmd_ov='${gp_cmd_ov}'")
  793. message(STATUS "</RawOutput>")
  794. endif()
  795. get_filename_component(target_dir "${target}" PATH)
  796. # Convert to a list of lines:
  797. #
  798. string(REPLACE ";" "\\;" candidates "${gp_cmd_ov}")
  799. string(REPLACE "\n" "${eol_char};" candidates "${candidates}")
  800. # check for install id and remove it from list, since otool -L can include a
  801. # reference to itself
  802. set(gp_install_id)
  803. if(gp_tool MATCHES "otool$")
  804. execute_process(
  805. COMMAND ${gp_cmd} -D ${target}
  806. RESULT_VARIABLE otool_rv
  807. OUTPUT_VARIABLE gp_install_id_ov
  808. ERROR_VARIABLE otool_ev
  809. )
  810. if(NOT otool_rv STREQUAL "0")
  811. message(FATAL_ERROR "otool -D failed: ${otool_rv}\n${otool_ev}")
  812. endif()
  813. # second line is install name
  814. string(REGEX REPLACE ".*:\n" "" gp_install_id "${gp_install_id_ov}")
  815. if(gp_install_id)
  816. # trim
  817. string(REGEX MATCH "[^\n ].*[^\n ]" gp_install_id "${gp_install_id}")
  818. #message("INSTALL ID is \"${gp_install_id}\"")
  819. endif()
  820. endif()
  821. # Analyze each line for file names that match the regular expression:
  822. #
  823. foreach(candidate ${candidates})
  824. if("${candidate}" MATCHES "${gp_regex}")
  825. # Extract information from each candidate:
  826. if(gp_regex_error AND "${candidate}" MATCHES "${gp_regex_error}")
  827. string(REGEX REPLACE "${gp_regex_fallback}" "\\1" raw_item "${candidate}")
  828. else()
  829. string(REGEX REPLACE "${gp_regex}" "\\1" raw_item "${candidate}")
  830. endif()
  831. if(gp_regex_cmp_count GREATER 1)
  832. string(REGEX REPLACE "${gp_regex}" "\\2" raw_compat_version "${candidate}")
  833. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\1" compat_major_version "${raw_compat_version}")
  834. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\2" compat_minor_version "${raw_compat_version}")
  835. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\3" compat_patch_version "${raw_compat_version}")
  836. endif()
  837. if(gp_regex_cmp_count GREATER 2)
  838. string(REGEX REPLACE "${gp_regex}" "\\3" raw_current_version "${candidate}")
  839. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\1" current_major_version "${raw_current_version}")
  840. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\2" current_minor_version "${raw_current_version}")
  841. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\3" current_patch_version "${raw_current_version}")
  842. endif()
  843. # Use the raw_item as the list entries returned by this function. Use the
  844. # gp_resolve_item function to resolve it to an actual full path file if
  845. # necessary.
  846. #
  847. set(item "${raw_item}")
  848. # Add each item unless it is excluded:
  849. #
  850. set(add_item 1)
  851. if(item STREQUAL gp_install_id)
  852. set(add_item 0)
  853. endif()
  854. if(add_item AND ${exclude_system})
  855. set(type "")
  856. gp_resolved_file_type("${target}" "${item}" "${exepath}" "${dirs}" type "${rpaths}")
  857. if(type STREQUAL "system")
  858. set(add_item 0)
  859. endif()
  860. endif()
  861. if(add_item)
  862. list(LENGTH ${prerequisites_var} list_length_before_append)
  863. gp_append_unique(${prerequisites_var} "${item}")
  864. list(LENGTH ${prerequisites_var} list_length_after_append)
  865. if(${recurse})
  866. # If item was really added, this is the first time we have seen it.
  867. # Add it to unseen_prereqs so that we can recursively add *its*
  868. # prerequisites...
  869. #
  870. # But first: resolve its name to an absolute full path name such
  871. # that the analysis tools can simply accept it as input.
  872. #
  873. if(NOT list_length_before_append EQUAL list_length_after_append)
  874. gp_resolve_item("${target}" "${item}" "${exepath}" "${dirs}" resolved_item "${rpaths}")
  875. if(EXISTS "${resolved_item}")
  876. # Recurse only if we could resolve the item.
  877. # Otherwise the prerequisites_var list will be cleared
  878. set(unseen_prereqs ${unseen_prereqs} "${resolved_item}")
  879. endif()
  880. endif()
  881. endif()
  882. endif()
  883. else()
  884. if(verbose)
  885. message(STATUS "ignoring non-matching line: '${candidate}'")
  886. endif()
  887. endif()
  888. endforeach()
  889. list(LENGTH ${prerequisites_var} prerequisites_var_length)
  890. if(prerequisites_var_length GREATER 0)
  891. list(SORT ${prerequisites_var})
  892. endif()
  893. if(${recurse})
  894. set(more_inputs ${unseen_prereqs})
  895. foreach(input ${more_inputs})
  896. get_prerequisites("${input}" ${prerequisites_var} ${exclude_system} ${recurse} "${exepath}" "${dirs}" "${rpaths}")
  897. endforeach()
  898. endif()
  899. set(${prerequisites_var} ${${prerequisites_var}} PARENT_SCOPE)
  900. endfunction()
  901. function(list_prerequisites target)
  902. if(ARGC GREATER 1 AND NOT "${ARGV1}" STREQUAL "")
  903. set(all "${ARGV1}")
  904. else()
  905. set(all 1)
  906. endif()
  907. if(ARGC GREATER 2 AND NOT "${ARGV2}" STREQUAL "")
  908. set(exclude_system "${ARGV2}")
  909. else()
  910. set(exclude_system 0)
  911. endif()
  912. if(ARGC GREATER 3 AND NOT "${ARGV3}" STREQUAL "")
  913. set(verbose "${ARGV3}")
  914. else()
  915. set(verbose 0)
  916. endif()
  917. set(count 0)
  918. set(count_str "")
  919. set(print_count "${verbose}")
  920. set(print_prerequisite_type "${verbose}")
  921. set(print_target "${verbose}")
  922. set(type_str "")
  923. get_filename_component(exepath "${target}" PATH)
  924. set(prereqs "")
  925. get_prerequisites("${target}" prereqs ${exclude_system} ${all} "${exepath}" "")
  926. if(print_target)
  927. message(STATUS "File '${target}' depends on:")
  928. endif()
  929. foreach(d ${prereqs})
  930. math(EXPR count "${count} + 1")
  931. if(print_count)
  932. set(count_str "${count}. ")
  933. endif()
  934. if(print_prerequisite_type)
  935. gp_file_type("${target}" "${d}" type)
  936. set(type_str " (${type})")
  937. endif()
  938. message(STATUS "${count_str}${d}${type_str}")
  939. endforeach()
  940. endfunction()
  941. function(list_prerequisites_by_glob glob_arg glob_exp)
  942. message(STATUS "=============================================================================")
  943. message(STATUS "List prerequisites of executables matching ${glob_arg} '${glob_exp}'")
  944. message(STATUS "")
  945. file(${glob_arg} file_list ${glob_exp})
  946. foreach(f ${file_list})
  947. is_file_executable("${f}" is_f_executable)
  948. if(is_f_executable)
  949. message(STATUS "=============================================================================")
  950. list_prerequisites("${f}" ${ARGN})
  951. message(STATUS "")
  952. endif()
  953. endforeach()
  954. endfunction()