GetPrerequisites.cmake 33 KB

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