frida 16.2.0 → 16.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (386) hide show
  1. package/BSDmakefile +6 -0
  2. package/Makefile +16 -0
  3. package/README.md +14 -11
  4. package/configure +18 -0
  5. package/configure.bat +22 -0
  6. package/dist/native.js +0 -8
  7. package/lib/application.ts +98 -0
  8. package/lib/authentication.ts +3 -0
  9. package/lib/build.py +50 -0
  10. package/lib/bus.ts +30 -0
  11. package/lib/cancellable.ts +33 -0
  12. package/lib/child.ts +15 -0
  13. package/lib/crash.ts +11 -0
  14. package/lib/device.ts +329 -0
  15. package/lib/device_manager.ts +69 -0
  16. package/lib/endpoint_parameters.ts +56 -0
  17. package/lib/icon.ts +15 -0
  18. package/lib/index.ts +311 -0
  19. package/lib/iostream.ts +78 -0
  20. package/lib/meson.build +53 -0
  21. package/lib/native.ts +9 -0
  22. package/lib/portal_membership.ts +10 -0
  23. package/lib/portal_service.ts +105 -0
  24. package/lib/process.ts +57 -0
  25. package/lib/relay.ts +44 -0
  26. package/lib/script.ts +352 -0
  27. package/lib/session.ts +113 -0
  28. package/lib/signals.ts +45 -0
  29. package/lib/socket_address.ts +35 -0
  30. package/lib/spawn.ts +4 -0
  31. package/lib/system_parameters.ts +78 -0
  32. package/make.bat +23 -0
  33. package/meson.build +160 -0
  34. package/meson.options +11 -0
  35. package/package.json +27 -6
  36. package/releng/deps.py +1133 -0
  37. package/releng/deps.toml +391 -0
  38. package/releng/devkit-assets/frida-core-example-unix.c +188 -0
  39. package/releng/devkit-assets/frida-core-example-windows.c +197 -0
  40. package/releng/devkit-assets/frida-core-example.sln +28 -0
  41. package/releng/devkit-assets/frida-core-example.vcxproj +157 -0
  42. package/releng/devkit-assets/frida-core-example.vcxproj.filters +27 -0
  43. package/releng/devkit-assets/frida-gum-example-unix.c +122 -0
  44. package/releng/devkit-assets/frida-gum-example-windows.c +132 -0
  45. package/releng/devkit-assets/frida-gum-example.sln +28 -0
  46. package/releng/devkit-assets/frida-gum-example.vcxproj +157 -0
  47. package/releng/devkit-assets/frida-gum-example.vcxproj.filters +27 -0
  48. package/releng/devkit-assets/frida-gumjs-example-unix.c +84 -0
  49. package/releng/devkit-assets/frida-gumjs-example-windows.c +91 -0
  50. package/releng/devkit-assets/frida-gumjs-example.sln +28 -0
  51. package/releng/devkit-assets/frida-gumjs-example.vcxproj +157 -0
  52. package/releng/devkit-assets/frida-gumjs-example.vcxproj.filters +27 -0
  53. package/releng/devkit.py +535 -0
  54. package/releng/env.py +420 -0
  55. package/releng/env_android.py +150 -0
  56. package/releng/env_apple.py +176 -0
  57. package/releng/env_generic.py +373 -0
  58. package/releng/frida_version.py +69 -0
  59. package/releng/machine_file.py +44 -0
  60. package/releng/machine_spec.py +290 -0
  61. package/releng/meson/meson.py +27 -0
  62. package/releng/meson/mesonbuild/__init__.py +0 -0
  63. package/releng/meson/mesonbuild/_pathlib.py +63 -0
  64. package/releng/meson/mesonbuild/_typing.py +69 -0
  65. package/releng/meson/mesonbuild/arglist.py +321 -0
  66. package/releng/meson/mesonbuild/ast/__init__.py +23 -0
  67. package/releng/meson/mesonbuild/ast/interpreter.py +441 -0
  68. package/releng/meson/mesonbuild/ast/introspection.py +374 -0
  69. package/releng/meson/mesonbuild/ast/postprocess.py +109 -0
  70. package/releng/meson/mesonbuild/ast/printer.py +620 -0
  71. package/releng/meson/mesonbuild/ast/visitor.py +161 -0
  72. package/releng/meson/mesonbuild/backend/__init__.py +0 -0
  73. package/releng/meson/mesonbuild/backend/backends.py +2047 -0
  74. package/releng/meson/mesonbuild/backend/ninjabackend.py +3808 -0
  75. package/releng/meson/mesonbuild/backend/nonebackend.py +26 -0
  76. package/releng/meson/mesonbuild/backend/vs2010backend.py +2078 -0
  77. package/releng/meson/mesonbuild/backend/vs2012backend.py +35 -0
  78. package/releng/meson/mesonbuild/backend/vs2013backend.py +34 -0
  79. package/releng/meson/mesonbuild/backend/vs2015backend.py +35 -0
  80. package/releng/meson/mesonbuild/backend/vs2017backend.py +59 -0
  81. package/releng/meson/mesonbuild/backend/vs2019backend.py +54 -0
  82. package/releng/meson/mesonbuild/backend/vs2022backend.py +54 -0
  83. package/releng/meson/mesonbuild/backend/xcodebackend.py +1781 -0
  84. package/releng/meson/mesonbuild/build.py +3249 -0
  85. package/releng/meson/mesonbuild/cargo/__init__.py +5 -0
  86. package/releng/meson/mesonbuild/cargo/builder.py +238 -0
  87. package/releng/meson/mesonbuild/cargo/cfg.py +274 -0
  88. package/releng/meson/mesonbuild/cargo/interpreter.py +733 -0
  89. package/releng/meson/mesonbuild/cargo/manifest.py +227 -0
  90. package/releng/meson/mesonbuild/cargo/version.py +95 -0
  91. package/releng/meson/mesonbuild/cmake/__init__.py +28 -0
  92. package/releng/meson/mesonbuild/cmake/common.py +331 -0
  93. package/releng/meson/mesonbuild/cmake/data/__init__.py +0 -0
  94. package/releng/meson/mesonbuild/cmake/data/preload.cmake +82 -0
  95. package/releng/meson/mesonbuild/cmake/executor.py +241 -0
  96. package/releng/meson/mesonbuild/cmake/fileapi.py +324 -0
  97. package/releng/meson/mesonbuild/cmake/generator.py +186 -0
  98. package/releng/meson/mesonbuild/cmake/interpreter.py +1267 -0
  99. package/releng/meson/mesonbuild/cmake/toolchain.py +248 -0
  100. package/releng/meson/mesonbuild/cmake/traceparser.py +814 -0
  101. package/releng/meson/mesonbuild/cmake/tracetargets.py +161 -0
  102. package/releng/meson/mesonbuild/compilers/__init__.py +86 -0
  103. package/releng/meson/mesonbuild/compilers/asm.py +307 -0
  104. package/releng/meson/mesonbuild/compilers/c.py +788 -0
  105. package/releng/meson/mesonbuild/compilers/c_function_attributes.py +143 -0
  106. package/releng/meson/mesonbuild/compilers/compilers.py +1388 -0
  107. package/releng/meson/mesonbuild/compilers/cpp.py +1035 -0
  108. package/releng/meson/mesonbuild/compilers/cs.py +136 -0
  109. package/releng/meson/mesonbuild/compilers/cuda.py +806 -0
  110. package/releng/meson/mesonbuild/compilers/cython.py +91 -0
  111. package/releng/meson/mesonbuild/compilers/d.py +861 -0
  112. package/releng/meson/mesonbuild/compilers/detect.py +1396 -0
  113. package/releng/meson/mesonbuild/compilers/fortran.py +523 -0
  114. package/releng/meson/mesonbuild/compilers/java.py +113 -0
  115. package/releng/meson/mesonbuild/compilers/mixins/__init__.py +0 -0
  116. package/releng/meson/mesonbuild/compilers/mixins/arm.py +167 -0
  117. package/releng/meson/mesonbuild/compilers/mixins/ccrx.py +113 -0
  118. package/releng/meson/mesonbuild/compilers/mixins/clang.py +170 -0
  119. package/releng/meson/mesonbuild/compilers/mixins/clike.py +1330 -0
  120. package/releng/meson/mesonbuild/compilers/mixins/compcert.py +117 -0
  121. package/releng/meson/mesonbuild/compilers/mixins/elbrus.py +93 -0
  122. package/releng/meson/mesonbuild/compilers/mixins/emscripten.py +89 -0
  123. package/releng/meson/mesonbuild/compilers/mixins/gnu.py +629 -0
  124. package/releng/meson/mesonbuild/compilers/mixins/intel.py +167 -0
  125. package/releng/meson/mesonbuild/compilers/mixins/islinker.py +120 -0
  126. package/releng/meson/mesonbuild/compilers/mixins/metrowerks.py +279 -0
  127. package/releng/meson/mesonbuild/compilers/mixins/pgi.py +88 -0
  128. package/releng/meson/mesonbuild/compilers/mixins/ti.py +130 -0
  129. package/releng/meson/mesonbuild/compilers/mixins/visualstudio.py +458 -0
  130. package/releng/meson/mesonbuild/compilers/mixins/xc16.py +111 -0
  131. package/releng/meson/mesonbuild/compilers/objc.py +120 -0
  132. package/releng/meson/mesonbuild/compilers/objcpp.py +102 -0
  133. package/releng/meson/mesonbuild/compilers/rust.py +230 -0
  134. package/releng/meson/mesonbuild/compilers/swift.py +131 -0
  135. package/releng/meson/mesonbuild/compilers/vala.py +121 -0
  136. package/releng/meson/mesonbuild/coredata.py +1532 -0
  137. package/releng/meson/mesonbuild/dependencies/__init__.py +252 -0
  138. package/releng/meson/mesonbuild/dependencies/base.py +663 -0
  139. package/releng/meson/mesonbuild/dependencies/boost.py +1083 -0
  140. package/releng/meson/mesonbuild/dependencies/cmake.py +656 -0
  141. package/releng/meson/mesonbuild/dependencies/coarrays.py +80 -0
  142. package/releng/meson/mesonbuild/dependencies/configtool.py +163 -0
  143. package/releng/meson/mesonbuild/dependencies/cuda.py +295 -0
  144. package/releng/meson/mesonbuild/dependencies/data/CMakeLists.txt +102 -0
  145. package/releng/meson/mesonbuild/dependencies/data/CMakeListsLLVM.txt +204 -0
  146. package/releng/meson/mesonbuild/dependencies/data/CMakePathInfo.txt +31 -0
  147. package/releng/meson/mesonbuild/dependencies/data/__init__.py +0 -0
  148. package/releng/meson/mesonbuild/dependencies/detect.py +225 -0
  149. package/releng/meson/mesonbuild/dependencies/dev.py +707 -0
  150. package/releng/meson/mesonbuild/dependencies/dub.py +424 -0
  151. package/releng/meson/mesonbuild/dependencies/factory.py +146 -0
  152. package/releng/meson/mesonbuild/dependencies/framework.py +111 -0
  153. package/releng/meson/mesonbuild/dependencies/hdf5.py +168 -0
  154. package/releng/meson/mesonbuild/dependencies/misc.py +618 -0
  155. package/releng/meson/mesonbuild/dependencies/mpi.py +231 -0
  156. package/releng/meson/mesonbuild/dependencies/pkgconfig.py +570 -0
  157. package/releng/meson/mesonbuild/dependencies/platform.py +52 -0
  158. package/releng/meson/mesonbuild/dependencies/python.py +431 -0
  159. package/releng/meson/mesonbuild/dependencies/qt.py +484 -0
  160. package/releng/meson/mesonbuild/dependencies/scalapack.py +142 -0
  161. package/releng/meson/mesonbuild/dependencies/ui.py +281 -0
  162. package/releng/meson/mesonbuild/depfile.py +82 -0
  163. package/releng/meson/mesonbuild/envconfig.py +480 -0
  164. package/releng/meson/mesonbuild/environment.py +987 -0
  165. package/releng/meson/mesonbuild/interpreter/__init__.py +47 -0
  166. package/releng/meson/mesonbuild/interpreter/compiler.py +900 -0
  167. package/releng/meson/mesonbuild/interpreter/dependencyfallbacks.py +386 -0
  168. package/releng/meson/mesonbuild/interpreter/interpreter.py +3595 -0
  169. package/releng/meson/mesonbuild/interpreter/interpreterobjects.py +1096 -0
  170. package/releng/meson/mesonbuild/interpreter/kwargs.py +479 -0
  171. package/releng/meson/mesonbuild/interpreter/mesonmain.py +487 -0
  172. package/releng/meson/mesonbuild/interpreter/primitives/__init__.py +29 -0
  173. package/releng/meson/mesonbuild/interpreter/primitives/array.py +108 -0
  174. package/releng/meson/mesonbuild/interpreter/primitives/boolean.py +52 -0
  175. package/releng/meson/mesonbuild/interpreter/primitives/dict.py +88 -0
  176. package/releng/meson/mesonbuild/interpreter/primitives/integer.py +86 -0
  177. package/releng/meson/mesonbuild/interpreter/primitives/range.py +38 -0
  178. package/releng/meson/mesonbuild/interpreter/primitives/string.py +247 -0
  179. package/releng/meson/mesonbuild/interpreter/type_checking.py +853 -0
  180. package/releng/meson/mesonbuild/interpreterbase/__init__.py +126 -0
  181. package/releng/meson/mesonbuild/interpreterbase/_unholder.py +25 -0
  182. package/releng/meson/mesonbuild/interpreterbase/baseobjects.py +174 -0
  183. package/releng/meson/mesonbuild/interpreterbase/decorators.py +806 -0
  184. package/releng/meson/mesonbuild/interpreterbase/disabler.py +35 -0
  185. package/releng/meson/mesonbuild/interpreterbase/exceptions.py +22 -0
  186. package/releng/meson/mesonbuild/interpreterbase/helpers.py +67 -0
  187. package/releng/meson/mesonbuild/interpreterbase/interpreterbase.py +665 -0
  188. package/releng/meson/mesonbuild/interpreterbase/operator.py +32 -0
  189. package/releng/meson/mesonbuild/linkers/__init__.py +20 -0
  190. package/releng/meson/mesonbuild/linkers/base.py +39 -0
  191. package/releng/meson/mesonbuild/linkers/detect.py +229 -0
  192. package/releng/meson/mesonbuild/linkers/linkers.py +1614 -0
  193. package/releng/meson/mesonbuild/mcompile.py +380 -0
  194. package/releng/meson/mesonbuild/mconf.py +368 -0
  195. package/releng/meson/mesonbuild/mdevenv.py +234 -0
  196. package/releng/meson/mesonbuild/mdist.py +376 -0
  197. package/releng/meson/mesonbuild/mesondata.py +38 -0
  198. package/releng/meson/mesonbuild/mesonlib.py +23 -0
  199. package/releng/meson/mesonbuild/mesonmain.py +289 -0
  200. package/releng/meson/mesonbuild/minit.py +204 -0
  201. package/releng/meson/mesonbuild/minstall.py +864 -0
  202. package/releng/meson/mesonbuild/mintro.py +667 -0
  203. package/releng/meson/mesonbuild/mlog.py +542 -0
  204. package/releng/meson/mesonbuild/modules/__init__.py +270 -0
  205. package/releng/meson/mesonbuild/modules/cmake.py +442 -0
  206. package/releng/meson/mesonbuild/modules/cuda.py +377 -0
  207. package/releng/meson/mesonbuild/modules/dlang.py +117 -0
  208. package/releng/meson/mesonbuild/modules/external_project.py +306 -0
  209. package/releng/meson/mesonbuild/modules/fs.py +323 -0
  210. package/releng/meson/mesonbuild/modules/gnome.py +2215 -0
  211. package/releng/meson/mesonbuild/modules/hotdoc.py +487 -0
  212. package/releng/meson/mesonbuild/modules/i18n.py +405 -0
  213. package/releng/meson/mesonbuild/modules/icestorm.py +123 -0
  214. package/releng/meson/mesonbuild/modules/java.py +112 -0
  215. package/releng/meson/mesonbuild/modules/keyval.py +65 -0
  216. package/releng/meson/mesonbuild/modules/modtest.py +33 -0
  217. package/releng/meson/mesonbuild/modules/pkgconfig.py +744 -0
  218. package/releng/meson/mesonbuild/modules/python.py +556 -0
  219. package/releng/meson/mesonbuild/modules/python3.py +85 -0
  220. package/releng/meson/mesonbuild/modules/qt.py +621 -0
  221. package/releng/meson/mesonbuild/modules/qt4.py +23 -0
  222. package/releng/meson/mesonbuild/modules/qt5.py +23 -0
  223. package/releng/meson/mesonbuild/modules/qt6.py +22 -0
  224. package/releng/meson/mesonbuild/modules/rust.py +355 -0
  225. package/releng/meson/mesonbuild/modules/simd.py +114 -0
  226. package/releng/meson/mesonbuild/modules/sourceset.py +291 -0
  227. package/releng/meson/mesonbuild/modules/wayland.py +151 -0
  228. package/releng/meson/mesonbuild/modules/windows.py +207 -0
  229. package/releng/meson/mesonbuild/mparser.py +1114 -0
  230. package/releng/meson/mesonbuild/msetup.py +365 -0
  231. package/releng/meson/mesonbuild/msubprojects.py +764 -0
  232. package/releng/meson/mesonbuild/mtest.py +2201 -0
  233. package/releng/meson/mesonbuild/munstable_coredata.py +107 -0
  234. package/releng/meson/mesonbuild/optinterpreter.py +276 -0
  235. package/releng/meson/mesonbuild/programs.py +367 -0
  236. package/releng/meson/mesonbuild/rewriter.py +1075 -0
  237. package/releng/meson/mesonbuild/scripts/__init__.py +10 -0
  238. package/releng/meson/mesonbuild/scripts/clangformat.py +55 -0
  239. package/releng/meson/mesonbuild/scripts/clangtidy.py +30 -0
  240. package/releng/meson/mesonbuild/scripts/cleantrees.py +35 -0
  241. package/releng/meson/mesonbuild/scripts/cmake_run_ctgt.py +103 -0
  242. package/releng/meson/mesonbuild/scripts/cmd_or_ps.ps1 +17 -0
  243. package/releng/meson/mesonbuild/scripts/copy.py +19 -0
  244. package/releng/meson/mesonbuild/scripts/coverage.py +214 -0
  245. package/releng/meson/mesonbuild/scripts/delwithsuffix.py +27 -0
  246. package/releng/meson/mesonbuild/scripts/depfixer.py +495 -0
  247. package/releng/meson/mesonbuild/scripts/depscan.py +198 -0
  248. package/releng/meson/mesonbuild/scripts/dirchanger.py +20 -0
  249. package/releng/meson/mesonbuild/scripts/env2mfile.py +402 -0
  250. package/releng/meson/mesonbuild/scripts/externalproject.py +106 -0
  251. package/releng/meson/mesonbuild/scripts/gettext.py +86 -0
  252. package/releng/meson/mesonbuild/scripts/gtkdochelper.py +286 -0
  253. package/releng/meson/mesonbuild/scripts/hotdochelper.py +40 -0
  254. package/releng/meson/mesonbuild/scripts/itstool.py +77 -0
  255. package/releng/meson/mesonbuild/scripts/meson_exe.py +115 -0
  256. package/releng/meson/mesonbuild/scripts/msgfmthelper.py +29 -0
  257. package/releng/meson/mesonbuild/scripts/pycompile.py +54 -0
  258. package/releng/meson/mesonbuild/scripts/python_info.py +121 -0
  259. package/releng/meson/mesonbuild/scripts/regen_checker.py +55 -0
  260. package/releng/meson/mesonbuild/scripts/run_tool.py +58 -0
  261. package/releng/meson/mesonbuild/scripts/scanbuild.py +57 -0
  262. package/releng/meson/mesonbuild/scripts/symbolextractor.py +322 -0
  263. package/releng/meson/mesonbuild/scripts/tags.py +44 -0
  264. package/releng/meson/mesonbuild/scripts/test_loaded_modules.py +14 -0
  265. package/releng/meson/mesonbuild/scripts/uninstall.py +41 -0
  266. package/releng/meson/mesonbuild/scripts/vcstagger.py +35 -0
  267. package/releng/meson/mesonbuild/scripts/yasm.py +24 -0
  268. package/releng/meson/mesonbuild/templates/__init__.py +0 -0
  269. package/releng/meson/mesonbuild/templates/cpptemplates.py +143 -0
  270. package/releng/meson/mesonbuild/templates/cstemplates.py +90 -0
  271. package/releng/meson/mesonbuild/templates/ctemplates.py +126 -0
  272. package/releng/meson/mesonbuild/templates/cudatemplates.py +143 -0
  273. package/releng/meson/mesonbuild/templates/dlangtemplates.py +109 -0
  274. package/releng/meson/mesonbuild/templates/fortrantemplates.py +101 -0
  275. package/releng/meson/mesonbuild/templates/javatemplates.py +94 -0
  276. package/releng/meson/mesonbuild/templates/mesontemplates.py +70 -0
  277. package/releng/meson/mesonbuild/templates/objcpptemplates.py +126 -0
  278. package/releng/meson/mesonbuild/templates/objctemplates.py +126 -0
  279. package/releng/meson/mesonbuild/templates/rusttemplates.py +79 -0
  280. package/releng/meson/mesonbuild/templates/samplefactory.py +41 -0
  281. package/releng/meson/mesonbuild/templates/sampleimpl.py +160 -0
  282. package/releng/meson/mesonbuild/templates/valatemplates.py +82 -0
  283. package/releng/meson/mesonbuild/utils/__init__.py +0 -0
  284. package/releng/meson/mesonbuild/utils/core.py +166 -0
  285. package/releng/meson/mesonbuild/utils/platform.py +27 -0
  286. package/releng/meson/mesonbuild/utils/posix.py +32 -0
  287. package/releng/meson/mesonbuild/utils/universal.py +2445 -0
  288. package/releng/meson/mesonbuild/utils/vsenv.py +126 -0
  289. package/releng/meson/mesonbuild/utils/win32.py +29 -0
  290. package/releng/meson/mesonbuild/wrap/__init__.py +59 -0
  291. package/releng/meson/mesonbuild/wrap/wrap.py +846 -0
  292. package/releng/meson/mesonbuild/wrap/wraptool.py +198 -0
  293. package/releng/meson-scripts/BSDmakefile +6 -0
  294. package/releng/meson-scripts/Makefile +16 -0
  295. package/releng/meson-scripts/configure +18 -0
  296. package/releng/meson-scripts/configure.bat +22 -0
  297. package/releng/meson-scripts/make.bat +23 -0
  298. package/releng/meson_configure.py +506 -0
  299. package/releng/meson_make.py +131 -0
  300. package/releng/mkdevkit.py +107 -0
  301. package/releng/mkfatmacho.py +54 -0
  302. package/releng/post-process-oabi.py +97 -0
  303. package/releng/progress.py +14 -0
  304. package/releng/sync-from-upstream.py +185 -0
  305. package/releng/tomlkit/tomlkit/__init__.py +59 -0
  306. package/releng/tomlkit/tomlkit/_compat.py +22 -0
  307. package/releng/tomlkit/tomlkit/_types.py +83 -0
  308. package/releng/tomlkit/tomlkit/_utils.py +158 -0
  309. package/releng/tomlkit/tomlkit/api.py +308 -0
  310. package/releng/tomlkit/tomlkit/container.py +875 -0
  311. package/releng/tomlkit/tomlkit/exceptions.py +227 -0
  312. package/releng/tomlkit/tomlkit/items.py +1967 -0
  313. package/releng/tomlkit/tomlkit/parser.py +1141 -0
  314. package/releng/tomlkit/tomlkit/py.typed +0 -0
  315. package/releng/tomlkit/tomlkit/source.py +180 -0
  316. package/releng/tomlkit/tomlkit/toml_char.py +52 -0
  317. package/releng/tomlkit/tomlkit/toml_document.py +7 -0
  318. package/releng/tomlkit/tomlkit/toml_file.py +58 -0
  319. package/releng/winenv.py +140 -0
  320. package/scripts/adjust-version.py +19 -0
  321. package/scripts/detect-version.py +40 -0
  322. package/scripts/fetch-abi-bits.py +343 -0
  323. package/scripts/install.js +23 -0
  324. package/scripts/package.py +15 -0
  325. package/src/addon.cc +76 -0
  326. package/src/application.cc +148 -0
  327. package/src/application.h +31 -0
  328. package/src/authentication.cc +174 -0
  329. package/src/authentication.h +24 -0
  330. package/src/bus.cc +167 -0
  331. package/src/bus.h +33 -0
  332. package/src/cancellable.cc +117 -0
  333. package/src/cancellable.h +31 -0
  334. package/src/child.cc +150 -0
  335. package/src/child.h +32 -0
  336. package/src/crash.cc +122 -0
  337. package/src/crash.h +30 -0
  338. package/src/device.cc +1302 -0
  339. package/src/device.h +55 -0
  340. package/src/device_manager.cc +362 -0
  341. package/src/device_manager.h +35 -0
  342. package/src/endpoint_parameters.cc +171 -0
  343. package/src/endpoint_parameters.h +28 -0
  344. package/src/glib_context.cc +62 -0
  345. package/src/glib_context.h +29 -0
  346. package/src/glib_object.cc +25 -0
  347. package/src/glib_object.h +37 -0
  348. package/src/iostream.cc +247 -0
  349. package/src/iostream.h +30 -0
  350. package/src/meson.build +26 -0
  351. package/src/operation.h +94 -0
  352. package/src/portal_membership.cc +100 -0
  353. package/src/portal_membership.h +26 -0
  354. package/src/portal_service.cc +401 -0
  355. package/src/portal_service.h +40 -0
  356. package/src/process.cc +135 -0
  357. package/src/process.h +30 -0
  358. package/src/relay.cc +139 -0
  359. package/src/relay.h +31 -0
  360. package/src/runtime.cc +443 -0
  361. package/src/runtime.h +64 -0
  362. package/src/script.cc +301 -0
  363. package/src/script.h +36 -0
  364. package/src/session.cc +860 -0
  365. package/src/session.h +42 -0
  366. package/src/signals.cc +334 -0
  367. package/src/signals.h +47 -0
  368. package/src/spawn.cc +95 -0
  369. package/src/spawn.h +27 -0
  370. package/src/usage_monitor.h +117 -0
  371. package/src/uv_context.cc +118 -0
  372. package/src/uv_context.h +40 -0
  373. package/src/win_delay_load_hook.cc +63 -0
  374. package/subprojects/frida-core.wrap +8 -0
  375. package/subprojects/nan.wrap +9 -0
  376. package/subprojects/packagefiles/nan.patch +13 -0
  377. package/test/data/index.ts +13 -0
  378. package/test/data/unixvictim-linux-x86 +0 -0
  379. package/test/data/unixvictim-linux-x86_64 +0 -0
  380. package/test/data/unixvictim-macos +0 -0
  381. package/test/device.ts +27 -0
  382. package/test/device_manager.ts +16 -0
  383. package/test/labrat.ts +32 -0
  384. package/test/script.ts +176 -0
  385. package/test/session.ts +73 -0
  386. package/tsconfig.json +18 -0
@@ -0,0 +1,3249 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2012-2017 The Meson development team
3
+
4
+ from __future__ import annotations
5
+ from collections import defaultdict, OrderedDict
6
+ from dataclasses import dataclass, field, InitVar
7
+ from functools import lru_cache
8
+ import abc
9
+ import copy
10
+ import hashlib
11
+ import itertools, pathlib
12
+ import os
13
+ import pickle
14
+ import re
15
+ import textwrap
16
+ import typing as T
17
+
18
+ from . import coredata
19
+ from . import dependencies
20
+ from . import mlog
21
+ from . import programs
22
+ from .mesonlib import (
23
+ HoldableObject, SecondLevelHolder,
24
+ File, MesonException, MachineChoice, PerMachine, OrderedSet, listify,
25
+ extract_as_list, typeslistify, stringlistify, classify_unity_sources,
26
+ get_filenames_templates_dict, substitute_values, has_path_sep,
27
+ OptionKey, PerMachineDefaultable,
28
+ MesonBugException, EnvironmentVariables, pickle_load,
29
+ )
30
+ from .compilers import (
31
+ is_header, is_object, is_source, clink_langs, sort_clink, all_languages,
32
+ is_known_suffix, detect_static_linker
33
+ )
34
+ from .interpreterbase import FeatureNew, FeatureDeprecated
35
+
36
+ if T.TYPE_CHECKING:
37
+ from typing_extensions import Literal, TypedDict
38
+
39
+ from . import environment
40
+ from ._typing import ImmutableListProtocol
41
+ from .backend.backends import Backend
42
+ from .compilers import Compiler
43
+ from .interpreter.interpreter import SourceOutputs, Interpreter
44
+ from .interpreter.interpreterobjects import Test
45
+ from .interpreterbase import SubProject
46
+ from .linkers.linkers import StaticLinker
47
+ from .mesonlib import ExecutableSerialisation, FileMode, FileOrString
48
+ from .modules import ModuleState
49
+ from .mparser import BaseNode
50
+ from .wrap import WrapMode
51
+
52
+ GeneratedTypes = T.Union['CustomTarget', 'CustomTargetIndex', 'GeneratedList']
53
+ LibTypes = T.Union['SharedLibrary', 'StaticLibrary', 'CustomTarget', 'CustomTargetIndex']
54
+ BuildTargetTypes = T.Union['BuildTarget', 'CustomTarget', 'CustomTargetIndex']
55
+ ObjectTypes = T.Union[str, 'File', 'ExtractedObjects', 'GeneratedTypes']
56
+
57
+ class DFeatures(TypedDict):
58
+
59
+ unittest: bool
60
+ debug: T.List[T.Union[str, int]]
61
+ import_dirs: T.List[IncludeDirs]
62
+ versions: T.List[T.Union[str, int]]
63
+
64
+ pch_kwargs = {'c_pch', 'cpp_pch'}
65
+
66
+ lang_arg_kwargs = {f'{lang}_args' for lang in all_languages}
67
+ lang_arg_kwargs |= {
68
+ 'd_import_dirs',
69
+ 'd_unittest',
70
+ 'd_module_versions',
71
+ 'd_debug',
72
+ }
73
+
74
+ vala_kwargs = {'vala_header', 'vala_gir', 'vala_vapi'}
75
+ rust_kwargs = {'rust_crate_type', 'rust_dependency_map'}
76
+ cs_kwargs = {'resources', 'cs_args'}
77
+
78
+ buildtarget_kwargs = {
79
+ 'build_by_default',
80
+ 'build_rpath',
81
+ 'dependencies',
82
+ 'extra_files',
83
+ 'gui_app',
84
+ 'link_with',
85
+ 'link_whole',
86
+ 'link_args',
87
+ 'link_depends',
88
+ 'implicit_include_directories',
89
+ 'include_directories',
90
+ 'install',
91
+ 'install_rpath',
92
+ 'install_dir',
93
+ 'install_mode',
94
+ 'install_tag',
95
+ 'name_prefix',
96
+ 'name_suffix',
97
+ 'native',
98
+ 'objects',
99
+ 'override_options',
100
+ 'sources',
101
+ 'gnu_symbol_visibility',
102
+ 'link_language',
103
+ 'win_subsystem',
104
+ }
105
+
106
+ known_build_target_kwargs = (
107
+ buildtarget_kwargs |
108
+ lang_arg_kwargs |
109
+ pch_kwargs |
110
+ vala_kwargs |
111
+ rust_kwargs |
112
+ cs_kwargs)
113
+
114
+ known_exe_kwargs = known_build_target_kwargs | {'implib', 'export_dynamic', 'pie', 'vs_module_defs'}
115
+ known_shlib_kwargs = known_build_target_kwargs | {'version', 'soversion', 'vs_module_defs', 'darwin_versions', 'rust_abi'}
116
+ known_shmod_kwargs = known_build_target_kwargs | {'vs_module_defs', 'rust_abi'}
117
+ known_stlib_kwargs = known_build_target_kwargs | {'pic', 'prelink', 'rust_abi'}
118
+ known_jar_kwargs = known_exe_kwargs | {'main_class', 'java_resources'}
119
+
120
+ def _process_install_tag(install_tag: T.Optional[T.List[T.Optional[str]]],
121
+ num_outputs: int) -> T.List[T.Optional[str]]:
122
+ _install_tag: T.List[T.Optional[str]]
123
+ if not install_tag:
124
+ _install_tag = [None] * num_outputs
125
+ elif len(install_tag) == 1:
126
+ _install_tag = install_tag * num_outputs
127
+ else:
128
+ _install_tag = install_tag
129
+ return _install_tag
130
+
131
+
132
+ @lru_cache(maxsize=None)
133
+ def get_target_macos_dylib_install_name(ld) -> str:
134
+ name = ['@rpath/', ld.prefix, ld.name]
135
+ if ld.soversion is not None:
136
+ name.append('.' + ld.soversion)
137
+ name.append('.dylib')
138
+ return ''.join(name)
139
+
140
+ class InvalidArguments(MesonException):
141
+ pass
142
+
143
+ @dataclass(eq=False)
144
+ class DependencyOverride(HoldableObject):
145
+ dep: dependencies.Dependency
146
+ node: 'BaseNode'
147
+ explicit: bool = True
148
+
149
+ @dataclass(eq=False)
150
+ class Headers(HoldableObject):
151
+ sources: T.List[File]
152
+ install_subdir: T.Optional[str]
153
+ custom_install_dir: T.Optional[str]
154
+ custom_install_mode: 'FileMode'
155
+ subproject: str
156
+ follow_symlinks: T.Optional[bool] = None
157
+
158
+ # TODO: we really don't need any of these methods, but they're preserved to
159
+ # keep APIs relying on them working.
160
+
161
+ def set_install_subdir(self, subdir: str) -> None:
162
+ self.install_subdir = subdir
163
+
164
+ def get_install_subdir(self) -> T.Optional[str]:
165
+ return self.install_subdir
166
+
167
+ def get_sources(self) -> T.List[File]:
168
+ return self.sources
169
+
170
+ def get_custom_install_dir(self) -> T.Optional[str]:
171
+ return self.custom_install_dir
172
+
173
+ def get_custom_install_mode(self) -> 'FileMode':
174
+ return self.custom_install_mode
175
+
176
+
177
+ @dataclass(eq=False)
178
+ class Man(HoldableObject):
179
+ sources: T.List[File]
180
+ custom_install_dir: T.Optional[str]
181
+ custom_install_mode: 'FileMode'
182
+ subproject: str
183
+ locale: T.Optional[str]
184
+
185
+ def get_custom_install_dir(self) -> T.Optional[str]:
186
+ return self.custom_install_dir
187
+
188
+ def get_custom_install_mode(self) -> 'FileMode':
189
+ return self.custom_install_mode
190
+
191
+ def get_sources(self) -> T.List['File']:
192
+ return self.sources
193
+
194
+
195
+ @dataclass(eq=False)
196
+ class EmptyDir(HoldableObject):
197
+ path: str
198
+ install_mode: 'FileMode'
199
+ subproject: str
200
+ install_tag: T.Optional[str] = None
201
+
202
+
203
+ @dataclass(eq=False)
204
+ class InstallDir(HoldableObject):
205
+ source_subdir: str
206
+ installable_subdir: str
207
+ install_dir: str
208
+ install_dir_name: str
209
+ install_mode: 'FileMode'
210
+ exclude: T.Tuple[T.Set[str], T.Set[str]]
211
+ strip_directory: bool
212
+ subproject: str
213
+ from_source_dir: bool = True
214
+ install_tag: T.Optional[str] = None
215
+ follow_symlinks: T.Optional[bool] = None
216
+
217
+ @dataclass(eq=False)
218
+ class DepManifest:
219
+ version: str
220
+ license: T.List[str]
221
+ license_files: T.List[T.Tuple[str, File]]
222
+ subproject: str
223
+
224
+ def to_json(self) -> T.Dict[str, T.Union[str, T.List[str]]]:
225
+ return {
226
+ 'version': self.version,
227
+ 'license': self.license,
228
+ 'license_files': [l[1].relative_name() for l in self.license_files],
229
+ }
230
+
231
+
232
+ # literally everything isn't dataclass stuff
233
+ class Build:
234
+ """A class that holds the status of one build including
235
+ all dependencies and so on.
236
+ """
237
+
238
+ def __init__(self, environment: environment.Environment):
239
+ self.version = coredata.version
240
+ self.project_name = 'name of master project'
241
+ self.project_version = None
242
+ self.environment = environment
243
+ self.projects: PerMachine[T.Dict[SubProject, str]] = PerMachineDefaultable.default(
244
+ environment.is_cross_build(), {}, {})
245
+ self.targets: 'T.OrderedDict[str, T.Union[CustomTarget, BuildTarget]]' = OrderedDict()
246
+ self.targetnames: T.Set[T.Tuple[str, str]] = set() # Set of executable names and their subdir
247
+ self.global_args: PerMachine[T.Dict[str, T.List[str]]] = PerMachine({}, {})
248
+ self.global_link_args: PerMachine[T.Dict[str, T.List[str]]] = PerMachine({}, {})
249
+ self.projects_args: PerMachine[T.Dict[str, T.Dict[str, T.List[str]]]] = PerMachine({}, {})
250
+ self.projects_link_args: PerMachine[T.Dict[str, T.Dict[str, T.List[str]]]] = PerMachine({}, {})
251
+ self.tests: T.List['Test'] = []
252
+ self.benchmarks: T.List['Test'] = []
253
+ self.headers: T.List[Headers] = []
254
+ self.man: T.List[Man] = []
255
+ self.emptydir: T.List[EmptyDir] = []
256
+ self.data: T.List[Data] = []
257
+ self.symlinks: T.List[SymlinkData] = []
258
+ self.static_linker: PerMachine[StaticLinker] = PerMachineDefaultable.default(
259
+ environment.is_cross_build(), None, None)
260
+ self.subprojects: PerMachine[T.Dict[SubProject, str]] = PerMachineDefaultable.default(
261
+ environment.is_cross_build(), {}, {})
262
+ self.subproject_dir = ''
263
+ self.install_scripts: T.List['ExecutableSerialisation'] = []
264
+ self.postconf_scripts: T.List['ExecutableSerialisation'] = []
265
+ self.dist_scripts: T.List['ExecutableSerialisation'] = []
266
+ self.install_dirs: T.List[InstallDir] = []
267
+ self.dep_manifest_name: T.Optional[str] = None
268
+ self.dep_manifest: T.Dict[str, DepManifest] = {}
269
+ self.stdlibs = PerMachine({}, {})
270
+ self.test_setups: T.Dict[str, TestSetup] = {}
271
+ self.test_setup_default_name = None
272
+ self.find_overrides: PerMachine[T.Dict[str, T.Union['Executable', programs.ExternalProgram, programs.OverrideProgram]]] = PerMachineDefaultable.default(
273
+ environment.is_cross_build(), {}, {})
274
+ # The list of all programs that have been searched for.
275
+ self.searched_programs: PerMachine[T.Set[str]] = PerMachineDefaultable.default(
276
+ environment.is_cross_build(), set(), set())
277
+
278
+ # If we are doing a cross build we need two caches, if we're doing a
279
+ # build == host compilation the both caches should point to the same place.
280
+ self.dependency_overrides: PerMachine[T.Dict[T.Tuple, DependencyOverride]] = PerMachineDefaultable.default(
281
+ environment.is_cross_build(), {}, {})
282
+ self.devenv: T.List[EnvironmentVariables] = []
283
+ self.modules: T.List[str] = []
284
+
285
+ def get_build_targets(self):
286
+ build_targets = OrderedDict()
287
+ for name, t in self.targets.items():
288
+ if isinstance(t, BuildTarget):
289
+ build_targets[name] = t
290
+ return build_targets
291
+
292
+ def get_custom_targets(self):
293
+ custom_targets = OrderedDict()
294
+ for name, t in self.targets.items():
295
+ if isinstance(t, CustomTarget):
296
+ custom_targets[name] = t
297
+ return custom_targets
298
+
299
+ def copy(self) -> Build:
300
+ other = Build(self.environment)
301
+ for k, v in self.__dict__.items():
302
+ if isinstance(v, (list, dict, set, OrderedDict)):
303
+ other.__dict__[k] = v.copy()
304
+ else:
305
+ other.__dict__[k] = v
306
+ return other
307
+
308
+ def copy_for_build_machine(self) -> Build:
309
+ if not self.environment.is_cross_build() or self.environment.coredata.is_build_only:
310
+ return self.copy()
311
+ new = copy.copy(self)
312
+ new.environment = self.environment.copy_for_build()
313
+ new.projects = PerMachineDefaultable(self.projects.build.copy()).default_missing()
314
+ new.projects_args = PerMachineDefaultable(self.projects_args.build.copy()).default_missing()
315
+ new.projects_link_args = PerMachineDefaultable(self.projects_link_args.build.copy()).default_missing()
316
+ new.subprojects = PerMachineDefaultable(self.subprojects.build.copy()).default_missing()
317
+ new.find_overrides = PerMachineDefaultable(self.find_overrides.build.copy()).default_missing()
318
+ new.searched_programs = PerMachineDefaultable(self.searched_programs.build.copy()).default_missing()
319
+ new.static_linker = PerMachineDefaultable(self.static_linker.build).default_missing()
320
+ new.dependency_overrides = PerMachineDefaultable(self.dependency_overrides.build).default_missing()
321
+ # TODO: the following doesn't seem like it should be necessary
322
+ new.emptydir = []
323
+ new.headers = []
324
+ new.man = []
325
+ new.data = []
326
+ new.symlinks = []
327
+ new.install_scripts = []
328
+ new.postconf_scripts = []
329
+ new.install_dirs = []
330
+ new.test_setups = {}
331
+ new.test_setup_default_name = None
332
+ # TODO: what about dist scripts?
333
+
334
+ return new
335
+
336
+ def merge(self, other: Build) -> None:
337
+ # TODO: this is incorrect for build-only
338
+ self_is_build_only = self.environment.coredata.is_build_only
339
+ other_is_build_only = other.environment.coredata.is_build_only
340
+ for k, v in other.__dict__.items():
341
+ # This is modified for the build-only config, and we don't want to
342
+ # copy it into the build != host config
343
+ if k == 'environment':
344
+ continue
345
+
346
+ # These are install data, and we don't want to install from a build only config
347
+ if other_is_build_only and k in {'emptydir', 'headers', 'man', 'data', 'symlinks',
348
+ 'install_dirs', 'install_scripts', 'postconf_scripts'}:
349
+ continue
350
+
351
+ if self_is_build_only != other_is_build_only:
352
+ assert self_is_build_only is False, 'We should never merge a multi machine subproject into a single machine subproject, right?'
353
+ # TODO: we likely need to drop some other values we're not going to
354
+ # use like install, man, postconf, etc
355
+ if isinstance(v, PerMachine):
356
+ # In this case v.build is v.host, and they are both for the
357
+ # build machine. As such, we need to take only the build values
358
+ # and not the host values
359
+ pm: PerMachine = getattr(self, k)
360
+ pm.build = v.build
361
+ continue
362
+ setattr(self, k, v)
363
+
364
+ self.environment.coredata.merge(other.environment.coredata)
365
+
366
+ def ensure_static_linker(self, compiler: Compiler) -> None:
367
+ if self.static_linker[compiler.for_machine] is None and compiler.needs_static_linker():
368
+ self.static_linker[compiler.for_machine] = detect_static_linker(self.environment, compiler)
369
+
370
+ def get_project(self) -> str:
371
+ return self.projects.host['']
372
+
373
+ def get_subproject_dir(self):
374
+ return self.subproject_dir
375
+
376
+ def get_targets(self) -> 'T.OrderedDict[str, T.Union[CustomTarget, BuildTarget]]':
377
+ return self.targets
378
+
379
+ def get_tests(self) -> T.List['Test']:
380
+ return self.tests
381
+
382
+ def get_benchmarks(self) -> T.List['Test']:
383
+ return self.benchmarks
384
+
385
+ def get_headers(self) -> T.List['Headers']:
386
+ return self.headers
387
+
388
+ def get_man(self) -> T.List['Man']:
389
+ return self.man
390
+
391
+ def get_data(self) -> T.List['Data']:
392
+ return self.data
393
+
394
+ def get_symlinks(self) -> T.List['SymlinkData']:
395
+ return self.symlinks
396
+
397
+ def get_emptydir(self) -> T.List['EmptyDir']:
398
+ return self.emptydir
399
+
400
+ def get_install_subdirs(self) -> T.List['InstallDir']:
401
+ return self.install_dirs
402
+
403
+ def get_global_args(self, compiler: 'Compiler', for_machine: 'MachineChoice') -> T.List[str]:
404
+ d = self.global_args[for_machine]
405
+ return d.get(compiler.get_language(), [])
406
+
407
+ def get_project_args(self, compiler: 'Compiler', project: str, for_machine: 'MachineChoice') -> T.List[str]:
408
+ d = self.projects_args[for_machine]
409
+ args = d.get(project)
410
+ if not args:
411
+ return []
412
+ return args.get(compiler.get_language(), [])
413
+
414
+ def get_global_link_args(self, compiler: 'Compiler', for_machine: 'MachineChoice') -> T.List[str]:
415
+ d = self.global_link_args[for_machine]
416
+ return d.get(compiler.get_language(), [])
417
+
418
+ def get_project_link_args(self, compiler: 'Compiler', project: str, for_machine: 'MachineChoice') -> T.List[str]:
419
+ d = self.projects_link_args[for_machine]
420
+
421
+ link_args = d.get(project)
422
+ if not link_args:
423
+ return []
424
+
425
+ return link_args.get(compiler.get_language(), [])
426
+
427
+ @dataclass(eq=False)
428
+ class IncludeDirs(HoldableObject):
429
+
430
+ """Internal representation of an include_directories call."""
431
+
432
+ curdir: str
433
+ incdirs: T.List[str]
434
+ is_system: bool
435
+ # Interpreter has validated that all given directories
436
+ # actually exist.
437
+ extra_build_dirs: T.List[str] = field(default_factory=list)
438
+
439
+ # We need to know this for stringifying correctly
440
+ is_build_only_subproject: bool = False
441
+
442
+ def __repr__(self) -> str:
443
+ r = '<{} {}/{}>'
444
+ return r.format(self.__class__.__name__, self.curdir, self.incdirs)
445
+
446
+ def get_curdir(self) -> str:
447
+ return self.curdir
448
+
449
+ def get_incdirs(self) -> T.List[str]:
450
+ return self.incdirs
451
+
452
+ def expand_incdirs(self, builddir: str) -> T.List[IncludeSubdirPair]:
453
+ pairlist = []
454
+
455
+ curdir = self.curdir
456
+ bsubdir = compute_build_subdir(curdir, self.is_build_only_subproject)
457
+ for d in self.incdirs:
458
+ # Avoid superfluous '/.' at the end of paths when d is '.'
459
+ if d not in ('', '.'):
460
+ sdir = os.path.normpath(os.path.join(curdir, d))
461
+ bdir = os.path.normpath(os.path.join(bsubdir, d))
462
+ else:
463
+ sdir = curdir
464
+ bdir = bsubdir
465
+
466
+ # There may be include dirs where a build directory has not been
467
+ # created for some source dir. For example if someone does this:
468
+ #
469
+ # inc = include_directories('foo/bar/baz')
470
+ #
471
+ # But never subdir()s into the actual dir.
472
+ if not os.path.isdir(os.path.join(builddir, bdir)):
473
+ bdir = None
474
+
475
+ pairlist.append(IncludeSubdirPair(sdir, bdir))
476
+
477
+ return pairlist
478
+
479
+ def get_extra_build_dirs(self) -> T.List[str]:
480
+ return self.extra_build_dirs
481
+
482
+ def expand_extra_build_dirs(self) -> T.List[str]:
483
+ dirlist = []
484
+ bsubdir = compute_build_subdir(self.curdir, self.is_build_only_subproject)
485
+ for d in self.extra_build_dirs:
486
+ dirlist.append(os.path.normpath(os.path.join(bsubdir, d)))
487
+ return dirlist
488
+
489
+ def to_string_list(self, sourcedir: str, builddir: str) -> T.List[str]:
490
+ """Convert IncludeDirs object to a list of strings.
491
+
492
+ :param sourcedir: The absolute source directory
493
+ :param builddir: The absolute build directory, option, build dir will not
494
+ be added if this is unset
495
+ :returns: A list of strings (without compiler argument)
496
+ """
497
+ strlist: T.List[str] = []
498
+ for d in self.expand_incdirs(builddir):
499
+ strlist.append(os.path.join(sourcedir, d.source))
500
+ if d.build is not None:
501
+ strlist.append(os.path.join(builddir, d.build))
502
+ return strlist
503
+
504
+ @dataclass
505
+ class IncludeSubdirPair:
506
+ source: str
507
+ build: T.Optional[str]
508
+
509
+ @dataclass(eq=False)
510
+ class ExtractedObjects(HoldableObject):
511
+ '''
512
+ Holds a list of sources for which the objects must be extracted
513
+ '''
514
+ target: 'BuildTarget'
515
+ srclist: T.List[File] = field(default_factory=list)
516
+ genlist: T.List['GeneratedTypes'] = field(default_factory=list)
517
+ objlist: T.List[T.Union[str, 'File', 'ExtractedObjects']] = field(default_factory=list)
518
+ recursive: bool = True
519
+ pch: bool = False
520
+
521
+ def __post_init__(self) -> None:
522
+ if self.target.is_unity:
523
+ self.check_unity_compatible()
524
+
525
+ def __repr__(self) -> str:
526
+ r = '<{0} {1!r}: {2}>'
527
+ return r.format(self.__class__.__name__, self.target.name, self.srclist)
528
+
529
+ @staticmethod
530
+ def get_sources(sources: T.Sequence['FileOrString'], generated_sources: T.Sequence['GeneratedTypes']) -> T.List['FileOrString']:
531
+ # Merge sources and generated sources
532
+ sources = list(sources)
533
+ for gensrc in generated_sources:
534
+ for s in gensrc.get_outputs():
535
+ # We cannot know the path where this source will be generated,
536
+ # but all we need here is the file extension to determine the
537
+ # compiler.
538
+ sources.append(s)
539
+
540
+ # Filter out headers and all non-source files
541
+ return [s for s in sources if is_source(s)]
542
+
543
+ def classify_all_sources(self, sources: T.List[FileOrString], generated_sources: T.Sequence['GeneratedTypes']) -> T.Dict['Compiler', T.List['FileOrString']]:
544
+ sources_ = self.get_sources(sources, generated_sources)
545
+ return classify_unity_sources(self.target.compilers.values(), sources_)
546
+
547
+ def check_unity_compatible(self) -> None:
548
+ # Figure out if the extracted object list is compatible with a Unity
549
+ # build. When we're doing a Unified build, we go through the sources,
550
+ # and create a single source file from each subset of the sources that
551
+ # can be compiled with a specific compiler. Then we create one object
552
+ # from each unified source file. So for each compiler we can either
553
+ # extra all its sources or none.
554
+ cmpsrcs = self.classify_all_sources(self.target.sources, self.target.generated)
555
+ extracted_cmpsrcs = self.classify_all_sources(self.srclist, self.genlist)
556
+
557
+ for comp, srcs in extracted_cmpsrcs.items():
558
+ if set(srcs) != set(cmpsrcs[comp]):
559
+ raise MesonException('Single object files cannot be extracted '
560
+ 'in Unity builds. You can only extract all '
561
+ 'the object files for each compiler at once.')
562
+
563
+
564
+ @dataclass(eq=False, order=False)
565
+ class StructuredSources(HoldableObject):
566
+
567
+ """A container for sources in languages that use filesystem hierarchy.
568
+
569
+ Languages like Rust and Cython rely on the layout of files in the filesystem
570
+ as part of the compiler implementation. This structure allows us to
571
+ represent the required filesystem layout.
572
+ """
573
+
574
+ sources: T.DefaultDict[str, T.List[T.Union[File, CustomTarget, CustomTargetIndex, GeneratedList]]] = field(
575
+ default_factory=lambda: defaultdict(list))
576
+
577
+ def __add__(self, other: StructuredSources) -> StructuredSources:
578
+ sources = self.sources.copy()
579
+ for k, v in other.sources.items():
580
+ sources[k].extend(v)
581
+ return StructuredSources(sources)
582
+
583
+ def __bool__(self) -> bool:
584
+ return bool(self.sources)
585
+
586
+ def first_file(self) -> T.Union[File, CustomTarget, CustomTargetIndex, GeneratedList]:
587
+ """Get the first source in the root
588
+
589
+ :return: The first source in the root
590
+ """
591
+ return self.sources[''][0]
592
+
593
+ def as_list(self) -> T.List[T.Union[File, CustomTarget, CustomTargetIndex, GeneratedList]]:
594
+ return list(itertools.chain.from_iterable(self.sources.values()))
595
+
596
+ def needs_copy(self) -> bool:
597
+ """Do we need to create a structure in the build directory.
598
+
599
+ This allows us to avoid making copies if the structures exists in the
600
+ source dir. Which could happen in situations where a generated source
601
+ only exists in some configurations
602
+ """
603
+ for files in self.sources.values():
604
+ for f in files:
605
+ if isinstance(f, File):
606
+ if f.is_built:
607
+ return True
608
+ else:
609
+ return True
610
+ return False
611
+
612
+
613
+ @dataclass(eq=False)
614
+ class Target(HoldableObject, metaclass=abc.ABCMeta):
615
+
616
+ name: str
617
+ subdir: str
618
+ subproject: 'SubProject'
619
+ build_by_default: bool
620
+ for_machine: MachineChoice
621
+ environment: environment.Environment
622
+ build_only_subproject: bool
623
+ install: bool = False
624
+ build_always_stale: bool = False
625
+ extra_files: T.List[File] = field(default_factory=list)
626
+ override_options: InitVar[T.Optional[T.Dict[OptionKey, str]]] = None
627
+
628
+ @abc.abstractproperty
629
+ def typename(self) -> str:
630
+ pass
631
+
632
+ @abc.abstractmethod
633
+ def type_suffix(self) -> str:
634
+ pass
635
+
636
+ def __post_init__(self, overrides: T.Optional[T.Dict[OptionKey, str]]) -> None:
637
+ # Patch up a few things if this is a build_only_subproject.
638
+ # We don't want to do any installation from such a project,
639
+ # and we need to set the machine to build to get the right compilers
640
+ if self.build_only_subproject:
641
+ self.install = False
642
+ self.for_machine = MachineChoice.BUILD
643
+
644
+ if overrides:
645
+ ovr = {k.evolve(machine=self.for_machine) if k.lang else k: v
646
+ for k, v in overrides.items()}
647
+ else:
648
+ ovr = {}
649
+ self.options = coredata.OptionsView(self.environment.coredata.options, self.subproject, ovr)
650
+ # XXX: this should happen in the interpreter
651
+ if has_path_sep(self.name):
652
+ # Fix failing test 53 when this becomes an error.
653
+ mlog.warning(textwrap.dedent(f'''\
654
+ Target "{self.name}" has a path separator in its name.
655
+ This is not supported, it can cause unexpected failures and will become
656
+ a hard error in the future.'''))
657
+
658
+ # dataclass comparators?
659
+ def __lt__(self, other: object) -> bool:
660
+ if not isinstance(other, Target):
661
+ return NotImplemented
662
+ return self.get_id() < other.get_id()
663
+
664
+ def __le__(self, other: object) -> bool:
665
+ if not isinstance(other, Target):
666
+ return NotImplemented
667
+ return self.get_id() <= other.get_id()
668
+
669
+ def __gt__(self, other: object) -> bool:
670
+ if not isinstance(other, Target):
671
+ return NotImplemented
672
+ return self.get_id() > other.get_id()
673
+
674
+ def __ge__(self, other: object) -> bool:
675
+ if not isinstance(other, Target):
676
+ return NotImplemented
677
+ return self.get_id() >= other.get_id()
678
+
679
+ def get_default_install_dir(self) -> T.Union[T.Tuple[str, str], T.Tuple[None, None]]:
680
+ raise NotImplementedError
681
+
682
+ def get_custom_install_dir(self) -> T.List[T.Union[str, Literal[False]]]:
683
+ raise NotImplementedError
684
+
685
+ def get_install_dir(self) -> T.Tuple[T.List[T.Union[str, Literal[False]]], T.List[T.Optional[str]], bool]:
686
+ # Find the installation directory.
687
+ default_install_dir, default_install_dir_name = self.get_default_install_dir()
688
+ outdirs: T.List[T.Union[str, Literal[False]]] = self.get_custom_install_dir()
689
+ install_dir_names: T.List[T.Optional[str]]
690
+ if outdirs and outdirs[0] != default_install_dir and outdirs[0] is not True:
691
+ # Either the value is set to a non-default value, or is set to
692
+ # False (which means we want this specific output out of many
693
+ # outputs to not be installed).
694
+ custom_install_dir = True
695
+ install_dir_names = [getattr(i, 'optname', None) for i in outdirs]
696
+ else:
697
+ custom_install_dir = False
698
+ # if outdirs is empty we need to set to something, otherwise we set
699
+ # only the first value to the default.
700
+ if outdirs:
701
+ outdirs[0] = default_install_dir
702
+ else:
703
+ outdirs = [default_install_dir]
704
+ install_dir_names = [default_install_dir_name] * len(outdirs)
705
+
706
+ return outdirs, install_dir_names, custom_install_dir
707
+
708
+ def get_basename(self) -> str:
709
+ return self.name
710
+
711
+ def get_source_subdir(self) -> str:
712
+ return self.subdir
713
+
714
+ def get_output_subdir(self) -> str:
715
+ return compute_build_subdir(self.subdir, self.build_only_subproject)
716
+
717
+ def get_typename(self) -> str:
718
+ return self.typename
719
+
720
+ @staticmethod
721
+ def _get_id_hash(target_id: str) -> str:
722
+ # We don't really need cryptographic security here.
723
+ # Small-digest hash function with unlikely collision is good enough.
724
+ h = hashlib.sha256()
725
+ h.update(target_id.encode(encoding='utf-8', errors='replace'))
726
+ # This ID should be case-insensitive and should work in Visual Studio,
727
+ # e.g. it should not start with leading '-'.
728
+ return h.hexdigest()[:7]
729
+
730
+ @staticmethod
731
+ def construct_id_from_path(subdir: str, name: str, type_suffix: str, build_subproject: bool = False) -> str:
732
+ """Construct target ID from subdir, name and type suffix.
733
+
734
+ This helper function is made public mostly for tests."""
735
+ # This ID must also be a valid file name on all OSs.
736
+ # It should also avoid shell metacharacters for obvious
737
+ # reasons. '@' is not used as often as '_' in source code names.
738
+ # In case of collisions consider using checksums.
739
+ # FIXME replace with assert when slash in names is prohibited
740
+ name_part = name.replace('/', '@').replace('\\', '@')
741
+ assert not has_path_sep(type_suffix)
742
+ my_id = name_part + type_suffix
743
+ if subdir:
744
+ subdir_part = Target._get_id_hash(subdir)
745
+ # preserve myid for better debuggability
746
+ my_id = f'{subdir_part}@@{my_id}'
747
+ if build_subproject:
748
+ my_id = f'build.{my_id}'
749
+ return my_id
750
+
751
+ def get_id(self) -> str:
752
+ """Get the unique ID of the target.
753
+
754
+ :return: A unique string id
755
+ """
756
+ name = self.name
757
+ if getattr(self, 'name_suffix_set', False):
758
+ name += '.' + self.suffix
759
+ return self.construct_id_from_path(
760
+ self.subdir, name, self.type_suffix(), self.build_only_subproject)
761
+
762
+ def process_kwargs_base(self, kwargs: T.Dict[str, T.Any]) -> None:
763
+ if 'build_by_default' in kwargs:
764
+ self.build_by_default = kwargs['build_by_default']
765
+ if not isinstance(self.build_by_default, bool):
766
+ raise InvalidArguments('build_by_default must be a boolean value.')
767
+
768
+ if not self.build_by_default and kwargs.get('install', False):
769
+ # For backward compatibility, if build_by_default is not explicitly
770
+ # set, use the value of 'install' if it's enabled.
771
+ self.build_by_default = True
772
+
773
+ self.set_option_overrides(self.parse_overrides(kwargs))
774
+
775
+ def set_option_overrides(self, option_overrides: T.Dict[OptionKey, str]) -> None:
776
+ self.options.overrides = {}
777
+ for k, v in option_overrides.items():
778
+ if k.lang:
779
+ self.options.overrides[k.evolve(machine=self.for_machine)] = v
780
+ else:
781
+ self.options.overrides[k] = v
782
+
783
+ def get_options(self) -> coredata.OptionsView:
784
+ return self.options
785
+
786
+ def get_option(self, key: 'OptionKey') -> T.Union[str, int, bool, 'WrapMode']:
787
+ # We don't actually have wrapmode here to do an assert, so just do a
788
+ # cast, we know what's in coredata anyway.
789
+ # TODO: if it's possible to annotate get_option or validate_option_value
790
+ # in the future we might be able to remove the cast here
791
+ return T.cast('T.Union[str, int, bool, WrapMode]', self.options[key].value)
792
+
793
+ @staticmethod
794
+ def parse_overrides(kwargs: T.Dict[str, T.Any]) -> T.Dict[OptionKey, str]:
795
+ opts = kwargs.get('override_options', [])
796
+
797
+ # In this case we have an already parsed and ready to go dictionary
798
+ # provided by typed_kwargs
799
+ if isinstance(opts, dict):
800
+ return T.cast('T.Dict[OptionKey, str]', opts)
801
+
802
+ result: T.Dict[OptionKey, str] = {}
803
+ overrides = stringlistify(opts)
804
+ for o in overrides:
805
+ if '=' not in o:
806
+ raise InvalidArguments('Overrides must be of form "key=value"')
807
+ k, v = o.split('=', 1)
808
+ key = OptionKey.from_string(k.strip())
809
+ v = v.strip()
810
+ result[key] = v
811
+ return result
812
+
813
+ def is_linkable_target(self) -> bool:
814
+ return False
815
+
816
+ def get_outputs(self) -> T.List[str]:
817
+ return []
818
+
819
+ def should_install(self) -> bool:
820
+ return False
821
+
822
+ class BuildTarget(Target):
823
+ known_kwargs = known_build_target_kwargs
824
+
825
+ install_dir: T.List[T.Union[str, Literal[False]]]
826
+
827
+ # This set contains all the languages a linker can link natively
828
+ # without extra flags. For instance, nvcc (cuda) can link C++
829
+ # without injecting -lc++/-lstdc++, see
830
+ # https://github.com/mesonbuild/meson/issues/10570
831
+ _MASK_LANGS: T.FrozenSet[T.Tuple[str, str]] = frozenset([
832
+ # (language, linker)
833
+ ('cpp', 'cuda'),
834
+ ])
835
+
836
+ def __init__(
837
+ self,
838
+ name: str,
839
+ subdir: str,
840
+ subproject: SubProject,
841
+ for_machine: MachineChoice,
842
+ sources: T.List['SourceOutputs'],
843
+ structured_sources: T.Optional[StructuredSources],
844
+ objects: T.List[ObjectTypes],
845
+ environment: environment.Environment,
846
+ compilers: T.Dict[str, 'Compiler'],
847
+ build_only_subproject: bool,
848
+ kwargs: T.Dict[str, T.Any]):
849
+ super().__init__(name, subdir, subproject, True, for_machine, environment, build_only_subproject, install=kwargs.get('install', False))
850
+ self.all_compilers = compilers
851
+ self.compilers: OrderedDict[str, Compiler] = OrderedDict()
852
+ self.objects: T.List[ObjectTypes] = []
853
+ self.structured_sources = structured_sources
854
+ self.external_deps: T.List[dependencies.Dependency] = []
855
+ self.include_dirs: T.List['IncludeDirs'] = []
856
+ self.link_language = kwargs.get('link_language')
857
+ self.link_targets: T.List[LibTypes] = []
858
+ self.link_whole_targets: T.List[T.Union[StaticLibrary, CustomTarget, CustomTargetIndex]] = []
859
+ self.depend_files: T.List[File] = []
860
+ self.link_depends = []
861
+ self.added_deps = set()
862
+ self.name_prefix_set = False
863
+ self.name_suffix_set = False
864
+ self.filename = 'no_name'
865
+ # The debugging information file this target will generate
866
+ self.debug_filename = None
867
+ # The list of all files outputted by this target. Useful in cases such
868
+ # as Vala which generates .vapi and .h besides the compiled output.
869
+ self.outputs = [self.filename]
870
+ self.pch: T.Dict[str, T.List[str]] = {}
871
+ self.extra_args: T.DefaultDict[str, T.List[str]] = kwargs.get('language_args', defaultdict(list))
872
+ self.sources: T.List[File] = []
873
+ self.generated: T.List['GeneratedTypes'] = []
874
+ self.extra_files: T.List[File] = []
875
+ self.d_features: DFeatures = {
876
+ 'debug': kwargs.get('d_debug', []),
877
+ 'import_dirs': kwargs.get('d_import_dirs', []),
878
+ 'versions': kwargs.get('d_module_versions', []),
879
+ 'unittest': kwargs.get('d_unittest', False),
880
+ }
881
+ self.pic = False
882
+ self.pie = False
883
+ # Track build_rpath entries so we can remove them at install time
884
+ self.rpath_dirs_to_remove: T.Set[bytes] = set()
885
+ self.process_sourcelist(sources)
886
+ # Objects can be:
887
+ # 1. Preexisting objects provided by the user with the `objects:` kwarg
888
+ # 2. Compiled objects created by and extracted from another target
889
+ self.process_objectlist(objects)
890
+ self.process_kwargs(kwargs)
891
+ self.missing_languages = self.process_compilers()
892
+
893
+ # self.link_targets and self.link_whole_targets contains libraries from
894
+ # dependencies (see add_deps()). They have not been processed yet because
895
+ # we have to call process_compilers() first and we need to process libraries
896
+ # from link_with and link_whole first.
897
+ # See https://github.com/mesonbuild/meson/pull/11957#issuecomment-1629243208.
898
+ link_targets = extract_as_list(kwargs, 'link_with') + self.link_targets
899
+ link_whole_targets = extract_as_list(kwargs, 'link_whole') + self.link_whole_targets
900
+ self.link_targets.clear()
901
+ self.link_whole_targets.clear()
902
+ self.link(link_targets)
903
+ self.link_whole(link_whole_targets)
904
+
905
+ if not any([self.sources, self.generated, self.objects, self.link_whole_targets, self.structured_sources,
906
+ kwargs.pop('_allow_no_sources', False)]):
907
+ mlog.warning(f'Build target {name} has no sources. '
908
+ 'This was never supposed to be allowed but did because of a bug, '
909
+ 'support will be removed in a future release of Meson')
910
+ self.check_unknown_kwargs(kwargs)
911
+ self.validate_install()
912
+ self.check_module_linking()
913
+
914
+ def post_init(self) -> None:
915
+ ''' Initialisations and checks requiring the final list of compilers to be known
916
+ '''
917
+ self.validate_sources()
918
+ if self.structured_sources and any([self.sources, self.generated]):
919
+ raise MesonException('cannot mix structured sources and unstructured sources')
920
+ if self.structured_sources and 'rust' not in self.compilers:
921
+ raise MesonException('structured sources are only supported in Rust targets')
922
+ if self.uses_rust():
923
+ # relocation-model=pic is rustc's default and Meson does not
924
+ # currently have a way to disable PIC.
925
+ self.pic = True
926
+ if 'vala' in self.compilers and self.is_linkable_target():
927
+ self.outputs += [self.vala_header, self.vala_vapi]
928
+ self.install_tag += ['devel', 'devel']
929
+ if self.vala_gir:
930
+ self.outputs.append(self.vala_gir)
931
+ self.install_tag.append('devel')
932
+
933
+ def __repr__(self):
934
+ repr_str = "<{0} {1}: {2}>"
935
+ return repr_str.format(self.__class__.__name__, self.get_id(), self.filename)
936
+
937
+ def __str__(self):
938
+ return f"{self.name}"
939
+
940
+ @property
941
+ def is_unity(self) -> bool:
942
+ unity_opt = self.get_option(OptionKey('unity'))
943
+ return unity_opt == 'on' or (unity_opt == 'subprojects' and self.subproject != '')
944
+
945
+ def validate_install(self):
946
+ if self.for_machine is MachineChoice.BUILD and self.install:
947
+ if self.environment.is_cross_build():
948
+ raise InvalidArguments('Tried to install a target for the build machine in a cross build.')
949
+ else:
950
+ mlog.warning('Installing target build for the build machine. This will fail in a cross build.')
951
+
952
+ def check_unknown_kwargs(self, kwargs):
953
+ # Override this method in derived classes that have more
954
+ # keywords.
955
+ self.check_unknown_kwargs_int(kwargs, self.known_kwargs)
956
+
957
+ def check_unknown_kwargs_int(self, kwargs, known_kwargs):
958
+ unknowns = []
959
+ for k in kwargs:
960
+ if k == 'language_args':
961
+ continue
962
+ if k not in known_kwargs:
963
+ unknowns.append(k)
964
+ if len(unknowns) > 0:
965
+ mlog.warning('Unknown keyword argument(s) in target {}: {}.'.format(self.name, ', '.join(unknowns)))
966
+
967
+ def process_objectlist(self, objects):
968
+ assert isinstance(objects, list)
969
+ deprecated_non_objects = []
970
+ for s in objects:
971
+ if isinstance(s, (str, File, ExtractedObjects)):
972
+ self.objects.append(s)
973
+ if not isinstance(s, ExtractedObjects) and not is_object(s):
974
+ deprecated_non_objects.append(s)
975
+ elif isinstance(s, (CustomTarget, CustomTargetIndex, GeneratedList)):
976
+ non_objects = [o for o in s.get_outputs() if not is_object(o)]
977
+ if non_objects:
978
+ raise InvalidArguments(f'Generated file {non_objects[0]} in the \'objects\' kwarg is not an object.')
979
+ self.generated.append(s)
980
+ else:
981
+ raise InvalidArguments(f'Bad object of type {type(s).__name__!r} in target {self.name!r}.')
982
+ if deprecated_non_objects:
983
+ FeatureDeprecated.single_use(f'Source file {deprecated_non_objects[0]} in the \'objects\' kwarg is not an object.',
984
+ '1.3.0', self.subproject)
985
+
986
+ def process_sourcelist(self, sources: T.List['SourceOutputs']) -> None:
987
+ """Split sources into generated and static sources.
988
+
989
+ Sources can be:
990
+ 1. Preexisting source files in the source tree (static)
991
+ 2. Preexisting sources generated by configure_file in the build tree.
992
+ (static as they are only regenerated if meson itself is regenerated)
993
+ 3. Sources files generated by another target or a Generator (generated)
994
+ """
995
+ added_sources: T.Set[File] = set() # If the same source is defined multiple times, use it only once.
996
+ for s in sources:
997
+ if isinstance(s, File):
998
+ if s not in added_sources:
999
+ self.sources.append(s)
1000
+ added_sources.add(s)
1001
+ elif isinstance(s, (CustomTarget, CustomTargetIndex, GeneratedList)):
1002
+ self.generated.append(s)
1003
+
1004
+ @staticmethod
1005
+ def can_compile_remove_sources(compiler: 'Compiler', sources: T.List['FileOrString']) -> bool:
1006
+ removed = False
1007
+ for s in sources[:]:
1008
+ if compiler.can_compile(s):
1009
+ sources.remove(s)
1010
+ removed = True
1011
+ return removed
1012
+
1013
+ def process_compilers_late(self) -> None:
1014
+ """Processes additional compilers after kwargs have been evaluated.
1015
+
1016
+ This can add extra compilers that might be required by keyword
1017
+ arguments, such as link_with or dependencies. It will also try to guess
1018
+ which compiler to use if one hasn't been selected already.
1019
+ """
1020
+ for lang in self.missing_languages:
1021
+ self.compilers[lang] = self.all_compilers[lang]
1022
+
1023
+ # did user override clink_langs for this target?
1024
+ link_langs = [self.link_language] if self.link_language else clink_langs
1025
+
1026
+ # If this library is linked against another library we need to consider
1027
+ # the languages of those libraries as well.
1028
+ if self.link_targets or self.link_whole_targets:
1029
+ for t in itertools.chain(self.link_targets, self.link_whole_targets):
1030
+ if isinstance(t, (CustomTarget, CustomTargetIndex)):
1031
+ continue # We can't know anything about these.
1032
+ for name, compiler in t.compilers.items():
1033
+ if name in link_langs and name not in self.compilers:
1034
+ self.compilers[name] = compiler
1035
+
1036
+ if not self.compilers:
1037
+ # No source files or parent targets, target consists of only object
1038
+ # files of unknown origin. Just add the first clink compiler
1039
+ # that we have and hope that it can link these objects
1040
+ for lang in link_langs:
1041
+ if lang in self.all_compilers:
1042
+ self.compilers[lang] = self.all_compilers[lang]
1043
+ break
1044
+
1045
+ # Now that we have the final list of compilers we can sort it according
1046
+ # to clink_langs and do sanity checks.
1047
+ self.compilers = OrderedDict(sorted(self.compilers.items(),
1048
+ key=lambda t: sort_clink(t[0])))
1049
+ self.post_init()
1050
+
1051
+ def process_compilers(self) -> T.List[str]:
1052
+ '''
1053
+ Populate self.compilers, which is the list of compilers that this
1054
+ target will use for compiling all its sources.
1055
+ We also add compilers that were used by extracted objects to simplify
1056
+ dynamic linker determination.
1057
+ Returns a list of missing languages that we can add implicitly, such as
1058
+ C/C++ compiler for cython.
1059
+ '''
1060
+ missing_languages: T.List[str] = []
1061
+ if not any([self.sources, self.generated, self.objects, self.structured_sources]):
1062
+ return missing_languages
1063
+ # Preexisting sources
1064
+ sources: T.List['FileOrString'] = list(self.sources)
1065
+ generated = self.generated.copy()
1066
+
1067
+ if self.structured_sources:
1068
+ for v in self.structured_sources.sources.values():
1069
+ for src in v:
1070
+ if isinstance(src, (str, File)):
1071
+ sources.append(src)
1072
+ else:
1073
+ generated.append(src)
1074
+
1075
+ # All generated sources
1076
+ for gensrc in generated:
1077
+ for s in gensrc.get_outputs():
1078
+ # Generated objects can't be compiled, so don't use them for
1079
+ # compiler detection. If our target only has generated objects,
1080
+ # we will fall back to using the first c-like compiler we find,
1081
+ # which is what we need.
1082
+ if not is_object(s):
1083
+ sources.append(s)
1084
+ for d in self.external_deps:
1085
+ for s in d.sources:
1086
+ if isinstance(s, (str, File)):
1087
+ sources.append(s)
1088
+
1089
+ # Sources that were used to create our extracted objects
1090
+ for o in self.objects:
1091
+ if not isinstance(o, ExtractedObjects):
1092
+ continue
1093
+ compsrcs = o.classify_all_sources(o.srclist, [])
1094
+ for comp in compsrcs:
1095
+ # Don't add Vala sources since that will pull in the Vala
1096
+ # compiler even though we will never use it since we are
1097
+ # dealing with compiled C code.
1098
+ if comp.language == 'vala':
1099
+ continue
1100
+ if comp.language not in self.compilers:
1101
+ self.compilers[comp.language] = comp
1102
+ if sources:
1103
+ # For each source, try to add one compiler that can compile it.
1104
+ #
1105
+ # If it has a suffix that belongs to a known language, we must have
1106
+ # a compiler for that language.
1107
+ #
1108
+ # Otherwise, it's ok if no compilers can compile it, because users
1109
+ # are expected to be able to add arbitrary non-source files to the
1110
+ # sources list
1111
+ for s in sources:
1112
+ for lang, compiler in self.all_compilers.items():
1113
+ if compiler.can_compile(s):
1114
+ if lang not in self.compilers:
1115
+ self.compilers[lang] = compiler
1116
+ break
1117
+ else:
1118
+ if is_known_suffix(s):
1119
+ path = pathlib.Path(str(s)).as_posix()
1120
+ m = f'No {self.for_machine.get_lower_case_name()} machine compiler for {path!r}'
1121
+ raise MesonException(m)
1122
+
1123
+ # If all our sources are Vala, our target also needs the C compiler but
1124
+ # it won't get added above.
1125
+ if 'vala' in self.compilers and 'c' not in self.compilers:
1126
+ self.compilers['c'] = self.all_compilers['c']
1127
+ if 'cython' in self.compilers:
1128
+ key = OptionKey('language', machine=self.for_machine, lang='cython')
1129
+ value = self.get_option(key)
1130
+
1131
+ try:
1132
+ self.compilers[value] = self.all_compilers[value]
1133
+ except KeyError:
1134
+ missing_languages.append(value)
1135
+
1136
+ return missing_languages
1137
+
1138
+ def validate_sources(self):
1139
+ if len(self.compilers) > 1 and any(lang in self.compilers for lang in ['cs', 'java']):
1140
+ langs = ', '.join(self.compilers.keys())
1141
+ raise InvalidArguments(f'Cannot mix those languages into a target: {langs}')
1142
+
1143
+ def process_link_depends(self, sources):
1144
+ """Process the link_depends keyword argument.
1145
+
1146
+ This is designed to handle strings, Files, and the output of Custom
1147
+ Targets. Notably it doesn't handle generator() returned objects, since
1148
+ adding them as a link depends would inherently cause them to be
1149
+ generated twice, since the output needs to be passed to the ld_args and
1150
+ link_depends.
1151
+ """
1152
+ sources = listify(sources)
1153
+ for s in sources:
1154
+ if isinstance(s, File):
1155
+ self.link_depends.append(s)
1156
+ elif isinstance(s, str):
1157
+ self.link_depends.append(
1158
+ File.from_source_file(self.environment.source_dir, self.get_source_subdir(), s))
1159
+ elif hasattr(s, 'get_outputs'):
1160
+ self.link_depends.append(s)
1161
+ else:
1162
+ raise InvalidArguments(
1163
+ 'Link_depends arguments must be strings, Files, '
1164
+ 'or a Custom Target, or lists thereof.')
1165
+
1166
+ def extract_objects(self, srclist: T.List[T.Union['FileOrString', 'GeneratedTypes']]) -> ExtractedObjects:
1167
+ sources_set = set(self.sources)
1168
+ generated_set = set(self.generated)
1169
+
1170
+ obj_src: T.List['File'] = []
1171
+ obj_gen: T.List['GeneratedTypes'] = []
1172
+ for src in srclist:
1173
+ if isinstance(src, (str, File)):
1174
+ if isinstance(src, str):
1175
+ src = File(False, self.subdir, src)
1176
+ else:
1177
+ FeatureNew.single_use('File argument for extract_objects', '0.50.0', self.subproject)
1178
+ if src not in sources_set:
1179
+ raise MesonException(f'Tried to extract unknown source {src}.')
1180
+ obj_src.append(src)
1181
+ elif isinstance(src, (CustomTarget, CustomTargetIndex, GeneratedList)):
1182
+ FeatureNew.single_use('Generated sources for extract_objects', '0.61.0', self.subproject)
1183
+ target = src.target if isinstance(src, CustomTargetIndex) else src
1184
+ if src not in generated_set and target not in generated_set:
1185
+ raise MesonException(f'Tried to extract unknown source {target.get_basename()}.')
1186
+ obj_gen.append(src)
1187
+ else:
1188
+ raise MesonException(f'Object extraction arguments must be strings, Files or targets (got {type(src).__name__}).')
1189
+ return ExtractedObjects(self, obj_src, obj_gen)
1190
+
1191
+ def extract_all_objects(self, recursive: bool = True) -> ExtractedObjects:
1192
+ return ExtractedObjects(self, self.sources, self.generated, self.objects,
1193
+ recursive, pch=True)
1194
+
1195
+ def get_all_link_deps(self) -> ImmutableListProtocol[BuildTargetTypes]:
1196
+ return self.get_transitive_link_deps()
1197
+
1198
+ @lru_cache(maxsize=None)
1199
+ def get_transitive_link_deps(self) -> ImmutableListProtocol[BuildTargetTypes]:
1200
+ result: T.List[Target] = []
1201
+ for i in self.link_targets:
1202
+ result += i.get_all_link_deps()
1203
+ return result
1204
+
1205
+ def get_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
1206
+ return self.get_transitive_link_deps_mapping(prefix)
1207
+
1208
+ @lru_cache(maxsize=None)
1209
+ def get_transitive_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
1210
+ result: T.Dict[str, str] = {}
1211
+ for i in self.link_targets:
1212
+ mapping = i.get_link_deps_mapping(prefix)
1213
+ #we are merging two dictionaries, while keeping the earlier one dominant
1214
+ result_tmp = mapping.copy()
1215
+ result_tmp.update(result)
1216
+ result = result_tmp
1217
+ return result
1218
+
1219
+ @lru_cache(maxsize=None)
1220
+ def get_link_dep_subdirs(self) -> T.AbstractSet[str]:
1221
+ result: OrderedSet[str] = OrderedSet()
1222
+ for i in self.link_targets:
1223
+ if not isinstance(i, StaticLibrary):
1224
+ result.add(i.get_output_subdir())
1225
+ result.update(i.get_link_dep_subdirs())
1226
+ return result
1227
+
1228
+ def get_default_install_dir(self) -> T.Union[T.Tuple[str, str], T.Tuple[None, None]]:
1229
+ return self.environment.get_libdir(), '{libdir}'
1230
+
1231
+ def get_custom_install_dir(self) -> T.List[T.Union[str, Literal[False]]]:
1232
+ return self.install_dir
1233
+
1234
+ def get_custom_install_mode(self) -> T.Optional['FileMode']:
1235
+ return self.install_mode
1236
+
1237
+ def process_kwargs(self, kwargs):
1238
+ self.process_kwargs_base(kwargs)
1239
+ self.original_kwargs = kwargs
1240
+
1241
+ self.add_pch('c', extract_as_list(kwargs, 'c_pch'))
1242
+ self.add_pch('cpp', extract_as_list(kwargs, 'cpp_pch'))
1243
+
1244
+ if not isinstance(self, Executable) or kwargs.get('export_dynamic', False):
1245
+ self.vala_header = kwargs.get('vala_header', self.name + '.h')
1246
+ self.vala_vapi = kwargs.get('vala_vapi', self.name + '.vapi')
1247
+ self.vala_gir = kwargs.get('vala_gir', None)
1248
+
1249
+ self.link_args = extract_as_list(kwargs, 'link_args')
1250
+ for i in self.link_args:
1251
+ if not isinstance(i, str):
1252
+ raise InvalidArguments('Link_args arguments must be strings.')
1253
+ for l in self.link_args:
1254
+ if '-Wl,-rpath' in l or l.startswith('-rpath'):
1255
+ mlog.warning(textwrap.dedent('''\
1256
+ Please do not define rpath with a linker argument, use install_rpath
1257
+ or build_rpath properties instead.
1258
+ This will become a hard error in a future Meson release.
1259
+ '''))
1260
+ self.process_link_depends(kwargs.get('link_depends', []))
1261
+ # Target-specific include dirs must be added BEFORE include dirs from
1262
+ # internal deps (added inside self.add_deps()) to override them.
1263
+ inclist = extract_as_list(kwargs, 'include_directories')
1264
+ self.add_include_dirs(inclist)
1265
+ # Add dependencies (which also have include_directories)
1266
+ deplist = extract_as_list(kwargs, 'dependencies')
1267
+ self.add_deps(deplist)
1268
+ # If an item in this list is False, the output corresponding to
1269
+ # the list index of that item will not be installed
1270
+ self.install_dir = typeslistify(kwargs.get('install_dir', []),
1271
+ (str, bool))
1272
+ self.install_mode = kwargs.get('install_mode', None)
1273
+ self.install_tag = stringlistify(kwargs.get('install_tag', [None]))
1274
+ if not isinstance(self, Executable):
1275
+ # build_target will always populate these as `None`, which is fine
1276
+ if kwargs.get('gui_app') is not None:
1277
+ raise InvalidArguments('Argument gui_app can only be used on executables.')
1278
+ if kwargs.get('win_subsystem') is not None:
1279
+ raise InvalidArguments('Argument win_subsystem can only be used on executables.')
1280
+ extra_files = extract_as_list(kwargs, 'extra_files')
1281
+ for i in extra_files:
1282
+ assert isinstance(i, File)
1283
+ if i in self.extra_files:
1284
+ continue
1285
+ trial = os.path.join(self.environment.get_source_dir(), i.subdir, i.fname)
1286
+ if not os.path.isfile(trial):
1287
+ raise InvalidArguments(f'Tried to add non-existing extra file {i}.')
1288
+ self.extra_files.append(i)
1289
+ self.install_rpath: str = kwargs.get('install_rpath', '')
1290
+ if not isinstance(self.install_rpath, str):
1291
+ raise InvalidArguments('Install_rpath is not a string.')
1292
+ self.build_rpath = kwargs.get('build_rpath', '')
1293
+ if not isinstance(self.build_rpath, str):
1294
+ raise InvalidArguments('Build_rpath is not a string.')
1295
+ resources = extract_as_list(kwargs, 'resources')
1296
+ for r in resources:
1297
+ if not isinstance(r, str):
1298
+ raise InvalidArguments('Resource argument is not a string.')
1299
+ trial = os.path.join(self.environment.get_source_dir(), self.get_source_subdir(), r)
1300
+ if not os.path.isfile(trial):
1301
+ raise InvalidArguments(f'Tried to add non-existing resource {r}.')
1302
+ self.resources = resources
1303
+ if kwargs.get('name_prefix') is not None:
1304
+ name_prefix = kwargs['name_prefix']
1305
+ if isinstance(name_prefix, list):
1306
+ if name_prefix:
1307
+ raise InvalidArguments('name_prefix array must be empty to signify default.')
1308
+ else:
1309
+ if not isinstance(name_prefix, str):
1310
+ raise InvalidArguments('name_prefix must be a string.')
1311
+ self.prefix = name_prefix
1312
+ self.name_prefix_set = True
1313
+ if kwargs.get('name_suffix') is not None:
1314
+ name_suffix = kwargs['name_suffix']
1315
+ if isinstance(name_suffix, list):
1316
+ if name_suffix:
1317
+ raise InvalidArguments('name_suffix array must be empty to signify default.')
1318
+ else:
1319
+ if not isinstance(name_suffix, str):
1320
+ raise InvalidArguments('name_suffix must be a string.')
1321
+ if name_suffix == '':
1322
+ raise InvalidArguments('name_suffix should not be an empty string. '
1323
+ 'If you want meson to use the default behaviour '
1324
+ 'for each platform pass `[]` (empty array)')
1325
+ self.suffix = name_suffix
1326
+ self.name_suffix_set = True
1327
+ if isinstance(self, StaticLibrary):
1328
+ # You can't disable PIC on OS X. The compiler ignores -fno-PIC.
1329
+ # PIC is always on for Windows (all code is position-independent
1330
+ # since library loading is done differently)
1331
+ m = self.environment.machines[self.for_machine]
1332
+ if m.is_darwin() or m.is_windows():
1333
+ self.pic = True
1334
+ else:
1335
+ self.pic = self._extract_pic_pie(kwargs, 'pic', 'b_staticpic')
1336
+ if isinstance(self, Executable) or (isinstance(self, StaticLibrary) and not self.pic):
1337
+ # Executables must be PIE on Android
1338
+ if self.environment.machines[self.for_machine].is_android():
1339
+ self.pie = True
1340
+ else:
1341
+ self.pie = self._extract_pic_pie(kwargs, 'pie', 'b_pie')
1342
+ self.implicit_include_directories = kwargs.get('implicit_include_directories', True)
1343
+ if not isinstance(self.implicit_include_directories, bool):
1344
+ raise InvalidArguments('Implicit_include_directories must be a boolean.')
1345
+ self.gnu_symbol_visibility = kwargs.get('gnu_symbol_visibility', '')
1346
+ if not isinstance(self.gnu_symbol_visibility, str):
1347
+ raise InvalidArguments('GNU symbol visibility must be a string.')
1348
+ if self.gnu_symbol_visibility != '':
1349
+ permitted = ['default', 'internal', 'hidden', 'protected', 'inlineshidden']
1350
+ if self.gnu_symbol_visibility not in permitted:
1351
+ raise InvalidArguments('GNU symbol visibility arg {} not one of: {}'.format(self.gnu_symbol_visibility, ', '.join(permitted)))
1352
+
1353
+ rust_dependency_map = kwargs.get('rust_dependency_map', {})
1354
+ if not isinstance(rust_dependency_map, dict):
1355
+ raise InvalidArguments(f'Invalid rust_dependency_map "{rust_dependency_map}": must be a dictionary.')
1356
+ if any(not isinstance(v, str) for v in rust_dependency_map.values()):
1357
+ raise InvalidArguments(f'Invalid rust_dependency_map "{rust_dependency_map}": must be a dictionary with string values.')
1358
+ self.rust_dependency_map = rust_dependency_map
1359
+
1360
+ def _extract_pic_pie(self, kwargs: T.Dict[str, T.Any], arg: str, option: str) -> bool:
1361
+ # Check if we have -fPIC, -fpic, -fPIE, or -fpie in cflags
1362
+ all_flags = self.extra_args['c'] + self.extra_args['cpp']
1363
+ if '-f' + arg.lower() in all_flags or '-f' + arg.upper() in all_flags:
1364
+ mlog.warning(f"Use the '{arg}' kwarg instead of passing '-f{arg}' manually to {self.name!r}")
1365
+ return True
1366
+
1367
+ k = OptionKey(option)
1368
+ if kwargs.get(arg) is not None:
1369
+ val = T.cast('bool', kwargs[arg])
1370
+ elif k in self.environment.coredata.options:
1371
+ val = self.environment.coredata.options[k].value
1372
+ else:
1373
+ val = False
1374
+
1375
+ if not isinstance(val, bool):
1376
+ raise InvalidArguments(f'Argument {arg} to {self.name!r} must be boolean')
1377
+ return val
1378
+
1379
+ def get_filename(self) -> str:
1380
+ return self.filename
1381
+
1382
+ def get_debug_filename(self) -> T.Optional[str]:
1383
+ """
1384
+ The name of debuginfo file that will be created by the compiler
1385
+
1386
+ Returns None if the build won't create any debuginfo file
1387
+ """
1388
+ return self.debug_filename
1389
+
1390
+ def get_outputs(self) -> T.List[str]:
1391
+ return self.outputs
1392
+
1393
+ def get_extra_args(self, language: str) -> T.List[str]:
1394
+ return self.extra_args[language]
1395
+
1396
+ @lru_cache(maxsize=None)
1397
+ def get_dependencies(self) -> OrderedSet[BuildTargetTypes]:
1398
+ # Get all targets needed for linking. This includes all link_with and
1399
+ # link_whole targets, and also all dependencies of static libraries
1400
+ # recursively. The algorithm here is closely related to what we do in
1401
+ # get_internal_static_libraries(): Installed static libraries include
1402
+ # objects from all their dependencies already.
1403
+ result: OrderedSet[BuildTargetTypes] = OrderedSet()
1404
+ for t in itertools.chain(self.link_targets, self.link_whole_targets):
1405
+ if t not in result:
1406
+ result.add(t)
1407
+ if isinstance(t, StaticLibrary):
1408
+ t.get_dependencies_recurse(result)
1409
+ return result
1410
+
1411
+ def get_dependencies_recurse(self, result: OrderedSet[BuildTargetTypes], include_internals: bool = True) -> None:
1412
+ # self is always a static library because we don't need to pull dependencies
1413
+ # of shared libraries. If self is installed (not internal) it already
1414
+ # include objects extracted from all its internal dependencies so we can
1415
+ # skip them.
1416
+ include_internals = include_internals and self.is_internal()
1417
+ for t in self.link_targets:
1418
+ if t in result:
1419
+ continue
1420
+ if include_internals or not t.is_internal():
1421
+ result.add(t)
1422
+ if isinstance(t, StaticLibrary):
1423
+ t.get_dependencies_recurse(result, include_internals)
1424
+ for t in self.link_whole_targets:
1425
+ t.get_dependencies_recurse(result, include_internals)
1426
+
1427
+ def get_sources(self):
1428
+ return self.sources
1429
+
1430
+ def get_objects(self) -> T.List[T.Union[str, 'File', 'ExtractedObjects']]:
1431
+ return self.objects
1432
+
1433
+ def get_generated_sources(self) -> T.List['GeneratedTypes']:
1434
+ return self.generated
1435
+
1436
+ def should_install(self) -> bool:
1437
+ return self.install
1438
+
1439
+ def has_pch(self) -> bool:
1440
+ return bool(self.pch)
1441
+
1442
+ def get_pch(self, language: str) -> T.List[str]:
1443
+ return self.pch.get(language, [])
1444
+
1445
+ def get_include_dirs(self) -> T.List['IncludeDirs']:
1446
+ return self.include_dirs
1447
+
1448
+ def add_deps(self, deps):
1449
+ deps = listify(deps)
1450
+ for dep in deps:
1451
+ if dep in self.added_deps:
1452
+ continue
1453
+
1454
+ if isinstance(dep, dependencies.InternalDependency):
1455
+ # Those parts that are internal.
1456
+ self.process_sourcelist(dep.sources)
1457
+ self.extra_files.extend(f for f in dep.extra_files if f not in self.extra_files)
1458
+ self.add_include_dirs(dep.include_directories, dep.get_include_type())
1459
+ self.objects.extend(dep.objects)
1460
+ self.link_targets.extend(dep.libraries)
1461
+ self.link_whole_targets.extend(dep.whole_libraries)
1462
+ if dep.get_compile_args() or dep.get_link_args():
1463
+ # Those parts that are external.
1464
+ extpart = dependencies.InternalDependency('undefined',
1465
+ [],
1466
+ dep.get_compile_args(),
1467
+ dep.get_link_args(),
1468
+ [], [], [], [], [], {}, [], [], [])
1469
+ self.external_deps.append(extpart)
1470
+ # Deps of deps.
1471
+ self.add_deps(dep.ext_deps)
1472
+ elif isinstance(dep, dependencies.Dependency):
1473
+ if dep not in self.external_deps:
1474
+ self.external_deps.append(dep)
1475
+ self.process_sourcelist(dep.get_sources())
1476
+ self.add_deps(dep.ext_deps)
1477
+ elif isinstance(dep, BuildTarget):
1478
+ raise InvalidArguments(f'Tried to use a build target {dep.name} as a dependency of target {self.name}.\n'
1479
+ 'You probably should put it in link_with instead.')
1480
+ else:
1481
+ # This is a bit of a hack. We do not want Build to know anything
1482
+ # about the interpreter so we can't import it and use isinstance.
1483
+ # This should be reliable enough.
1484
+ if hasattr(dep, 'held_object'):
1485
+ # FIXME: subproject is not a real ObjectHolder so we have to do this by hand
1486
+ dep = dep.held_object
1487
+ if hasattr(dep, 'project_args_frozen') or hasattr(dep, 'global_args_frozen'):
1488
+ raise InvalidArguments('Tried to use subproject object as a dependency.\n'
1489
+ 'You probably wanted to use a dependency declared in it instead.\n'
1490
+ 'Access it by calling get_variable() on the subproject object.')
1491
+ raise InvalidArguments(f'Argument is of an unacceptable type {type(dep).__name__!r}.\nMust be '
1492
+ 'either an external dependency (returned by find_library() or '
1493
+ 'dependency()) or an internal dependency (returned by '
1494
+ 'declare_dependency()).')
1495
+
1496
+ dep_d_features = dep.d_features
1497
+
1498
+ for feature in ('versions', 'import_dirs'):
1499
+ if feature in dep_d_features:
1500
+ self.d_features[feature].extend(dep_d_features[feature])
1501
+
1502
+ self.added_deps.add(dep)
1503
+
1504
+ def get_external_deps(self) -> T.List[dependencies.Dependency]:
1505
+ return self.external_deps
1506
+
1507
+ def is_internal(self) -> bool:
1508
+ return False
1509
+
1510
+ def link(self, targets: T.List[BuildTargetTypes]) -> None:
1511
+ for t in targets:
1512
+ if not isinstance(t, (Target, CustomTargetIndex)):
1513
+ if isinstance(t, dependencies.ExternalLibrary):
1514
+ raise MesonException(textwrap.dedent('''\
1515
+ An external library was used in link_with keyword argument, which
1516
+ is reserved for libraries built as part of this project. External
1517
+ libraries must be passed using the dependencies keyword argument
1518
+ instead, because they are conceptually "external dependencies",
1519
+ just like those detected with the dependency() function.
1520
+ '''))
1521
+ raise InvalidArguments(f'{t!r} is not a target.')
1522
+ if not t.is_linkable_target():
1523
+ raise InvalidArguments(f"Link target '{t!s}' is not linkable.")
1524
+ if isinstance(self, StaticLibrary) and self.install and t.is_internal():
1525
+ # When we're a static library and we link_with to an
1526
+ # internal/convenience library, promote to link_whole.
1527
+ self.link_whole([t], promoted=True)
1528
+ continue
1529
+ if isinstance(self, SharedLibrary) and isinstance(t, StaticLibrary) and not t.pic:
1530
+ msg = f"Can't link non-PIC static library {t.name!r} into shared library {self.name!r}. "
1531
+ msg += "Use the 'pic' option to static_library to build with PIC."
1532
+ raise InvalidArguments(msg)
1533
+ self.check_can_link_together(t)
1534
+ self.link_targets.append(t)
1535
+
1536
+ def link_whole(self, targets: T.List[BuildTargetTypes], promoted: bool = False) -> None:
1537
+ for t in targets:
1538
+ if isinstance(t, (CustomTarget, CustomTargetIndex)):
1539
+ if not t.is_linkable_target():
1540
+ raise InvalidArguments(f'Custom target {t!r} is not linkable.')
1541
+ if t.links_dynamically():
1542
+ raise InvalidArguments('Can only link_whole custom targets that are static archives.')
1543
+ elif not isinstance(t, StaticLibrary):
1544
+ raise InvalidArguments(f'{t!r} is not a static library.')
1545
+ elif isinstance(self, SharedLibrary) and not t.pic:
1546
+ msg = f"Can't link non-PIC static library {t.name!r} into shared library {self.name!r}. "
1547
+ msg += "Use the 'pic' option to static_library to build with PIC."
1548
+ raise InvalidArguments(msg)
1549
+ self.check_can_link_together(t)
1550
+ if isinstance(self, StaticLibrary):
1551
+ # When we're a static library and we link_whole: to another static
1552
+ # library, we need to add that target's objects to ourselves.
1553
+ self._bundle_static_library(t, promoted)
1554
+ # If we install this static library we also need to include objects
1555
+ # from all uninstalled static libraries it depends on.
1556
+ if self.install:
1557
+ for lib in t.get_internal_static_libraries():
1558
+ self._bundle_static_library(lib, True)
1559
+ self.link_whole_targets.append(t)
1560
+
1561
+ @lru_cache(maxsize=None)
1562
+ def get_internal_static_libraries(self) -> OrderedSet[BuildTargetTypes]:
1563
+ result: OrderedSet[BuildTargetTypes] = OrderedSet()
1564
+ self.get_internal_static_libraries_recurse(result)
1565
+ return result
1566
+
1567
+ def get_internal_static_libraries_recurse(self, result: OrderedSet[BuildTargetTypes]) -> None:
1568
+ for t in self.link_targets:
1569
+ if t.is_internal() and t not in result:
1570
+ result.add(t)
1571
+ t.get_internal_static_libraries_recurse(result)
1572
+ for t in self.link_whole_targets:
1573
+ if t.is_internal():
1574
+ t.get_internal_static_libraries_recurse(result)
1575
+
1576
+ def _bundle_static_library(self, t: T.Union[BuildTargetTypes], promoted: bool = False) -> None:
1577
+ if self.uses_rust():
1578
+ # Rustc can bundle static libraries, no need to extract objects.
1579
+ self.link_whole_targets.append(t)
1580
+ elif isinstance(t, (CustomTarget, CustomTargetIndex)) or t.uses_rust():
1581
+ # To extract objects from a custom target we would have to extract
1582
+ # the archive, WIP implementation can be found in
1583
+ # https://github.com/mesonbuild/meson/pull/9218.
1584
+ # For Rust C ABI we could in theory have access to objects, but there
1585
+ # are several meson issues that need to be fixed:
1586
+ # https://github.com/mesonbuild/meson/issues/10722
1587
+ # https://github.com/mesonbuild/meson/issues/10723
1588
+ # https://github.com/mesonbuild/meson/issues/10724
1589
+ m = (f'Cannot link_whole a custom or Rust target {t.name!r} into a static library {self.name!r}. '
1590
+ 'Instead, pass individual object files with the "objects:" keyword argument if possible.')
1591
+ if promoted:
1592
+ m += (f' Meson had to promote link to link_whole because {self.name!r} is installed but not {t.name!r},'
1593
+ f' and thus has to include objects from {t.name!r} to be usable.')
1594
+ raise InvalidArguments(m)
1595
+ else:
1596
+ self.objects.append(t.extract_all_objects())
1597
+
1598
+ def check_can_link_together(self, t: BuildTargetTypes) -> None:
1599
+ links_with_rust_abi = isinstance(t, BuildTarget) and t.uses_rust_abi()
1600
+ if not self.uses_rust() and links_with_rust_abi:
1601
+ raise InvalidArguments(f'Try to link Rust ABI library {t.name!r} with a non-Rust target {self.name!r}')
1602
+ if self.for_machine is not t.for_machine and (not links_with_rust_abi or t.rust_crate_type != 'proc-macro'):
1603
+ msg = f'Tried to tied to mix a {t.for_machine} library ("{t.name}") with a {self.for_machine} target "{self.name}"'
1604
+ if self.environment.is_cross_build():
1605
+ raise InvalidArguments(msg + ' This is not possible in a cross build.')
1606
+ else:
1607
+ mlog.warning(msg + ' This will fail in cross build.')
1608
+
1609
+ def add_pch(self, language: str, pchlist: T.List[str]) -> None:
1610
+ if not pchlist:
1611
+ return
1612
+ elif len(pchlist) == 1:
1613
+ if not is_header(pchlist[0]):
1614
+ raise InvalidArguments(f'PCH argument {pchlist[0]} is not a header.')
1615
+ elif len(pchlist) == 2:
1616
+ if is_header(pchlist[0]):
1617
+ if not is_source(pchlist[1]):
1618
+ raise InvalidArguments('PCH definition must contain one header and at most one source.')
1619
+ elif is_source(pchlist[0]):
1620
+ if not is_header(pchlist[1]):
1621
+ raise InvalidArguments('PCH definition must contain one header and at most one source.')
1622
+ pchlist = [pchlist[1], pchlist[0]]
1623
+ else:
1624
+ raise InvalidArguments(f'PCH argument {pchlist[0]} is of unknown type.')
1625
+
1626
+ if os.path.dirname(pchlist[0]) != os.path.dirname(pchlist[1]):
1627
+ raise InvalidArguments('PCH files must be stored in the same folder.')
1628
+
1629
+ FeatureDeprecated.single_use('PCH source files', '0.50.0', self.subproject,
1630
+ 'Only a single header file should be used.')
1631
+ elif len(pchlist) > 2:
1632
+ raise InvalidArguments('PCH definition may have a maximum of 2 files.')
1633
+ for f in pchlist:
1634
+ if not isinstance(f, str):
1635
+ raise MesonException('PCH arguments must be strings.')
1636
+ if not os.path.isfile(os.path.join(self.environment.source_dir, self.get_source_subdir(), f)):
1637
+ raise MesonException(f'File {f} does not exist.')
1638
+ self.pch[language] = pchlist
1639
+
1640
+ def add_include_dirs(self, args: T.Sequence['IncludeDirs'], set_is_system: T.Optional[str] = None) -> None:
1641
+ ids: T.List['IncludeDirs'] = []
1642
+ for a in args:
1643
+ if not isinstance(a, IncludeDirs):
1644
+ raise InvalidArguments('Include directory to be added is not an include directory object.')
1645
+ ids.append(a)
1646
+ if set_is_system is None:
1647
+ set_is_system = 'preserve'
1648
+ if set_is_system != 'preserve':
1649
+ is_system = set_is_system == 'system'
1650
+ ids = [IncludeDirs(x.get_curdir(), x.get_incdirs(), is_system, x.get_extra_build_dirs(), x.is_build_only_subproject) for x in ids]
1651
+ self.include_dirs += ids
1652
+
1653
+ def get_aliases(self) -> T.List[T.Tuple[str, str, str]]:
1654
+ return []
1655
+
1656
+ def get_langs_used_by_deps(self) -> T.List[str]:
1657
+ '''
1658
+ Sometimes you want to link to a C++ library that exports C API, which
1659
+ means the linker must link in the C++ stdlib, and we must use a C++
1660
+ compiler for linking. The same is also applicable for objc/objc++, etc,
1661
+ so we can keep using clink_langs for the priority order.
1662
+
1663
+ See: https://github.com/mesonbuild/meson/issues/1653
1664
+ '''
1665
+ langs: T.List[str] = []
1666
+
1667
+ # Check if any of the external libraries were written in this language
1668
+ for dep in self.external_deps:
1669
+ if dep.language is None:
1670
+ continue
1671
+ if dep.language not in langs:
1672
+ langs.append(dep.language)
1673
+ # Check if any of the internal libraries this target links to were
1674
+ # written in this language
1675
+ for link_target in itertools.chain(self.link_targets, self.link_whole_targets):
1676
+ if isinstance(link_target, (CustomTarget, CustomTargetIndex)):
1677
+ continue
1678
+ for language in link_target.compilers:
1679
+ if language not in langs:
1680
+ langs.append(language)
1681
+
1682
+ return langs
1683
+
1684
+ def get_prelinker(self):
1685
+ if self.link_language:
1686
+ comp = self.all_compilers[self.link_language]
1687
+ return comp
1688
+ for l in clink_langs:
1689
+ if l in self.compilers:
1690
+ try:
1691
+ prelinker = self.all_compilers[l]
1692
+ except KeyError:
1693
+ raise MesonException(
1694
+ f'Could not get a prelinker linker for build target {self.name!r}. '
1695
+ f'Requires a compiler for language "{l}", but that is not '
1696
+ 'a project language.')
1697
+ return prelinker
1698
+ raise MesonException(f'Could not determine prelinker for {self.name!r}.')
1699
+
1700
+ def get_clink_dynamic_linker_and_stdlibs(self) -> T.Tuple['Compiler', T.List[str]]:
1701
+ '''
1702
+ We use the order of languages in `clink_langs` to determine which
1703
+ linker to use in case the target has sources compiled with multiple
1704
+ compilers. All languages other than those in this list have their own
1705
+ linker.
1706
+ Note that Vala outputs C code, so Vala sources can use any linker
1707
+ that can link compiled C. We don't actually need to add an exception
1708
+ for Vala here because of that.
1709
+ '''
1710
+ # If the user set the link_language, just return that.
1711
+ if self.link_language:
1712
+ comp = self.all_compilers[self.link_language]
1713
+ return comp, comp.language_stdlib_only_link_flags(self.environment)
1714
+
1715
+ # Since dependencies could come from subprojects, they could have
1716
+ # languages we don't have in self.all_compilers. Use the global list of
1717
+ # all compilers here.
1718
+ all_compilers = self.environment.coredata.compilers[self.for_machine]
1719
+
1720
+ # Languages used by dependencies
1721
+ dep_langs = self.get_langs_used_by_deps()
1722
+
1723
+ # Pick a compiler based on the language priority-order
1724
+ for l in clink_langs:
1725
+ if l in self.compilers or l in dep_langs:
1726
+ try:
1727
+ linker = all_compilers[l]
1728
+ except KeyError:
1729
+ raise MesonException(
1730
+ f'Could not get a dynamic linker for build target {self.name!r}. '
1731
+ f'Requires a linker for language "{l}", but that is not '
1732
+ 'a project language.')
1733
+ stdlib_args: T.List[str] = self.get_used_stdlib_args(linker.language)
1734
+ # Type of var 'linker' is Compiler.
1735
+ # Pretty hard to fix because the return value is passed everywhere
1736
+ return linker, stdlib_args
1737
+
1738
+ # None of our compilers can do clink, this happens for example if the
1739
+ # target only has ASM sources. Pick the first capable compiler.
1740
+ for l in clink_langs:
1741
+ try:
1742
+ comp = self.all_compilers[l]
1743
+ return comp, comp.language_stdlib_only_link_flags(self.environment)
1744
+ except KeyError:
1745
+ pass
1746
+
1747
+ raise AssertionError(f'Could not get a dynamic linker for build target {self.name!r}')
1748
+
1749
+ def get_used_stdlib_args(self, link_language: str) -> T.List[str]:
1750
+ all_compilers = self.environment.coredata.compilers[self.for_machine]
1751
+ all_langs = set(self.compilers).union(self.get_langs_used_by_deps())
1752
+ stdlib_args: T.List[str] = []
1753
+ for dl in all_langs:
1754
+ if dl != link_language and (dl, link_language) not in self._MASK_LANGS:
1755
+ # We need to use all_compilers here because
1756
+ # get_langs_used_by_deps could return a language from a
1757
+ # subproject
1758
+ stdlib_args.extend(all_compilers[dl].language_stdlib_only_link_flags(self.environment))
1759
+ return stdlib_args
1760
+
1761
+ def uses_rust(self) -> bool:
1762
+ return 'rust' in self.compilers
1763
+
1764
+ def uses_rust_abi(self) -> bool:
1765
+ return self.uses_rust() and self.rust_crate_type in {'dylib', 'rlib', 'proc-macro'}
1766
+
1767
+ def uses_fortran(self) -> bool:
1768
+ return 'fortran' in self.compilers
1769
+
1770
+ def get_using_msvc(self) -> bool:
1771
+ '''
1772
+ Check if the dynamic linker is MSVC. Used by Executable, StaticLibrary,
1773
+ and SharedLibrary for deciding when to use MSVC-specific file naming
1774
+ and debug filenames.
1775
+
1776
+ If at least some code is built with MSVC and the final library is
1777
+ linked with MSVC, we can be sure that some debug info will be
1778
+ generated. We only check the dynamic linker here because the static
1779
+ linker is guaranteed to be of the same type.
1780
+
1781
+ Interesting cases:
1782
+ 1. The Vala compiler outputs C code to be compiled by whatever
1783
+ C compiler we're using, so all objects will still be created by the
1784
+ MSVC compiler.
1785
+ 2. If the target contains only objects, process_compilers guesses and
1786
+ picks the first compiler that smells right.
1787
+ '''
1788
+ # Rustc can use msvc style linkers
1789
+ if self.uses_rust():
1790
+ compiler = self.all_compilers['rust']
1791
+ else:
1792
+ compiler, _ = self.get_clink_dynamic_linker_and_stdlibs()
1793
+ # Mixing many languages with MSVC is not supported yet so ignore stdlibs.
1794
+ return compiler and compiler.get_linker_id() in {'link', 'lld-link', 'xilink', 'optlink'}
1795
+
1796
+ def check_module_linking(self):
1797
+ '''
1798
+ Warn if shared modules are linked with target: (link_with) #2865
1799
+ '''
1800
+ for link_target in self.link_targets:
1801
+ if isinstance(link_target, SharedModule) and not link_target.force_soname:
1802
+ if self.environment.machines[self.for_machine].is_darwin():
1803
+ raise MesonException(
1804
+ f'target {self.name} links against shared module {link_target.name}. This is not permitted on OSX')
1805
+ elif self.environment.machines[self.for_machine].is_android() and isinstance(self, SharedModule):
1806
+ # Android requires shared modules that use symbols from other shared modules to
1807
+ # be linked before they can be dlopen()ed in the correct order. Not doing so
1808
+ # leads to a missing symbol error: https://github.com/android/ndk/issues/201
1809
+ link_target.force_soname = True
1810
+ else:
1811
+ mlog.deprecation(f'target {self.name} links against shared module {link_target.name}, which is incorrect.'
1812
+ '\n '
1813
+ f'This will be an error in the future, so please use shared_library() for {link_target.name} instead.'
1814
+ '\n '
1815
+ f'If shared_module() was used for {link_target.name} because it has references to undefined symbols,'
1816
+ '\n '
1817
+ 'use shared_library() with `override_options: [\'b_lundef=false\']` instead.')
1818
+ link_target.force_soname = True
1819
+
1820
+ def process_vs_module_defs_kw(self, kwargs: T.Dict[str, T.Any]) -> None:
1821
+ if kwargs.get('vs_module_defs') is None:
1822
+ return
1823
+
1824
+ path: T.Union[str, File, CustomTarget, CustomTargetIndex] = kwargs['vs_module_defs']
1825
+ if isinstance(path, str):
1826
+ if os.path.isabs(path):
1827
+ self.vs_module_defs = File.from_absolute_file(path)
1828
+ else:
1829
+ self.vs_module_defs = File.from_source_file(self.environment.source_dir, self.subdir, path)
1830
+ elif isinstance(path, File):
1831
+ # When passing a generated file.
1832
+ self.vs_module_defs = path
1833
+ elif isinstance(path, (CustomTarget, CustomTargetIndex)):
1834
+ # When passing output of a Custom Target
1835
+ self.vs_module_defs = File.from_built_file(path.get_output_subdir(), path.get_filename())
1836
+ else:
1837
+ raise InvalidArguments(
1838
+ 'vs_module_defs must be either a string, '
1839
+ 'a file object, a Custom Target, or a Custom Target Index')
1840
+ self.process_link_depends(path)
1841
+
1842
+ class FileInTargetPrivateDir:
1843
+ """Represents a file with the path '/path/to/build/target_private_dir/fname'.
1844
+ target_private_dir is the return value of get_target_private_dir which is e.g. 'subdir/target.p'.
1845
+ """
1846
+
1847
+ def __init__(self, fname: str):
1848
+ self.fname = fname
1849
+
1850
+ def __str__(self) -> str:
1851
+ return self.fname
1852
+
1853
+ class FileMaybeInTargetPrivateDir:
1854
+ """Union between 'File' and 'FileInTargetPrivateDir'"""
1855
+
1856
+ def __init__(self, inner: T.Union[File, FileInTargetPrivateDir]):
1857
+ self.inner = inner
1858
+
1859
+ @property
1860
+ def fname(self) -> str:
1861
+ return self.inner.fname
1862
+
1863
+ def rel_to_builddir(self, build_to_src: str, target_private_dir: str) -> str:
1864
+ if isinstance(self.inner, FileInTargetPrivateDir):
1865
+ return os.path.join(target_private_dir, self.inner.fname)
1866
+ return self.inner.rel_to_builddir(build_to_src)
1867
+
1868
+ def absolute_path(self, srcdir: str, builddir: str) -> str:
1869
+ if isinstance(self.inner, FileInTargetPrivateDir):
1870
+ raise RuntimeError('Unreachable code')
1871
+ return self.inner.absolute_path(srcdir, builddir)
1872
+
1873
+ def __str__(self) -> str:
1874
+ return self.fname
1875
+
1876
+ class Generator(HoldableObject):
1877
+ def __init__(self, exe: T.Union['Executable', programs.ExternalProgram],
1878
+ arguments: T.List[str],
1879
+ output: T.List[str],
1880
+ # how2dataclass
1881
+ *,
1882
+ depfile: T.Optional[str] = None,
1883
+ capture: bool = False,
1884
+ depends: T.Optional[T.List[T.Union[BuildTarget, 'CustomTarget', 'CustomTargetIndex']]] = None,
1885
+ name: str = 'Generator'):
1886
+ self.exe = exe
1887
+ self.depfile = depfile
1888
+ self.capture = capture
1889
+ self.depends: T.List[T.Union[BuildTarget, 'CustomTarget', 'CustomTargetIndex']] = depends or []
1890
+ self.arglist = arguments
1891
+ self.outputs = output
1892
+ self.name = name
1893
+
1894
+ def __repr__(self) -> str:
1895
+ repr_str = "<{0}: {1}>"
1896
+ return repr_str.format(self.__class__.__name__, self.exe)
1897
+
1898
+ def get_exe(self) -> T.Union['Executable', programs.ExternalProgram]:
1899
+ return self.exe
1900
+
1901
+ def get_base_outnames(self, inname: str) -> T.List[str]:
1902
+ plainname = os.path.basename(inname)
1903
+ basename = os.path.splitext(plainname)[0]
1904
+ bases = [x.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname) for x in self.outputs]
1905
+ return bases
1906
+
1907
+ def get_dep_outname(self, inname: str) -> T.List[str]:
1908
+ if self.depfile is None:
1909
+ raise InvalidArguments('Tried to get dep name for rule that does not have dependency file defined.')
1910
+ plainname = os.path.basename(inname)
1911
+ basename = os.path.splitext(plainname)[0]
1912
+ return self.depfile.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname)
1913
+
1914
+ def get_arglist(self, inname: str) -> T.List[str]:
1915
+ plainname = os.path.basename(inname)
1916
+ basename = os.path.splitext(plainname)[0]
1917
+ return [x.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname) for x in self.arglist]
1918
+
1919
+ @staticmethod
1920
+ def is_parent_path(parent: str, trial: str) -> bool:
1921
+ try:
1922
+ common = os.path.commonpath((parent, trial))
1923
+ except ValueError: # Windows on different drives
1924
+ return False
1925
+ return pathlib.PurePath(common) == pathlib.PurePath(parent)
1926
+
1927
+ def process_files(self, files: T.Iterable[T.Union[str, File, 'CustomTarget', 'CustomTargetIndex', 'GeneratedList']],
1928
+ state: T.Union['Interpreter', 'ModuleState'],
1929
+ preserve_path_from: T.Optional[str] = None,
1930
+ extra_args: T.Optional[T.List[str]] = None,
1931
+ env: T.Optional[EnvironmentVariables] = None) -> 'GeneratedList':
1932
+ # TODO: need a test for a generator in a build-only subproject
1933
+ is_build_only: T.Optional[bool] = getattr(state, 'is_build_only_subproject', None)
1934
+ if is_build_only is None:
1935
+ is_build_only = T.cast('Interpreter', state).coredata.is_build_only
1936
+ output = GeneratedList(
1937
+ self,
1938
+ state.subdir,
1939
+ preserve_path_from,
1940
+ extra_args=extra_args if extra_args is not None else [],
1941
+ env=env if env is not None else EnvironmentVariables(),
1942
+ is_build_only_subproject=is_build_only,
1943
+ )
1944
+
1945
+ for e in files:
1946
+ if isinstance(e, CustomTarget):
1947
+ output.depends.add(e)
1948
+ if isinstance(e, CustomTargetIndex):
1949
+ output.depends.add(e.target)
1950
+ if isinstance(e, (CustomTarget, CustomTargetIndex)):
1951
+ output.depends.add(e)
1952
+ fs = [File.from_built_file(e.get_output_subdir(), f) for f in e.get_outputs()]
1953
+ elif isinstance(e, GeneratedList):
1954
+ if preserve_path_from:
1955
+ raise InvalidArguments("generator.process: 'preserve_path_from' is not allowed if one input is a 'generated_list'.")
1956
+ output.depends.add(e)
1957
+ fs = [FileInTargetPrivateDir(f) for f in e.get_outputs()]
1958
+ elif isinstance(e, str):
1959
+ fs = [File.from_source_file(state.environment.source_dir, state.subdir, e)]
1960
+ else:
1961
+ fs = [e]
1962
+
1963
+ for f in fs:
1964
+ if preserve_path_from:
1965
+ abs_f = f.absolute_path(state.environment.source_dir, state.environment.build_dir)
1966
+ if not self.is_parent_path(preserve_path_from, abs_f):
1967
+ raise InvalidArguments('generator.process: When using preserve_path_from, all input files must be in a subdirectory of the given dir.')
1968
+ f = FileMaybeInTargetPrivateDir(f)
1969
+ output.add_file(f, state)
1970
+ return output
1971
+
1972
+
1973
+ @dataclass(eq=False)
1974
+ class GeneratedList(HoldableObject):
1975
+
1976
+ """The output of generator.process."""
1977
+
1978
+ generator: Generator
1979
+ subdir: str
1980
+ preserve_path_from: T.Optional[str]
1981
+ extra_args: T.List[str]
1982
+ env: T.Optional[EnvironmentVariables]
1983
+ is_build_only_subproject: bool
1984
+
1985
+ def __post_init__(self) -> None:
1986
+ self.name = self.generator.exe
1987
+ self.depends: T.Set[GeneratedTypes] = set()
1988
+ self.infilelist: T.List[FileMaybeInTargetPrivateDir] = []
1989
+ self.outfilelist: T.List[str] = []
1990
+ self.outmap: T.Dict[FileMaybeInTargetPrivateDir, T.List[str]] = {}
1991
+ self.extra_depends = [] # XXX: Doesn't seem to be used?
1992
+ self.depend_files: T.List[File] = []
1993
+
1994
+ if self.extra_args is None:
1995
+ self.extra_args: T.List[str] = []
1996
+
1997
+ if self.env is None:
1998
+ self.env: EnvironmentVariables = EnvironmentVariables()
1999
+
2000
+ if isinstance(self.generator.exe, programs.ExternalProgram):
2001
+ if not self.generator.exe.found():
2002
+ raise InvalidArguments('Tried to use not-found external program as generator')
2003
+ path = self.generator.exe.get_path()
2004
+ if os.path.isabs(path):
2005
+ # Can only add a dependency on an external program which we
2006
+ # know the absolute path of
2007
+ self.depend_files.append(File.from_absolute_file(path))
2008
+
2009
+ def add_preserved_path_segment(self, infile: FileMaybeInTargetPrivateDir, outfiles: T.List[str], state: T.Union['Interpreter', 'ModuleState']) -> T.List[str]:
2010
+ result: T.List[str] = []
2011
+ in_abs = infile.absolute_path(state.environment.source_dir, state.environment.build_dir)
2012
+ assert os.path.isabs(self.preserve_path_from)
2013
+ rel = os.path.relpath(in_abs, self.preserve_path_from)
2014
+ path_segment = os.path.dirname(rel)
2015
+ for of in outfiles:
2016
+ result.append(os.path.join(path_segment, of))
2017
+ return result
2018
+
2019
+ def add_file(self, newfile: FileMaybeInTargetPrivateDir, state: T.Union['Interpreter', 'ModuleState']) -> None:
2020
+ self.infilelist.append(newfile)
2021
+ outfiles = self.generator.get_base_outnames(newfile.fname)
2022
+ if self.preserve_path_from:
2023
+ outfiles = self.add_preserved_path_segment(newfile, outfiles, state)
2024
+ self.outfilelist += outfiles
2025
+ self.outmap[newfile] = outfiles
2026
+
2027
+ def get_inputs(self) -> T.List[FileMaybeInTargetPrivateDir]:
2028
+ return self.infilelist
2029
+
2030
+ def get_outputs(self) -> T.List[str]:
2031
+ return self.outfilelist
2032
+
2033
+ def get_outputs_for(self, filename: FileMaybeInTargetPrivateDir) -> T.List[str]:
2034
+ return self.outmap[filename]
2035
+
2036
+ def get_generator(self) -> 'Generator':
2037
+ return self.generator
2038
+
2039
+ def get_extra_args(self) -> T.List[str]:
2040
+ return self.extra_args
2041
+
2042
+ def get_source_subdir(self) -> str:
2043
+ return self.subdir
2044
+
2045
+ def get_output_subdir(self) -> str:
2046
+ return compute_build_subdir(self.subdir, self.is_build_only_subproject)
2047
+
2048
+
2049
+ class Executable(BuildTarget):
2050
+ known_kwargs = known_exe_kwargs
2051
+
2052
+ typename = 'executable'
2053
+
2054
+ def __init__(
2055
+ self,
2056
+ name: str,
2057
+ subdir: str,
2058
+ subproject: SubProject,
2059
+ for_machine: MachineChoice,
2060
+ sources: T.List['SourceOutputs'],
2061
+ structured_sources: T.Optional[StructuredSources],
2062
+ objects: T.List[ObjectTypes],
2063
+ environment: environment.Environment,
2064
+ compilers: T.Dict[str, 'Compiler'],
2065
+ build_only_subproject: bool,
2066
+ kwargs):
2067
+ key = OptionKey('b_pie')
2068
+ if 'pie' not in kwargs and key in environment.coredata.options:
2069
+ kwargs['pie'] = environment.coredata.options[key].value
2070
+ super().__init__(name, subdir, subproject, for_machine, sources, structured_sources, objects,
2071
+ environment, compilers, build_only_subproject, kwargs)
2072
+ self.win_subsystem = kwargs.get('win_subsystem') or 'console'
2073
+ # Check for export_dynamic
2074
+ self.export_dynamic = kwargs.get('export_dynamic', False)
2075
+ if not isinstance(self.export_dynamic, bool):
2076
+ raise InvalidArguments('"export_dynamic" keyword argument must be a boolean')
2077
+ self.implib = kwargs.get('implib')
2078
+ if not isinstance(self.implib, (bool, str, type(None))):
2079
+ raise InvalidArguments('"export_dynamic" keyword argument must be a boolean or string')
2080
+ # Only linkwithable if using export_dynamic
2081
+ self.is_linkwithable = self.export_dynamic
2082
+ # Remember that this exe was returned by `find_program()` through an override
2083
+ self.was_returned_by_find_program = False
2084
+
2085
+ self.vs_module_defs: T.Optional[File] = None
2086
+ self.process_vs_module_defs_kw(kwargs)
2087
+
2088
+ def post_init(self) -> None:
2089
+ super().post_init()
2090
+ machine = self.environment.machines[self.for_machine]
2091
+ # Unless overridden, executables have no suffix or prefix. Except on
2092
+ # Windows and with C#/Mono executables where the suffix is 'exe'
2093
+ if not hasattr(self, 'prefix'):
2094
+ self.prefix = ''
2095
+ if not hasattr(self, 'suffix'):
2096
+ # Executable for Windows or C#/Mono
2097
+ if machine.is_windows() or machine.is_cygwin() or 'cs' in self.compilers:
2098
+ self.suffix = 'exe'
2099
+ elif machine.system.startswith('wasm') or machine.system == 'emscripten':
2100
+ self.suffix = 'js'
2101
+ elif ('c' in self.compilers and self.compilers['c'].get_id().startswith('armclang') or
2102
+ 'cpp' in self.compilers and self.compilers['cpp'].get_id().startswith('armclang')):
2103
+ self.suffix = 'axf'
2104
+ elif ('c' in self.compilers and self.compilers['c'].get_id().startswith('ccrx') or
2105
+ 'cpp' in self.compilers and self.compilers['cpp'].get_id().startswith('ccrx')):
2106
+ self.suffix = 'abs'
2107
+ elif ('c' in self.compilers and self.compilers['c'].get_id().startswith('xc16')):
2108
+ self.suffix = 'elf'
2109
+ elif ('c' in self.compilers and self.compilers['c'].get_id() in {'ti', 'c2000', 'c6000'} or
2110
+ 'cpp' in self.compilers and self.compilers['cpp'].get_id() in {'ti', 'c2000', 'c6000'}):
2111
+ self.suffix = 'out'
2112
+ elif ('c' in self.compilers and self.compilers['c'].get_id() in {'mwccarm', 'mwcceppc'} or
2113
+ 'cpp' in self.compilers and self.compilers['cpp'].get_id() in {'mwccarm', 'mwcceppc'}):
2114
+ self.suffix = 'nef'
2115
+ else:
2116
+ self.suffix = machine.get_exe_suffix()
2117
+ self.filename = self.name
2118
+ if self.suffix:
2119
+ self.filename += '.' + self.suffix
2120
+ self.outputs[0] = self.filename
2121
+
2122
+ # The import library this target will generate
2123
+ self.import_filename = None
2124
+ # The debugging information file this target will generate
2125
+ self.debug_filename = None
2126
+
2127
+ # If using export_dynamic, set the import library name
2128
+ if self.export_dynamic:
2129
+ implib_basename = self.name + '.exe'
2130
+ if isinstance(self.implib, str):
2131
+ implib_basename = self.implib
2132
+ if machine.is_windows() or machine.is_cygwin():
2133
+ if self.get_using_msvc():
2134
+ self.import_filename = f'{implib_basename}.lib'
2135
+ else:
2136
+ self.import_filename = f'lib{implib_basename}.a'
2137
+
2138
+ create_debug_file = (
2139
+ machine.is_windows()
2140
+ and ('cs' in self.compilers or self.uses_rust() or self.get_using_msvc())
2141
+ # .pdb file is created only when debug symbols are enabled
2142
+ and self.environment.coredata.get_option(OptionKey("debug"))
2143
+ )
2144
+ if create_debug_file:
2145
+ # If the target is has a standard exe extension (i.e. 'foo.exe'),
2146
+ # then the pdb name simply becomes 'foo.pdb'. If the extension is
2147
+ # something exotic, then include that in the name for uniqueness
2148
+ # reasons (e.g. 'foo_com.pdb').
2149
+ name = self.name
2150
+ if getattr(self, 'suffix', 'exe') != 'exe':
2151
+ name += '_' + self.suffix
2152
+ self.debug_filename = name + '.pdb'
2153
+
2154
+ def process_kwargs(self, kwargs):
2155
+ super().process_kwargs(kwargs)
2156
+
2157
+ self.rust_crate_type = kwargs.get('rust_crate_type') or 'bin'
2158
+ if self.rust_crate_type != 'bin':
2159
+ raise InvalidArguments('Invalid rust_crate_type: must be "bin" for executables.')
2160
+
2161
+ def get_default_install_dir(self) -> T.Union[T.Tuple[str, str], T.Tuple[None, None]]:
2162
+ return self.environment.get_bindir(), '{bindir}'
2163
+
2164
+ def description(self):
2165
+ '''Human friendly description of the executable'''
2166
+ return self.name
2167
+
2168
+ def type_suffix(self):
2169
+ return "@exe"
2170
+
2171
+ def get_import_filename(self) -> T.Optional[str]:
2172
+ """
2173
+ The name of the import library that will be outputted by the compiler
2174
+
2175
+ Returns None if there is no import library required for this platform
2176
+ """
2177
+ return self.import_filename
2178
+
2179
+ def get_debug_filename(self) -> T.Optional[str]:
2180
+ """
2181
+ The name of debuginfo file that will be created by the compiler
2182
+
2183
+ Returns None if the build won't create any debuginfo file
2184
+ """
2185
+ return self.debug_filename
2186
+
2187
+ def is_linkable_target(self):
2188
+ return self.is_linkwithable
2189
+
2190
+ def get_command(self) -> 'ImmutableListProtocol[str]':
2191
+ """Provides compatibility with ExternalProgram.
2192
+
2193
+ Since you can override ExternalProgram instances with Executables.
2194
+ """
2195
+ return self.outputs
2196
+
2197
+ def get_path(self) -> str:
2198
+ """Provides compatibility with ExternalProgram."""
2199
+ return os.path.join(self.subdir, self.filename)
2200
+
2201
+ def found(self) -> bool:
2202
+ """Provides compatibility with ExternalProgram."""
2203
+ return True
2204
+
2205
+
2206
+ class StaticLibrary(BuildTarget):
2207
+ known_kwargs = known_stlib_kwargs
2208
+
2209
+ typename = 'static library'
2210
+
2211
+ def __init__(
2212
+ self,
2213
+ name: str,
2214
+ subdir: str,
2215
+ subproject: SubProject,
2216
+ for_machine: MachineChoice,
2217
+ sources: T.List['SourceOutputs'],
2218
+ structured_sources: T.Optional[StructuredSources],
2219
+ objects: T.List[ObjectTypes],
2220
+ environment: environment.Environment,
2221
+ compilers: T.Dict[str, 'Compiler'],
2222
+ build_only_subproject: bool,
2223
+ kwargs):
2224
+ self.prelink = T.cast('bool', kwargs.get('prelink', False))
2225
+ super().__init__(name, subdir, subproject, for_machine, sources, structured_sources, objects,
2226
+ environment, compilers, build_only_subproject, kwargs)
2227
+
2228
+ def post_init(self) -> None:
2229
+ super().post_init()
2230
+ if 'cs' in self.compilers:
2231
+ raise InvalidArguments('Static libraries not supported for C#.')
2232
+ if self.uses_rust():
2233
+ # See https://github.com/rust-lang/rust/issues/110460
2234
+ if self.rust_crate_type == 'rlib' and any(c in self.name for c in ['-', ' ', '.']):
2235
+ raise InvalidArguments(f'Rust crate {self.name} type {self.rust_crate_type} does not allow spaces, '
2236
+ 'periods or dashes in the library name due to a limitation of rustc. '
2237
+ 'Replace them with underscores, for example')
2238
+ if self.rust_crate_type == 'staticlib':
2239
+ # FIXME: In the case of no-std we should not add those libraries,
2240
+ # but we have no way to know currently.
2241
+ rustc = self.compilers['rust']
2242
+ d = dependencies.InternalDependency('undefined', [], [],
2243
+ rustc.native_static_libs,
2244
+ [], [], [], [], [], {}, [], [], [])
2245
+ self.external_deps.append(d)
2246
+ # By default a static library is named libfoo.a even on Windows because
2247
+ # MSVC does not have a consistent convention for what static libraries
2248
+ # are called. The MSVC CRT uses libfoo.lib syntax but nothing else uses
2249
+ # it and GCC only looks for static libraries called foo.lib and
2250
+ # libfoo.a. However, we cannot use foo.lib because that's the same as
2251
+ # the import library. Using libfoo.a is ok because people using MSVC
2252
+ # always pass the library filename while linking anyway.
2253
+ #
2254
+ # See our FAQ for more detailed rationale:
2255
+ # https://mesonbuild.com/FAQ.html#why-does-building-my-project-with-msvc-output-static-libraries-called-libfooa
2256
+ if not hasattr(self, 'prefix'):
2257
+ self.prefix = 'lib'
2258
+ if not hasattr(self, 'suffix'):
2259
+ if self.uses_rust():
2260
+ if self.rust_crate_type == 'rlib':
2261
+ # default Rust static library suffix
2262
+ self.suffix = 'rlib'
2263
+ elif self.rust_crate_type == 'staticlib':
2264
+ self.suffix = 'a'
2265
+ else:
2266
+ self.suffix = 'a'
2267
+ self.filename = self.prefix + self.name + '.' + self.suffix
2268
+ self.outputs[0] = self.filename
2269
+
2270
+ def get_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
2271
+ return {}
2272
+
2273
+ def get_default_install_dir(self) -> T.Union[T.Tuple[str, str], T.Tuple[None, None]]:
2274
+ return self.environment.get_static_lib_dir(), '{libdir_static}'
2275
+
2276
+ def type_suffix(self):
2277
+ return "@sta"
2278
+
2279
+ def process_kwargs(self, kwargs):
2280
+ super().process_kwargs(kwargs)
2281
+
2282
+ rust_abi = kwargs.get('rust_abi')
2283
+ rust_crate_type = kwargs.get('rust_crate_type')
2284
+ if rust_crate_type:
2285
+ if rust_abi:
2286
+ raise InvalidArguments('rust_abi and rust_crate_type are mutually exclusive.')
2287
+ if rust_crate_type == 'lib':
2288
+ self.rust_crate_type = 'rlib'
2289
+ elif rust_crate_type in {'rlib', 'staticlib'}:
2290
+ self.rust_crate_type = rust_crate_type
2291
+ else:
2292
+ raise InvalidArguments(f'Crate type {rust_crate_type!r} invalid for static libraries; must be "rlib" or "staticlib"')
2293
+ else:
2294
+ self.rust_crate_type = 'staticlib' if rust_abi == 'c' else 'rlib'
2295
+
2296
+ def is_linkable_target(self):
2297
+ return True
2298
+
2299
+ def is_internal(self) -> bool:
2300
+ return not self.install
2301
+
2302
+ class SharedLibrary(BuildTarget):
2303
+ known_kwargs = known_shlib_kwargs
2304
+
2305
+ typename = 'shared library'
2306
+
2307
+ # Used by AIX to decide whether to archive shared library or not.
2308
+ aix_so_archive = True
2309
+
2310
+ def __init__(
2311
+ self,
2312
+ name: str,
2313
+ subdir: str,
2314
+ subproject: SubProject,
2315
+ for_machine: MachineChoice,
2316
+ sources: T.List['SourceOutputs'],
2317
+ structured_sources: T.Optional[StructuredSources],
2318
+ objects: T.List[ObjectTypes],
2319
+ environment: environment.Environment,
2320
+ compilers: T.Dict[str, 'Compiler'],
2321
+ build_only_subproject: bool,
2322
+ kwargs):
2323
+ self.soversion: T.Optional[str] = None
2324
+ self.ltversion: T.Optional[str] = None
2325
+ # Max length 2, first element is compatibility_version, second is current_version
2326
+ self.darwin_versions: T.Optional[T.Tuple[str, str]] = None
2327
+ self.vs_module_defs = None
2328
+ # The import library this target will generate
2329
+ self.import_filename = None
2330
+ # The debugging information file this target will generate
2331
+ self.debug_filename = None
2332
+ # Use by the pkgconfig module
2333
+ self.shared_library_only = False
2334
+ super().__init__(name, subdir, subproject, for_machine, sources, structured_sources, objects,
2335
+ environment, compilers, build_only_subproject, kwargs)
2336
+
2337
+ def post_init(self) -> None:
2338
+ super().post_init()
2339
+ if self.uses_rust():
2340
+ # See https://github.com/rust-lang/rust/issues/110460
2341
+ if self.rust_crate_type != 'cdylib' and any(c in self.name for c in ['-', ' ', '.']):
2342
+ raise InvalidArguments(f'Rust crate {self.name} type {self.rust_crate_type} does not allow spaces, '
2343
+ 'periods or dashes in the library name due to a limitation of rustc. '
2344
+ 'Replace them with underscores, for example')
2345
+
2346
+ if not hasattr(self, 'prefix'):
2347
+ self.prefix = None
2348
+ if not hasattr(self, 'suffix'):
2349
+ self.suffix = None
2350
+ self.basic_filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2351
+ self.determine_filenames()
2352
+
2353
+ def get_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
2354
+ result: T.Dict[str, str] = {}
2355
+ mappings = self.get_transitive_link_deps_mapping(prefix)
2356
+ old = get_target_macos_dylib_install_name(self)
2357
+ if old not in mappings:
2358
+ fname = self.get_filename()
2359
+ outdirs, _, _ = self.get_install_dir()
2360
+ new = os.path.join(prefix, outdirs[0], fname)
2361
+ result.update({old: new})
2362
+ mappings.update(result)
2363
+ return mappings
2364
+
2365
+ def get_default_install_dir(self) -> T.Union[T.Tuple[str, str], T.Tuple[None, None]]:
2366
+ return self.environment.get_shared_lib_dir(), '{libdir_shared}'
2367
+
2368
+ def determine_filenames(self):
2369
+ """
2370
+ See https://github.com/mesonbuild/meson/pull/417 for details.
2371
+
2372
+ First we determine the filename template (self.filename_tpl), then we
2373
+ set the output filename (self.filename).
2374
+
2375
+ The template is needed while creating aliases (self.get_aliases),
2376
+ which are needed while generating .so shared libraries for Linux.
2377
+
2378
+ Besides this, there's also the import library name (self.import_filename),
2379
+ which is only used on Windows since on that platform the linker uses a
2380
+ separate library called the "import library" during linking instead of
2381
+ the shared library (DLL).
2382
+ """
2383
+ prefix = ''
2384
+ suffix = ''
2385
+ create_debug_file = False
2386
+ self.filename_tpl = self.basic_filename_tpl
2387
+ import_filename_tpl = None
2388
+ # NOTE: manual prefix/suffix override is currently only tested for C/C++
2389
+ # C# and Mono
2390
+ if 'cs' in self.compilers:
2391
+ prefix = ''
2392
+ suffix = 'dll'
2393
+ self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2394
+ create_debug_file = True
2395
+ # C, C++, Swift, Vala
2396
+ # Only Windows uses a separate import library for linking
2397
+ # For all other targets/platforms import_filename stays None
2398
+ elif self.environment.machines[self.for_machine].is_windows():
2399
+ suffix = 'dll'
2400
+ if self.uses_rust():
2401
+ # Shared library is of the form foo.dll
2402
+ prefix = ''
2403
+ # Import library is called foo.dll.lib
2404
+ import_filename_tpl = '{0.prefix}{0.name}.dll.lib'
2405
+ # .pdb file is only created when debug symbols are enabled
2406
+ create_debug_file = self.environment.coredata.get_option(OptionKey("debug"))
2407
+ elif self.get_using_msvc():
2408
+ # Shared library is of the form foo.dll
2409
+ prefix = ''
2410
+ # Import library is called foo.lib
2411
+ import_filename_tpl = '{0.prefix}{0.name}.lib'
2412
+ # .pdb file is only created when debug symbols are enabled
2413
+ create_debug_file = self.environment.coredata.get_option(OptionKey("debug"))
2414
+ # Assume GCC-compatible naming
2415
+ else:
2416
+ # Shared library is of the form libfoo.dll
2417
+ prefix = 'lib'
2418
+ # Import library is called libfoo.dll.a
2419
+ import_filename_tpl = '{0.prefix}{0.name}.dll.a'
2420
+ # Shared library has the soversion if it is defined
2421
+ if self.soversion:
2422
+ self.filename_tpl = '{0.prefix}{0.name}-{0.soversion}.{0.suffix}'
2423
+ else:
2424
+ self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2425
+ elif self.environment.machines[self.for_machine].is_cygwin():
2426
+ suffix = 'dll'
2427
+ # Shared library is of the form cygfoo.dll
2428
+ # (ld --dll-search-prefix=cyg is the default)
2429
+ prefix = 'cyg'
2430
+ # Import library is called libfoo.dll.a
2431
+ import_prefix = self.prefix if self.prefix is not None else 'lib'
2432
+ import_filename_tpl = import_prefix + '{0.name}.dll.a'
2433
+ if self.soversion:
2434
+ self.filename_tpl = '{0.prefix}{0.name}-{0.soversion}.{0.suffix}'
2435
+ else:
2436
+ self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2437
+ elif self.environment.machines[self.for_machine].is_darwin():
2438
+ prefix = 'lib'
2439
+ suffix = 'dylib'
2440
+ # On macOS, the filename can only contain the major version
2441
+ if self.soversion:
2442
+ # libfoo.X.dylib
2443
+ self.filename_tpl = '{0.prefix}{0.name}.{0.soversion}.{0.suffix}'
2444
+ else:
2445
+ # libfoo.dylib
2446
+ self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2447
+ elif self.environment.machines[self.for_machine].is_android():
2448
+ prefix = 'lib'
2449
+ suffix = 'so'
2450
+ # Android doesn't support shared_library versioning
2451
+ self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2452
+ else:
2453
+ prefix = 'lib'
2454
+ suffix = 'so'
2455
+ if self.ltversion:
2456
+ # libfoo.so.X[.Y[.Z]] (.Y and .Z are optional)
2457
+ self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}.{0.ltversion}'
2458
+ elif self.soversion:
2459
+ # libfoo.so.X
2460
+ self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}.{0.soversion}'
2461
+ else:
2462
+ # No versioning, libfoo.so
2463
+ self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2464
+ if self.prefix is None:
2465
+ self.prefix = prefix
2466
+ if self.suffix is None:
2467
+ self.suffix = suffix
2468
+ self.filename = self.filename_tpl.format(self)
2469
+ if import_filename_tpl:
2470
+ self.import_filename = import_filename_tpl.format(self)
2471
+ # There may have been more outputs added by the time we get here, so
2472
+ # only replace the first entry
2473
+ self.outputs[0] = self.filename
2474
+ if create_debug_file:
2475
+ self.debug_filename = os.path.splitext(self.filename)[0] + '.pdb'
2476
+
2477
+ def process_kwargs(self, kwargs):
2478
+ super().process_kwargs(kwargs)
2479
+
2480
+ if not self.environment.machines[self.for_machine].is_android():
2481
+ # Shared library version
2482
+ self.ltversion = T.cast('T.Optional[str]', kwargs.get('version'))
2483
+ self.soversion = T.cast('T.Optional[str]', kwargs.get('soversion'))
2484
+ if self.soversion is None and self.ltversion is not None:
2485
+ # library version is defined, get the soversion from that
2486
+ # We replicate what Autotools does here and take the first
2487
+ # number of the version by default.
2488
+ self.soversion = self.ltversion.split('.')[0]
2489
+ # macOS, iOS and tvOS dylib compatibility_version and current_version
2490
+ self.darwin_versions = T.cast('T.Optional[T.Tuple[str, str]]', kwargs.get('darwin_versions'))
2491
+ if self.darwin_versions is None and self.soversion is not None:
2492
+ # If unspecified, pick the soversion
2493
+ self.darwin_versions = (self.soversion, self.soversion)
2494
+
2495
+ # Visual Studio module-definitions file
2496
+ self.process_vs_module_defs_kw(kwargs)
2497
+
2498
+ rust_abi = kwargs.get('rust_abi')
2499
+ rust_crate_type = kwargs.get('rust_crate_type')
2500
+ if rust_crate_type:
2501
+ if rust_abi:
2502
+ raise InvalidArguments('rust_abi and rust_crate_type are mutually exclusive.')
2503
+ if rust_crate_type == 'lib':
2504
+ self.rust_crate_type = 'dylib'
2505
+ elif rust_crate_type in {'dylib', 'cdylib', 'proc-macro'}:
2506
+ self.rust_crate_type = rust_crate_type
2507
+ else:
2508
+ raise InvalidArguments(f'Crate type {rust_crate_type!r} invalid for shared libraries; must be "dylib", "cdylib" or "proc-macro"')
2509
+ else:
2510
+ self.rust_crate_type = 'cdylib' if rust_abi == 'c' else 'dylib'
2511
+
2512
+ def get_import_filename(self) -> T.Optional[str]:
2513
+ """
2514
+ The name of the import library that will be outputted by the compiler
2515
+
2516
+ Returns None if there is no import library required for this platform
2517
+ """
2518
+ return self.import_filename
2519
+
2520
+ def get_debug_filename(self) -> T.Optional[str]:
2521
+ """
2522
+ The name of debuginfo file that will be created by the compiler
2523
+
2524
+ Returns None if the build won't create any debuginfo file
2525
+ """
2526
+ return self.debug_filename
2527
+
2528
+ def get_all_link_deps(self):
2529
+ return [self] + self.get_transitive_link_deps()
2530
+
2531
+ def get_aliases(self) -> T.List[T.Tuple[str, str, str]]:
2532
+ """
2533
+ If the versioned library name is libfoo.so.0.100.0, aliases are:
2534
+ * libfoo.so.0 (soversion) -> libfoo.so.0.100.0
2535
+ * libfoo.so (unversioned; for linking) -> libfoo.so.0
2536
+ Same for dylib:
2537
+ * libfoo.dylib (unversioned; for linking) -> libfoo.0.dylib
2538
+ """
2539
+ aliases: T.List[T.Tuple[str, str, str]] = []
2540
+ # Aliases are only useful with .so and .dylib libraries. Also if
2541
+ # there's no self.soversion (no versioning), we don't need aliases.
2542
+ if self.suffix not in ('so', 'dylib') or not self.soversion:
2543
+ return aliases
2544
+ # With .so libraries, the minor and micro versions are also in the
2545
+ # filename. If ltversion != soversion we create an soversion alias:
2546
+ # libfoo.so.0 -> libfoo.so.0.100.0
2547
+ # Where libfoo.so.0.100.0 is the actual library
2548
+ if self.suffix == 'so' and self.ltversion and self.ltversion != self.soversion:
2549
+ alias_tpl = self.filename_tpl.replace('ltversion', 'soversion')
2550
+ ltversion_filename = alias_tpl.format(self)
2551
+ tag = self.install_tag[0] or 'runtime'
2552
+ aliases.append((ltversion_filename, self.filename, tag))
2553
+ # libfoo.so.0/libfoo.0.dylib is the actual library
2554
+ else:
2555
+ ltversion_filename = self.filename
2556
+ # Unversioned alias:
2557
+ # libfoo.so -> libfoo.so.0
2558
+ # libfoo.dylib -> libfoo.0.dylib
2559
+ tag = self.install_tag[0] or 'devel'
2560
+ aliases.append((self.basic_filename_tpl.format(self), ltversion_filename, tag))
2561
+ return aliases
2562
+
2563
+ def type_suffix(self):
2564
+ return "@sha"
2565
+
2566
+ def is_linkable_target(self):
2567
+ return True
2568
+
2569
+ # A shared library that is meant to be used with dlopen rather than linking
2570
+ # into something else.
2571
+ class SharedModule(SharedLibrary):
2572
+ known_kwargs = known_shmod_kwargs
2573
+
2574
+ typename = 'shared module'
2575
+
2576
+ # Used by AIX to not archive shared library for dlopen mechanism
2577
+ aix_so_archive = False
2578
+
2579
+ def __init__(
2580
+ self,
2581
+ name: str,
2582
+ subdir: str,
2583
+ subproject: SubProject,
2584
+ for_machine: MachineChoice,
2585
+ sources: T.List['SourceOutputs'],
2586
+ structured_sources: T.Optional[StructuredSources],
2587
+ objects: T.List[ObjectTypes],
2588
+ environment: environment.Environment,
2589
+ compilers: T.Dict[str, 'Compiler'],
2590
+ build_only_subproject: bool,
2591
+ kwargs):
2592
+ if 'version' in kwargs:
2593
+ raise MesonException('Shared modules must not specify the version kwarg.')
2594
+ if 'soversion' in kwargs:
2595
+ raise MesonException('Shared modules must not specify the soversion kwarg.')
2596
+ super().__init__(name, subdir, subproject, for_machine, sources,
2597
+ structured_sources, objects, environment, compilers, build_only_subproject, kwargs)
2598
+ # We need to set the soname in cases where build files link the module
2599
+ # to build targets, see: https://github.com/mesonbuild/meson/issues/9492
2600
+ self.force_soname = False
2601
+
2602
+ def get_default_install_dir(self) -> T.Union[T.Tuple[str, str], T.Tuple[None, None]]:
2603
+ return self.environment.get_shared_module_dir(), '{moduledir_shared}'
2604
+
2605
+ class BothLibraries(SecondLevelHolder):
2606
+ def __init__(self, shared: SharedLibrary, static: StaticLibrary) -> None:
2607
+ self._preferred_library = 'shared'
2608
+ self.shared = shared
2609
+ self.static = static
2610
+ self.subproject = self.shared.subproject
2611
+
2612
+ def __repr__(self) -> str:
2613
+ return f'<BothLibraries: static={repr(self.static)}; shared={repr(self.shared)}>'
2614
+
2615
+ def get_default_object(self) -> BuildTarget:
2616
+ if self._preferred_library == 'shared':
2617
+ return self.shared
2618
+ elif self._preferred_library == 'static':
2619
+ return self.static
2620
+ raise MesonBugException(f'self._preferred_library == "{self._preferred_library}" is neither "shared" nor "static".')
2621
+
2622
+ class CommandBase:
2623
+
2624
+ depend_files: T.List[File]
2625
+ dependencies: T.List[T.Union[BuildTarget, 'CustomTarget']]
2626
+ subproject: str
2627
+
2628
+ def flatten_command(self, cmd: T.Sequence[T.Union[str, File, programs.ExternalProgram, BuildTargetTypes]]) -> \
2629
+ T.List[T.Union[str, File, BuildTarget, 'CustomTarget']]:
2630
+ cmd = listify(cmd)
2631
+ final_cmd: T.List[T.Union[str, File, BuildTarget, 'CustomTarget']] = []
2632
+ for c in cmd:
2633
+ if isinstance(c, str):
2634
+ final_cmd.append(c)
2635
+ elif isinstance(c, File):
2636
+ self.depend_files.append(c)
2637
+ final_cmd.append(c)
2638
+ elif isinstance(c, programs.ExternalProgram):
2639
+ if not c.found():
2640
+ raise InvalidArguments('Tried to use not-found external program in "command"')
2641
+ path = c.get_path()
2642
+ if os.path.isabs(path):
2643
+ # Can only add a dependency on an external program which we
2644
+ # know the absolute path of
2645
+ self.depend_files.append(File.from_absolute_file(path))
2646
+ final_cmd += c.get_command()
2647
+ elif isinstance(c, (BuildTarget, CustomTarget)):
2648
+ self.dependencies.append(c)
2649
+ final_cmd.append(c)
2650
+ elif isinstance(c, CustomTargetIndex):
2651
+ FeatureNew.single_use('CustomTargetIndex for command argument', '0.60', self.subproject)
2652
+ self.dependencies.append(c.target)
2653
+ final_cmd += self.flatten_command(File.from_built_file(c.get_source_subdir(), c.get_filename()))
2654
+ elif isinstance(c, list):
2655
+ final_cmd += self.flatten_command(c)
2656
+ else:
2657
+ raise InvalidArguments(f'Argument {c!r} in "command" is invalid')
2658
+ return final_cmd
2659
+
2660
+ class CustomTargetBase:
2661
+ ''' Base class for CustomTarget and CustomTargetIndex
2662
+
2663
+ This base class can be used to provide a dummy implementation of some
2664
+ private methods to avoid repeating `isinstance(t, BuildTarget)` when dealing
2665
+ with custom targets.
2666
+ '''
2667
+
2668
+ rust_crate_type = ''
2669
+
2670
+ def get_dependencies_recurse(self, result: OrderedSet[BuildTargetTypes], include_internals: bool = True) -> None:
2671
+ pass
2672
+
2673
+ def get_internal_static_libraries(self) -> OrderedSet[BuildTargetTypes]:
2674
+ return OrderedSet()
2675
+
2676
+ def get_internal_static_libraries_recurse(self, result: OrderedSet[BuildTargetTypes]) -> None:
2677
+ pass
2678
+
2679
+ class CustomTarget(Target, CustomTargetBase, CommandBase):
2680
+
2681
+ typename = 'custom'
2682
+
2683
+ def __init__(self,
2684
+ name: T.Optional[str],
2685
+ subdir: str,
2686
+ subproject: str,
2687
+ environment: environment.Environment,
2688
+ command: T.Sequence[T.Union[
2689
+ str, BuildTargetTypes, GeneratedList,
2690
+ programs.ExternalProgram, File]],
2691
+ sources: T.Sequence[T.Union[
2692
+ str, File, BuildTargetTypes, ExtractedObjects,
2693
+ GeneratedList, programs.ExternalProgram]],
2694
+ outputs: T.List[str],
2695
+ build_only_subproject: bool,
2696
+ *,
2697
+ build_always_stale: bool = False,
2698
+ build_by_default: T.Optional[bool] = None,
2699
+ capture: bool = False,
2700
+ console: bool = False,
2701
+ depend_files: T.Optional[T.Sequence[FileOrString]] = None,
2702
+ extra_depends: T.Optional[T.Sequence[T.Union[str, SourceOutputs]]] = None,
2703
+ depfile: T.Optional[str] = None,
2704
+ env: T.Optional[EnvironmentVariables] = None,
2705
+ feed: bool = False,
2706
+ install: bool = False,
2707
+ install_dir: T.Optional[T.List[T.Union[str, Literal[False]]]] = None,
2708
+ install_mode: T.Optional[FileMode] = None,
2709
+ install_tag: T.Optional[T.List[T.Optional[str]]] = None,
2710
+ absolute_paths: bool = False,
2711
+ backend: T.Optional['Backend'] = None,
2712
+ description: str = 'Generating {} with a custom command',
2713
+ ):
2714
+ # TODO expose keyword arg to make MachineChoice.HOST configurable
2715
+ super().__init__(name, subdir, subproject, False, MachineChoice.HOST, environment,
2716
+ build_only_subproject, install, build_always_stale)
2717
+ self.sources = list(sources)
2718
+ self.outputs = substitute_values(
2719
+ outputs, get_filenames_templates_dict(
2720
+ get_sources_string_names(sources, backend),
2721
+ []))
2722
+ self.build_by_default = build_by_default if build_by_default is not None else install
2723
+ self.capture = capture
2724
+ self.console = console
2725
+ self.depend_files = list(depend_files or [])
2726
+ self.dependencies: T.List[T.Union[CustomTarget, BuildTarget]] = []
2727
+ # must be after depend_files and dependencies
2728
+ self.command = self.flatten_command(command)
2729
+ self.depfile = depfile
2730
+ self.env = env or EnvironmentVariables()
2731
+ self.extra_depends = list(extra_depends or [])
2732
+ self.feed = feed
2733
+ self.install_dir = list(install_dir or [])
2734
+ self.install_mode = install_mode
2735
+ self.install_tag = _process_install_tag(install_tag, len(self.outputs))
2736
+ self.name = name if name else self.outputs[0]
2737
+ self.description = description
2738
+
2739
+ # Whether to use absolute paths for all files on the commandline
2740
+ self.absolute_paths = absolute_paths
2741
+
2742
+ def get_default_install_dir(self) -> T.Union[T.Tuple[str, str], T.Tuple[None, None]]:
2743
+ return None, None
2744
+
2745
+ def __repr__(self):
2746
+ repr_str = "<{0} {1}: {2}>"
2747
+ return repr_str.format(self.__class__.__name__, self.get_id(), self.command)
2748
+
2749
+ def get_target_dependencies(self) -> T.List[T.Union[SourceOutputs, str]]:
2750
+ deps: T.List[T.Union[SourceOutputs, str]] = []
2751
+ deps.extend(self.dependencies)
2752
+ deps.extend(self.extra_depends)
2753
+ for c in self.sources:
2754
+ if isinstance(c, CustomTargetIndex):
2755
+ deps.append(c.target)
2756
+ elif not isinstance(c, programs.ExternalProgram):
2757
+ deps.append(c)
2758
+ return deps
2759
+
2760
+ def get_transitive_build_target_deps(self) -> T.Set[T.Union[BuildTarget, 'CustomTarget']]:
2761
+ '''
2762
+ Recursively fetch the build targets that this custom target depends on,
2763
+ whether through `command:`, `depends:`, or `sources:` The recursion is
2764
+ only performed on custom targets.
2765
+ This is useful for setting PATH on Windows for finding required DLLs.
2766
+ F.ex, if you have a python script that loads a C module that links to
2767
+ other DLLs in your project.
2768
+ '''
2769
+ bdeps: T.Set[T.Union[BuildTarget, 'CustomTarget']] = set()
2770
+ deps = self.get_target_dependencies()
2771
+ for d in deps:
2772
+ if isinstance(d, BuildTarget):
2773
+ bdeps.add(d)
2774
+ elif isinstance(d, CustomTarget):
2775
+ bdeps.update(d.get_transitive_build_target_deps())
2776
+ return bdeps
2777
+
2778
+ def get_dependencies(self):
2779
+ return self.dependencies
2780
+
2781
+ def should_install(self) -> bool:
2782
+ return self.install
2783
+
2784
+ def get_custom_install_dir(self) -> T.List[T.Union[str, Literal[False]]]:
2785
+ return self.install_dir
2786
+
2787
+ def get_custom_install_mode(self) -> T.Optional['FileMode']:
2788
+ return self.install_mode
2789
+
2790
+ def get_outputs(self) -> T.List[str]:
2791
+ return self.outputs
2792
+
2793
+ def get_filename(self) -> str:
2794
+ return self.outputs[0]
2795
+
2796
+ def get_sources(self) -> T.List[T.Union[str, File, BuildTarget, GeneratedTypes, ExtractedObjects, programs.ExternalProgram]]:
2797
+ return self.sources
2798
+
2799
+ def get_generated_lists(self) -> T.List[GeneratedList]:
2800
+ genlists: T.List[GeneratedList] = []
2801
+ for c in self.sources:
2802
+ if isinstance(c, GeneratedList):
2803
+ genlists.append(c)
2804
+ return genlists
2805
+
2806
+ def get_generated_sources(self) -> T.List[GeneratedList]:
2807
+ return self.get_generated_lists()
2808
+
2809
+ def get_dep_outname(self, infilenames):
2810
+ if self.depfile is None:
2811
+ raise InvalidArguments('Tried to get depfile name for custom_target that does not have depfile defined.')
2812
+ if infilenames:
2813
+ plainname = os.path.basename(infilenames[0])
2814
+ basename = os.path.splitext(plainname)[0]
2815
+ return self.depfile.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname)
2816
+ else:
2817
+ if '@BASENAME@' in self.depfile or '@PLAINNAME@' in self.depfile:
2818
+ raise InvalidArguments('Substitution in depfile for custom_target that does not have an input file.')
2819
+ return self.depfile
2820
+
2821
+ def is_linkable_output(self, output: str) -> bool:
2822
+ if output.endswith(('.a', '.dll', '.lib', '.so', '.dylib')):
2823
+ return True
2824
+ # libfoo.so.X soname
2825
+ if re.search(r'\.so(\.\d+)*$', output):
2826
+ return True
2827
+ return False
2828
+
2829
+ def is_linkable_target(self) -> bool:
2830
+ if len(self.outputs) != 1:
2831
+ return False
2832
+ return self.is_linkable_output(self.outputs[0])
2833
+
2834
+ def links_dynamically(self) -> bool:
2835
+ """Whether this target links dynamically or statically
2836
+
2837
+ Does not assert the target is linkable, just that it is not shared
2838
+
2839
+ :return: True if is dynamically linked, otherwise False
2840
+ """
2841
+ suf = os.path.splitext(self.outputs[0])[-1]
2842
+ return suf not in {'.a', '.lib'}
2843
+
2844
+ def get_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
2845
+ return {}
2846
+
2847
+ def get_link_dep_subdirs(self) -> T.AbstractSet[str]:
2848
+ return OrderedSet()
2849
+
2850
+ def get_all_link_deps(self):
2851
+ return []
2852
+
2853
+ def is_internal(self) -> bool:
2854
+ '''
2855
+ Returns True if this is a not installed static library.
2856
+ '''
2857
+ if len(self.outputs) != 1:
2858
+ return False
2859
+ return CustomTargetIndex(self, self.outputs[0]).is_internal()
2860
+
2861
+ def extract_all_objects(self) -> T.List[T.Union[str, 'ExtractedObjects']]:
2862
+ return self.get_outputs()
2863
+
2864
+ def type_suffix(self):
2865
+ return "@cus"
2866
+
2867
+ def __getitem__(self, index: int) -> 'CustomTargetIndex':
2868
+ return CustomTargetIndex(self, self.outputs[index])
2869
+
2870
+ def __setitem__(self, index, value):
2871
+ raise NotImplementedError
2872
+
2873
+ def __delitem__(self, index):
2874
+ raise NotImplementedError
2875
+
2876
+ def __iter__(self):
2877
+ for i in self.outputs:
2878
+ yield CustomTargetIndex(self, i)
2879
+
2880
+ def __len__(self) -> int:
2881
+ return len(self.outputs)
2882
+
2883
+ class CompileTarget(BuildTarget):
2884
+ '''
2885
+ Target that only compile sources without linking them together.
2886
+ It can be used as preprocessor, or transpiler.
2887
+ '''
2888
+
2889
+ typename = 'compile'
2890
+
2891
+ def __init__(self,
2892
+ name: str,
2893
+ subdir: str,
2894
+ subproject: str,
2895
+ environment: environment.Environment,
2896
+ sources: T.List['SourceOutputs'],
2897
+ output_templ: str,
2898
+ compiler: Compiler,
2899
+ backend: Backend,
2900
+ compile_args: T.List[str],
2901
+ include_directories: T.List[IncludeDirs],
2902
+ dependencies: T.List[dependencies.Dependency],
2903
+ depends: T.List[T.Union[BuildTarget, CustomTarget, CustomTargetIndex]],
2904
+ build_only_subproject: bool):
2905
+ compilers = {compiler.get_language(): compiler}
2906
+ kwargs = {
2907
+ 'build_by_default': False,
2908
+ 'language_args': {compiler.language: compile_args},
2909
+ 'include_directories': include_directories,
2910
+ 'dependencies': dependencies,
2911
+ }
2912
+ super().__init__(name, subdir, subproject, compiler.for_machine,
2913
+ sources, None, [], environment, compilers,
2914
+ build_only_subproject, kwargs)
2915
+ self.filename = name
2916
+ self.compiler = compiler
2917
+ self.output_templ = output_templ
2918
+ self.outputs = []
2919
+ self.sources_map: T.Dict[File, str] = {}
2920
+ self.depends = list(depends or [])
2921
+ for f in self.sources:
2922
+ self._add_output(f)
2923
+ for gensrc in self.generated:
2924
+ for s in gensrc.get_outputs():
2925
+ rel_src = backend.get_target_generated_dir(self, gensrc, s)
2926
+ self._add_output(File.from_built_relative(rel_src))
2927
+
2928
+ def type_suffix(self) -> str:
2929
+ return "@compile"
2930
+
2931
+ @property
2932
+ def is_unity(self) -> bool:
2933
+ return False
2934
+
2935
+ def _add_output(self, f: File) -> None:
2936
+ plainname = os.path.basename(f.fname)
2937
+ basename = os.path.splitext(plainname)[0]
2938
+ o = self.output_templ.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname)
2939
+ self.outputs.append(o)
2940
+ self.sources_map[f] = o
2941
+
2942
+ def get_generated_headers(self) -> T.List[File]:
2943
+ gen_headers: T.List[File] = []
2944
+ for dep in self.depends:
2945
+ gen_headers += [File(True, dep.subdir, o) for o in dep.get_outputs()]
2946
+ return gen_headers
2947
+
2948
+ class RunTarget(Target, CommandBase):
2949
+
2950
+ typename = 'run'
2951
+
2952
+ def __init__(self, name: str,
2953
+ command: T.Sequence[T.Union[str, File, BuildTargetTypes, programs.ExternalProgram]],
2954
+ dependencies: T.Sequence[Target],
2955
+ subdir: str,
2956
+ subproject: str,
2957
+ environment: environment.Environment,
2958
+ env: T.Optional['EnvironmentVariables'] = None,
2959
+ default_env: bool = True):
2960
+ # These don't produce output artifacts
2961
+ super().__init__(name, subdir, subproject, False, MachineChoice.BUILD, environment, False)
2962
+ self.dependencies = dependencies
2963
+ self.depend_files = []
2964
+ self.command = self.flatten_command(command)
2965
+ self.absolute_paths = False
2966
+ self.env = env
2967
+ self.default_env = default_env
2968
+
2969
+ def __repr__(self) -> str:
2970
+ repr_str = "<{0} {1}: {2}>"
2971
+ return repr_str.format(self.__class__.__name__, self.get_id(), self.command[0])
2972
+
2973
+ def get_dependencies(self) -> T.List[T.Union[BuildTarget, 'CustomTarget']]:
2974
+ return self.dependencies
2975
+
2976
+ def get_generated_sources(self) -> T.List['GeneratedTypes']:
2977
+ return []
2978
+
2979
+ def get_sources(self) -> T.List[File]:
2980
+ return []
2981
+
2982
+ def should_install(self) -> bool:
2983
+ return False
2984
+
2985
+ def get_filename(self) -> str:
2986
+ return self.name
2987
+
2988
+ def get_outputs(self) -> T.List[str]:
2989
+ if isinstance(self.name, str):
2990
+ return [self.name]
2991
+ elif isinstance(self.name, list):
2992
+ return self.name
2993
+ else:
2994
+ raise RuntimeError('RunTarget: self.name is neither a list nor a string. This is a bug')
2995
+
2996
+ def type_suffix(self) -> str:
2997
+ return "@run"
2998
+
2999
+ class AliasTarget(RunTarget):
3000
+
3001
+ typename = 'alias'
3002
+
3003
+ def __init__(self, name: str, dependencies: T.Sequence['Target'],
3004
+ subdir: str, subproject: str, environment: environment.Environment):
3005
+ super().__init__(name, [], dependencies, subdir, subproject, environment)
3006
+
3007
+ def __repr__(self):
3008
+ repr_str = "<{0} {1}>"
3009
+ return repr_str.format(self.__class__.__name__, self.get_id())
3010
+
3011
+ class Jar(BuildTarget):
3012
+ known_kwargs = known_jar_kwargs
3013
+
3014
+ typename = 'jar'
3015
+
3016
+ def __init__(self, name: str, subdir: str, subproject: str, for_machine: MachineChoice,
3017
+ sources: T.List[SourceOutputs], structured_sources: T.Optional['StructuredSources'],
3018
+ objects, environment: environment.Environment, compilers: T.Dict[str, 'Compiler'],
3019
+ build_only_subproject: bool, kwargs):
3020
+ super().__init__(name, subdir, subproject, for_machine, sources, structured_sources, objects,
3021
+ environment, compilers, build_only_subproject, kwargs)
3022
+ for s in self.sources:
3023
+ if not s.endswith('.java'):
3024
+ raise InvalidArguments(f'Jar source {s} is not a java file.')
3025
+ for t in self.link_targets:
3026
+ if not isinstance(t, Jar):
3027
+ raise InvalidArguments(f'Link target {t} is not a jar target.')
3028
+ if self.structured_sources:
3029
+ raise InvalidArguments('structured sources are not supported in Java targets.')
3030
+ self.filename = self.name + '.jar'
3031
+ self.outputs = [self.filename]
3032
+ self.java_args = self.extra_args['java']
3033
+ self.main_class = kwargs.get('main_class', '')
3034
+ self.java_resources: T.Optional[StructuredSources] = kwargs.get('java_resources', None)
3035
+
3036
+ def get_main_class(self):
3037
+ return self.main_class
3038
+
3039
+ def type_suffix(self):
3040
+ return "@jar"
3041
+
3042
+ def get_java_args(self):
3043
+ return self.java_args
3044
+
3045
+ def get_java_resources(self) -> T.Optional[StructuredSources]:
3046
+ return self.java_resources
3047
+
3048
+ def validate_install(self):
3049
+ # All jar targets are installable.
3050
+ pass
3051
+
3052
+ def is_linkable_target(self):
3053
+ return True
3054
+
3055
+ def get_classpath_args(self):
3056
+ cp_paths = [os.path.join(l.get_source_subdir(), l.get_filename()) for l in self.link_targets]
3057
+ cp_string = os.pathsep.join(cp_paths)
3058
+ if cp_string:
3059
+ return ['-cp', os.pathsep.join(cp_paths)]
3060
+ return []
3061
+
3062
+ def get_default_install_dir(self) -> T.Union[T.Tuple[str, str], T.Tuple[None, None]]:
3063
+ return self.environment.get_jar_dir(), '{jardir}'
3064
+
3065
+ @dataclass(eq=False)
3066
+ class CustomTargetIndex(CustomTargetBase, HoldableObject):
3067
+
3068
+ """A special opaque object returned by indexing a CustomTarget. This object
3069
+ exists in Meson, but acts as a proxy in the backends, making targets depend
3070
+ on the CustomTarget it's derived from, but only adding one source file to
3071
+ the sources.
3072
+ """
3073
+
3074
+ typename: T.ClassVar[str] = 'custom'
3075
+
3076
+ target: T.Union[CustomTarget, CompileTarget]
3077
+ output: str
3078
+
3079
+ def __post_init__(self) -> None:
3080
+ self.for_machine = self.target.for_machine
3081
+
3082
+ @property
3083
+ def name(self) -> str:
3084
+ return f'{self.target.name}[{self.output}]'
3085
+
3086
+ def __repr__(self):
3087
+ return '<CustomTargetIndex: {!r}[{}]>'.format(self.target, self.output)
3088
+
3089
+ def get_outputs(self) -> T.List[str]:
3090
+ return [self.output]
3091
+
3092
+ def get_source_subdir(self) -> str:
3093
+ return self.target.get_source_subdir()
3094
+
3095
+ def get_output_subdir(self) -> str:
3096
+ return self.target.get_output_subdir()
3097
+
3098
+ def get_filename(self) -> str:
3099
+ return self.output
3100
+
3101
+ def get_id(self) -> str:
3102
+ return self.target.get_id()
3103
+
3104
+ def get_all_link_deps(self):
3105
+ return self.target.get_all_link_deps()
3106
+
3107
+ def get_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
3108
+ return self.target.get_link_deps_mapping(prefix)
3109
+
3110
+ def get_link_dep_subdirs(self) -> T.AbstractSet[str]:
3111
+ return self.target.get_link_dep_subdirs()
3112
+
3113
+ def is_linkable_target(self) -> bool:
3114
+ return self.target.is_linkable_output(self.output)
3115
+
3116
+ def links_dynamically(self) -> bool:
3117
+ """Whether this target links dynamically or statically
3118
+
3119
+ Does not assert the target is linkable, just that it is not shared
3120
+
3121
+ :return: True if is dynamically linked, otherwise False
3122
+ """
3123
+ suf = os.path.splitext(self.output)[-1]
3124
+ return suf not in {'.a', '.lib'}
3125
+
3126
+ def should_install(self) -> bool:
3127
+ return self.target.should_install()
3128
+
3129
+ def is_internal(self) -> bool:
3130
+ '''
3131
+ Returns True if this is a not installed static library
3132
+ '''
3133
+ suf = os.path.splitext(self.output)[-1]
3134
+ return suf in {'.a', '.lib'} and not self.should_install()
3135
+
3136
+ def extract_all_objects(self) -> T.List[T.Union[str, 'ExtractedObjects']]:
3137
+ return self.target.extract_all_objects()
3138
+
3139
+ def get_custom_install_dir(self) -> T.List[T.Union[str, Literal[False]]]:
3140
+ return self.target.get_custom_install_dir()
3141
+
3142
+ class ConfigurationData(HoldableObject):
3143
+ def __init__(self, initial_values: T.Optional[T.Union[
3144
+ T.Dict[str, T.Tuple[T.Union[str, int, bool], T.Optional[str]]],
3145
+ T.Dict[str, T.Union[str, int, bool]]]
3146
+ ] = None):
3147
+ super().__init__()
3148
+ self.values: T.Dict[str, T.Tuple[T.Union[str, int, bool], T.Optional[str]]] = \
3149
+ {k: v if isinstance(v, tuple) else (v, None) for k, v in initial_values.items()} if initial_values else {}
3150
+ self.used: bool = False
3151
+
3152
+ def __repr__(self) -> str:
3153
+ return repr(self.values)
3154
+
3155
+ def __contains__(self, value: str) -> bool:
3156
+ return value in self.values
3157
+
3158
+ def __bool__(self) -> bool:
3159
+ return bool(self.values)
3160
+
3161
+ def get(self, name: str) -> T.Tuple[T.Union[str, int, bool], T.Optional[str]]:
3162
+ return self.values[name] # (val, desc)
3163
+
3164
+ def keys(self) -> T.Iterator[str]:
3165
+ return self.values.keys()
3166
+
3167
+ # A bit poorly named, but this represents plain data files to copy
3168
+ # during install.
3169
+ @dataclass(eq=False)
3170
+ class Data(HoldableObject):
3171
+ sources: T.List[File]
3172
+ install_dir: str
3173
+ install_dir_name: str
3174
+ install_mode: 'FileMode'
3175
+ subproject: str
3176
+ rename: T.List[str] = None
3177
+ install_tag: T.Optional[str] = None
3178
+ data_type: str = None
3179
+ follow_symlinks: T.Optional[bool] = None
3180
+
3181
+ def __post_init__(self) -> None:
3182
+ if self.rename is None:
3183
+ self.rename = [os.path.basename(f.fname) for f in self.sources]
3184
+
3185
+ @dataclass(eq=False)
3186
+ class SymlinkData(HoldableObject):
3187
+ target: str
3188
+ name: str
3189
+ install_dir: str
3190
+ subproject: str
3191
+ install_tag: T.Optional[str] = None
3192
+
3193
+ def __post_init__(self) -> None:
3194
+ if self.name != os.path.basename(self.name):
3195
+ raise InvalidArguments(f'Link name is "{self.name}", but link names cannot contain path separators. '
3196
+ 'The dir part should be in install_dir.')
3197
+
3198
+ @dataclass(eq=False)
3199
+ class TestSetup:
3200
+ exe_wrapper: T.List[str]
3201
+ gdb: bool
3202
+ timeout_multiplier: int
3203
+ env: EnvironmentVariables
3204
+ exclude_suites: T.List[str]
3205
+
3206
+ def get_sources_string_names(sources, backend):
3207
+ '''
3208
+ For the specified list of @sources which can be strings, Files, or targets,
3209
+ get all the output basenames.
3210
+ '''
3211
+ names = []
3212
+ for s in sources:
3213
+ if isinstance(s, str):
3214
+ names.append(s)
3215
+ elif isinstance(s, (BuildTarget, CustomTarget, CustomTargetIndex, GeneratedList)):
3216
+ names += s.get_outputs()
3217
+ elif isinstance(s, ExtractedObjects):
3218
+ names += backend.determine_ext_objs(s)
3219
+ elif isinstance(s, File):
3220
+ names.append(s.fname)
3221
+ else:
3222
+ raise AssertionError(f'Unknown source type: {s!r}')
3223
+ return names
3224
+
3225
+ def compute_build_subdir(subdir: str, build_only_subproject: bool) -> str:
3226
+ if build_only_subproject:
3227
+ return f'build.{subdir}'
3228
+ return subdir
3229
+
3230
+ def load(build_dir: str) -> Build:
3231
+ filename = os.path.join(build_dir, 'meson-private', 'build.dat')
3232
+ try:
3233
+ b = pickle_load(filename, 'Build data', Build)
3234
+ # We excluded coredata when saving Build object, load it separately
3235
+ b.environment.coredata = coredata.load(build_dir)
3236
+ return b
3237
+ except FileNotFoundError:
3238
+ raise MesonException(f'No such build data file as {filename!r}.')
3239
+
3240
+
3241
+ def save(obj: Build, filename: str) -> None:
3242
+ # Exclude coredata because we pickle it separately already
3243
+ cdata = obj.environment.coredata
3244
+ obj.environment.coredata = None
3245
+ try:
3246
+ with open(filename, 'wb') as f:
3247
+ pickle.dump(obj, f)
3248
+ finally:
3249
+ obj.environment.coredata = cdata