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,2445 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2012-2020 The Meson development team
3
+
4
+
5
+ """A library of random helper functionality."""
6
+
7
+ from __future__ import annotations
8
+ from pathlib import Path
9
+ import argparse
10
+ import ast
11
+ import enum
12
+ import sys
13
+ import stat
14
+ import time
15
+ import abc
16
+ import platform, subprocess, operator, os, shlex, shutil, re
17
+ import collections
18
+ from functools import lru_cache, wraps, total_ordering
19
+ from itertools import tee
20
+ from tempfile import TemporaryDirectory, NamedTemporaryFile
21
+ import typing as T
22
+ import textwrap
23
+ import pickle
24
+ import errno
25
+ import json
26
+
27
+ from mesonbuild import mlog
28
+ from .core import MesonException, HoldableObject
29
+
30
+ if T.TYPE_CHECKING:
31
+ from typing_extensions import Literal, Protocol
32
+
33
+ from .._typing import ImmutableListProtocol
34
+ from ..build import ConfigurationData
35
+ from ..coredata import StrOrBytesPath
36
+ from ..environment import Environment
37
+ from ..compilers.compilers import Compiler
38
+ from ..interpreterbase.baseobjects import SubProject
39
+
40
+ class _EnvPickleLoadable(Protocol):
41
+
42
+ environment: Environment
43
+
44
+ class _VerPickleLoadable(Protocol):
45
+
46
+ version: str
47
+
48
+ # A generic type for pickle_load. This allows any type that has either a
49
+ # .version or a .environment to be passed.
50
+ _PL = T.TypeVar('_PL', bound=T.Union[_EnvPickleLoadable, _VerPickleLoadable])
51
+
52
+ FileOrString = T.Union['File', str]
53
+
54
+ _T = T.TypeVar('_T')
55
+ _U = T.TypeVar('_U')
56
+
57
+ __all__ = [
58
+ 'GIT',
59
+ 'python_command',
60
+ 'project_meson_versions',
61
+ 'SecondLevelHolder',
62
+ 'File',
63
+ 'FileMode',
64
+ 'GitException',
65
+ 'LibType',
66
+ 'MachineChoice',
67
+ 'EnvironmentException',
68
+ 'FileOrString',
69
+ 'GitException',
70
+ 'OptionKey',
71
+ 'dump_conf_header',
72
+ 'OptionType',
73
+ 'OrderedSet',
74
+ 'PerMachine',
75
+ 'PerMachineDefaultable',
76
+ 'PerThreeMachine',
77
+ 'PerThreeMachineDefaultable',
78
+ 'ProgressBar',
79
+ 'RealPathAction',
80
+ 'TemporaryDirectoryWinProof',
81
+ 'Version',
82
+ 'check_direntry_issues',
83
+ 'classify_unity_sources',
84
+ 'current_vs_supports_modules',
85
+ 'darwin_get_object_archs',
86
+ 'default_libdir',
87
+ 'default_libexecdir',
88
+ 'default_prefix',
89
+ 'default_datadir',
90
+ 'default_includedir',
91
+ 'default_infodir',
92
+ 'default_localedir',
93
+ 'default_mandir',
94
+ 'default_sbindir',
95
+ 'default_sysconfdir',
96
+ 'detect_subprojects',
97
+ 'detect_vcs',
98
+ 'do_conf_file',
99
+ 'do_conf_str',
100
+ 'do_replacement',
101
+ 'exe_exists',
102
+ 'expand_arguments',
103
+ 'extract_as_list',
104
+ 'first',
105
+ 'generate_list',
106
+ 'get_compiler_for_source',
107
+ 'get_filenames_templates_dict',
108
+ 'get_variable_regex',
109
+ 'get_wine_shortpath',
110
+ 'git',
111
+ 'has_path_sep',
112
+ 'is_aix',
113
+ 'is_android',
114
+ 'is_ascii_string',
115
+ 'is_cygwin',
116
+ 'is_debianlike',
117
+ 'is_dragonflybsd',
118
+ 'is_freebsd',
119
+ 'is_haiku',
120
+ 'is_hurd',
121
+ 'is_irix',
122
+ 'is_linux',
123
+ 'is_netbsd',
124
+ 'is_openbsd',
125
+ 'is_osx',
126
+ 'is_qnx',
127
+ 'is_sunos',
128
+ 'is_windows',
129
+ 'is_wsl',
130
+ 'iter_regexin_iter',
131
+ 'join_args',
132
+ 'listify',
133
+ 'listify_array_value',
134
+ 'partition',
135
+ 'path_is_in_root',
136
+ 'pickle_load',
137
+ 'Popen_safe',
138
+ 'Popen_safe_logged',
139
+ 'quiet_git',
140
+ 'quote_arg',
141
+ 'relative_to_if_possible',
142
+ 'relpath',
143
+ 'replace_if_different',
144
+ 'run_once',
145
+ 'get_meson_command',
146
+ 'set_meson_command',
147
+ 'split_args',
148
+ 'stringlistify',
149
+ 'substitute_values',
150
+ 'substring_is_in_list',
151
+ 'typeslistify',
152
+ 'verbose_git',
153
+ 'version_compare',
154
+ 'version_compare_condition_with_min',
155
+ 'version_compare_many',
156
+ 'search_version',
157
+ 'windows_detect_native_arch',
158
+ 'windows_proof_rm',
159
+ 'windows_proof_rmtree',
160
+ ]
161
+
162
+
163
+ # TODO: this is such a hack, this really should be either in coredata or in the
164
+ # interpreter
165
+ # {subproject: project_meson_version}
166
+ project_meson_versions: T.DefaultDict[str, str] = collections.defaultdict(str)
167
+
168
+
169
+ from glob import glob
170
+
171
+ if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
172
+ # using a PyInstaller bundle, e.g. the MSI installed executable
173
+ python_command = [sys.executable, 'runpython']
174
+ else:
175
+ python_command = [sys.executable]
176
+ _meson_command: T.Optional['ImmutableListProtocol[str]'] = None
177
+
178
+
179
+ class EnvironmentException(MesonException):
180
+ '''Exceptions thrown while processing and creating the build environment'''
181
+
182
+ class GitException(MesonException):
183
+ def __init__(self, msg: str, output: T.Optional[str] = None):
184
+ super().__init__(msg)
185
+ self.output = output.strip() if output else ''
186
+
187
+ GIT = shutil.which('git')
188
+ def git(cmd: T.List[str], workingdir: StrOrBytesPath, check: bool = False, **kwargs: T.Any) -> T.Tuple[subprocess.Popen[str], str, str]:
189
+ assert GIT is not None, 'Callers should make sure it exists'
190
+ cmd = [GIT, *cmd]
191
+ p, o, e = Popen_safe(cmd, cwd=workingdir, **kwargs)
192
+ if check and p.returncode != 0:
193
+ raise GitException('Git command failed: ' + str(cmd), e)
194
+ return p, o, e
195
+
196
+ def quiet_git(cmd: T.List[str], workingdir: StrOrBytesPath, check: bool = False) -> T.Tuple[bool, str]:
197
+ if not GIT:
198
+ m = 'Git program not found.'
199
+ if check:
200
+ raise GitException(m)
201
+ return False, m
202
+ p, o, e = git(cmd, workingdir, check)
203
+ if p.returncode != 0:
204
+ return False, e
205
+ return True, o
206
+
207
+ def verbose_git(cmd: T.List[str], workingdir: StrOrBytesPath, check: bool = False) -> bool:
208
+ if not GIT:
209
+ m = 'Git program not found.'
210
+ if check:
211
+ raise GitException(m)
212
+ return False
213
+ p, _, _ = git(cmd, workingdir, check, stdout=None, stderr=None)
214
+ return p.returncode == 0
215
+
216
+ def set_meson_command(mainfile: str) -> None:
217
+ global _meson_command # pylint: disable=global-statement
218
+ # On UNIX-like systems `meson` is a Python script
219
+ # On Windows `meson` and `meson.exe` are wrapper exes
220
+ if not mainfile.endswith('.py'):
221
+ _meson_command = [mainfile]
222
+ elif os.path.isabs(mainfile) and mainfile.endswith('mesonmain.py'):
223
+ # Can't actually run meson with an absolute path to mesonmain.py, it must be run as -m mesonbuild.mesonmain
224
+ _meson_command = python_command + ['-m', 'mesonbuild.mesonmain']
225
+ else:
226
+ # Either run uninstalled, or full path to meson-script.py
227
+ _meson_command = python_command + [mainfile]
228
+ # We print this value for unit tests.
229
+ if 'MESON_COMMAND_TESTS' in os.environ:
230
+ mlog.log(f'meson_command is {_meson_command!r}')
231
+
232
+
233
+ def get_meson_command() -> T.Optional['ImmutableListProtocol[str]']:
234
+ return _meson_command
235
+
236
+
237
+ def is_ascii_string(astring: T.Union[str, bytes]) -> bool:
238
+ try:
239
+ if isinstance(astring, str):
240
+ astring.encode('ascii')
241
+ elif isinstance(astring, bytes):
242
+ astring.decode('ascii')
243
+ except UnicodeDecodeError:
244
+ return False
245
+ return True
246
+
247
+
248
+ def check_direntry_issues(direntry_array: T.Union[T.Iterable[T.Union[str, bytes]], str, bytes]) -> None:
249
+ import locale
250
+ # Warn if the locale is not UTF-8. This can cause various unfixable issues
251
+ # such as os.stat not being able to decode filenames with unicode in them.
252
+ # There is no way to reset both the preferred encoding and the filesystem
253
+ # encoding, so we can just warn about it.
254
+ e = locale.getpreferredencoding()
255
+ if e.upper() != 'UTF-8' and not is_windows():
256
+ if isinstance(direntry_array, (str, bytes)):
257
+ direntry_array = [direntry_array]
258
+ for de in direntry_array:
259
+ if is_ascii_string(de):
260
+ continue
261
+ mlog.warning(textwrap.dedent(f'''
262
+ You are using {e!r} which is not a Unicode-compatible
263
+ locale but you are trying to access a file system entry called {de!r} which is
264
+ not pure ASCII. This may cause problems.
265
+ '''))
266
+
267
+ class SecondLevelHolder(HoldableObject, metaclass=abc.ABCMeta):
268
+ ''' A second level object holder. The primary purpose
269
+ of such objects is to hold multiple objects with one
270
+ default option. '''
271
+
272
+ @abc.abstractmethod
273
+ def get_default_object(self) -> HoldableObject: ...
274
+
275
+ class FileMode:
276
+ # The first triad is for owner permissions, the second for group permissions,
277
+ # and the third for others (everyone else).
278
+ # For the 1st character:
279
+ # 'r' means can read
280
+ # '-' means not allowed
281
+ # For the 2nd character:
282
+ # 'w' means can write
283
+ # '-' means not allowed
284
+ # For the 3rd character:
285
+ # 'x' means can execute
286
+ # 's' means can execute and setuid/setgid is set (owner/group triads only)
287
+ # 'S' means cannot execute and setuid/setgid is set (owner/group triads only)
288
+ # 't' means can execute and sticky bit is set ("others" triads only)
289
+ # 'T' means cannot execute and sticky bit is set ("others" triads only)
290
+ # '-' means none of these are allowed
291
+ #
292
+ # The meanings of 'rwx' perms is not obvious for directories; see:
293
+ # https://www.hackinglinuxexposed.com/articles/20030424.html
294
+ #
295
+ # For information on this notation such as setuid/setgid/sticky bits, see:
296
+ # https://en.wikipedia.org/wiki/File_system_permissions#Symbolic_notation
297
+ symbolic_perms_regex = re.compile('[r-][w-][xsS-]' # Owner perms
298
+ '[r-][w-][xsS-]' # Group perms
299
+ '[r-][w-][xtT-]') # Others perms
300
+
301
+ def __init__(self, perms: T.Optional[str] = None, owner: T.Union[str, int, None] = None,
302
+ group: T.Union[str, int, None] = None):
303
+ self.perms_s = perms
304
+ self.perms = self.perms_s_to_bits(perms)
305
+ self.owner = owner
306
+ self.group = group
307
+
308
+ def __repr__(self) -> str:
309
+ ret = '<FileMode: {!r} owner={} group={}'
310
+ return ret.format(self.perms_s, self.owner, self.group)
311
+
312
+ @classmethod
313
+ def perms_s_to_bits(cls, perms_s: T.Optional[str]) -> int:
314
+ '''
315
+ Does the opposite of stat.filemode(), converts strings of the form
316
+ 'rwxr-xr-x' to st_mode enums which can be passed to os.chmod()
317
+ '''
318
+ if perms_s is None:
319
+ # No perms specified, we will not touch the permissions
320
+ return -1
321
+ eg = 'rwxr-xr-x'
322
+ if not isinstance(perms_s, str):
323
+ raise MesonException(f'Install perms must be a string. For example, {eg!r}')
324
+ if len(perms_s) != 9 or not cls.symbolic_perms_regex.match(perms_s):
325
+ raise MesonException(f'File perms {perms_s!r} must be exactly 9 chars. For example, {eg!r}')
326
+ perms = 0
327
+ # Owner perms
328
+ if perms_s[0] == 'r':
329
+ perms |= stat.S_IRUSR
330
+ if perms_s[1] == 'w':
331
+ perms |= stat.S_IWUSR
332
+ if perms_s[2] == 'x':
333
+ perms |= stat.S_IXUSR
334
+ elif perms_s[2] == 'S':
335
+ perms |= stat.S_ISUID
336
+ elif perms_s[2] == 's':
337
+ perms |= stat.S_IXUSR
338
+ perms |= stat.S_ISUID
339
+ # Group perms
340
+ if perms_s[3] == 'r':
341
+ perms |= stat.S_IRGRP
342
+ if perms_s[4] == 'w':
343
+ perms |= stat.S_IWGRP
344
+ if perms_s[5] == 'x':
345
+ perms |= stat.S_IXGRP
346
+ elif perms_s[5] == 'S':
347
+ perms |= stat.S_ISGID
348
+ elif perms_s[5] == 's':
349
+ perms |= stat.S_IXGRP
350
+ perms |= stat.S_ISGID
351
+ # Others perms
352
+ if perms_s[6] == 'r':
353
+ perms |= stat.S_IROTH
354
+ if perms_s[7] == 'w':
355
+ perms |= stat.S_IWOTH
356
+ if perms_s[8] == 'x':
357
+ perms |= stat.S_IXOTH
358
+ elif perms_s[8] == 'T':
359
+ perms |= stat.S_ISVTX
360
+ elif perms_s[8] == 't':
361
+ perms |= stat.S_IXOTH
362
+ perms |= stat.S_ISVTX
363
+ return perms
364
+
365
+ dot_C_dot_H_warning = """You are using .C or .H files in your project. This is deprecated.
366
+ Currently, Meson treats this as C++ code, but they
367
+ used to be treated as C code.
368
+ Note that the situation is a bit more complex if you are using the
369
+ Visual Studio compiler, as it treats .C files as C code, unless you add
370
+ the /TP compiler flag, but this is unreliable.
371
+ See https://github.com/mesonbuild/meson/pull/8747 for the discussions."""
372
+ class File(HoldableObject):
373
+ def __init__(self, is_built: bool, subdir: str, fname: str):
374
+ if fname.endswith(".C") or fname.endswith(".H"):
375
+ mlog.warning(dot_C_dot_H_warning, once=True)
376
+ self.is_built = is_built
377
+ self.subdir = subdir
378
+ self.fname = fname
379
+ self.hash = hash((is_built, subdir, fname))
380
+
381
+ def __str__(self) -> str:
382
+ return self.relative_name()
383
+
384
+ def __repr__(self) -> str:
385
+ ret = '<File: {0}'
386
+ if not self.is_built:
387
+ ret += ' (not built)'
388
+ ret += '>'
389
+ return ret.format(self.relative_name())
390
+
391
+ @staticmethod
392
+ @lru_cache(maxsize=None)
393
+ def from_source_file(source_root: str, subdir: str, fname: str) -> 'File':
394
+ if not os.path.isfile(os.path.join(source_root, subdir, fname)):
395
+ raise MesonException(f'File {fname} does not exist.')
396
+ return File(False, subdir, fname)
397
+
398
+ @staticmethod
399
+ def from_built_file(subdir: str, fname: str) -> 'File':
400
+ return File(True, subdir, fname)
401
+
402
+ @staticmethod
403
+ def from_built_relative(relative: str) -> 'File':
404
+ dirpart, fnamepart = os.path.split(relative)
405
+ return File(True, dirpart, fnamepart)
406
+
407
+ @staticmethod
408
+ def from_absolute_file(fname: str) -> 'File':
409
+ return File(False, '', fname)
410
+
411
+ @lru_cache(maxsize=None)
412
+ def rel_to_builddir(self, build_to_src: str) -> str:
413
+ if self.is_built:
414
+ return self.relative_name()
415
+ else:
416
+ return os.path.join(build_to_src, self.subdir, self.fname)
417
+
418
+ @lru_cache(maxsize=None)
419
+ def absolute_path(self, srcdir: str, builddir: str) -> str:
420
+ absdir = srcdir
421
+ if self.is_built:
422
+ absdir = builddir
423
+ return os.path.join(absdir, self.relative_name())
424
+
425
+ @property
426
+ def suffix(self) -> str:
427
+ return os.path.splitext(self.fname)[1][1:].lower()
428
+
429
+ def endswith(self, ending: T.Union[str, T.Tuple[str, ...]]) -> bool:
430
+ return self.fname.endswith(ending)
431
+
432
+ def split(self, s: str, maxsplit: int = -1) -> T.List[str]:
433
+ return self.fname.split(s, maxsplit=maxsplit)
434
+
435
+ def rsplit(self, s: str, maxsplit: int = -1) -> T.List[str]:
436
+ return self.fname.rsplit(s, maxsplit=maxsplit)
437
+
438
+ def __eq__(self, other: object) -> bool:
439
+ if not isinstance(other, File):
440
+ return NotImplemented
441
+ if self.hash != other.hash:
442
+ return False
443
+ return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
444
+
445
+ def __hash__(self) -> int:
446
+ return self.hash
447
+
448
+ @lru_cache(maxsize=None)
449
+ def relative_name(self) -> str:
450
+ return os.path.join(self.subdir, self.fname)
451
+
452
+
453
+ def get_compiler_for_source(compilers: T.Iterable['Compiler'], src: 'FileOrString') -> 'Compiler':
454
+ """Given a set of compilers and a source, find the compiler for that source type."""
455
+ for comp in compilers:
456
+ if comp.can_compile(src):
457
+ return comp
458
+ raise MesonException(f'No specified compiler can handle file {src!s}')
459
+
460
+
461
+ def classify_unity_sources(compilers: T.Iterable['Compiler'], sources: T.Sequence['FileOrString']) -> T.Dict['Compiler', T.List['FileOrString']]:
462
+ compsrclist: T.Dict['Compiler', T.List['FileOrString']] = {}
463
+ for src in sources:
464
+ comp = get_compiler_for_source(compilers, src)
465
+ if comp not in compsrclist:
466
+ compsrclist[comp] = [src]
467
+ else:
468
+ compsrclist[comp].append(src)
469
+ return compsrclist
470
+
471
+
472
+ class MachineChoice(enum.IntEnum):
473
+
474
+ """Enum class representing one of the two abstract machine names used in
475
+ most places: the build, and host, machines.
476
+ """
477
+
478
+ BUILD = 0
479
+ HOST = 1
480
+
481
+ def __str__(self) -> str:
482
+ return f'{self.get_lower_case_name()} machine'
483
+
484
+ def get_lower_case_name(self) -> str:
485
+ return PerMachine('build', 'host')[self]
486
+
487
+ def get_prefix(self) -> str:
488
+ return PerMachine('build.', '')[self]
489
+
490
+
491
+ class PerMachine(T.Generic[_T]):
492
+ def __init__(self, build: _T, host: _T) -> None:
493
+ self.build = build
494
+ self.host = host
495
+
496
+ def __getitem__(self, machine: MachineChoice) -> _T:
497
+ return {
498
+ MachineChoice.BUILD: self.build,
499
+ MachineChoice.HOST: self.host,
500
+ }[machine]
501
+
502
+ def __setitem__(self, machine: MachineChoice, val: _T) -> None:
503
+ setattr(self, machine.get_lower_case_name(), val)
504
+
505
+ def miss_defaulting(self) -> "PerMachineDefaultable[T.Optional[_T]]":
506
+ """Unset definition duplicated from their previous to None
507
+
508
+ This is the inverse of ''default_missing''. By removing defaulted
509
+ machines, we can elaborate the original and then redefault them and thus
510
+ avoid repeating the elaboration explicitly.
511
+ """
512
+ unfreeze: PerMachineDefaultable[T.Optional[_T]] = PerMachineDefaultable()
513
+ unfreeze.build = self.build
514
+ unfreeze.host = self.host
515
+ if unfreeze.host == unfreeze.build:
516
+ unfreeze.host = None
517
+ return unfreeze
518
+
519
+ def assign(self, build: _T, host: _T) -> None:
520
+ self.build = build
521
+ self.host = host
522
+
523
+ def __repr__(self) -> str:
524
+ return f'PerMachine({self.build!r}, {self.host!r})'
525
+
526
+
527
+ class PerThreeMachine(PerMachine[_T]):
528
+ """Like `PerMachine` but includes `target` too.
529
+
530
+ It turns out just one thing do we need track the target machine. There's no
531
+ need to computer the `target` field so we don't bother overriding the
532
+ `__getitem__`/`__setitem__` methods.
533
+ """
534
+ def __init__(self, build: _T, host: _T, target: _T) -> None:
535
+ super().__init__(build, host)
536
+ self.target = target
537
+
538
+ def miss_defaulting(self) -> "PerThreeMachineDefaultable[T.Optional[_T]]":
539
+ """Unset definition duplicated from their previous to None
540
+
541
+ This is the inverse of ''default_missing''. By removing defaulted
542
+ machines, we can elaborate the original and then redefault them and thus
543
+ avoid repeating the elaboration explicitly.
544
+ """
545
+ unfreeze: PerThreeMachineDefaultable[T.Optional[_T]] = PerThreeMachineDefaultable()
546
+ unfreeze.build = self.build
547
+ unfreeze.host = self.host
548
+ unfreeze.target = self.target
549
+ if unfreeze.target == unfreeze.host:
550
+ unfreeze.target = None
551
+ if unfreeze.host == unfreeze.build:
552
+ unfreeze.host = None
553
+ return unfreeze
554
+
555
+ def matches_build_machine(self, machine: MachineChoice) -> bool:
556
+ return self.build == self[machine]
557
+
558
+ def __repr__(self) -> str:
559
+ return f'PerThreeMachine({self.build!r}, {self.host!r}, {self.target!r})'
560
+
561
+
562
+ class PerMachineDefaultable(PerMachine[T.Optional[_T]]):
563
+ """Extends `PerMachine` with the ability to default from `None`s.
564
+ """
565
+ def __init__(self, build: T.Optional[_T] = None, host: T.Optional[_T] = None) -> None:
566
+ super().__init__(build, host)
567
+
568
+ def default_missing(self) -> "PerMachine[_T]":
569
+ """Default host to build
570
+
571
+ This allows just specifying nothing in the native case, and just host in the
572
+ cross non-compiler case.
573
+ """
574
+ freeze = PerMachine(self.build, self.host)
575
+ if freeze.host is None:
576
+ freeze.host = freeze.build
577
+ return freeze
578
+
579
+ def __repr__(self) -> str:
580
+ return f'PerMachineDefaultable({self.build!r}, {self.host!r})'
581
+
582
+ @classmethod
583
+ def default(cls, is_cross: bool, build: _T, host: _T) -> PerMachine[_T]:
584
+ """Easy way to get a defaulted value
585
+
586
+ This allows simplifying the case where you can control whether host and
587
+ build are separate or not with a boolean. If the is_cross value is set
588
+ to true then the optional host value will be used, otherwise the host
589
+ will be set to the build value.
590
+ """
591
+ m = cls(build)
592
+ if is_cross:
593
+ m.host = host
594
+ return m.default_missing()
595
+
596
+
597
+ class PerThreeMachineDefaultable(PerMachineDefaultable[T.Optional[_T]], PerThreeMachine[T.Optional[_T]]):
598
+ """Extends `PerThreeMachine` with the ability to default from `None`s.
599
+ """
600
+ def __init__(self, build: T.Optional[_T] = None, host: T.Optional[_T] = None, target: T.Optional[_T] = None) -> None:
601
+ PerThreeMachine.__init__(self, build, host, target)
602
+
603
+ def default_missing(self) -> "PerThreeMachine[T.Optional[_T]]":
604
+ """Default host to build and target to host.
605
+
606
+ This allows just specifying nothing in the native case, just host in the
607
+ cross non-compiler case, and just target in the native-built
608
+ cross-compiler case.
609
+ """
610
+ freeze = PerThreeMachine(self.build, self.host, self.target)
611
+ if freeze.host is None:
612
+ freeze.host = freeze.build
613
+ if freeze.target is None:
614
+ freeze.target = freeze.host
615
+ return freeze
616
+
617
+ def __repr__(self) -> str:
618
+ return f'PerThreeMachineDefaultable({self.build!r}, {self.host!r}, {self.target!r})'
619
+
620
+
621
+ def is_sunos() -> bool:
622
+ return platform.system().lower() == 'sunos'
623
+
624
+
625
+ def is_osx() -> bool:
626
+ return platform.system().lower() == 'darwin'
627
+
628
+
629
+ def is_linux() -> bool:
630
+ return platform.system().lower() == 'linux'
631
+
632
+
633
+ def is_android() -> bool:
634
+ return platform.system().lower() == 'android'
635
+
636
+
637
+ def is_haiku() -> bool:
638
+ return platform.system().lower() == 'haiku'
639
+
640
+
641
+ def is_openbsd() -> bool:
642
+ return platform.system().lower() == 'openbsd'
643
+
644
+
645
+ def is_windows() -> bool:
646
+ platname = platform.system().lower()
647
+ return platname == 'windows'
648
+
649
+ def is_wsl() -> bool:
650
+ return is_linux() and 'microsoft' in platform.release().lower()
651
+
652
+ def is_cygwin() -> bool:
653
+ return sys.platform == 'cygwin'
654
+
655
+
656
+ def is_debianlike() -> bool:
657
+ return os.path.isfile('/etc/debian_version')
658
+
659
+
660
+ def is_dragonflybsd() -> bool:
661
+ return platform.system().lower() == 'dragonfly'
662
+
663
+
664
+ def is_netbsd() -> bool:
665
+ return platform.system().lower() == 'netbsd'
666
+
667
+
668
+ def is_freebsd() -> bool:
669
+ return platform.system().lower() == 'freebsd'
670
+
671
+ def is_irix() -> bool:
672
+ return platform.system().startswith('irix')
673
+
674
+ def is_hurd() -> bool:
675
+ return platform.system().lower() == 'gnu'
676
+
677
+ def is_qnx() -> bool:
678
+ return platform.system().lower() == 'qnx'
679
+
680
+ def is_aix() -> bool:
681
+ return platform.system().lower() == 'aix'
682
+
683
+ def exe_exists(arglist: T.List[str]) -> bool:
684
+ try:
685
+ if subprocess.run(arglist, timeout=10).returncode == 0:
686
+ return True
687
+ except (FileNotFoundError, subprocess.TimeoutExpired):
688
+ pass
689
+ return False
690
+
691
+
692
+ @lru_cache(maxsize=None)
693
+ def darwin_get_object_archs(objpath: str) -> 'ImmutableListProtocol[str]':
694
+ '''
695
+ For a specific object (executable, static library, dylib, etc), run `lipo`
696
+ to fetch the list of archs supported by it. Supports both thin objects and
697
+ 'fat' objects.
698
+ '''
699
+ _, stdo, stderr = Popen_safe(['lipo', '-info', objpath])
700
+ if not stdo:
701
+ mlog.debug(f'lipo {objpath}: {stderr}')
702
+ return None
703
+ stdo = stdo.rsplit(': ', 1)[1]
704
+
705
+ # Convert from lipo-style archs to meson-style CPUs
706
+ map_arch = {
707
+ 'i386': 'x86',
708
+ 'arm64': 'aarch64',
709
+ 'arm64e': 'aarch64',
710
+ 'ppc7400': 'ppc',
711
+ 'ppc970': 'ppc',
712
+ }
713
+ lipo_archs = stdo.split()
714
+ meson_archs = [map_arch.get(lipo_arch, lipo_arch) for lipo_arch in lipo_archs]
715
+
716
+ # Add generic name for armv7 and armv7s
717
+ if 'armv7' in stdo:
718
+ meson_archs.append('arm')
719
+
720
+ return meson_archs
721
+
722
+ def windows_detect_native_arch() -> str:
723
+ """
724
+ The architecture of Windows itself: x86, amd64 or arm64
725
+ """
726
+ if sys.platform != 'win32':
727
+ return ''
728
+ try:
729
+ import ctypes
730
+ process_arch = ctypes.c_ushort()
731
+ native_arch = ctypes.c_ushort()
732
+ kernel32 = ctypes.windll.kernel32
733
+ process = ctypes.c_void_p(kernel32.GetCurrentProcess())
734
+ # This is the only reliable way to detect an arm system if we are an x86/x64 process being emulated
735
+ if kernel32.IsWow64Process2(process, ctypes.byref(process_arch), ctypes.byref(native_arch)):
736
+ # https://docs.microsoft.com/en-us/windows/win32/sysinfo/image-file-machine-constants
737
+ if native_arch.value == 0x8664:
738
+ return 'amd64'
739
+ elif native_arch.value == 0x014C:
740
+ return 'x86'
741
+ elif native_arch.value == 0xAA64:
742
+ return 'arm64'
743
+ elif native_arch.value == 0x01C4:
744
+ return 'arm'
745
+ except (OSError, AttributeError):
746
+ pass
747
+ # These env variables are always available. See:
748
+ # https://msdn.microsoft.com/en-us/library/aa384274(VS.85).aspx
749
+ # https://blogs.msdn.microsoft.com/david.wang/2006/03/27/howto-detect-process-bitness/
750
+ arch = os.environ.get('PROCESSOR_ARCHITEW6432', '').lower()
751
+ if not arch:
752
+ try:
753
+ # If this doesn't exist, something is messing with the environment
754
+ arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()
755
+ except KeyError:
756
+ raise EnvironmentException('Unable to detect native OS architecture')
757
+ return arch
758
+
759
+ def detect_vcs(source_dir: T.Union[str, Path]) -> T.Optional[T.Dict[str, str]]:
760
+ vcs_systems = [
761
+ {
762
+ 'name': 'git',
763
+ 'cmd': 'git',
764
+ 'repo_dir': '.git',
765
+ 'get_rev': 'git describe --dirty=+ --always',
766
+ 'rev_regex': '(.*)',
767
+ 'dep': '.git/logs/HEAD'
768
+ },
769
+ {
770
+ 'name': 'mercurial',
771
+ 'cmd': 'hg',
772
+ 'repo_dir': '.hg',
773
+ 'get_rev': 'hg id -i',
774
+ 'rev_regex': '(.*)',
775
+ 'dep': '.hg/dirstate'
776
+ },
777
+ {
778
+ 'name': 'subversion',
779
+ 'cmd': 'svn',
780
+ 'repo_dir': '.svn',
781
+ 'get_rev': 'svn info',
782
+ 'rev_regex': 'Revision: (.*)',
783
+ 'dep': '.svn/wc.db'
784
+ },
785
+ {
786
+ 'name': 'bazaar',
787
+ 'cmd': 'bzr',
788
+ 'repo_dir': '.bzr',
789
+ 'get_rev': 'bzr revno',
790
+ 'rev_regex': '(.*)',
791
+ 'dep': '.bzr'
792
+ },
793
+ ]
794
+ if isinstance(source_dir, str):
795
+ source_dir = Path(source_dir)
796
+
797
+ parent_paths_and_self = collections.deque(source_dir.parents)
798
+ # Prepend the source directory to the front so we can check it;
799
+ # source_dir.parents doesn't include source_dir
800
+ parent_paths_and_self.appendleft(source_dir)
801
+ for curdir in parent_paths_and_self:
802
+ for vcs in vcs_systems:
803
+ if Path.is_dir(curdir.joinpath(vcs['repo_dir'])) and shutil.which(vcs['cmd']):
804
+ vcs['wc_dir'] = str(curdir)
805
+ return vcs
806
+ return None
807
+
808
+ def current_vs_supports_modules() -> bool:
809
+ vsver = os.environ.get('VSCMD_VER', '')
810
+ nums = vsver.split('.', 2)
811
+ major = int(nums[0])
812
+ if major >= 17:
813
+ return True
814
+ if major == 16 and int(nums[1]) >= 10:
815
+ return True
816
+ return vsver.startswith('16.9.0') and '-pre.' in vsver
817
+
818
+ # a helper class which implements the same version ordering as RPM
819
+ class Version:
820
+ def __init__(self, s: str) -> None:
821
+ self._s = s
822
+
823
+ # split into numeric, alphabetic and non-alphanumeric sequences
824
+ sequences1 = re.finditer(r'(\d+|[a-zA-Z]+|[^a-zA-Z\d]+)', s)
825
+
826
+ # non-alphanumeric separators are discarded
827
+ sequences2 = [m for m in sequences1 if not re.match(r'[^a-zA-Z\d]+', m.group(1))]
828
+
829
+ # numeric sequences are converted from strings to ints
830
+ sequences3 = [int(m.group(1)) if m.group(1).isdigit() else m.group(1) for m in sequences2]
831
+
832
+ self._v = sequences3
833
+
834
+ def __str__(self) -> str:
835
+ return '{} (V={})'.format(self._s, str(self._v))
836
+
837
+ def __repr__(self) -> str:
838
+ return f'<Version: {self._s}>'
839
+
840
+ def __lt__(self, other: object) -> bool:
841
+ if isinstance(other, Version):
842
+ return self.__cmp(other, operator.lt)
843
+ return NotImplemented
844
+
845
+ def __gt__(self, other: object) -> bool:
846
+ if isinstance(other, Version):
847
+ return self.__cmp(other, operator.gt)
848
+ return NotImplemented
849
+
850
+ def __le__(self, other: object) -> bool:
851
+ if isinstance(other, Version):
852
+ return self.__cmp(other, operator.le)
853
+ return NotImplemented
854
+
855
+ def __ge__(self, other: object) -> bool:
856
+ if isinstance(other, Version):
857
+ return self.__cmp(other, operator.ge)
858
+ return NotImplemented
859
+
860
+ def __eq__(self, other: object) -> bool:
861
+ if isinstance(other, Version):
862
+ return self._v == other._v
863
+ return NotImplemented
864
+
865
+ def __ne__(self, other: object) -> bool:
866
+ if isinstance(other, Version):
867
+ return self._v != other._v
868
+ return NotImplemented
869
+
870
+ def __cmp(self, other: 'Version', comparator: T.Callable[[T.Any, T.Any], bool]) -> bool:
871
+ # compare each sequence in order
872
+ for ours, theirs in zip(self._v, other._v):
873
+ # sort a non-digit sequence before a digit sequence
874
+ ours_is_int = isinstance(ours, int)
875
+ theirs_is_int = isinstance(theirs, int)
876
+ if ours_is_int != theirs_is_int:
877
+ return comparator(ours_is_int, theirs_is_int)
878
+
879
+ if ours != theirs:
880
+ return comparator(ours, theirs)
881
+
882
+ # if equal length, all components have matched, so equal
883
+ # otherwise, the version with a suffix remaining is greater
884
+ return comparator(len(self._v), len(other._v))
885
+
886
+
887
+ def _version_extract_cmpop(vstr2: str) -> T.Tuple[T.Callable[[T.Any, T.Any], bool], str]:
888
+ if vstr2.startswith('>='):
889
+ cmpop = operator.ge
890
+ vstr2 = vstr2[2:]
891
+ elif vstr2.startswith('<='):
892
+ cmpop = operator.le
893
+ vstr2 = vstr2[2:]
894
+ elif vstr2.startswith('!='):
895
+ cmpop = operator.ne
896
+ vstr2 = vstr2[2:]
897
+ elif vstr2.startswith('=='):
898
+ cmpop = operator.eq
899
+ vstr2 = vstr2[2:]
900
+ elif vstr2.startswith('='):
901
+ cmpop = operator.eq
902
+ vstr2 = vstr2[1:]
903
+ elif vstr2.startswith('>'):
904
+ cmpop = operator.gt
905
+ vstr2 = vstr2[1:]
906
+ elif vstr2.startswith('<'):
907
+ cmpop = operator.lt
908
+ vstr2 = vstr2[1:]
909
+ else:
910
+ cmpop = operator.eq
911
+
912
+ return (cmpop, vstr2)
913
+
914
+
915
+ def version_compare(vstr1: str, vstr2: str) -> bool:
916
+ (cmpop, vstr2) = _version_extract_cmpop(vstr2)
917
+ return cmpop(Version(vstr1), Version(vstr2))
918
+
919
+
920
+ def version_compare_many(vstr1: str, conditions: T.Union[str, T.Iterable[str]]) -> T.Tuple[bool, T.List[str], T.List[str]]:
921
+ if isinstance(conditions, str):
922
+ conditions = [conditions]
923
+ found: T.List[str] = []
924
+ not_found: T.List[str] = []
925
+ for req in conditions:
926
+ if not version_compare(vstr1, req):
927
+ not_found.append(req)
928
+ else:
929
+ found.append(req)
930
+ return not not_found, not_found, found
931
+
932
+
933
+ # determine if the minimum version satisfying the condition |condition| exceeds
934
+ # the minimum version for a feature |minimum|
935
+ def version_compare_condition_with_min(condition: str, minimum: str) -> bool:
936
+ if condition.startswith('>='):
937
+ cmpop = operator.le
938
+ condition = condition[2:]
939
+ elif condition.startswith('<='):
940
+ return False
941
+ elif condition.startswith('!='):
942
+ return False
943
+ elif condition.startswith('=='):
944
+ cmpop = operator.le
945
+ condition = condition[2:]
946
+ elif condition.startswith('='):
947
+ cmpop = operator.le
948
+ condition = condition[1:]
949
+ elif condition.startswith('>'):
950
+ cmpop = operator.lt
951
+ condition = condition[1:]
952
+ elif condition.startswith('<'):
953
+ return False
954
+ else:
955
+ cmpop = operator.le
956
+
957
+ # Declaring a project(meson_version: '>=0.46') and then using features in
958
+ # 0.46.0 is valid, because (knowing the meson versioning scheme) '0.46.0' is
959
+ # the lowest version which satisfies the constraint '>=0.46'.
960
+ #
961
+ # But this will fail here, because the minimum version required by the
962
+ # version constraint ('0.46') is strictly less (in our version comparison)
963
+ # than the minimum version needed for the feature ('0.46.0').
964
+ #
965
+ # Map versions in the constraint of the form '0.46' to '0.46.0', to embed
966
+ # this knowledge of the meson versioning scheme.
967
+ condition = condition.strip()
968
+ if re.match(r'^\d+.\d+$', condition):
969
+ condition += '.0'
970
+
971
+ return T.cast('bool', cmpop(Version(minimum), Version(condition)))
972
+
973
+ def search_version(text: str) -> str:
974
+ # Usually of the type 4.1.4 but compiler output may contain
975
+ # stuff like this:
976
+ # (Sourcery CodeBench Lite 2014.05-29) 4.8.3 20140320 (prerelease)
977
+ # Limiting major version number to two digits seems to work
978
+ # thus far. When we get to GCC 100, this will break, but
979
+ # if we are still relevant when that happens, it can be
980
+ # considered an achievement in itself.
981
+ #
982
+ # This regex is reaching magic levels. If it ever needs
983
+ # to be updated, do not complexify but convert to something
984
+ # saner instead.
985
+ # We'll demystify it a bit with a verbose definition.
986
+ version_regex = re.compile(r"""
987
+ (?<! # Zero-width negative lookbehind assertion
988
+ (
989
+ \d # One digit
990
+ | \. # Or one period
991
+ ) # One occurrence
992
+ )
993
+ # Following pattern must not follow a digit or period
994
+ (
995
+ \d{1,2} # One or two digits
996
+ (
997
+ \.\d+ # Period and one or more digits
998
+ )+ # One or more occurrences
999
+ (
1000
+ -[a-zA-Z0-9]+ # Hyphen and one or more alphanumeric
1001
+ )? # Zero or one occurrence
1002
+ ) # One occurrence
1003
+ """, re.VERBOSE)
1004
+ match = version_regex.search(text)
1005
+ if match:
1006
+ return match.group(0)
1007
+
1008
+ # try a simpler regex that has like "blah 2020.01.100 foo" or "blah 2020.01 foo"
1009
+ version_regex = re.compile(r"(\d{1,4}\.\d{1,4}\.?\d{0,4})")
1010
+ match = version_regex.search(text)
1011
+ if match:
1012
+ return match.group(0)
1013
+
1014
+ return 'unknown version'
1015
+
1016
+
1017
+ def default_libdir() -> str:
1018
+ if is_debianlike():
1019
+ try:
1020
+ pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
1021
+ stdout=subprocess.PIPE,
1022
+ stderr=subprocess.DEVNULL)
1023
+ (stdo, _) = pc.communicate()
1024
+ if pc.returncode == 0:
1025
+ archpath = stdo.decode().strip()
1026
+ return 'lib/' + archpath
1027
+ except Exception:
1028
+ pass
1029
+ if is_freebsd() or is_irix():
1030
+ return 'lib'
1031
+ if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
1032
+ return 'lib64'
1033
+ return 'lib'
1034
+
1035
+
1036
+ def default_libexecdir() -> str:
1037
+ if is_haiku():
1038
+ return 'lib'
1039
+ # There is no way to auto-detect this, so it must be set at build time
1040
+ return 'libexec'
1041
+
1042
+
1043
+ def default_prefix() -> str:
1044
+ if is_windows():
1045
+ return 'c:/'
1046
+ if is_haiku():
1047
+ return '/boot/system/non-packaged'
1048
+ return '/usr/local'
1049
+
1050
+
1051
+ def default_datadir() -> str:
1052
+ if is_haiku():
1053
+ return 'data'
1054
+ return 'share'
1055
+
1056
+
1057
+ def default_includedir() -> str:
1058
+ if is_haiku():
1059
+ return 'develop/headers'
1060
+ return 'include'
1061
+
1062
+
1063
+ def default_infodir() -> str:
1064
+ if is_haiku():
1065
+ return 'documentation/info'
1066
+ return 'share/info'
1067
+
1068
+
1069
+ def default_localedir() -> str:
1070
+ if is_haiku():
1071
+ return 'data/locale'
1072
+ return 'share/locale'
1073
+
1074
+
1075
+ def default_mandir() -> str:
1076
+ if is_haiku():
1077
+ return 'documentation/man'
1078
+ return 'share/man'
1079
+
1080
+
1081
+ def default_sbindir() -> str:
1082
+ if is_haiku():
1083
+ return 'bin'
1084
+ return 'sbin'
1085
+
1086
+
1087
+ def default_sysconfdir() -> str:
1088
+ if is_haiku():
1089
+ return 'settings'
1090
+ return 'etc'
1091
+
1092
+
1093
+ def has_path_sep(name: str, sep: str = '/\\') -> bool:
1094
+ 'Checks if any of the specified @sep path separators are in @name'
1095
+ for each in sep:
1096
+ if each in name:
1097
+ return True
1098
+ return False
1099
+
1100
+
1101
+ if is_windows():
1102
+ # shlex.split is not suitable for splitting command line on Window (https://bugs.python.org/issue1724822);
1103
+ # shlex.quote is similarly problematic. Below are "proper" implementations of these functions according to
1104
+ # https://docs.microsoft.com/en-us/cpp/c-language/parsing-c-command-line-arguments and
1105
+ # https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
1106
+
1107
+ _whitespace = ' \t\n\r'
1108
+ _find_unsafe_char = re.compile(fr'[{_whitespace}"]').search
1109
+
1110
+ def quote_arg(arg: str) -> str:
1111
+ if arg and not _find_unsafe_char(arg):
1112
+ return arg
1113
+
1114
+ result = '"'
1115
+ num_backslashes = 0
1116
+ for c in arg:
1117
+ if c == '\\':
1118
+ num_backslashes += 1
1119
+ else:
1120
+ if c == '"':
1121
+ # Escape all backslashes and the following double quotation mark
1122
+ num_backslashes = num_backslashes * 2 + 1
1123
+
1124
+ result += num_backslashes * '\\' + c
1125
+ num_backslashes = 0
1126
+
1127
+ # Escape all backslashes, but let the terminating double quotation
1128
+ # mark we add below be interpreted as a metacharacter
1129
+ result += (num_backslashes * 2) * '\\' + '"'
1130
+ return result
1131
+
1132
+ def split_args(cmd: str) -> T.List[str]:
1133
+ result: T.List[str] = []
1134
+ arg = ''
1135
+ num_backslashes = 0
1136
+ num_quotes = 0
1137
+ in_quotes = False
1138
+ for c in cmd:
1139
+ if c == '\\':
1140
+ num_backslashes += 1
1141
+ else:
1142
+ if c == '"' and not num_backslashes % 2:
1143
+ # unescaped quote, eat it
1144
+ arg += (num_backslashes // 2) * '\\'
1145
+ num_quotes += 1
1146
+ in_quotes = not in_quotes
1147
+ elif c in _whitespace and not in_quotes:
1148
+ if arg or num_quotes:
1149
+ # reached the end of the argument
1150
+ result.append(arg)
1151
+ arg = ''
1152
+ num_quotes = 0
1153
+ else:
1154
+ if c == '"':
1155
+ # escaped quote
1156
+ num_backslashes = (num_backslashes - 1) // 2
1157
+
1158
+ arg += num_backslashes * '\\' + c
1159
+
1160
+ num_backslashes = 0
1161
+
1162
+ if arg or num_quotes:
1163
+ result.append(arg)
1164
+
1165
+ return result
1166
+ else:
1167
+ def quote_arg(arg: str) -> str:
1168
+ return shlex.quote(arg)
1169
+
1170
+ def split_args(cmd: str) -> T.List[str]:
1171
+ return shlex.split(cmd)
1172
+
1173
+
1174
+ def join_args(args: T.Iterable[str]) -> str:
1175
+ return ' '.join([quote_arg(x) for x in args])
1176
+
1177
+
1178
+ def do_replacement(regex: T.Pattern[str], line: str,
1179
+ variable_format: Literal['meson', 'cmake', 'cmake@'],
1180
+ confdata: T.Union[T.Dict[str, T.Tuple[str, T.Optional[str]]], 'ConfigurationData']) -> T.Tuple[str, T.Set[str]]:
1181
+ missing_variables: T.Set[str] = set()
1182
+ if variable_format == 'cmake':
1183
+ start_tag = '${'
1184
+ backslash_tag = '\\${'
1185
+ else:
1186
+ start_tag = '@'
1187
+ backslash_tag = '\\@'
1188
+
1189
+ def variable_replace(match: T.Match[str]) -> str:
1190
+ # Pairs of escape characters before '@' or '\@'
1191
+ if match.group(0).endswith('\\'):
1192
+ num_escapes = match.end(0) - match.start(0)
1193
+ return '\\' * (num_escapes // 2)
1194
+ # Single escape character and '@'
1195
+ elif match.group(0) == backslash_tag:
1196
+ return start_tag
1197
+ # Template variable to be replaced
1198
+ else:
1199
+ varname = match.group(1)
1200
+ var_str = ''
1201
+ if varname in confdata:
1202
+ var, _ = confdata.get(varname)
1203
+ if isinstance(var, str):
1204
+ var_str = var
1205
+ elif variable_format.startswith("cmake") and isinstance(var, bool):
1206
+ var_str = str(int(var))
1207
+ elif isinstance(var, int):
1208
+ var_str = str(var)
1209
+ else:
1210
+ msg = f'Tried to replace variable {varname!r} value with ' \
1211
+ f'something other than a string or int: {var!r}'
1212
+ raise MesonException(msg)
1213
+ else:
1214
+ missing_variables.add(varname)
1215
+ return var_str
1216
+ return re.sub(regex, variable_replace, line), missing_variables
1217
+
1218
+ def do_define(regex: T.Pattern[str], line: str, confdata: 'ConfigurationData',
1219
+ variable_format: Literal['meson', 'cmake', 'cmake@'], subproject: T.Optional[SubProject] = None) -> str:
1220
+ cmake_bool_define = False
1221
+ if variable_format != "meson":
1222
+ cmake_bool_define = "cmakedefine01" in line
1223
+
1224
+ def get_cmake_define(line: str, confdata: 'ConfigurationData') -> str:
1225
+ arr = line.split()
1226
+
1227
+ if cmake_bool_define:
1228
+ (v, desc) = confdata.get(arr[1])
1229
+ return str(int(bool(v)))
1230
+
1231
+ define_value: T.List[str] = []
1232
+ for token in arr[2:]:
1233
+ try:
1234
+ v, _ = confdata.get(token)
1235
+ define_value += [str(v)]
1236
+ except KeyError:
1237
+ define_value += [token]
1238
+ return ' '.join(define_value)
1239
+
1240
+ arr = line.split()
1241
+ if len(arr) != 2:
1242
+ if variable_format == 'meson':
1243
+ raise MesonException('#mesondefine does not contain exactly two tokens: %s' % line.strip())
1244
+ elif subproject is not None:
1245
+ from ..interpreterbase.decorators import FeatureNew
1246
+ FeatureNew.single_use('cmakedefine without exactly two tokens', '0.54.1', subproject)
1247
+
1248
+ varname = arr[1]
1249
+ try:
1250
+ v, _ = confdata.get(varname)
1251
+ except KeyError:
1252
+ if cmake_bool_define:
1253
+ return '#define %s 0\n' % varname
1254
+ else:
1255
+ return '/* #undef %s */\n' % varname
1256
+
1257
+ if isinstance(v, str) or variable_format != "meson":
1258
+ if variable_format == 'meson':
1259
+ result = v
1260
+ else:
1261
+ if not cmake_bool_define and not v:
1262
+ return '/* #undef %s */\n' % varname
1263
+
1264
+ result = get_cmake_define(line, confdata)
1265
+ result = f'#define {varname} {result}'.strip() + '\n'
1266
+ result, _ = do_replacement(regex, result, variable_format, confdata)
1267
+ return result
1268
+ elif isinstance(v, bool):
1269
+ if v:
1270
+ return '#define %s\n' % varname
1271
+ else:
1272
+ return '#undef %s\n' % varname
1273
+ elif isinstance(v, int):
1274
+ return '#define %s %d\n' % (varname, v)
1275
+ else:
1276
+ raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
1277
+
1278
+ def get_variable_regex(variable_format: Literal['meson', 'cmake', 'cmake@'] = 'meson') -> T.Pattern[str]:
1279
+ # Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
1280
+ # Also allow escaping '@' with '\@'
1281
+ if variable_format in {'meson', 'cmake@'}:
1282
+ regex = re.compile(r'(?:\\\\)+(?=\\?@)|\\@|@([-a-zA-Z0-9_]+)@')
1283
+ else:
1284
+ regex = re.compile(r'(?:\\\\)+(?=\\?\$)|\\\${|\${([-a-zA-Z0-9_]+)}')
1285
+ return regex
1286
+
1287
+ def do_conf_str(src: str, data: T.List[str], confdata: 'ConfigurationData',
1288
+ variable_format: Literal['meson', 'cmake', 'cmake@'],
1289
+ subproject: T.Optional[SubProject] = None) -> T.Tuple[T.List[str], T.Set[str], bool]:
1290
+ def line_is_valid(line: str, variable_format: str) -> bool:
1291
+ if variable_format == 'meson':
1292
+ if '#cmakedefine' in line:
1293
+ return False
1294
+ else: # cmake format
1295
+ if '#mesondefine' in line:
1296
+ return False
1297
+ return True
1298
+
1299
+ regex = get_variable_regex(variable_format)
1300
+
1301
+ search_token = '#mesondefine'
1302
+ if variable_format != 'meson':
1303
+ search_token = '#cmakedefine'
1304
+
1305
+ result: T.List[str] = []
1306
+ missing_variables: T.Set[str] = set()
1307
+ # Detect when the configuration data is empty and no tokens were found
1308
+ # during substitution so we can warn the user to use the `copy:` kwarg.
1309
+ confdata_useless = not confdata.keys()
1310
+ for line in data:
1311
+ if line.lstrip().startswith(search_token):
1312
+ confdata_useless = False
1313
+ line = do_define(regex, line, confdata, variable_format, subproject)
1314
+ else:
1315
+ if not line_is_valid(line, variable_format):
1316
+ raise MesonException(f'Format error in {src}: saw "{line.strip()}" when format set to "{variable_format}"')
1317
+ line, missing = do_replacement(regex, line, variable_format, confdata)
1318
+ missing_variables.update(missing)
1319
+ if missing:
1320
+ confdata_useless = False
1321
+ result.append(line)
1322
+
1323
+ return result, missing_variables, confdata_useless
1324
+
1325
+ def do_conf_file(src: str, dst: str, confdata: 'ConfigurationData',
1326
+ variable_format: Literal['meson', 'cmake', 'cmake@'],
1327
+ encoding: str = 'utf-8', subproject: T.Optional[SubProject] = None) -> T.Tuple[T.Set[str], bool]:
1328
+ try:
1329
+ with open(src, encoding=encoding, newline='') as f:
1330
+ data = f.readlines()
1331
+ except Exception as e:
1332
+ raise MesonException(f'Could not read input file {src}: {e!s}')
1333
+
1334
+ (result, missing_variables, confdata_useless) = do_conf_str(src, data, confdata, variable_format, subproject)
1335
+ dst_tmp = dst + '~'
1336
+ try:
1337
+ with open(dst_tmp, 'w', encoding=encoding, newline='') as f:
1338
+ f.writelines(result)
1339
+ except Exception as e:
1340
+ raise MesonException(f'Could not write output file {dst}: {e!s}')
1341
+ shutil.copymode(src, dst_tmp)
1342
+ replace_if_different(dst, dst_tmp)
1343
+ return missing_variables, confdata_useless
1344
+
1345
+ CONF_C_PRELUDE = '''/*
1346
+ * Autogenerated by the Meson build system.
1347
+ * Do not edit, your changes will be lost.
1348
+ */
1349
+
1350
+ {}
1351
+
1352
+ '''
1353
+
1354
+ CONF_NASM_PRELUDE = '''; Autogenerated by the Meson build system.
1355
+ ; Do not edit, your changes will be lost.
1356
+
1357
+ '''
1358
+
1359
+ def _dump_c_header(ofile: T.TextIO,
1360
+ cdata: ConfigurationData,
1361
+ output_format: Literal['c', 'nasm'],
1362
+ macro_name: T.Optional[str]) -> None:
1363
+ format_desc: T.Callable[[str], str]
1364
+ if output_format == 'c':
1365
+ if macro_name:
1366
+ prelude = CONF_C_PRELUDE.format('#ifndef {0}\n#define {0}'.format(macro_name))
1367
+ else:
1368
+ prelude = CONF_C_PRELUDE.format('#pragma once')
1369
+ prefix = '#'
1370
+ format_desc = lambda desc: f'/* {desc} */\n'
1371
+ else: # nasm
1372
+ prelude = CONF_NASM_PRELUDE
1373
+ prefix = '%'
1374
+ format_desc = lambda desc: '; ' + '\n; '.join(desc.splitlines()) + '\n'
1375
+
1376
+ ofile.write(prelude)
1377
+ for k in sorted(cdata.keys()):
1378
+ (v, desc) = cdata.get(k)
1379
+ if desc:
1380
+ ofile.write(format_desc(desc))
1381
+ if isinstance(v, bool):
1382
+ if v:
1383
+ ofile.write(f'{prefix}define {k}\n\n')
1384
+ else:
1385
+ ofile.write(f'{prefix}undef {k}\n\n')
1386
+ elif isinstance(v, (int, str)):
1387
+ ofile.write(f'{prefix}define {k} {v}\n\n')
1388
+ else:
1389
+ raise MesonException('Unknown data type in configuration file entry: ' + k)
1390
+ if output_format == 'c' and macro_name:
1391
+ ofile.write('#endif\n')
1392
+
1393
+
1394
+ def dump_conf_header(ofilename: str, cdata: ConfigurationData,
1395
+ output_format: Literal['c', 'nasm', 'json'],
1396
+ macro_name: T.Optional[str]) -> None:
1397
+ ofilename_tmp = ofilename + '~'
1398
+ with open(ofilename_tmp, 'w', encoding='utf-8') as ofile:
1399
+ if output_format == 'json':
1400
+ data = {k: v[0] for k, v in cdata.values.items()}
1401
+ json.dump(data, ofile, sort_keys=True)
1402
+ else: # c, nasm
1403
+ _dump_c_header(ofile, cdata, output_format, macro_name)
1404
+
1405
+ replace_if_different(ofilename, ofilename_tmp)
1406
+
1407
+
1408
+ def replace_if_different(dst: str, dst_tmp: str) -> None:
1409
+ # If contents are identical, don't touch the file to prevent
1410
+ # unnecessary rebuilds.
1411
+ different = True
1412
+ try:
1413
+ with open(dst, 'rb') as f1, open(dst_tmp, 'rb') as f2:
1414
+ if f1.read() == f2.read():
1415
+ different = False
1416
+ except FileNotFoundError:
1417
+ pass
1418
+ if different:
1419
+ os.replace(dst_tmp, dst)
1420
+ else:
1421
+ os.unlink(dst_tmp)
1422
+
1423
+
1424
+ def listify(item: T.Any, flatten: bool = True) -> T.List[T.Any]:
1425
+ '''
1426
+ Returns a list with all args embedded in a list if they are not a list.
1427
+ This function preserves order.
1428
+ @flatten: Convert lists of lists to a flat list
1429
+ '''
1430
+ if not isinstance(item, list):
1431
+ return [item]
1432
+ result: T.List[T.Any] = []
1433
+ for i in item:
1434
+ if flatten and isinstance(i, list):
1435
+ result += listify(i, flatten=True)
1436
+ else:
1437
+ result.append(i)
1438
+ return result
1439
+
1440
+ def listify_array_value(value: T.Union[str, T.List[str]], shlex_split_args: bool = False) -> T.List[str]:
1441
+ if isinstance(value, str):
1442
+ if value.startswith('['):
1443
+ try:
1444
+ newvalue = ast.literal_eval(value)
1445
+ except ValueError:
1446
+ raise MesonException(f'malformed value {value}')
1447
+ elif value == '':
1448
+ newvalue = []
1449
+ else:
1450
+ if shlex_split_args:
1451
+ newvalue = split_args(value)
1452
+ else:
1453
+ newvalue = [v.strip() for v in value.split(',')]
1454
+ elif isinstance(value, list):
1455
+ newvalue = value
1456
+ else:
1457
+ raise MesonException(f'"{value}" should be a string array, but it is not')
1458
+ assert isinstance(newvalue, list)
1459
+ return newvalue
1460
+
1461
+ def extract_as_list(dict_object: T.Dict[_T, _U], key: _T, pop: bool = False) -> T.List[_U]:
1462
+ '''
1463
+ Extracts all values from given dict_object and listifies them.
1464
+ '''
1465
+ fetch: T.Callable[[_T], _U] = dict_object.get
1466
+ if pop:
1467
+ fetch = dict_object.pop
1468
+ # If there's only one key, we don't return a list with one element
1469
+ return listify(fetch(key) or [], flatten=True)
1470
+
1471
+
1472
+ def typeslistify(item: 'T.Union[_T, T.Sequence[_T]]',
1473
+ types: 'T.Union[T.Type[_T], T.Tuple[T.Type[_T]]]') -> T.List[_T]:
1474
+ '''
1475
+ Ensure that type(@item) is one of @types or a
1476
+ list of items all of which are of type @types
1477
+ '''
1478
+ if isinstance(item, types):
1479
+ item = T.cast('T.List[_T]', [item])
1480
+ if not isinstance(item, list):
1481
+ raise MesonException('Item must be a list or one of {!r}, not {!r}'.format(types, type(item)))
1482
+ for i in item:
1483
+ if i is not None and not isinstance(i, types):
1484
+ raise MesonException('List item must be one of {!r}, not {!r}'.format(types, type(i)))
1485
+ return item
1486
+
1487
+
1488
+ def stringlistify(item: T.Union[T.Any, T.Sequence[T.Any]]) -> T.List[str]:
1489
+ return typeslistify(item, str)
1490
+
1491
+
1492
+ def expand_arguments(args: T.Iterable[str]) -> T.Optional[T.List[str]]:
1493
+ expended_args: T.List[str] = []
1494
+ for arg in args:
1495
+ if not arg.startswith('@'):
1496
+ expended_args.append(arg)
1497
+ continue
1498
+
1499
+ args_file = arg[1:]
1500
+ try:
1501
+ with open(args_file, encoding='utf-8') as f:
1502
+ extended_args = f.read().split()
1503
+ expended_args += extended_args
1504
+ except Exception as e:
1505
+ mlog.error('Expanding command line arguments:', args_file, 'not found')
1506
+ mlog.exception(e)
1507
+ return None
1508
+ return expended_args
1509
+
1510
+
1511
+ def partition(pred: T.Callable[[_T], object], iterable: T.Iterable[_T]) -> T.Tuple[T.Iterator[_T], T.Iterator[_T]]:
1512
+ """Use a predicate to partition entries into false entries and true
1513
+ entries.
1514
+
1515
+ >>> x, y = partition(is_odd, range(10))
1516
+ >>> (list(x), list(y))
1517
+ ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9])
1518
+ """
1519
+ t1, t2 = tee(iterable)
1520
+ return (t for t in t1 if not pred(t)), (t for t in t2 if pred(t))
1521
+
1522
+
1523
+ def Popen_safe(args: T.List[str], write: T.Optional[str] = None,
1524
+ stdin: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.DEVNULL,
1525
+ stdout: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.PIPE,
1526
+ stderr: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.PIPE,
1527
+ **kwargs: T.Any) -> T.Tuple['subprocess.Popen[str]', str, str]:
1528
+ import locale
1529
+ encoding = locale.getpreferredencoding()
1530
+ # Stdin defaults to DEVNULL otherwise the command run by us here might mess
1531
+ # up the console and ANSI colors will stop working on Windows.
1532
+ # If write is not None, set stdin to PIPE so data can be sent.
1533
+ if write is not None:
1534
+ stdin = subprocess.PIPE
1535
+
1536
+ try:
1537
+ if not sys.stdout.encoding or encoding.upper() != 'UTF-8':
1538
+ p, o, e = Popen_safe_legacy(args, write=write, stdin=stdin, stdout=stdout, stderr=stderr, **kwargs)
1539
+ else:
1540
+ p = subprocess.Popen(args, universal_newlines=True, encoding=encoding, close_fds=False,
1541
+ stdin=stdin, stdout=stdout, stderr=stderr, **kwargs)
1542
+ o, e = p.communicate(write)
1543
+ except OSError as oserr:
1544
+ if oserr.errno == errno.ENOEXEC:
1545
+ raise MesonException(f'Failed running {args[0]!r}, binary or interpreter not executable.\n'
1546
+ 'Possibly wrong architecture or the executable bit is not set.')
1547
+ raise
1548
+ # Sometimes the command that we run will call another command which will be
1549
+ # without the above stdin workaround, so set the console mode again just in
1550
+ # case.
1551
+ mlog.setup_console()
1552
+ return p, o, e
1553
+
1554
+
1555
+ def Popen_safe_legacy(args: T.List[str], write: T.Optional[str] = None,
1556
+ stdin: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.DEVNULL,
1557
+ stdout: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.PIPE,
1558
+ stderr: T.Union[None, T.TextIO, T.BinaryIO, int] = subprocess.PIPE,
1559
+ **kwargs: T.Any) -> T.Tuple['subprocess.Popen[str]', str, str]:
1560
+ p = subprocess.Popen(args, universal_newlines=False, close_fds=False,
1561
+ stdin=stdin, stdout=stdout, stderr=stderr, **kwargs)
1562
+ input_: T.Optional[bytes] = None
1563
+ if write is not None:
1564
+ input_ = write.encode('utf-8')
1565
+ o, e = p.communicate(input_)
1566
+ if o is not None:
1567
+ if sys.stdout.encoding is not None:
1568
+ o = o.decode(encoding=sys.stdout.encoding, errors='replace').replace('\r\n', '\n')
1569
+ else:
1570
+ o = o.decode(errors='replace').replace('\r\n', '\n')
1571
+ if e is not None:
1572
+ if sys.stderr is not None and sys.stderr.encoding:
1573
+ e = e.decode(encoding=sys.stderr.encoding, errors='replace').replace('\r\n', '\n')
1574
+ else:
1575
+ e = e.decode(errors='replace').replace('\r\n', '\n')
1576
+ return p, o, e
1577
+
1578
+
1579
+ def Popen_safe_logged(args: T.List[str], msg: str = 'Called', **kwargs: T.Any) -> T.Tuple['subprocess.Popen[str]', str, str]:
1580
+ '''
1581
+ Wrapper around Popen_safe that assumes standard piped o/e and logs this to the meson log.
1582
+ '''
1583
+ try:
1584
+ p, o, e = Popen_safe(args, **kwargs)
1585
+ except Exception as excp:
1586
+ mlog.debug('-----------')
1587
+ mlog.debug(f'{msg}: `{join_args(args)}` -> {excp}')
1588
+ raise
1589
+
1590
+ rc, out, err = p.returncode, o.strip(), e.strip()
1591
+ mlog.debug('-----------')
1592
+ mlog.debug(f'{msg}: `{join_args(args)}` -> {rc}')
1593
+ if out:
1594
+ mlog.debug(f'stdout:\n{out}\n-----------')
1595
+ if err:
1596
+ mlog.debug(f'stderr:\n{err}\n-----------')
1597
+ return p, o, e
1598
+
1599
+
1600
+ def iter_regexin_iter(regexiter: T.Iterable[str], initer: T.Iterable[str]) -> T.Optional[str]:
1601
+ '''
1602
+ Takes each regular expression in @regexiter and tries to search for it in
1603
+ every item in @initer. If there is a match, returns that match.
1604
+ Else returns False.
1605
+ '''
1606
+ for regex in regexiter:
1607
+ for ii in initer:
1608
+ if not isinstance(ii, str):
1609
+ continue
1610
+ match = re.search(regex, ii)
1611
+ if match:
1612
+ return match.group()
1613
+ return None
1614
+
1615
+
1616
+ def _substitute_values_check_errors(command: T.List[str], values: T.Dict[str, T.Union[str, T.List[str]]]) -> None:
1617
+ # Error checking
1618
+ inregex: T.List[str] = ['@INPUT([0-9]+)?@', '@PLAINNAME@', '@BASENAME@']
1619
+ outregex: T.List[str] = ['@OUTPUT([0-9]+)?@', '@OUTDIR@']
1620
+ if '@INPUT@' not in values:
1621
+ # Error out if any input-derived templates are present in the command
1622
+ match = iter_regexin_iter(inregex, command)
1623
+ if match:
1624
+ raise MesonException(f'Command cannot have {match!r}, since no input files were specified')
1625
+ else:
1626
+ if len(values['@INPUT@']) > 1:
1627
+ # Error out if @PLAINNAME@ or @BASENAME@ is present in the command
1628
+ match = iter_regexin_iter(inregex[1:], command)
1629
+ if match:
1630
+ raise MesonException(f'Command cannot have {match!r} when there is '
1631
+ 'more than one input file')
1632
+ # Error out if an invalid @INPUTnn@ template was specified
1633
+ for each in command:
1634
+ if not isinstance(each, str):
1635
+ continue
1636
+ match2 = re.search(inregex[0], each)
1637
+ if match2 and match2.group() not in values:
1638
+ m = 'Command cannot have {!r} since there are only {!r} inputs'
1639
+ raise MesonException(m.format(match2.group(), len(values['@INPUT@'])))
1640
+ if '@OUTPUT@' not in values:
1641
+ # Error out if any output-derived templates are present in the command
1642
+ match = iter_regexin_iter(outregex, command)
1643
+ if match:
1644
+ raise MesonException(f'Command cannot have {match!r} since there are no outputs')
1645
+ else:
1646
+ # Error out if an invalid @OUTPUTnn@ template was specified
1647
+ for each in command:
1648
+ if not isinstance(each, str):
1649
+ continue
1650
+ match2 = re.search(outregex[0], each)
1651
+ if match2 and match2.group() not in values:
1652
+ m = 'Command cannot have {!r} since there are only {!r} outputs'
1653
+ raise MesonException(m.format(match2.group(), len(values['@OUTPUT@'])))
1654
+
1655
+
1656
+ def substitute_values(command: T.List[str], values: T.Dict[str, T.Union[str, T.List[str]]]) -> T.List[str]:
1657
+ '''
1658
+ Substitute the template strings in the @values dict into the list of
1659
+ strings @command and return a new list. For a full list of the templates,
1660
+ see get_filenames_templates_dict()
1661
+
1662
+ If multiple inputs/outputs are given in the @values dictionary, we
1663
+ substitute @INPUT@ and @OUTPUT@ only if they are the entire string, not
1664
+ just a part of it, and in that case we substitute *all* of them.
1665
+
1666
+ The typing of this function is difficult, as only @OUTPUT@ and @INPUT@ can
1667
+ be lists, everything else is a string. However, TypeDict cannot represent
1668
+ this, as you can have optional keys, but not extra keys. We end up just
1669
+ having to us asserts to convince type checkers that this is okay.
1670
+
1671
+ https://github.com/python/mypy/issues/4617
1672
+ '''
1673
+
1674
+ def replace(m: T.Match[str]) -> str:
1675
+ v = values[m.group(0)]
1676
+ assert isinstance(v, str), 'for mypy'
1677
+ return v
1678
+
1679
+ # Error checking
1680
+ _substitute_values_check_errors(command, values)
1681
+
1682
+ # Substitution
1683
+ outcmd: T.List[str] = []
1684
+ rx_keys = [re.escape(key) for key in values if key not in ('@INPUT@', '@OUTPUT@')]
1685
+ value_rx = re.compile('|'.join(rx_keys)) if rx_keys else None
1686
+ for vv in command:
1687
+ more: T.Optional[str] = None
1688
+ if not isinstance(vv, str):
1689
+ outcmd.append(vv)
1690
+ elif '@INPUT@' in vv:
1691
+ inputs = values['@INPUT@']
1692
+ if vv == '@INPUT@':
1693
+ outcmd += inputs
1694
+ elif len(inputs) == 1:
1695
+ outcmd.append(vv.replace('@INPUT@', inputs[0]))
1696
+ else:
1697
+ raise MesonException("Command has '@INPUT@' as part of a "
1698
+ "string and more than one input file")
1699
+ elif '@OUTPUT@' in vv:
1700
+ outputs = values['@OUTPUT@']
1701
+ if vv == '@OUTPUT@':
1702
+ outcmd += outputs
1703
+ elif len(outputs) == 1:
1704
+ outcmd.append(vv.replace('@OUTPUT@', outputs[0]))
1705
+ else:
1706
+ raise MesonException("Command has '@OUTPUT@' as part of a "
1707
+ "string and more than one output file")
1708
+
1709
+ # Append values that are exactly a template string.
1710
+ # This is faster than a string replace.
1711
+ elif vv in values:
1712
+ o = values[vv]
1713
+ assert isinstance(o, str), 'for mypy'
1714
+ more = o
1715
+ # Substitute everything else with replacement
1716
+ elif value_rx:
1717
+ more = value_rx.sub(replace, vv)
1718
+ else:
1719
+ more = vv
1720
+
1721
+ if more is not None:
1722
+ outcmd.append(more)
1723
+
1724
+ return outcmd
1725
+
1726
+
1727
+ def get_filenames_templates_dict(inputs: T.List[str], outputs: T.List[str]) -> T.Dict[str, T.Union[str, T.List[str]]]:
1728
+ '''
1729
+ Create a dictionary with template strings as keys and values as values for
1730
+ the following templates:
1731
+
1732
+ @INPUT@ - the full path to one or more input files, from @inputs
1733
+ @OUTPUT@ - the full path to one or more output files, from @outputs
1734
+ @OUTDIR@ - the full path to the directory containing the output files
1735
+
1736
+ If there is only one input file, the following keys are also created:
1737
+
1738
+ @PLAINNAME@ - the filename of the input file
1739
+ @BASENAME@ - the filename of the input file with the extension removed
1740
+
1741
+ If there is more than one input file, the following keys are also created:
1742
+
1743
+ @INPUT0@, @INPUT1@, ... one for each input file
1744
+
1745
+ If there is more than one output file, the following keys are also created:
1746
+
1747
+ @OUTPUT0@, @OUTPUT1@, ... one for each output file
1748
+ '''
1749
+ values: T.Dict[str, T.Union[str, T.List[str]]] = {}
1750
+ # Gather values derived from the input
1751
+ if inputs:
1752
+ # We want to substitute all the inputs.
1753
+ values['@INPUT@'] = inputs
1754
+ for (ii, vv) in enumerate(inputs):
1755
+ # Write out @INPUT0@, @INPUT1@, ...
1756
+ values[f'@INPUT{ii}@'] = vv
1757
+ if len(inputs) == 1:
1758
+ # Just one value, substitute @PLAINNAME@ and @BASENAME@
1759
+ values['@PLAINNAME@'] = plain = os.path.basename(inputs[0])
1760
+ values['@BASENAME@'] = os.path.splitext(plain)[0]
1761
+ if outputs:
1762
+ # Gather values derived from the outputs, similar to above.
1763
+ values['@OUTPUT@'] = outputs
1764
+ for (ii, vv) in enumerate(outputs):
1765
+ values[f'@OUTPUT{ii}@'] = vv
1766
+ # Outdir should be the same for all outputs
1767
+ values['@OUTDIR@'] = os.path.dirname(outputs[0])
1768
+ # Many external programs fail on empty arguments.
1769
+ if values['@OUTDIR@'] == '':
1770
+ values['@OUTDIR@'] = '.'
1771
+ return values
1772
+
1773
+
1774
+ def _make_tree_writable(topdir: str) -> None:
1775
+ # Ensure all files and directories under topdir are writable
1776
+ # (and readable) by owner.
1777
+ for d, _, files in os.walk(topdir):
1778
+ os.chmod(d, os.stat(d).st_mode | stat.S_IWRITE | stat.S_IREAD)
1779
+ for fname in files:
1780
+ fpath = os.path.join(d, fname)
1781
+ if os.path.isfile(fpath):
1782
+ os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
1783
+
1784
+
1785
+ def windows_proof_rmtree(f: str) -> None:
1786
+ # On Windows if anyone is holding a file open you can't
1787
+ # delete it. As an example an anti virus scanner might
1788
+ # be scanning files you are trying to delete. The only
1789
+ # way to fix this is to try again and again.
1790
+ delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
1791
+ writable = False
1792
+ for d in delays:
1793
+ try:
1794
+ # Start by making the tree writable.
1795
+ if not writable:
1796
+ _make_tree_writable(f)
1797
+ writable = True
1798
+ except PermissionError:
1799
+ time.sleep(d)
1800
+ continue
1801
+ try:
1802
+ shutil.rmtree(f)
1803
+ return
1804
+ except FileNotFoundError:
1805
+ return
1806
+ except OSError:
1807
+ time.sleep(d)
1808
+ # Try one last time and throw if it fails.
1809
+ shutil.rmtree(f)
1810
+
1811
+
1812
+ def windows_proof_rm(fpath: str) -> None:
1813
+ """Like windows_proof_rmtree, but for a single file."""
1814
+ if os.path.isfile(fpath):
1815
+ os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
1816
+ delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
1817
+ for d in delays:
1818
+ try:
1819
+ os.unlink(fpath)
1820
+ return
1821
+ except FileNotFoundError:
1822
+ return
1823
+ except OSError:
1824
+ time.sleep(d)
1825
+ os.unlink(fpath)
1826
+
1827
+
1828
+ class TemporaryDirectoryWinProof(TemporaryDirectory):
1829
+ """
1830
+ Like TemporaryDirectory, but cleans things up using
1831
+ windows_proof_rmtree()
1832
+ """
1833
+
1834
+ def __exit__(self, exc: T.Any, value: T.Any, tb: T.Any) -> None:
1835
+ try:
1836
+ super().__exit__(exc, value, tb)
1837
+ except OSError:
1838
+ windows_proof_rmtree(self.name)
1839
+
1840
+ def cleanup(self) -> None:
1841
+ try:
1842
+ super().cleanup()
1843
+ except OSError:
1844
+ windows_proof_rmtree(self.name)
1845
+
1846
+
1847
+ def detect_subprojects(spdir_name: str, current_dir: str = '',
1848
+ result: T.Optional[T.Dict[str, T.List[str]]] = None) -> T.Dict[str, T.List[str]]:
1849
+ if result is None:
1850
+ result = {}
1851
+ spdir = os.path.join(current_dir, spdir_name)
1852
+ if not os.path.exists(spdir):
1853
+ return result
1854
+ for trial in glob(os.path.join(spdir, '*')):
1855
+ basename = os.path.basename(trial)
1856
+ if trial == 'packagecache':
1857
+ continue
1858
+ append_this = True
1859
+ if os.path.isdir(trial):
1860
+ detect_subprojects(spdir_name, trial, result)
1861
+ elif trial.endswith('.wrap') and os.path.isfile(trial):
1862
+ basename = os.path.splitext(basename)[0]
1863
+ else:
1864
+ append_this = False
1865
+ if append_this:
1866
+ if basename in result:
1867
+ result[basename].append(trial)
1868
+ else:
1869
+ result[basename] = [trial]
1870
+ return result
1871
+
1872
+
1873
+ def substring_is_in_list(substr: str, strlist: T.List[str]) -> bool:
1874
+ for s in strlist:
1875
+ if substr in s:
1876
+ return True
1877
+ return False
1878
+
1879
+
1880
+ class OrderedSet(T.MutableSet[_T]):
1881
+ """A set that preserves the order in which items are added, by first
1882
+ insertion.
1883
+ """
1884
+ def __init__(self, iterable: T.Optional[T.Iterable[_T]] = None):
1885
+ self.__container: T.OrderedDict[_T, None] = collections.OrderedDict()
1886
+ if iterable:
1887
+ self.update(iterable)
1888
+
1889
+ def __contains__(self, value: object) -> bool:
1890
+ return value in self.__container
1891
+
1892
+ def __iter__(self) -> T.Iterator[_T]:
1893
+ return iter(self.__container.keys())
1894
+
1895
+ def __len__(self) -> int:
1896
+ return len(self.__container)
1897
+
1898
+ def __repr__(self) -> str:
1899
+ # Don't print 'OrderedSet("")' for an empty set.
1900
+ if self.__container:
1901
+ return 'OrderedSet([{}])'.format(
1902
+ ', '.join(repr(e) for e in self.__container.keys()))
1903
+ return 'OrderedSet()'
1904
+
1905
+ def __reversed__(self) -> T.Iterator[_T]:
1906
+ return reversed(self.__container.keys())
1907
+
1908
+ def add(self, value: _T) -> None:
1909
+ self.__container[value] = None
1910
+
1911
+ def discard(self, value: _T) -> None:
1912
+ if value in self.__container:
1913
+ del self.__container[value]
1914
+
1915
+ def move_to_end(self, value: _T, last: bool = True) -> None:
1916
+ self.__container.move_to_end(value, last)
1917
+
1918
+ def pop(self, last: bool = True) -> _T:
1919
+ item, _ = self.__container.popitem(last)
1920
+ return item
1921
+
1922
+ def update(self, iterable: T.Iterable[_T]) -> None:
1923
+ for item in iterable:
1924
+ self.__container[item] = None
1925
+
1926
+ def difference(self, set_: T.Iterable[_T]) -> 'OrderedSet[_T]':
1927
+ return type(self)(e for e in self if e not in set_)
1928
+
1929
+ def difference_update(self, iterable: T.Iterable[_T]) -> None:
1930
+ for item in iterable:
1931
+ self.discard(item)
1932
+
1933
+ def relpath(path: str, start: str) -> str:
1934
+ # On Windows a relative path can't be evaluated for paths on two different
1935
+ # drives (i.e. c:\foo and f:\bar). The only thing left to do is to use the
1936
+ # original absolute path.
1937
+ try:
1938
+ return os.path.relpath(path, start)
1939
+ except (TypeError, ValueError):
1940
+ return path
1941
+
1942
+ def path_is_in_root(path: Path, root: Path, resolve: bool = False) -> bool:
1943
+ # Check whether a path is within the root directory root
1944
+ try:
1945
+ if resolve:
1946
+ path.resolve().relative_to(root.resolve())
1947
+ else:
1948
+ path.relative_to(root)
1949
+ except ValueError:
1950
+ return False
1951
+ return True
1952
+
1953
+ def relative_to_if_possible(path: Path, root: Path, resolve: bool = False) -> Path:
1954
+ try:
1955
+ if resolve:
1956
+ return path.resolve().relative_to(root.resolve())
1957
+ else:
1958
+ return path.relative_to(root)
1959
+ except ValueError:
1960
+ return path
1961
+
1962
+ class LibType(enum.IntEnum):
1963
+
1964
+ """Enumeration for library types."""
1965
+
1966
+ SHARED = 0
1967
+ STATIC = 1
1968
+ PREFER_SHARED = 2
1969
+ PREFER_STATIC = 3
1970
+
1971
+
1972
+ class ProgressBarFallback: # lgtm [py/iter-returns-non-self]
1973
+ '''
1974
+ Fallback progress bar implementation when tqdm is not found
1975
+
1976
+ Since this class is not an actual iterator, but only provides a minimal
1977
+ fallback, it is safe to ignore the 'Iterator does not return self from
1978
+ __iter__ method' warning.
1979
+ '''
1980
+ def __init__(self, iterable: T.Optional[T.Iterable[str]] = None, total: T.Optional[int] = None,
1981
+ bar_type: T.Optional[str] = None, desc: T.Optional[str] = None,
1982
+ disable: T.Optional[bool] = None):
1983
+ if iterable is not None:
1984
+ self.iterable = iter(iterable)
1985
+ return
1986
+ self.total = total
1987
+ self.done = 0
1988
+ self.printed_dots = 0
1989
+ self.disable = not mlog.colorize_console() if disable is None else disable
1990
+ if not self.disable:
1991
+ if self.total and bar_type == 'download':
1992
+ print('Download size:', self.total)
1993
+ if desc:
1994
+ print(f'{desc}: ', end='')
1995
+
1996
+ # Pretend to be an iterator when called as one and don't print any
1997
+ # progress
1998
+ def __iter__(self) -> T.Iterator[str]:
1999
+ return self.iterable
2000
+
2001
+ def __next__(self) -> str:
2002
+ return next(self.iterable)
2003
+
2004
+ def print_dot(self) -> None:
2005
+ if not self.disable:
2006
+ print('.', end='')
2007
+ sys.stdout.flush()
2008
+ self.printed_dots += 1
2009
+
2010
+ def update(self, progress: int) -> None:
2011
+ self.done += progress
2012
+ if not self.total:
2013
+ # Just print one dot per call if we don't have a total length
2014
+ self.print_dot()
2015
+ return
2016
+ ratio = int(self.done / self.total * 10)
2017
+ while self.printed_dots < ratio:
2018
+ self.print_dot()
2019
+
2020
+ def close(self) -> None:
2021
+ if not self.disable:
2022
+ print()
2023
+
2024
+ try:
2025
+ from tqdm import tqdm
2026
+ except ImportError:
2027
+ # ideally we would use a typing.Protocol here, but it's part of typing_extensions until 3.8
2028
+ ProgressBar: T.Union[T.Type[ProgressBarFallback], T.Type[ProgressBarTqdm]] = ProgressBarFallback
2029
+ else:
2030
+ class ProgressBarTqdm(tqdm):
2031
+ def __init__(self, *args: T.Any, bar_type: T.Optional[str] = None, **kwargs: T.Any) -> None:
2032
+ if bar_type == 'download':
2033
+ kwargs.update({'unit': 'B',
2034
+ 'unit_scale': True,
2035
+ 'unit_divisor': 1024,
2036
+ 'leave': True,
2037
+ 'bar_format': '{l_bar}{bar}| {n_fmt}/{total_fmt} {rate_fmt} eta {remaining}',
2038
+ })
2039
+
2040
+ else:
2041
+ kwargs.update({'leave': False,
2042
+ 'bar_format': '{l_bar}{bar}| {n_fmt}/{total_fmt} eta {remaining}',
2043
+ })
2044
+ super().__init__(*args, **kwargs)
2045
+
2046
+ ProgressBar = ProgressBarTqdm
2047
+
2048
+
2049
+ class RealPathAction(argparse.Action):
2050
+ def __init__(self, option_strings: T.List[str], dest: str, default: str = '.', **kwargs: T.Any):
2051
+ default = os.path.abspath(os.path.realpath(default))
2052
+ super().__init__(option_strings, dest, nargs=None, default=default, **kwargs)
2053
+
2054
+ def __call__(self, parser: argparse.ArgumentParser, namespace: argparse.Namespace,
2055
+ values: T.Union[str, T.Sequence[T.Any], None], option_string: T.Optional[str] = None) -> None:
2056
+ assert isinstance(values, str)
2057
+ setattr(namespace, self.dest, os.path.abspath(os.path.realpath(values)))
2058
+
2059
+
2060
+ def get_wine_shortpath(winecmd: T.List[str], wine_paths: T.List[str],
2061
+ workdir: T.Optional[str] = None) -> str:
2062
+ '''
2063
+ WINEPATH size is limited to 1024 bytes which can easily be exceeded when
2064
+ adding the path to every dll inside build directory. See
2065
+ https://bugs.winehq.org/show_bug.cgi?id=45810.
2066
+
2067
+ To shorten it as much as possible we use path relative to `workdir`
2068
+ where possible and convert absolute paths to Windows shortpath (e.g.
2069
+ "/usr/x86_64-w64-mingw32/lib" to "Z:\\usr\\X86_~FWL\\lib").
2070
+
2071
+ This limitation reportedly has been fixed with wine >= 6.4
2072
+ '''
2073
+
2074
+ # Remove duplicates
2075
+ wine_paths = list(OrderedSet(wine_paths))
2076
+
2077
+ # Check if it's already short enough
2078
+ wine_path = ';'.join(wine_paths)
2079
+ if len(wine_path) <= 1024:
2080
+ return wine_path
2081
+
2082
+ # Check if we have wine >= 6.4
2083
+ from ..programs import ExternalProgram
2084
+ wine = ExternalProgram('wine', winecmd, silent=True)
2085
+ if version_compare(wine.get_version(), '>=6.4'):
2086
+ return wine_path
2087
+
2088
+ # Check paths that can be reduced by making them relative to workdir.
2089
+ rel_paths: T.List[str] = []
2090
+ if workdir:
2091
+ abs_paths: T.List[str] = []
2092
+ for p in wine_paths:
2093
+ try:
2094
+ rel = Path(p).relative_to(workdir)
2095
+ rel_paths.append(str(rel))
2096
+ except ValueError:
2097
+ abs_paths.append(p)
2098
+ wine_paths = abs_paths
2099
+
2100
+ if wine_paths:
2101
+ # BAT script that takes a list of paths in argv and prints semi-colon separated shortpaths
2102
+ with NamedTemporaryFile('w', suffix='.bat', encoding='utf-8', delete=False) as bat_file:
2103
+ bat_file.write('''
2104
+ @ECHO OFF
2105
+ for %%x in (%*) do (
2106
+ echo|set /p=;%~sx
2107
+ )
2108
+ ''')
2109
+ try:
2110
+ stdout = subprocess.check_output(winecmd + ['cmd', '/C', bat_file.name] + wine_paths,
2111
+ encoding='utf-8', stderr=subprocess.DEVNULL)
2112
+ stdout = stdout.strip(';')
2113
+ if stdout:
2114
+ wine_paths = stdout.split(';')
2115
+ else:
2116
+ mlog.warning('Could not shorten WINEPATH: empty stdout')
2117
+ except subprocess.CalledProcessError as e:
2118
+ mlog.warning(f'Could not shorten WINEPATH: {str(e)}')
2119
+ finally:
2120
+ os.unlink(bat_file.name)
2121
+ wine_path = ';'.join(rel_paths + wine_paths)
2122
+ if len(wine_path) > 1024:
2123
+ mlog.warning('WINEPATH exceeds 1024 characters which could cause issues')
2124
+ return wine_path
2125
+
2126
+
2127
+ def run_once(func: T.Callable[..., _T]) -> T.Callable[..., _T]:
2128
+ ret: T.List[_T] = []
2129
+
2130
+ @wraps(func)
2131
+ def wrapper(*args: T.Any, **kwargs: T.Any) -> _T:
2132
+ if ret:
2133
+ return ret[0]
2134
+
2135
+ val = func(*args, **kwargs)
2136
+ ret.append(val)
2137
+ return val
2138
+
2139
+ return wrapper
2140
+
2141
+
2142
+ def generate_list(func: T.Callable[..., T.Generator[_T, None, None]]) -> T.Callable[..., T.List[_T]]:
2143
+ @wraps(func)
2144
+ def wrapper(*args: T.Any, **kwargs: T.Any) -> T.List[_T]:
2145
+ return list(func(*args, **kwargs))
2146
+
2147
+ return wrapper
2148
+
2149
+
2150
+ class OptionType(enum.IntEnum):
2151
+
2152
+ """Enum used to specify what kind of argument a thing is."""
2153
+
2154
+ BUILTIN = 0
2155
+ BACKEND = 1
2156
+ BASE = 2
2157
+ COMPILER = 3
2158
+ PROJECT = 4
2159
+
2160
+ # This is copied from coredata. There is no way to share this, because this
2161
+ # is used in the OptionKey constructor, and the coredata lists are
2162
+ # OptionKeys...
2163
+ _BUILTIN_NAMES = {
2164
+ 'prefix',
2165
+ 'bindir',
2166
+ 'datadir',
2167
+ 'includedir',
2168
+ 'infodir',
2169
+ 'libdir',
2170
+ 'licensedir',
2171
+ 'libexecdir',
2172
+ 'localedir',
2173
+ 'localstatedir',
2174
+ 'mandir',
2175
+ 'sbindir',
2176
+ 'sharedstatedir',
2177
+ 'sysconfdir',
2178
+ 'auto_features',
2179
+ 'backend',
2180
+ 'buildtype',
2181
+ 'debug',
2182
+ 'default_library',
2183
+ 'errorlogs',
2184
+ 'genvslite',
2185
+ 'install_umask',
2186
+ 'layout',
2187
+ 'optimization',
2188
+ 'prefer_static',
2189
+ 'stdsplit',
2190
+ 'strip',
2191
+ 'unity',
2192
+ 'unity_size',
2193
+ 'warning_level',
2194
+ 'werror',
2195
+ 'wrap_mode',
2196
+ 'force_fallback_for',
2197
+ 'pkg_config_path',
2198
+ 'cmake_prefix_path',
2199
+ 'vsenv',
2200
+ }
2201
+
2202
+
2203
+ def _classify_argument(key: 'OptionKey') -> OptionType:
2204
+ """Classify arguments into groups so we know which dict to assign them to."""
2205
+
2206
+ if key.name.startswith('b_'):
2207
+ return OptionType.BASE
2208
+ elif key.lang is not None:
2209
+ return OptionType.COMPILER
2210
+ elif key.name in _BUILTIN_NAMES or key.module:
2211
+ return OptionType.BUILTIN
2212
+ elif key.name.startswith('backend_'):
2213
+ assert key.machine is MachineChoice.HOST, str(key)
2214
+ return OptionType.BACKEND
2215
+ else:
2216
+ assert key.machine is MachineChoice.HOST or key.subproject, str(key)
2217
+ return OptionType.PROJECT
2218
+
2219
+
2220
+ @total_ordering
2221
+ class OptionKey:
2222
+
2223
+ """Represents an option key in the various option dictionaries.
2224
+
2225
+ This provides a flexible, powerful way to map option names from their
2226
+ external form (things like subproject:build.option) to something that
2227
+ internally easier to reason about and produce.
2228
+ """
2229
+
2230
+ __slots__ = ['name', 'subproject', 'machine', 'lang', '_hash', 'type', 'module']
2231
+
2232
+ name: str
2233
+ subproject: str
2234
+ machine: MachineChoice
2235
+ lang: T.Optional[str]
2236
+ _hash: int
2237
+ type: OptionType
2238
+ module: T.Optional[str]
2239
+
2240
+ def __init__(self, name: str, subproject: str = '',
2241
+ machine: MachineChoice = MachineChoice.HOST,
2242
+ lang: T.Optional[str] = None,
2243
+ module: T.Optional[str] = None,
2244
+ _type: T.Optional[OptionType] = None):
2245
+ # the _type option to the constructor is kinda private. We want to be
2246
+ # able tos ave the state and avoid the lookup function when
2247
+ # pickling/unpickling, but we need to be able to calculate it when
2248
+ # constructing a new OptionKey
2249
+ object.__setattr__(self, 'name', name)
2250
+ object.__setattr__(self, 'subproject', subproject)
2251
+ object.__setattr__(self, 'machine', machine)
2252
+ object.__setattr__(self, 'lang', lang)
2253
+ object.__setattr__(self, 'module', module)
2254
+ object.__setattr__(self, '_hash', hash((name, subproject, machine, lang, module)))
2255
+ if _type is None:
2256
+ _type = _classify_argument(self)
2257
+ object.__setattr__(self, 'type', _type)
2258
+
2259
+ def __setattr__(self, key: str, value: T.Any) -> None:
2260
+ raise AttributeError('OptionKey instances do not support mutation.')
2261
+
2262
+ def __getstate__(self) -> T.Dict[str, T.Any]:
2263
+ return {
2264
+ 'name': self.name,
2265
+ 'subproject': self.subproject,
2266
+ 'machine': self.machine,
2267
+ 'lang': self.lang,
2268
+ '_type': self.type,
2269
+ 'module': self.module,
2270
+ }
2271
+
2272
+ def __setstate__(self, state: T.Dict[str, T.Any]) -> None:
2273
+ """De-serialize the state of a pickle.
2274
+
2275
+ This is very clever. __init__ is not a constructor, it's an
2276
+ initializer, therefore it's safe to call more than once. We create a
2277
+ state in the custom __getstate__ method, which is valid to pass
2278
+ splatted to the initializer.
2279
+ """
2280
+ # Mypy doesn't like this, because it's so clever.
2281
+ self.__init__(**state) # type: ignore
2282
+
2283
+ def __hash__(self) -> int:
2284
+ return self._hash
2285
+
2286
+ def _to_tuple(self) -> T.Tuple[str, OptionType, str, str, MachineChoice, str]:
2287
+ return (self.subproject, self.type, self.lang or '', self.module or '', self.machine, self.name)
2288
+
2289
+ def __eq__(self, other: object) -> bool:
2290
+ if isinstance(other, OptionKey):
2291
+ return self._to_tuple() == other._to_tuple()
2292
+ return NotImplemented
2293
+
2294
+ def __lt__(self, other: object) -> bool:
2295
+ if isinstance(other, OptionKey):
2296
+ return self._to_tuple() < other._to_tuple()
2297
+ return NotImplemented
2298
+
2299
+ def __str__(self) -> str:
2300
+ out = self.name
2301
+ if self.lang:
2302
+ out = f'{self.lang}_{out}'
2303
+ if self.machine is MachineChoice.BUILD:
2304
+ out = f'build.{out}'
2305
+ if self.module:
2306
+ out = f'{self.module}.{out}'
2307
+ if self.subproject:
2308
+ out = f'{self.subproject}:{out}'
2309
+ return out
2310
+
2311
+ def __repr__(self) -> str:
2312
+ return f'OptionKey({self.name!r}, {self.subproject!r}, {self.machine!r}, {self.lang!r}, {self.module!r}, {self.type!r})'
2313
+
2314
+ @classmethod
2315
+ def from_string(cls, raw: str) -> 'OptionKey':
2316
+ """Parse the raw command line format into a three part tuple.
2317
+
2318
+ This takes strings like `mysubproject:build.myoption` and Creates an
2319
+ OptionKey out of them.
2320
+ """
2321
+ try:
2322
+ subproject, raw2 = raw.split(':')
2323
+ except ValueError:
2324
+ subproject, raw2 = '', raw
2325
+
2326
+ module = None
2327
+ for_machine = MachineChoice.HOST
2328
+ try:
2329
+ prefix, raw3 = raw2.split('.')
2330
+ if prefix == 'build':
2331
+ for_machine = MachineChoice.BUILD
2332
+ else:
2333
+ module = prefix
2334
+ except ValueError:
2335
+ raw3 = raw2
2336
+
2337
+ from ..compilers import all_languages
2338
+ if any(raw3.startswith(f'{l}_') for l in all_languages):
2339
+ lang, opt = raw3.split('_', 1)
2340
+ else:
2341
+ lang, opt = None, raw3
2342
+ assert ':' not in opt
2343
+ assert '.' not in opt
2344
+
2345
+ return cls(opt, subproject, for_machine, lang, module)
2346
+
2347
+ def evolve(self, name: T.Optional[str] = None, subproject: T.Optional[str] = None,
2348
+ machine: T.Optional[MachineChoice] = None, lang: T.Optional[str] = '',
2349
+ module: T.Optional[str] = '') -> 'OptionKey':
2350
+ """Create a new copy of this key, but with altered members.
2351
+
2352
+ For example:
2353
+ >>> a = OptionKey('foo', '', MachineChoice.Host)
2354
+ >>> b = OptionKey('foo', 'bar', MachineChoice.Host)
2355
+ >>> b == a.evolve(subproject='bar')
2356
+ True
2357
+ """
2358
+ # We have to be a little clever with lang here, because lang is valid
2359
+ # as None, for non-compiler options
2360
+ return OptionKey(
2361
+ name if name is not None else self.name,
2362
+ subproject if subproject is not None else self.subproject,
2363
+ machine if machine is not None else self.machine,
2364
+ lang if lang != '' else self.lang,
2365
+ module if module != '' else self.module
2366
+ )
2367
+
2368
+ def as_root(self) -> 'OptionKey':
2369
+ """Convenience method for key.evolve(subproject='')."""
2370
+ return self.evolve(subproject='')
2371
+
2372
+ def as_build(self) -> 'OptionKey':
2373
+ """Convenience method for key.evolve(machine=MachineChoice.BUILD)."""
2374
+ return self.evolve(machine=MachineChoice.BUILD)
2375
+
2376
+ def as_host(self) -> 'OptionKey':
2377
+ """Convenience method for key.evolve(machine=MachineChoice.HOST)."""
2378
+ return self.evolve(machine=MachineChoice.HOST)
2379
+
2380
+ def is_backend(self) -> bool:
2381
+ """Convenience method to check if this is a backend option."""
2382
+ return self.type is OptionType.BACKEND
2383
+
2384
+ def is_builtin(self) -> bool:
2385
+ """Convenience method to check if this is a builtin option."""
2386
+ return self.type is OptionType.BUILTIN
2387
+
2388
+ def is_compiler(self) -> bool:
2389
+ """Convenience method to check if this is a builtin option."""
2390
+ return self.type is OptionType.COMPILER
2391
+
2392
+ def is_project(self) -> bool:
2393
+ """Convenience method to check if this is a project option."""
2394
+ return self.type is OptionType.PROJECT
2395
+
2396
+ def is_base(self) -> bool:
2397
+ """Convenience method to check if this is a base option."""
2398
+ return self.type is OptionType.BASE
2399
+
2400
+
2401
+ def pickle_load(filename: str, object_name: str, object_type: T.Type[_PL], suggest_reconfigure: bool = True) -> _PL:
2402
+ load_fail_msg = f'{object_name} file {filename!r} is corrupted.'
2403
+ extra_msg = ' Consider reconfiguring the directory with "meson setup --reconfigure".' if suggest_reconfigure else ''
2404
+ try:
2405
+ with open(filename, 'rb') as f:
2406
+ obj = pickle.load(f)
2407
+ except (pickle.UnpicklingError, EOFError):
2408
+ raise MesonException(load_fail_msg + extra_msg)
2409
+ except (TypeError, ModuleNotFoundError, AttributeError):
2410
+ raise MesonException(
2411
+ f"{object_name} file {filename!r} references functions or classes that don't "
2412
+ "exist. This probably means that it was generated with an old "
2413
+ "version of meson." + extra_msg)
2414
+
2415
+ if not isinstance(obj, object_type):
2416
+ raise MesonException(load_fail_msg + extra_msg)
2417
+
2418
+ # Because these Protocols are not available at runtime (and cannot be made
2419
+ # available at runtime until we drop support for Python < 3.8), we have to
2420
+ # do a bit of hackery so that mypy understands what's going on here
2421
+ version: str
2422
+ if hasattr(obj, 'version'):
2423
+ version = T.cast('_VerPickleLoadable', obj).version
2424
+ else:
2425
+ version = T.cast('_EnvPickleLoadable', obj).environment.coredata.version
2426
+
2427
+ from ..coredata import version as coredata_version
2428
+ from ..coredata import major_versions_differ, MesonVersionMismatchException
2429
+ if major_versions_differ(version, coredata_version):
2430
+ raise MesonVersionMismatchException(version, coredata_version, extra_msg)
2431
+ return obj
2432
+
2433
+
2434
+ def first(iter: T.Iterable[_T], predicate: T.Callable[[_T], bool]) -> T.Optional[_T]:
2435
+ """Find the first entry in an iterable where the given predicate is true
2436
+
2437
+ :param iter: The iterable to search
2438
+ :param predicate: A finding function that takes an element from the iterable
2439
+ and returns True if found, otherwise False
2440
+ :return: The first found element, or None if it is not found
2441
+ """
2442
+ for i in iter:
2443
+ if predicate(i):
2444
+ return i
2445
+ return None