compilers.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633
  1. # Copyright 2012-2017 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. import contextlib, os.path, re, tempfile, shlex
  12. import subprocess
  13. from ..linkers import StaticLinker
  14. from .. import coredata
  15. from .. import mlog
  16. from .. import mesonlib
  17. from ..mesonlib import EnvironmentException, MesonException, version_compare, Popen_safe
  18. """This file contains the data files of all compilers Meson knows
  19. about. To support a new compiler, add its information below.
  20. Also add corresponding autodetection code in environment.py."""
  21. header_suffixes = ('h', 'hh', 'hpp', 'hxx', 'H', 'ipp', 'moc', 'vapi', 'di')
  22. obj_suffixes = ('o', 'obj', 'res')
  23. lib_suffixes = ('a', 'lib', 'dll', 'dylib', 'so')
  24. # Mapping of language to suffixes of files that should always be in that language
  25. # This means we can't include .h headers here since they could be C, C++, ObjC, etc.
  26. lang_suffixes = {
  27. 'c': ('c',),
  28. 'cpp': ('cpp', 'cc', 'cxx', 'c++', 'hh', 'hpp', 'ipp', 'hxx'),
  29. # f90, f95, f03, f08 are for free-form fortran ('f90' recommended)
  30. # f, for, ftn, fpp are for fixed-form fortran ('f' or 'for' recommended)
  31. 'fortran': ('f90', 'f95', 'f03', 'f08', 'f', 'for', 'ftn', 'fpp'),
  32. 'd': ('d', 'di'),
  33. 'objc': ('m',),
  34. 'objcpp': ('mm',),
  35. 'rust': ('rs',),
  36. 'vala': ('vala', 'vapi', 'gs'),
  37. 'cs': ('cs',),
  38. 'swift': ('swift',),
  39. 'java': ('java',),
  40. }
  41. all_languages = lang_suffixes.keys()
  42. cpp_suffixes = lang_suffixes['cpp'] + ('h',)
  43. c_suffixes = lang_suffixes['c'] + ('h',)
  44. # List of languages that by default consume and output libraries following the
  45. # C ABI; these can generally be used interchangebly
  46. clib_langs = ('objcpp', 'cpp', 'objc', 'c', 'fortran',)
  47. # List of languages that can be linked with C code directly by the linker
  48. # used in build.py:process_compilers() and build.py:get_dynamic_linker()
  49. # XXX: Add Rust to this?
  50. clink_langs = ('d',) + clib_langs
  51. clink_suffixes = ()
  52. for _l in clink_langs + ('vala',):
  53. clink_suffixes += lang_suffixes[_l]
  54. clink_suffixes += ('h', 'll', 's')
  55. soregex = re.compile(r'.*\.so(\.[0-9]+)?(\.[0-9]+)?(\.[0-9]+)?$')
  56. # Environment variables that each lang uses.
  57. cflags_mapping = {'c': 'CFLAGS',
  58. 'cpp': 'CXXFLAGS',
  59. 'objc': 'OBJCFLAGS',
  60. 'objcpp': 'OBJCXXFLAGS',
  61. 'fortran': 'FFLAGS',
  62. 'd': 'DFLAGS',
  63. 'vala': 'VALAFLAGS',
  64. 'rust': 'RUSTFLAGS'}
  65. # All these are only for C-linkable languages; see `clink_langs` above.
  66. def sort_clink(lang):
  67. '''
  68. Sorting function to sort the list of languages according to
  69. reversed(compilers.clink_langs) and append the unknown langs in the end.
  70. The purpose is to prefer C over C++ for files that can be compiled by
  71. both such as assembly, C, etc. Also applies to ObjC, ObjC++, etc.
  72. '''
  73. if lang not in clink_langs:
  74. return 1
  75. return -clink_langs.index(lang)
  76. def is_header(fname):
  77. if hasattr(fname, 'fname'):
  78. fname = fname.fname
  79. suffix = fname.split('.')[-1]
  80. return suffix in header_suffixes
  81. def is_source(fname):
  82. if hasattr(fname, 'fname'):
  83. fname = fname.fname
  84. suffix = fname.split('.')[-1].lower()
  85. return suffix in clink_suffixes
  86. def is_assembly(fname):
  87. if hasattr(fname, 'fname'):
  88. fname = fname.fname
  89. return fname.split('.')[-1].lower() == 's'
  90. def is_llvm_ir(fname):
  91. if hasattr(fname, 'fname'):
  92. fname = fname.fname
  93. return fname.split('.')[-1] == 'll'
  94. def is_object(fname):
  95. if hasattr(fname, 'fname'):
  96. fname = fname.fname
  97. suffix = fname.split('.')[-1]
  98. return suffix in obj_suffixes
  99. def is_library(fname):
  100. if hasattr(fname, 'fname'):
  101. fname = fname.fname
  102. if soregex.match(fname):
  103. return True
  104. suffix = fname.split('.')[-1]
  105. return suffix in lib_suffixes
  106. gnulike_buildtype_args = {'plain': [],
  107. # -O0 is passed for improved debugging information with gcc
  108. # See https://github.com/mesonbuild/meson/pull/509
  109. 'debug': ['-O0', '-g'],
  110. 'debugoptimized': ['-O2', '-g'],
  111. 'release': ['-O3'],
  112. 'minsize': ['-Os', '-g']}
  113. armclang_buildtype_args = {'plain': [],
  114. 'debug': ['-O0', '-g'],
  115. 'debugoptimized': ['-O1', '-g'],
  116. 'release': ['-Os'],
  117. 'minsize': ['-Oz']}
  118. arm_buildtype_args = {'plain': [],
  119. 'debug': ['-O0', '--debug'],
  120. 'debugoptimized': ['-O1', '--debug'],
  121. 'release': ['-O3', '-Otime'],
  122. 'minsize': ['-O3', '-Ospace'],
  123. }
  124. msvc_buildtype_args = {'plain': [],
  125. 'debug': ["/MDd", "/ZI", "/Ob0", "/Od", "/RTC1"],
  126. 'debugoptimized': ["/MD", "/Zi", "/O2", "/Ob1"],
  127. 'release': ["/MD", "/O2", "/Ob2"],
  128. 'minsize': ["/MD", "/Zi", "/Os", "/Ob1"],
  129. }
  130. apple_buildtype_linker_args = {'plain': [],
  131. 'debug': [],
  132. 'debugoptimized': [],
  133. 'release': [],
  134. 'minsize': [],
  135. }
  136. gnulike_buildtype_linker_args = {'plain': [],
  137. 'debug': [],
  138. 'debugoptimized': [],
  139. 'release': ['-Wl,-O1'],
  140. 'minsize': [],
  141. }
  142. arm_buildtype_linker_args = {'plain': [],
  143. 'debug': [],
  144. 'debugoptimized': [],
  145. 'release': [],
  146. 'minsize': [],
  147. }
  148. msvc_buildtype_linker_args = {'plain': [],
  149. 'debug': [],
  150. 'debugoptimized': [],
  151. # The otherwise implicit REF and ICF linker
  152. # optimisations are disabled by /DEBUG.
  153. # REF implies ICF.
  154. 'release': ['/OPT:REF'],
  155. 'minsize': ['/INCREMENTAL:NO', '/OPT:REF'],
  156. }
  157. java_buildtype_args = {'plain': [],
  158. 'debug': ['-g'],
  159. 'debugoptimized': ['-g'],
  160. 'release': [],
  161. 'minsize': [],
  162. }
  163. rust_buildtype_args = {'plain': [],
  164. 'debug': ['-C', 'debuginfo=2'],
  165. 'debugoptimized': ['-C', 'debuginfo=2', '-C', 'opt-level=2'],
  166. 'release': ['-C', 'opt-level=3'],
  167. 'minsize': [], # In a future release: ['-C', 'opt-level=s'],
  168. }
  169. d_gdc_buildtype_args = {'plain': [],
  170. 'debug': ['-g', '-O0'],
  171. 'debugoptimized': ['-g', '-O'],
  172. 'release': ['-O3', '-frelease'],
  173. 'minsize': [],
  174. }
  175. d_ldc_buildtype_args = {'plain': [],
  176. 'debug': ['-g', '-O0'],
  177. 'debugoptimized': ['-g', '-O'],
  178. 'release': ['-O3', '-release'],
  179. 'minsize': [],
  180. }
  181. d_dmd_buildtype_args = {'plain': [],
  182. 'debug': ['-g'],
  183. 'debugoptimized': ['-g', '-O'],
  184. 'release': ['-O', '-release'],
  185. 'minsize': [],
  186. }
  187. mono_buildtype_args = {'plain': [],
  188. 'debug': ['-debug'],
  189. 'debugoptimized': ['-debug', '-optimize+'],
  190. 'release': ['-optimize+'],
  191. 'minsize': [],
  192. }
  193. swift_buildtype_args = {'plain': [],
  194. 'debug': ['-g'],
  195. 'debugoptimized': ['-g', '-O'],
  196. 'release': ['-O'],
  197. 'minsize': [],
  198. }
  199. gnu_winlibs = ['-lkernel32', '-luser32', '-lgdi32', '-lwinspool', '-lshell32',
  200. '-lole32', '-loleaut32', '-luuid', '-lcomdlg32', '-ladvapi32']
  201. msvc_winlibs = ['kernel32.lib', 'user32.lib', 'gdi32.lib',
  202. 'winspool.lib', 'shell32.lib', 'ole32.lib', 'oleaut32.lib',
  203. 'uuid.lib', 'comdlg32.lib', 'advapi32.lib']
  204. gnu_color_args = {'auto': ['-fdiagnostics-color=auto'],
  205. 'always': ['-fdiagnostics-color=always'],
  206. 'never': ['-fdiagnostics-color=never'],
  207. }
  208. clang_color_args = {'auto': ['-Xclang', '-fcolor-diagnostics'],
  209. 'always': ['-Xclang', '-fcolor-diagnostics'],
  210. 'never': ['-Xclang', '-fno-color-diagnostics'],
  211. }
  212. base_options = {'b_pch': coredata.UserBooleanOption('b_pch', 'Use precompiled headers', True),
  213. 'b_lto': coredata.UserBooleanOption('b_lto', 'Use link time optimization', False),
  214. 'b_sanitize': coredata.UserComboOption('b_sanitize',
  215. 'Code sanitizer to use',
  216. ['none', 'address', 'thread', 'undefined', 'memory', 'address,undefined'],
  217. 'none'),
  218. 'b_lundef': coredata.UserBooleanOption('b_lundef', 'Use -Wl,--no-undefined when linking', True),
  219. 'b_asneeded': coredata.UserBooleanOption('b_asneeded', 'Use -Wl,--as-needed when linking', True),
  220. 'b_pgo': coredata.UserComboOption('b_pgo', 'Use profile guided optimization',
  221. ['off', 'generate', 'use'],
  222. 'off'),
  223. 'b_coverage': coredata.UserBooleanOption('b_coverage',
  224. 'Enable coverage tracking.',
  225. False),
  226. 'b_colorout': coredata.UserComboOption('b_colorout', 'Use colored output',
  227. ['auto', 'always', 'never'],
  228. 'always'),
  229. 'b_ndebug': coredata.UserComboOption('b_ndebug', 'Disable asserts',
  230. ['true', 'false', 'if-release'], 'false'),
  231. 'b_staticpic': coredata.UserBooleanOption('b_staticpic',
  232. 'Build static libraries as position independent',
  233. True),
  234. 'b_bitcode': coredata.UserBooleanOption('b_bitcode',
  235. 'Generate and embed bitcode (only macOS and iOS)',
  236. False),
  237. }
  238. gnulike_instruction_set_args = {'mmx': ['-mmmx'],
  239. 'sse': ['-msse'],
  240. 'sse2': ['-msse2'],
  241. 'sse3': ['-msse3'],
  242. 'ssse3': ['-mssse3'],
  243. 'sse41': ['-msse4.1'],
  244. 'sse42': ['-msse4.2'],
  245. 'avx': ['-mavx'],
  246. 'avx2': ['-mavx2'],
  247. 'neon': ['-mfpu=neon'],
  248. }
  249. vs32_instruction_set_args = {'mmx': ['/arch:SSE'], # There does not seem to be a flag just for MMX
  250. 'sse': ['/arch:SSE'],
  251. 'sse2': ['/arch:SSE2'],
  252. 'sse3': ['/arch:AVX'], # VS leaped from SSE2 directly to AVX.
  253. 'sse41': ['/arch:AVX'],
  254. 'sse42': ['/arch:AVX'],
  255. 'avx': ['/arch:AVX'],
  256. 'avx2': ['/arch:AVX2'],
  257. 'neon': None,
  258. }
  259. # The 64 bit compiler defaults to /arch:avx.
  260. vs64_instruction_set_args = {'mmx': ['/arch:AVX'],
  261. 'sse': ['/arch:AVX'],
  262. 'sse2': ['/arch:AVX'],
  263. 'sse3': ['/arch:AVX'],
  264. 'ssse3': ['/arch:AVX'],
  265. 'sse41': ['/arch:AVX'],
  266. 'sse42': ['/arch:AVX'],
  267. 'avx': ['/arch:AVX'],
  268. 'avx2': ['/arch:AVX2'],
  269. 'neon': None,
  270. }
  271. def sanitizer_compile_args(value):
  272. if value == 'none':
  273. return []
  274. args = ['-fsanitize=' + value]
  275. if 'address' in value: # For -fsanitize=address,undefined
  276. args.append('-fno-omit-frame-pointer')
  277. return args
  278. def sanitizer_link_args(value):
  279. if value == 'none':
  280. return []
  281. args = ['-fsanitize=' + value]
  282. return args
  283. def option_enabled(boptions, options, option):
  284. try:
  285. if option not in boptions:
  286. return False
  287. return options[option].value
  288. except KeyError:
  289. return False
  290. def get_base_compile_args(options, compiler):
  291. args = []
  292. # FIXME, gcc/clang specific.
  293. try:
  294. if options['b_lto'].value:
  295. args.append('-flto')
  296. except KeyError:
  297. pass
  298. try:
  299. args += compiler.get_colorout_args(options['b_colorout'].value)
  300. except KeyError:
  301. pass
  302. try:
  303. args += sanitizer_compile_args(options['b_sanitize'].value)
  304. except KeyError:
  305. pass
  306. try:
  307. pgo_val = options['b_pgo'].value
  308. if pgo_val == 'generate':
  309. args.append('-fprofile-generate')
  310. elif pgo_val == 'use':
  311. args.append('-fprofile-use')
  312. except KeyError:
  313. pass
  314. try:
  315. if options['b_coverage'].value:
  316. args += compiler.get_coverage_args()
  317. except KeyError:
  318. pass
  319. try:
  320. if (options['b_ndebug'].value == 'true' or
  321. (options['b_ndebug'].value == 'if-release' and
  322. options['buildtype'].value == 'release')):
  323. args += ['-DNDEBUG']
  324. except KeyError:
  325. pass
  326. # This does not need a try...except
  327. if option_enabled(compiler.base_options, options, 'b_bitcode'):
  328. args.append('-fembed-bitcode')
  329. return args
  330. def get_base_link_args(options, linker, is_shared_module):
  331. args = []
  332. # FIXME, gcc/clang specific.
  333. try:
  334. if options['b_lto'].value:
  335. args.append('-flto')
  336. except KeyError:
  337. pass
  338. try:
  339. args += sanitizer_link_args(options['b_sanitize'].value)
  340. except KeyError:
  341. pass
  342. try:
  343. pgo_val = options['b_pgo'].value
  344. if pgo_val == 'generate':
  345. args.append('-fprofile-generate')
  346. elif pgo_val == 'use':
  347. args.append('-fprofile-use')
  348. except KeyError:
  349. pass
  350. try:
  351. if options['b_coverage'].value:
  352. args += linker.get_coverage_link_args()
  353. except KeyError:
  354. pass
  355. # These do not need a try...except
  356. if not is_shared_module and option_enabled(linker.base_options, options, 'b_lundef'):
  357. args.append('-Wl,--no-undefined')
  358. as_needed = option_enabled(linker.base_options, options, 'b_asneeded')
  359. bitcode = option_enabled(linker.base_options, options, 'b_bitcode')
  360. # Shared modules cannot be built with bitcode_bundle because
  361. # -bitcode_bundle is incompatible with -undefined and -bundle
  362. if bitcode and not is_shared_module:
  363. args.append('-Wl,-bitcode_bundle')
  364. elif as_needed:
  365. # -Wl,-dead_strip_dylibs is incompatible with bitcode
  366. args.append(linker.get_asneeded_args())
  367. return args
  368. class CrossNoRunException(MesonException):
  369. pass
  370. class RunResult:
  371. def __init__(self, compiled, returncode=999, stdout='UNDEFINED', stderr='UNDEFINED'):
  372. self.compiled = compiled
  373. self.returncode = returncode
  374. self.stdout = stdout
  375. self.stderr = stderr
  376. class CompilerArgs(list):
  377. '''
  378. Class derived from list() that manages a list of compiler arguments. Should
  379. be used while constructing compiler arguments from various sources. Can be
  380. operated with ordinary lists, so this does not need to be used everywhere.
  381. All arguments must be inserted and stored in GCC-style (-lfoo, -Idir, etc)
  382. and can converted to the native type of each compiler by using the
  383. .to_native() method to which you must pass an instance of the compiler or
  384. the compiler class.
  385. New arguments added to this class (either with .append(), .extend(), or +=)
  386. are added in a way that ensures that they override previous arguments.
  387. For example:
  388. >>> a = ['-Lfoo', '-lbar']
  389. >>> a += ['-Lpho', '-lbaz']
  390. >>> print(a)
  391. ['-Lpho', '-Lfoo', '-lbar', '-lbaz']
  392. Arguments will also be de-duped if they can be de-duped safely.
  393. Note that because of all this, this class is not commutative and does not
  394. preserve the order of arguments if it is safe to not. For example:
  395. >>> ['-Ifoo', '-Ibar'] + ['-Ifez', '-Ibaz', '-Werror']
  396. ['-Ifez', '-Ibaz', '-Ifoo', '-Ibar', '-Werror']
  397. >>> ['-Ifez', '-Ibaz', '-Werror'] + ['-Ifoo', '-Ibar']
  398. ['-Ifoo', '-Ibar', '-Ifez', '-Ibaz', '-Werror']
  399. '''
  400. # NOTE: currently this class is only for C-like compilers, but it can be
  401. # extended to other languages easily. Just move the following to the
  402. # compiler class and initialize when self.compiler is set.
  403. # Arg prefixes that override by prepending instead of appending
  404. prepend_prefixes = ('-I', '-L')
  405. # Arg prefixes and args that must be de-duped by returning 2
  406. dedup2_prefixes = ('-I', '-L', '-D', '-U')
  407. dedup2_suffixes = ()
  408. dedup2_args = ()
  409. # Arg prefixes and args that must be de-duped by returning 1
  410. dedup1_prefixes = ('-l',)
  411. dedup1_suffixes = ('.lib', '.dll', '.so', '.dylib', '.a')
  412. # Match a .so of the form path/to/libfoo.so.0.1.0
  413. # Only UNIX shared libraries require this. Others have a fixed extension.
  414. dedup1_regex = re.compile(r'([\/\\]|\A)lib.*\.so(\.[0-9]+)?(\.[0-9]+)?(\.[0-9]+)?$')
  415. dedup1_args = ('-c', '-S', '-E', '-pipe', '-pthread')
  416. compiler = None
  417. def _check_args(self, args):
  418. cargs = []
  419. if len(args) > 2:
  420. raise TypeError("CompilerArgs() only accepts at most 2 arguments: "
  421. "The compiler, and optionally an initial list")
  422. elif not args:
  423. return cargs
  424. elif len(args) == 1:
  425. if isinstance(args[0], (Compiler, StaticLinker)):
  426. self.compiler = args[0]
  427. else:
  428. raise TypeError("you must pass a Compiler instance as one of "
  429. "the arguments")
  430. elif len(args) == 2:
  431. if isinstance(args[0], (Compiler, StaticLinker)):
  432. self.compiler = args[0]
  433. cargs = args[1]
  434. elif isinstance(args[1], (Compiler, StaticLinker)):
  435. cargs = args[0]
  436. self.compiler = args[1]
  437. else:
  438. raise TypeError("you must pass a Compiler instance as one of "
  439. "the two arguments")
  440. else:
  441. raise AssertionError('Not reached')
  442. return cargs
  443. def __init__(self, *args):
  444. super().__init__(self._check_args(args))
  445. @classmethod
  446. def _can_dedup(cls, arg):
  447. '''
  448. Returns whether the argument can be safely de-duped. This is dependent
  449. on three things:
  450. a) Whether an argument can be 'overridden' by a later argument. For
  451. example, -DFOO defines FOO and -UFOO undefines FOO. In this case, we
  452. can safely remove the previous occurrence and add a new one. The same
  453. is true for include paths and library paths with -I and -L. For
  454. these we return `2`. See `dedup2_prefixes` and `dedup2_args`.
  455. b) Arguments that once specified cannot be undone, such as `-c` or
  456. `-pipe`. New instances of these can be completely skipped. For these
  457. we return `1`. See `dedup1_prefixes` and `dedup1_args`.
  458. c) Whether it matters where or how many times on the command-line
  459. a particular argument is present. This can matter for symbol
  460. resolution in static or shared libraries, so we cannot de-dup or
  461. reorder them. For these we return `0`. This is the default.
  462. In addition to these, we handle library arguments specially.
  463. With GNU ld, we surround library arguments with -Wl,--start/end-group
  464. to recursively search for symbols in the libraries. This is not needed
  465. with other linkers.
  466. '''
  467. # A standalone argument must never be deduplicated because it is
  468. # defined by what comes _after_ it. Thus dedupping this:
  469. # -D FOO -D BAR
  470. # would yield either
  471. # -D FOO BAR
  472. # or
  473. # FOO -D BAR
  474. # both of which are invalid.
  475. if arg in cls.dedup2_prefixes:
  476. return 0
  477. if arg in cls.dedup2_args or \
  478. arg.startswith(cls.dedup2_prefixes) or \
  479. arg.endswith(cls.dedup2_suffixes):
  480. return 2
  481. if arg in cls.dedup1_args or \
  482. arg.startswith(cls.dedup1_prefixes) or \
  483. arg.endswith(cls.dedup1_suffixes) or \
  484. re.search(cls.dedup1_regex, arg):
  485. return 1
  486. return 0
  487. @classmethod
  488. def _should_prepend(cls, arg):
  489. if arg.startswith(cls.prepend_prefixes):
  490. return True
  491. return False
  492. def to_native(self):
  493. # Check if we need to add --start/end-group for circular dependencies
  494. # between static libraries, and for recursively searching for symbols
  495. # needed by static libraries that are provided by object files or
  496. # shared libraries.
  497. if get_compiler_uses_gnuld(self.compiler):
  498. global soregex
  499. group_start = -1
  500. for each in self:
  501. if not each.startswith('-l') and not each.endswith('.a') and \
  502. not soregex.match(each):
  503. continue
  504. i = self.index(each)
  505. if group_start < 0:
  506. # First occurrence of a library
  507. group_start = i
  508. if group_start >= 0:
  509. # Last occurrence of a library
  510. self.insert(i + 1, '-Wl,--end-group')
  511. self.insert(group_start, '-Wl,--start-group')
  512. return self.compiler.unix_args_to_native(self)
  513. def append_direct(self, arg):
  514. '''
  515. Append the specified argument without any reordering or de-dup
  516. except for absolute paths where the order of include search directories
  517. is not relevant
  518. '''
  519. if os.path.isabs(arg):
  520. self.append(arg)
  521. else:
  522. super().append(arg)
  523. def extend_direct(self, iterable):
  524. '''
  525. Extend using the elements in the specified iterable without any
  526. reordering or de-dup except for absolute paths where the order of
  527. include search directories is not relevant
  528. '''
  529. for elem in iterable:
  530. self.append_direct(elem)
  531. def __add__(self, args):
  532. new = CompilerArgs(self, self.compiler)
  533. new += args
  534. return new
  535. def __iadd__(self, args):
  536. '''
  537. Add two CompilerArgs while taking into account overriding of arguments
  538. and while preserving the order of arguments as much as possible
  539. '''
  540. pre = []
  541. post = []
  542. if not isinstance(args, list):
  543. raise TypeError('can only concatenate list (not "{}") to list'.format(args))
  544. for arg in args:
  545. # If the argument can be de-duped, do it either by removing the
  546. # previous occurrence of it and adding a new one, or not adding the
  547. # new occurrence.
  548. dedup = self._can_dedup(arg)
  549. if dedup == 1:
  550. # Argument already exists and adding a new instance is useless
  551. if arg in self or arg in pre or arg in post:
  552. continue
  553. if dedup == 2:
  554. # Remove all previous occurrences of the arg and add it anew
  555. if arg in self:
  556. self.remove(arg)
  557. if arg in pre:
  558. pre.remove(arg)
  559. if arg in post:
  560. post.remove(arg)
  561. if self._should_prepend(arg):
  562. pre.append(arg)
  563. else:
  564. post.append(arg)
  565. # Insert at the beginning
  566. self[:0] = pre
  567. # Append to the end
  568. super().__iadd__(post)
  569. return self
  570. def __radd__(self, args):
  571. new = CompilerArgs(args, self.compiler)
  572. new += self
  573. return new
  574. def __mul__(self, args):
  575. raise TypeError("can't multiply compiler arguments")
  576. def __imul__(self, args):
  577. raise TypeError("can't multiply compiler arguments")
  578. def __rmul__(self, args):
  579. raise TypeError("can't multiply compiler arguments")
  580. def append(self, arg):
  581. self.__iadd__([arg])
  582. def extend(self, args):
  583. self.__iadd__(args)
  584. class Compiler:
  585. # Libraries to ignore in find_library() since they are provided by the
  586. # compiler or the C library. Currently only used for MSVC.
  587. ignore_libs = ()
  588. # Cache for the result of compiler checks which can be cached
  589. compiler_check_cache = {}
  590. def __init__(self, exelist, version, **kwargs):
  591. if isinstance(exelist, str):
  592. self.exelist = [exelist]
  593. elif isinstance(exelist, list):
  594. self.exelist = exelist
  595. else:
  596. raise TypeError('Unknown argument to Compiler')
  597. # In case it's been overridden by a child class already
  598. if not hasattr(self, 'file_suffixes'):
  599. self.file_suffixes = lang_suffixes[self.language]
  600. if not hasattr(self, 'can_compile_suffixes'):
  601. self.can_compile_suffixes = set(self.file_suffixes)
  602. self.default_suffix = self.file_suffixes[0]
  603. self.version = version
  604. if 'full_version' in kwargs:
  605. self.full_version = kwargs['full_version']
  606. else:
  607. self.full_version = None
  608. self.base_options = []
  609. def __repr__(self):
  610. repr_str = "<{0}: v{1} `{2}`>"
  611. return repr_str.format(self.__class__.__name__, self.version,
  612. ' '.join(self.exelist))
  613. def can_compile(self, src):
  614. if hasattr(src, 'fname'):
  615. src = src.fname
  616. suffix = os.path.splitext(src)[1].lower()
  617. if suffix and suffix[1:] in self.can_compile_suffixes:
  618. return True
  619. return False
  620. def get_id(self):
  621. return self.id
  622. def get_language(self):
  623. return self.language
  624. def get_display_language(self):
  625. return self.language.capitalize()
  626. def get_default_suffix(self):
  627. return self.default_suffix
  628. def get_define(self, dname, prefix, env, extra_args, dependencies):
  629. raise EnvironmentException('%s does not support get_define ' % self.get_id())
  630. def compute_int(self, expression, low, high, guess, prefix, env, extra_args, dependencies):
  631. raise EnvironmentException('%s does not support compute_int ' % self.get_id())
  632. def has_members(self, typename, membernames, prefix, env, extra_args=None, dependencies=None):
  633. raise EnvironmentException('%s does not support has_member(s) ' % self.get_id())
  634. def has_type(self, typename, prefix, env, extra_args, dependencies=None):
  635. raise EnvironmentException('%s does not support has_type ' % self.get_id())
  636. def symbols_have_underscore_prefix(self, env):
  637. raise EnvironmentException('%s does not support symbols_have_underscore_prefix ' % self.get_id())
  638. def get_exelist(self):
  639. return self.exelist[:]
  640. def get_builtin_define(self, *args, **kwargs):
  641. raise EnvironmentException('%s does not support get_builtin_define.' % self.id)
  642. def has_builtin_define(self, *args, **kwargs):
  643. raise EnvironmentException('%s does not support has_builtin_define.' % self.id)
  644. def get_always_args(self):
  645. return []
  646. def can_linker_accept_rsp(self):
  647. """
  648. Determines whether the linker can accept arguments using the @rsp syntax.
  649. """
  650. return mesonlib.is_windows()
  651. def get_linker_always_args(self):
  652. return []
  653. def gen_import_library_args(self, implibname):
  654. """
  655. Used only on Windows for libraries that need an import library.
  656. This currently means C, C++, Fortran.
  657. """
  658. return []
  659. def get_preproc_flags(self):
  660. if self.get_language() in ('c', 'cpp', 'objc', 'objcpp'):
  661. return os.environ.get('CPPFLAGS', '')
  662. return ''
  663. def get_args_from_envvars(self):
  664. """
  665. Returns a tuple of (compile_flags, link_flags) for the specified language
  666. from the inherited environment
  667. """
  668. def log_var(var, val):
  669. if val:
  670. mlog.log('Appending {} from environment: {!r}'.format(var, val))
  671. lang = self.get_language()
  672. compiler_is_linker = False
  673. if hasattr(self, 'get_linker_exelist'):
  674. compiler_is_linker = (self.get_exelist() == self.get_linker_exelist())
  675. if lang not in cflags_mapping:
  676. return [], []
  677. compile_flags = os.environ.get(cflags_mapping[lang], '')
  678. log_var(cflags_mapping[lang], compile_flags)
  679. compile_flags = shlex.split(compile_flags)
  680. # Link flags (same for all languages)
  681. link_flags = os.environ.get('LDFLAGS', '')
  682. log_var('LDFLAGS', link_flags)
  683. link_flags = shlex.split(link_flags)
  684. if compiler_is_linker:
  685. # When the compiler is used as a wrapper around the linker (such as
  686. # with GCC and Clang), the compile flags can be needed while linking
  687. # too. This is also what Autotools does. However, we don't want to do
  688. # this when the linker is stand-alone such as with MSVC C/C++, etc.
  689. link_flags = compile_flags + link_flags
  690. # Pre-processor flags (not for fortran or D)
  691. preproc_flags = self.get_preproc_flags()
  692. log_var('CPPFLAGS', preproc_flags)
  693. preproc_flags = shlex.split(preproc_flags)
  694. compile_flags += preproc_flags
  695. return compile_flags, link_flags
  696. def get_options(self):
  697. opts = {} # build afresh every time
  698. # Take default values from env variables.
  699. compile_args, link_args = self.get_args_from_envvars()
  700. description = 'Extra arguments passed to the {}'.format(self.get_display_language())
  701. opts.update({
  702. self.language + '_args': coredata.UserArrayOption(
  703. self.language + '_args',
  704. description + ' compiler',
  705. compile_args, shlex_split=True, user_input=True),
  706. self.language + '_link_args': coredata.UserArrayOption(
  707. self.language + '_link_args',
  708. description + ' linker',
  709. link_args, shlex_split=True, user_input=True),
  710. })
  711. return opts
  712. def get_option_compile_args(self, options):
  713. return []
  714. def get_option_link_args(self, options):
  715. return []
  716. def check_header(self, *args, **kwargs):
  717. raise EnvironmentException('Language %s does not support header checks.' % self.get_display_language())
  718. def has_header(self, *args, **kwargs):
  719. raise EnvironmentException('Language %s does not support header checks.' % self.get_display_language())
  720. def has_header_symbol(self, *args, **kwargs):
  721. raise EnvironmentException('Language %s does not support header symbol checks.' % self.get_display_language())
  722. def compiles(self, *args, **kwargs):
  723. raise EnvironmentException('Language %s does not support compile checks.' % self.get_display_language())
  724. def links(self, *args, **kwargs):
  725. raise EnvironmentException('Language %s does not support link checks.' % self.get_display_language())
  726. def run(self, *args, **kwargs):
  727. raise EnvironmentException('Language %s does not support run checks.' % self.get_display_language())
  728. def sizeof(self, *args, **kwargs):
  729. raise EnvironmentException('Language %s does not support sizeof checks.' % self.get_display_language())
  730. def alignment(self, *args, **kwargs):
  731. raise EnvironmentException('Language %s does not support alignment checks.' % self.get_display_language())
  732. def has_function(self, *args, **kwargs):
  733. raise EnvironmentException('Language %s does not support function checks.' % self.get_display_language())
  734. @classmethod
  735. def unix_args_to_native(cls, args):
  736. "Always returns a copy that can be independently mutated"
  737. return args[:]
  738. def find_library(self, *args, **kwargs):
  739. raise EnvironmentException('Language {} does not support library finding.'.format(self.get_display_language()))
  740. def get_library_dirs(self):
  741. return []
  742. def has_multi_arguments(self, args, env):
  743. raise EnvironmentException(
  744. 'Language {} does not support has_multi_arguments.'.format(
  745. self.get_display_language()))
  746. def has_multi_link_arguments(self, args, env):
  747. raise EnvironmentException(
  748. 'Language {} does not support has_multi_link_arguments.'.format(
  749. self.get_display_language()))
  750. def get_cross_extra_flags(self, environment, link):
  751. extra_flags = []
  752. if self.is_cross and environment:
  753. if 'properties' in environment.cross_info.config:
  754. props = environment.cross_info.config['properties']
  755. lang_args_key = self.language + '_args'
  756. extra_flags += props.get(lang_args_key, [])
  757. lang_link_args_key = self.language + '_link_args'
  758. if link:
  759. extra_flags += props.get(lang_link_args_key, [])
  760. return extra_flags
  761. def _get_compile_output(self, dirname, mode):
  762. # In pre-processor mode, the output is sent to stdout and discarded
  763. if mode == 'preprocess':
  764. return None
  765. # Extension only matters if running results; '.exe' is
  766. # guaranteed to be executable on every platform.
  767. if mode == 'link':
  768. suffix = 'exe'
  769. else:
  770. suffix = 'obj'
  771. return os.path.join(dirname, 'output.' + suffix)
  772. @contextlib.contextmanager
  773. def compile(self, code, extra_args=None, mode='link', want_output=False):
  774. if extra_args is None:
  775. textra_args = None
  776. extra_args = []
  777. else:
  778. textra_args = tuple(extra_args)
  779. key = (code, textra_args, mode)
  780. if not want_output:
  781. if key in self.compiler_check_cache:
  782. p = self.compiler_check_cache[key]
  783. mlog.debug('Using cached compile:')
  784. mlog.debug('Cached command line: ', ' '.join(p.commands), '\n')
  785. mlog.debug('Code:\n', code)
  786. mlog.debug('Cached compiler stdout:\n', p.stdo)
  787. mlog.debug('Cached compiler stderr:\n', p.stde)
  788. yield p
  789. return
  790. try:
  791. with tempfile.TemporaryDirectory() as tmpdirname:
  792. if isinstance(code, str):
  793. srcname = os.path.join(tmpdirname,
  794. 'testfile.' + self.default_suffix)
  795. with open(srcname, 'w') as ofile:
  796. ofile.write(code)
  797. elif isinstance(code, mesonlib.File):
  798. srcname = code.fname
  799. # Construct the compiler command-line
  800. commands = CompilerArgs(self)
  801. commands.append(srcname)
  802. commands += self.get_always_args()
  803. if mode == 'compile':
  804. commands += self.get_compile_only_args()
  805. # Preprocess mode outputs to stdout, so no output args
  806. if mode == 'preprocess':
  807. commands += self.get_preprocess_only_args()
  808. else:
  809. output = self._get_compile_output(tmpdirname, mode)
  810. commands += self.get_output_args(output)
  811. # extra_args must be last because it could contain '/link' to
  812. # pass args to VisualStudio's linker. In that case everything
  813. # in the command line after '/link' is given to the linker.
  814. commands += extra_args
  815. # Generate full command-line with the exelist
  816. commands = self.get_exelist() + commands.to_native()
  817. mlog.debug('Running compile:')
  818. mlog.debug('Working directory: ', tmpdirname)
  819. mlog.debug('Command line: ', ' '.join(commands), '\n')
  820. mlog.debug('Code:\n', code)
  821. p, p.stdo, p.stde = Popen_safe(commands, cwd=tmpdirname)
  822. mlog.debug('Compiler stdout:\n', p.stdo)
  823. mlog.debug('Compiler stderr:\n', p.stde)
  824. p.commands = commands
  825. p.input_name = srcname
  826. if want_output:
  827. p.output_name = output
  828. else:
  829. self.compiler_check_cache[key] = p
  830. yield p
  831. except (PermissionError, OSError):
  832. # On Windows antivirus programs and the like hold on to files so
  833. # they can't be deleted. There's not much to do in this case. Also,
  834. # catch OSError because the directory is then no longer empty.
  835. pass
  836. def get_colorout_args(self, colortype):
  837. return []
  838. # Some compilers (msvc) write debug info to a separate file.
  839. # These args specify where it should be written.
  840. def get_compile_debugfile_args(self, rel_obj, **kwargs):
  841. return []
  842. def get_link_debugfile_args(self, rel_obj):
  843. return []
  844. def get_std_shared_lib_link_args(self):
  845. return []
  846. def get_std_shared_module_link_args(self, options):
  847. return self.get_std_shared_lib_link_args()
  848. def get_link_whole_for(self, args):
  849. if isinstance(args, list) and not args:
  850. return []
  851. raise EnvironmentException('Language %s does not support linking whole archives.' % self.get_display_language())
  852. # Compiler arguments needed to enable the given instruction set.
  853. # May be [] meaning nothing needed or None meaning the given set
  854. # is not supported.
  855. def get_instruction_set_args(self, instruction_set):
  856. return None
  857. def build_osx_rpath_args(self, build_dir, rpath_paths, build_rpath):
  858. if not rpath_paths and not build_rpath:
  859. return []
  860. # On OSX, rpaths must be absolute.
  861. abs_rpaths = [os.path.join(build_dir, p) for p in rpath_paths]
  862. if build_rpath != '':
  863. abs_rpaths.append(build_rpath)
  864. # Ensure that there is enough space for large RPATHs
  865. args = ['-Wl,-headerpad_max_install_names']
  866. args += ['-Wl,-rpath,' + rp for rp in abs_rpaths]
  867. return args
  868. def build_unix_rpath_args(self, build_dir, from_dir, rpath_paths, build_rpath, install_rpath):
  869. if not rpath_paths and not install_rpath and not build_rpath:
  870. return []
  871. # The rpaths we write must be relative, because otherwise
  872. # they have different length depending on the build
  873. # directory. This breaks reproducible builds.
  874. rel_rpaths = []
  875. for p in rpath_paths:
  876. if p == from_dir:
  877. relative = '' # relpath errors out in this case
  878. else:
  879. relative = os.path.relpath(os.path.join(build_dir, p), os.path.join(build_dir, from_dir))
  880. rel_rpaths.append(relative)
  881. paths = ':'.join([os.path.join('$ORIGIN', p) for p in rel_rpaths])
  882. # Build_rpath is used as-is (it is usually absolute).
  883. if build_rpath != '':
  884. if paths != '':
  885. paths += ':'
  886. paths += build_rpath
  887. if len(paths) < len(install_rpath):
  888. padding = 'X' * (len(install_rpath) - len(paths))
  889. if not paths:
  890. paths = padding
  891. else:
  892. paths = paths + ':' + padding
  893. args = []
  894. if mesonlib.is_dragonflybsd() or mesonlib.is_openbsd():
  895. # This argument instructs the compiler to record the value of
  896. # ORIGIN in the .dynamic section of the elf. On Linux this is done
  897. # by default, but is not on dragonfly/openbsd for some reason. Without this
  898. # $ORIGIN in the runtime path will be undefined and any binaries
  899. # linked against local libraries will fail to resolve them.
  900. args.append('-Wl,-z,origin')
  901. args.append('-Wl,-rpath,' + paths)
  902. if get_compiler_is_linuxlike(self):
  903. # Rpaths to use while linking must be absolute. These are not
  904. # written to the binary. Needed only with GNU ld:
  905. # https://sourceware.org/bugzilla/show_bug.cgi?id=16936
  906. # Not needed on Windows or other platforms that don't use RPATH
  907. # https://github.com/mesonbuild/meson/issues/1897
  908. lpaths = ':'.join([os.path.join(build_dir, p) for p in rpath_paths])
  909. # clang expands '-Wl,rpath-link,' to ['-rpath-link'] instead of ['-rpath-link','']
  910. # This eats the next argument, which happens to be 'ldstdc++', causing link failures.
  911. # We can dodge this problem by not adding any rpath_paths if the argument is empty.
  912. if lpaths.strip() != '':
  913. args += ['-Wl,-rpath-link,' + lpaths]
  914. return args
  915. def thread_flags(self, env):
  916. return []
  917. def openmp_flags(self):
  918. raise EnvironmentException('Language %s does not support OpenMP flags.' % self.get_display_language())
  919. def language_stdlib_only_link_flags(self):
  920. # The linker flags needed to link the standard library of the current
  921. # language in. This is needed in cases where you e.g. combine D and C++
  922. # and both of which need to link their runtime library in or otherwise
  923. # building fails with undefined symbols.
  924. return []
  925. GCC_STANDARD = 0
  926. GCC_OSX = 1
  927. GCC_MINGW = 2
  928. GCC_CYGWIN = 3
  929. CLANG_STANDARD = 0
  930. CLANG_OSX = 1
  931. CLANG_WIN = 2
  932. # Possibly clang-cl?
  933. ICC_STANDARD = 0
  934. ICC_OSX = 1
  935. ICC_WIN = 2
  936. # GNU ld cannot be installed on macOS
  937. # https://github.com/Homebrew/homebrew-core/issues/17794#issuecomment-328174395
  938. # Hence, we don't need to differentiate between OS and ld
  939. # for the sake of adding as-needed support
  940. GNU_LD_AS_NEEDED = '-Wl,--as-needed'
  941. APPLE_LD_AS_NEEDED = '-Wl,-dead_strip_dylibs'
  942. def get_macos_dylib_install_name(prefix, shlib_name, suffix, soversion):
  943. install_name = prefix + shlib_name
  944. if soversion is not None:
  945. install_name += '.' + soversion
  946. install_name += '.dylib'
  947. return '@rpath/' + install_name
  948. def get_gcc_soname_args(gcc_type, prefix, shlib_name, suffix, soversion, is_shared_module):
  949. if soversion is None:
  950. sostr = ''
  951. else:
  952. sostr = '.' + soversion
  953. if gcc_type == GCC_STANDARD:
  954. return ['-Wl,-soname,%s%s.%s%s' % (prefix, shlib_name, suffix, sostr)]
  955. elif gcc_type in (GCC_MINGW, GCC_CYGWIN):
  956. # For PE/COFF the soname argument has no effect with GNU LD
  957. return []
  958. elif gcc_type == GCC_OSX:
  959. if is_shared_module:
  960. return []
  961. name = get_macos_dylib_install_name(prefix, shlib_name, suffix, soversion)
  962. return ['-install_name', name]
  963. else:
  964. raise RuntimeError('Not implemented yet.')
  965. def get_compiler_is_linuxlike(compiler):
  966. if (getattr(compiler, 'gcc_type', None) == GCC_STANDARD) or \
  967. (getattr(compiler, 'clang_type', None) == CLANG_STANDARD) or \
  968. (getattr(compiler, 'icc_type', None) == ICC_STANDARD):
  969. return True
  970. return False
  971. def get_compiler_uses_gnuld(c):
  972. # FIXME: Perhaps we should detect the linker in the environment?
  973. # FIXME: Assumes that *BSD use GNU ld, but they might start using lld soon
  974. if (getattr(c, 'gcc_type', None) in (GCC_STANDARD, GCC_MINGW, GCC_CYGWIN)) or \
  975. (getattr(c, 'clang_type', None) in (CLANG_STANDARD, CLANG_WIN)) or \
  976. (getattr(c, 'icc_type', None) in (ICC_STANDARD, ICC_WIN)):
  977. return True
  978. return False
  979. def get_largefile_args(compiler):
  980. '''
  981. Enable transparent large-file-support for 32-bit UNIX systems
  982. '''
  983. if get_compiler_is_linuxlike(compiler):
  984. # Enable large-file support unconditionally on all platforms other
  985. # than macOS and Windows. macOS is now 64-bit-only so it doesn't
  986. # need anything special, and Windows doesn't have automatic LFS.
  987. # You must use the 64-bit counterparts explicitly.
  988. # glibc, musl, and uclibc, and all BSD libcs support this. On Android,
  989. # support for transparent LFS is available depending on the version of
  990. # Bionic: https://github.com/android/platform_bionic#32-bit-abi-bugs
  991. # https://code.google.com/p/android/issues/detail?id=64613
  992. #
  993. # If this breaks your code, fix it! It's been 20+ years!
  994. return ['-D_FILE_OFFSET_BITS=64']
  995. # We don't enable -D_LARGEFILE64_SOURCE since that enables
  996. # transitionary features and must be enabled by programs that use
  997. # those features explicitly.
  998. return []
  999. # TODO: The result from calling compiler should be cached. So that calling this
  1000. # function multiple times don't add latency.
  1001. def gnulike_default_include_dirs(compiler, lang):
  1002. if lang == 'cpp':
  1003. lang = 'c++'
  1004. env = os.environ.copy()
  1005. env["LC_ALL"] = 'C'
  1006. cmd = compiler + ['-x{}'.format(lang), '-E', '-v', '-']
  1007. p = subprocess.Popen(
  1008. cmd,
  1009. stdin=subprocess.DEVNULL,
  1010. stderr=subprocess.PIPE,
  1011. stdout=subprocess.PIPE,
  1012. env=env
  1013. )
  1014. stderr = p.stderr.read().decode('utf-8', errors='replace')
  1015. parse_state = 0
  1016. paths = []
  1017. for line in stderr.split('\n'):
  1018. if parse_state == 0:
  1019. if line == '#include "..." search starts here:':
  1020. parse_state = 1
  1021. elif parse_state == 1:
  1022. if line == '#include <...> search starts here:':
  1023. parse_state = 2
  1024. else:
  1025. paths.append(line[1:])
  1026. elif parse_state == 2:
  1027. if line == 'End of search list.':
  1028. break
  1029. else:
  1030. paths.append(line[1:])
  1031. if len(paths) == 0:
  1032. mlog.warning('No include directory found parsing "{cmd}" output'.format(cmd=" ".join(cmd)))
  1033. return paths
  1034. class GnuCompiler:
  1035. # Functionality that is common to all GNU family compilers.
  1036. def __init__(self, gcc_type, defines):
  1037. self.id = 'gcc'
  1038. self.gcc_type = gcc_type
  1039. self.defines = defines or {}
  1040. self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage',
  1041. 'b_colorout', 'b_ndebug', 'b_staticpic']
  1042. if self.gcc_type == GCC_OSX:
  1043. self.base_options.append('b_bitcode')
  1044. else:
  1045. self.base_options.append('b_lundef')
  1046. self.base_options.append('b_asneeded')
  1047. # All GCC backends can do assembly
  1048. self.can_compile_suffixes.add('s')
  1049. # TODO: centralise this policy more globally, instead
  1050. # of fragmenting it into GnuCompiler and ClangCompiler
  1051. def get_asneeded_args(self):
  1052. if self.gcc_type == GCC_OSX:
  1053. return APPLE_LD_AS_NEEDED
  1054. else:
  1055. return GNU_LD_AS_NEEDED
  1056. def get_colorout_args(self, colortype):
  1057. if mesonlib.version_compare(self.version, '>=4.9.0'):
  1058. return gnu_color_args[colortype][:]
  1059. return []
  1060. def get_warn_args(self, level):
  1061. args = super().get_warn_args(level)
  1062. if mesonlib.version_compare(self.version, '<4.8.0') and '-Wpedantic' in args:
  1063. # -Wpedantic was added in 4.8.0
  1064. # https://gcc.gnu.org/gcc-4.8/changes.html
  1065. args[args.index('-Wpedantic')] = '-pedantic'
  1066. return args
  1067. def has_builtin_define(self, define):
  1068. return define in self.defines
  1069. def get_builtin_define(self, define):
  1070. if define in self.defines:
  1071. return self.defines[define]
  1072. def get_pic_args(self):
  1073. if self.gcc_type in (GCC_CYGWIN, GCC_MINGW, GCC_OSX):
  1074. return [] # On Window and OS X, pic is always on.
  1075. return ['-fPIC']
  1076. def get_buildtype_args(self, buildtype):
  1077. return gnulike_buildtype_args[buildtype]
  1078. def get_buildtype_linker_args(self, buildtype):
  1079. if self.gcc_type == GCC_OSX:
  1080. return apple_buildtype_linker_args[buildtype]
  1081. return gnulike_buildtype_linker_args[buildtype]
  1082. def get_pch_suffix(self):
  1083. return 'gch'
  1084. def split_shlib_to_parts(self, fname):
  1085. return os.path.dirname(fname), fname
  1086. def get_soname_args(self, prefix, shlib_name, suffix, soversion, is_shared_module):
  1087. return get_gcc_soname_args(self.gcc_type, prefix, shlib_name, suffix, soversion, is_shared_module)
  1088. def get_std_shared_lib_link_args(self):
  1089. return ['-shared']
  1090. def get_link_whole_for(self, args):
  1091. return ['-Wl,--whole-archive'] + args + ['-Wl,--no-whole-archive']
  1092. def gen_vs_module_defs_args(self, defsfile):
  1093. if not isinstance(defsfile, str):
  1094. raise RuntimeError('Module definitions file should be str')
  1095. # On Windows targets, .def files may be specified on the linker command
  1096. # line like an object file.
  1097. if self.gcc_type in (GCC_CYGWIN, GCC_MINGW):
  1098. return [defsfile]
  1099. # For other targets, discard the .def file.
  1100. return []
  1101. def get_gui_app_args(self):
  1102. if self.gcc_type in (GCC_CYGWIN, GCC_MINGW):
  1103. return ['-mwindows']
  1104. return []
  1105. def get_instruction_set_args(self, instruction_set):
  1106. return gnulike_instruction_set_args.get(instruction_set, None)
  1107. def get_default_include_dirs(self):
  1108. return gnulike_default_include_dirs(self.exelist, self.language)
  1109. def openmp_flags(self):
  1110. return ['-fopenmp']
  1111. class ElbrusCompiler(GnuCompiler):
  1112. # Elbrus compiler is nearly like GCC, but does not support
  1113. # PCH, LTO, sanitizers and color output as of version 1.21.x.
  1114. def __init__(self, gcc_type, defines):
  1115. GnuCompiler.__init__(self, gcc_type, defines)
  1116. self.id = 'lcc'
  1117. self.base_options = ['b_pgo', 'b_coverage',
  1118. 'b_ndebug', 'b_staticpic',
  1119. 'b_lundef', 'b_asneeded']
  1120. def get_library_dirs(self):
  1121. env = os.environ.copy()
  1122. env['LC_ALL'] = 'C'
  1123. stdo = Popen_safe(self.exelist + ['--print-search-dirs'], env=env)[1]
  1124. paths = []
  1125. for line in stdo.split('\n'):
  1126. if line.startswith('libraries:'):
  1127. # lcc does not include '=' in --print-search-dirs output.
  1128. libstr = line.split(' ', 1)[1]
  1129. paths = [os.path.realpath(p) for p in libstr.split(':')]
  1130. break
  1131. return paths
  1132. def get_program_dirs(self):
  1133. env = os.environ.copy()
  1134. env['LC_ALL'] = 'C'
  1135. stdo = Popen_safe(self.exelist + ['--print-search-dirs'], env=env)[1]
  1136. paths = []
  1137. for line in stdo.split('\n'):
  1138. if line.startswith('programs:'):
  1139. # lcc does not include '=' in --print-search-dirs output.
  1140. libstr = line.split(' ', 1)[1]
  1141. paths = [os.path.realpath(p) for p in libstr.split(':')]
  1142. break
  1143. return paths
  1144. class ClangCompiler:
  1145. def __init__(self, clang_type):
  1146. self.id = 'clang'
  1147. self.clang_type = clang_type
  1148. self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage',
  1149. 'b_ndebug', 'b_staticpic', 'b_colorout']
  1150. if self.clang_type == CLANG_OSX:
  1151. self.base_options.append('b_bitcode')
  1152. else:
  1153. self.base_options.append('b_lundef')
  1154. self.base_options.append('b_asneeded')
  1155. # All Clang backends can do assembly and LLVM IR
  1156. self.can_compile_suffixes.update(['ll', 's'])
  1157. # TODO: centralise this policy more globally, instead
  1158. # of fragmenting it into GnuCompiler and ClangCompiler
  1159. def get_asneeded_args(self):
  1160. if self.clang_type == CLANG_OSX:
  1161. return APPLE_LD_AS_NEEDED
  1162. else:
  1163. return GNU_LD_AS_NEEDED
  1164. def get_pic_args(self):
  1165. if self.clang_type in (CLANG_WIN, CLANG_OSX):
  1166. return [] # On Window and OS X, pic is always on.
  1167. return ['-fPIC']
  1168. def get_colorout_args(self, colortype):
  1169. return clang_color_args[colortype][:]
  1170. def get_buildtype_args(self, buildtype):
  1171. return gnulike_buildtype_args[buildtype]
  1172. def get_buildtype_linker_args(self, buildtype):
  1173. if self.clang_type == CLANG_OSX:
  1174. return apple_buildtype_linker_args[buildtype]
  1175. return gnulike_buildtype_linker_args[buildtype]
  1176. def get_pch_suffix(self):
  1177. return 'pch'
  1178. def get_pch_use_args(self, pch_dir, header):
  1179. # Workaround for Clang bug http://llvm.org/bugs/show_bug.cgi?id=15136
  1180. # This flag is internal to Clang (or at least not documented on the man page)
  1181. # so it might change semantics at any time.
  1182. return ['-include-pch', os.path.join(pch_dir, self.get_pch_name(header))]
  1183. def get_soname_args(self, prefix, shlib_name, suffix, soversion, is_shared_module):
  1184. if self.clang_type == CLANG_STANDARD:
  1185. gcc_type = GCC_STANDARD
  1186. elif self.clang_type == CLANG_OSX:
  1187. gcc_type = GCC_OSX
  1188. elif self.clang_type == CLANG_WIN:
  1189. gcc_type = GCC_MINGW
  1190. else:
  1191. raise MesonException('Unreachable code when converting clang type to gcc type.')
  1192. return get_gcc_soname_args(gcc_type, prefix, shlib_name, suffix, soversion, is_shared_module)
  1193. def has_multi_arguments(self, args, env):
  1194. myargs = ['-Werror=unknown-warning-option', '-Werror=unused-command-line-argument']
  1195. if mesonlib.version_compare(self.version, '>=3.6.0'):
  1196. myargs.append('-Werror=ignored-optimization-argument')
  1197. return super().has_multi_arguments(
  1198. myargs + args,
  1199. env)
  1200. def has_function(self, funcname, prefix, env, extra_args=None, dependencies=None):
  1201. if extra_args is None:
  1202. extra_args = []
  1203. # Starting with XCode 8, we need to pass this to force linker
  1204. # visibility to obey OS X and iOS minimum version targets with
  1205. # -mmacosx-version-min, -miphoneos-version-min, etc.
  1206. # https://github.com/Homebrew/homebrew-core/issues/3727
  1207. if self.clang_type == CLANG_OSX and version_compare(self.version, '>=8.0'):
  1208. extra_args.append('-Wl,-no_weak_imports')
  1209. return super().has_function(funcname, prefix, env, extra_args, dependencies)
  1210. def get_std_shared_module_link_args(self, options):
  1211. if self.clang_type == CLANG_OSX:
  1212. return ['-bundle', '-Wl,-undefined,dynamic_lookup']
  1213. return ['-shared']
  1214. def get_link_whole_for(self, args):
  1215. if self.clang_type == CLANG_OSX:
  1216. result = []
  1217. for a in args:
  1218. result += ['-Wl,-force_load', a]
  1219. return result
  1220. return ['-Wl,--whole-archive'] + args + ['-Wl,--no-whole-archive']
  1221. def get_instruction_set_args(self, instruction_set):
  1222. return gnulike_instruction_set_args.get(instruction_set, None)
  1223. def get_default_include_dirs(self):
  1224. return gnulike_default_include_dirs(self.exelist, self.language)
  1225. def openmp_flags(self):
  1226. if version_compare(self.version, '>=3.8.0'):
  1227. return ['-fopenmp']
  1228. elif version_compare(self.version, '>=3.7.0'):
  1229. return ['-fopenmp=libomp']
  1230. else:
  1231. # Shouldn't work, but it'll be checked explicitly in the OpenMP dependency.
  1232. return []
  1233. class ArmclangCompiler:
  1234. def __init__(self):
  1235. if not self.is_cross:
  1236. raise EnvironmentException('armclang supports only cross-compilation.')
  1237. # Check whether 'armlink.exe' is available in path
  1238. self.linker_exe = 'armlink.exe'
  1239. args = '--vsn'
  1240. try:
  1241. p, stdo, stderr = Popen_safe(self.linker_exe, args)
  1242. except OSError as e:
  1243. err_msg = 'Unknown linker\nRunning "{0}" gave \n"{1}"'.format(' '.join([self.linker_exe] + [args]), e)
  1244. raise EnvironmentException(err_msg)
  1245. # Verify the armlink version
  1246. ver_str = re.search('.*Component.*', stdo)
  1247. if ver_str:
  1248. ver_str = ver_str.group(0)
  1249. else:
  1250. EnvironmentException('armlink version string not found')
  1251. # Using the regular expression from environment.search_version,
  1252. # which is used for searching compiler version
  1253. version_regex = '(?<!(\d|\.))(\d{1,2}(\.\d+)+(-[a-zA-Z0-9]+)?)'
  1254. linker_ver = re.search(version_regex, ver_str)
  1255. if linker_ver:
  1256. linker_ver = linker_ver.group(0)
  1257. if not version_compare(self.version, '==' + linker_ver):
  1258. raise EnvironmentException('armlink version does not match with compiler version')
  1259. self.id = 'armclang'
  1260. self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage',
  1261. 'b_ndebug', 'b_staticpic', 'b_colorout']
  1262. # Assembly
  1263. self.can_compile_suffixes.update('s')
  1264. def can_linker_accept_rsp(self):
  1265. return False
  1266. def get_pic_args(self):
  1267. # PIC support is not enabled by default for ARM,
  1268. # if users want to use it, they need to add the required arguments explicitly
  1269. return []
  1270. def get_colorout_args(self, colortype):
  1271. return clang_color_args[colortype][:]
  1272. def get_buildtype_args(self, buildtype):
  1273. return armclang_buildtype_args[buildtype]
  1274. def get_buildtype_linker_args(self, buildtype):
  1275. return arm_buildtype_linker_args[buildtype]
  1276. # Override CCompiler.get_std_shared_lib_link_args
  1277. def get_std_shared_lib_link_args(self):
  1278. return []
  1279. def get_pch_suffix(self):
  1280. return 'gch'
  1281. def get_pch_use_args(self, pch_dir, header):
  1282. # Workaround for Clang bug http://llvm.org/bugs/show_bug.cgi?id=15136
  1283. # This flag is internal to Clang (or at least not documented on the man page)
  1284. # so it might change semantics at any time.
  1285. return ['-include-pch', os.path.join(pch_dir, self.get_pch_name(header))]
  1286. # Override CCompiler.get_dependency_gen_args
  1287. def get_dependency_gen_args(self, outtarget, outfile):
  1288. return []
  1289. # Override CCompiler.build_rpath_args
  1290. def build_rpath_args(self, build_dir, from_dir, rpath_paths, build_rpath, install_rpath):
  1291. return []
  1292. def get_linker_exelist(self):
  1293. return [self.linker_exe]
  1294. # Tested on linux for ICC 14.0.3, 15.0.6, 16.0.4, 17.0.1
  1295. class IntelCompiler:
  1296. def __init__(self, icc_type):
  1297. self.id = 'intel'
  1298. self.icc_type = icc_type
  1299. self.lang_header = 'none'
  1300. self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage',
  1301. 'b_colorout', 'b_ndebug', 'b_staticpic', 'b_lundef', 'b_asneeded']
  1302. # Assembly
  1303. self.can_compile_suffixes.add('s')
  1304. def get_pic_args(self):
  1305. return ['-fPIC']
  1306. def get_buildtype_args(self, buildtype):
  1307. return gnulike_buildtype_args[buildtype]
  1308. def get_buildtype_linker_args(self, buildtype):
  1309. return gnulike_buildtype_linker_args[buildtype]
  1310. def get_pch_suffix(self):
  1311. return 'pchi'
  1312. def get_pch_use_args(self, pch_dir, header):
  1313. return ['-pch', '-pch_dir', os.path.join(pch_dir), '-x',
  1314. self.lang_header, '-include', header, '-x', 'none']
  1315. def get_pch_name(self, header_name):
  1316. return os.path.basename(header_name) + '.' + self.get_pch_suffix()
  1317. def split_shlib_to_parts(self, fname):
  1318. return os.path.dirname(fname), fname
  1319. def get_soname_args(self, prefix, shlib_name, suffix, soversion, is_shared_module):
  1320. if self.icc_type == ICC_STANDARD:
  1321. gcc_type = GCC_STANDARD
  1322. elif self.icc_type == ICC_OSX:
  1323. gcc_type = GCC_OSX
  1324. elif self.icc_type == ICC_WIN:
  1325. gcc_type = GCC_MINGW
  1326. else:
  1327. raise MesonException('Unreachable code when converting icc type to gcc type.')
  1328. return get_gcc_soname_args(gcc_type, prefix, shlib_name, suffix, soversion, is_shared_module)
  1329. # TODO: centralise this policy more globally, instead
  1330. # of fragmenting it into GnuCompiler and ClangCompiler
  1331. def get_asneeded_args(self):
  1332. if self.icc_type == CLANG_OSX:
  1333. return APPLE_LD_AS_NEEDED
  1334. else:
  1335. return GNU_LD_AS_NEEDED
  1336. def get_std_shared_lib_link_args(self):
  1337. # FIXME: Don't know how icc works on OSX
  1338. # if self.icc_type == ICC_OSX:
  1339. # return ['-bundle']
  1340. return ['-shared']
  1341. def get_default_include_dirs(self):
  1342. return gnulike_default_include_dirs(self.exelist, self.language)
  1343. def openmp_flags(self):
  1344. if version_compare(self.version, '>=15.0.0'):
  1345. return ['-qopenmp']
  1346. else:
  1347. return ['-openmp']
  1348. class ArmCompiler:
  1349. # Functionality that is common to all ARM family compilers.
  1350. def __init__(self):
  1351. if not self.is_cross:
  1352. raise EnvironmentException('armcc supports only cross-compilation.')
  1353. self.id = 'arm'
  1354. default_warn_args = []
  1355. self.warn_args = {'1': default_warn_args,
  1356. '2': default_warn_args + [],
  1357. '3': default_warn_args + []}
  1358. # Assembly
  1359. self.can_compile_suffixes.add('s')
  1360. def can_linker_accept_rsp(self):
  1361. return False
  1362. def get_pic_args(self):
  1363. # FIXME: Add /ropi, /rwpi, /fpic etc. qualifiers to --apcs
  1364. return []
  1365. def get_buildtype_args(self, buildtype):
  1366. return arm_buildtype_args[buildtype]
  1367. def get_buildtype_linker_args(self, buildtype):
  1368. return arm_buildtype_linker_args[buildtype]
  1369. # Override CCompiler.get_always_args
  1370. def get_always_args(self):
  1371. return []
  1372. # Override CCompiler.get_dependency_gen_args
  1373. def get_dependency_gen_args(self, outtarget, outfile):
  1374. return []
  1375. # Override CCompiler.get_std_shared_lib_link_args
  1376. def get_std_shared_lib_link_args(self):
  1377. return []
  1378. def get_pch_use_args(self, pch_dir, header):
  1379. # FIXME: Add required arguments
  1380. # NOTE from armcc user guide:
  1381. # "Support for Precompiled Header (PCH) files is deprecated from ARM Compiler 5.05
  1382. # onwards on all platforms. Note that ARM Compiler on Windows 8 never supported
  1383. # PCH files."
  1384. return []
  1385. def get_pch_suffix(self):
  1386. # NOTE from armcc user guide:
  1387. # "Support for Precompiled Header (PCH) files is deprecated from ARM Compiler 5.05
  1388. # onwards on all platforms. Note that ARM Compiler on Windows 8 never supported
  1389. # PCH files."
  1390. return 'pch'
  1391. def thread_flags(self, env):
  1392. return []
  1393. def thread_link_flags(self, env):
  1394. return []
  1395. def get_linker_exelist(self):
  1396. args = ['armlink']
  1397. return args
  1398. def get_coverage_args(self):
  1399. return []
  1400. def get_coverage_link_args(self):
  1401. return []