compilers.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  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
  12. from ..linkers import StaticLinker
  13. from .. import coredata
  14. from .. import mlog
  15. from .. import mesonlib
  16. from ..mesonlib import EnvironmentException, MesonException, version_compare, Popen_safe
  17. """This file contains the data files of all compilers Meson knows
  18. about. To support a new compiler, add its information below.
  19. Also add corresponding autodetection code in environment.py."""
  20. header_suffixes = ('h', 'hh', 'hpp', 'hxx', 'H', 'ipp', 'moc', 'vapi', 'di')
  21. obj_suffixes = ('o', 'obj', 'res')
  22. lib_suffixes = ('a', 'lib', 'dll', 'dylib', 'so')
  23. # Mapping of language to suffixes of files that should always be in that language
  24. # This means we can't include .h headers here since they could be C, C++, ObjC, etc.
  25. lang_suffixes = {
  26. 'c': ('c',),
  27. 'cpp': ('cpp', 'cc', 'cxx', 'c++', 'hh', 'hpp', 'ipp', 'hxx'),
  28. # f90, f95, f03, f08 are for free-form fortran ('f90' recommended)
  29. # f, for, ftn, fpp are for fixed-form fortran ('f' or 'for' recommended)
  30. 'fortran': ('f90', 'f95', 'f03', 'f08', 'f', 'for', 'ftn', 'fpp'),
  31. 'd': ('d', 'di'),
  32. 'objc': ('m',),
  33. 'objcpp': ('mm',),
  34. 'rust': ('rs',),
  35. 'vala': ('vala', 'vapi', 'gs'),
  36. 'cs': ('cs',),
  37. 'swift': ('swift',),
  38. 'java': ('java',),
  39. }
  40. cpp_suffixes = lang_suffixes['cpp'] + ('h',)
  41. c_suffixes = lang_suffixes['c'] + ('h',)
  42. # List of languages that can be linked with C code directly by the linker
  43. # used in build.py:process_compilers() and build.py:get_dynamic_linker()
  44. clike_langs = ('objcpp', 'objc', 'd', 'cpp', 'c', 'fortran',)
  45. clike_suffixes = ()
  46. for _l in clike_langs:
  47. clike_suffixes += lang_suffixes[_l]
  48. clike_suffixes += ('h', 'll', 's')
  49. # XXX: Use this in is_library()?
  50. soregex = re.compile(r'.*\.so(\.[0-9]+)?(\.[0-9]+)?(\.[0-9]+)?$')
  51. # All these are only for C-like languages; see `clike_langs` above.
  52. def sort_clike(lang):
  53. '''
  54. Sorting function to sort the list of languages according to
  55. reversed(compilers.clike_langs) and append the unknown langs in the end.
  56. The purpose is to prefer C over C++ for files that can be compiled by
  57. both such as assembly, C, etc. Also applies to ObjC, ObjC++, etc.
  58. '''
  59. if lang not in clike_langs:
  60. return 1
  61. return -clike_langs.index(lang)
  62. def is_header(fname):
  63. if hasattr(fname, 'fname'):
  64. fname = fname.fname
  65. suffix = fname.split('.')[-1]
  66. return suffix in header_suffixes
  67. def is_source(fname):
  68. if hasattr(fname, 'fname'):
  69. fname = fname.fname
  70. suffix = fname.split('.')[-1].lower()
  71. return suffix in clike_suffixes
  72. def is_assembly(fname):
  73. if hasattr(fname, 'fname'):
  74. fname = fname.fname
  75. return fname.split('.')[-1].lower() == 's'
  76. def is_llvm_ir(fname):
  77. if hasattr(fname, 'fname'):
  78. fname = fname.fname
  79. return fname.split('.')[-1] == 'll'
  80. def is_object(fname):
  81. if hasattr(fname, 'fname'):
  82. fname = fname.fname
  83. suffix = fname.split('.')[-1]
  84. return suffix in obj_suffixes
  85. def is_library(fname):
  86. if hasattr(fname, 'fname'):
  87. fname = fname.fname
  88. suffix = fname.split('.')[-1]
  89. return suffix in lib_suffixes
  90. gnulike_buildtype_args = {'plain': [],
  91. # -O0 is passed for improved debugging information with gcc
  92. # See https://github.com/mesonbuild/meson/pull/509
  93. 'debug': ['-O0', '-g'],
  94. 'debugoptimized': ['-O2', '-g'],
  95. 'release': ['-O3'],
  96. 'minsize': ['-Os', '-g']}
  97. msvc_buildtype_args = {'plain': [],
  98. 'debug': ["/MDd", "/ZI", "/Ob0", "/Od", "/RTC1"],
  99. 'debugoptimized': ["/MD", "/Zi", "/O2", "/Ob1"],
  100. 'release': ["/MD", "/O2", "/Ob2"],
  101. 'minsize': ["/MD", "/Zi", "/Os", "/Ob1"],
  102. }
  103. apple_buildtype_linker_args = {'plain': [],
  104. 'debug': [],
  105. 'debugoptimized': [],
  106. 'release': [],
  107. 'minsize': [],
  108. }
  109. gnulike_buildtype_linker_args = {'plain': [],
  110. 'debug': [],
  111. 'debugoptimized': [],
  112. 'release': ['-Wl,-O1'],
  113. 'minsize': [],
  114. }
  115. msvc_buildtype_linker_args = {'plain': [],
  116. 'debug': [],
  117. 'debugoptimized': [],
  118. 'release': [],
  119. 'minsize': ['/INCREMENTAL:NO'],
  120. }
  121. java_buildtype_args = {'plain': [],
  122. 'debug': ['-g'],
  123. 'debugoptimized': ['-g'],
  124. 'release': [],
  125. 'minsize': [],
  126. }
  127. rust_buildtype_args = {'plain': [],
  128. 'debug': ['-C', 'debuginfo=2'],
  129. 'debugoptimized': ['-C', 'debuginfo=2', '-C', 'opt-level=2'],
  130. 'release': ['-C', 'opt-level=3'],
  131. 'minsize': [], # In a future release: ['-C', 'opt-level=s'],
  132. }
  133. d_gdc_buildtype_args = {'plain': [],
  134. 'debug': ['-g', '-O0'],
  135. 'debugoptimized': ['-g', '-O'],
  136. 'release': ['-O3', '-frelease'],
  137. 'minsize': [],
  138. }
  139. d_ldc_buildtype_args = {'plain': [],
  140. 'debug': ['-g', '-O0'],
  141. 'debugoptimized': ['-g', '-O'],
  142. 'release': ['-O3', '-release'],
  143. 'minsize': [],
  144. }
  145. d_dmd_buildtype_args = {'plain': [],
  146. 'debug': ['-g'],
  147. 'debugoptimized': ['-g', '-O'],
  148. 'release': ['-O', '-release'],
  149. 'minsize': [],
  150. }
  151. mono_buildtype_args = {'plain': [],
  152. 'debug': ['-debug'],
  153. 'debugoptimized': ['-debug', '-optimize+'],
  154. 'release': ['-optimize+'],
  155. 'minsize': [],
  156. }
  157. swift_buildtype_args = {'plain': [],
  158. 'debug': ['-g'],
  159. 'debugoptimized': ['-g', '-O'],
  160. 'release': ['-O'],
  161. 'minsize': [],
  162. }
  163. gnu_winlibs = ['-lkernel32', '-luser32', '-lgdi32', '-lwinspool', '-lshell32',
  164. '-lole32', '-loleaut32', '-luuid', '-lcomdlg32', '-ladvapi32']
  165. msvc_winlibs = ['kernel32.lib', 'user32.lib', 'gdi32.lib',
  166. 'winspool.lib', 'shell32.lib', 'ole32.lib', 'oleaut32.lib',
  167. 'uuid.lib', 'comdlg32.lib', 'advapi32.lib']
  168. gnu_color_args = {'auto': ['-fdiagnostics-color=auto'],
  169. 'always': ['-fdiagnostics-color=always'],
  170. 'never': ['-fdiagnostics-color=never'],
  171. }
  172. clang_color_args = {'auto': ['-Xclang', '-fcolor-diagnostics'],
  173. 'always': ['-Xclang', '-fcolor-diagnostics'],
  174. 'never': ['-Xclang', '-fno-color-diagnostics'],
  175. }
  176. base_options = {'b_pch': coredata.UserBooleanOption('b_pch', 'Use precompiled headers', True),
  177. 'b_lto': coredata.UserBooleanOption('b_lto', 'Use link time optimization', False),
  178. 'b_sanitize': coredata.UserComboOption('b_sanitize',
  179. 'Code sanitizer to use',
  180. ['none', 'address', 'thread', 'undefined', 'memory', 'address,undefined'],
  181. 'none'),
  182. 'b_lundef': coredata.UserBooleanOption('b_lundef', 'Use -Wl,--no-undefined when linking', True),
  183. 'b_asneeded': coredata.UserBooleanOption('b_asneeded', 'Use -Wl,--as-needed when linking', True),
  184. 'b_pgo': coredata.UserComboOption('b_pgo', 'Use profile guided optimization',
  185. ['off', 'generate', 'use'],
  186. 'off'),
  187. 'b_coverage': coredata.UserBooleanOption('b_coverage',
  188. 'Enable coverage tracking.',
  189. False),
  190. 'b_colorout': coredata.UserComboOption('b_colorout', 'Use colored output',
  191. ['auto', 'always', 'never'],
  192. 'always'),
  193. 'b_ndebug': coredata.UserBooleanOption('b_ndebug',
  194. 'Disable asserts',
  195. False),
  196. 'b_staticpic': coredata.UserBooleanOption('b_staticpic',
  197. 'Build static libraries as position independent',
  198. True),
  199. }
  200. gnulike_instruction_set_args = {'mmx': ['-mmmx'],
  201. 'sse': ['-msse'],
  202. 'sse2': ['-msse2'],
  203. 'sse3': ['-msse3'],
  204. 'ssse3': ['-mssse3'],
  205. 'sse41': ['-msse4.1'],
  206. 'sse42': ['-msse4.2'],
  207. 'avx': ['-mavx'],
  208. 'avx2': ['-mavx2'],
  209. 'neon': ['-mfpu=neon'],
  210. }
  211. vs32_instruction_set_args = {'mmx': ['/arch:SSE'], # There does not seem to be a flag just for MMX
  212. 'sse': ['/arch:SSE'],
  213. 'sse2': ['/arch:SSE2'],
  214. 'sse3': ['/arch:AVX'], # VS leaped from SSE2 directly to AVX.
  215. 'sse41': ['/arch:AVX'],
  216. 'sse42': ['/arch:AVX'],
  217. 'avx': ['/arch:AVX'],
  218. 'avx2': ['/arch:AVX2'],
  219. 'neon': None,
  220. }
  221. # The 64 bit compiler defaults to /arch:avx.
  222. vs64_instruction_set_args = {'mmx': ['/arch:AVX'],
  223. 'sse': ['/arch:AVX'],
  224. 'sse2': ['/arch:AVX'],
  225. 'sse3': ['/arch:AVX'],
  226. 'ssse3': ['/arch:AVX'],
  227. 'sse41': ['/arch:AVX'],
  228. 'sse42': ['/arch:AVX'],
  229. 'avx': ['/arch:AVX'],
  230. 'avx2': ['/arch:AVX2'],
  231. 'neon': None,
  232. }
  233. def sanitizer_compile_args(value):
  234. if value == 'none':
  235. return []
  236. args = ['-fsanitize=' + value]
  237. if value == 'address':
  238. args.append('-fno-omit-frame-pointer')
  239. return args
  240. def sanitizer_link_args(value):
  241. if value == 'none':
  242. return []
  243. args = ['-fsanitize=' + value]
  244. return args
  245. def get_base_compile_args(options, compiler):
  246. args = []
  247. # FIXME, gcc/clang specific.
  248. try:
  249. if options['b_lto'].value:
  250. args.append('-flto')
  251. except KeyError:
  252. pass
  253. try:
  254. args += compiler.get_colorout_args(options['b_colorout'].value)
  255. except KeyError:
  256. pass
  257. try:
  258. args += sanitizer_compile_args(options['b_sanitize'].value)
  259. except KeyError:
  260. pass
  261. try:
  262. pgo_val = options['b_pgo'].value
  263. if pgo_val == 'generate':
  264. args.append('-fprofile-generate')
  265. elif pgo_val == 'use':
  266. args.append('-fprofile-use')
  267. except KeyError:
  268. pass
  269. try:
  270. if options['b_coverage'].value:
  271. args += compiler.get_coverage_args()
  272. except KeyError:
  273. pass
  274. try:
  275. if options['b_ndebug'].value:
  276. args += ['-DNDEBUG']
  277. except KeyError:
  278. pass
  279. return args
  280. def get_base_link_args(options, linker, is_shared_module):
  281. args = []
  282. # FIXME, gcc/clang specific.
  283. try:
  284. if options['b_lto'].value:
  285. args.append('-flto')
  286. except KeyError:
  287. pass
  288. try:
  289. args += sanitizer_link_args(options['b_sanitize'].value)
  290. except KeyError:
  291. pass
  292. try:
  293. pgo_val = options['b_pgo'].value
  294. if pgo_val == 'generate':
  295. args.append('-fprofile-generate')
  296. elif pgo_val == 'use':
  297. args.append('-fprofile-use')
  298. except KeyError:
  299. pass
  300. try:
  301. if not is_shared_module and 'b_lundef' in linker.base_options and options['b_lundef'].value:
  302. args.append('-Wl,--no-undefined')
  303. except KeyError:
  304. pass
  305. try:
  306. if 'b_asneeded' in linker.base_options and options['b_asneeded'].value:
  307. args.append('-Wl,--as-needed')
  308. except KeyError:
  309. pass
  310. try:
  311. if options['b_coverage'].value:
  312. args += linker.get_coverage_link_args()
  313. except KeyError:
  314. pass
  315. return args
  316. class CrossNoRunException(MesonException):
  317. pass
  318. class RunResult:
  319. def __init__(self, compiled, returncode=999, stdout='UNDEFINED', stderr='UNDEFINED'):
  320. self.compiled = compiled
  321. self.returncode = returncode
  322. self.stdout = stdout
  323. self.stderr = stderr
  324. class CompilerArgs(list):
  325. '''
  326. Class derived from list() that manages a list of compiler arguments. Should
  327. be used while constructing compiler arguments from various sources. Can be
  328. operated with ordinary lists, so this does not need to be used everywhere.
  329. All arguments must be inserted and stored in GCC-style (-lfoo, -Idir, etc)
  330. and can converted to the native type of each compiler by using the
  331. .to_native() method to which you must pass an instance of the compiler or
  332. the compiler class.
  333. New arguments added to this class (either with .append(), .extend(), or +=)
  334. are added in a way that ensures that they override previous arguments.
  335. For example:
  336. >>> a = ['-Lfoo', '-lbar']
  337. >>> a += ['-Lpho', '-lbaz']
  338. >>> print(a)
  339. ['-Lpho', '-Lfoo', '-lbar', '-lbaz']
  340. Arguments will also be de-duped if they can be de-duped safely.
  341. Note that because of all this, this class is not commutative and does not
  342. preserve the order of arguments if it is safe to not. For example:
  343. >>> ['-Ifoo', '-Ibar'] + ['-Ifez', '-Ibaz', '-Werror']
  344. ['-Ifez', '-Ibaz', '-Ifoo', '-Ibar', '-Werror']
  345. >>> ['-Ifez', '-Ibaz', '-Werror'] + ['-Ifoo', '-Ibar']
  346. ['-Ifoo', '-Ibar', '-Ifez', '-Ibaz', '-Werror']
  347. '''
  348. # NOTE: currently this class is only for C-like compilers, but it can be
  349. # extended to other languages easily. Just move the following to the
  350. # compiler class and initialize when self.compiler is set.
  351. # Arg prefixes that override by prepending instead of appending
  352. prepend_prefixes = ('-I', '-L')
  353. # Arg prefixes and args that must be de-duped by returning 2
  354. dedup2_prefixes = ('-I', '-L', '-D', '-U')
  355. dedup2_suffixes = ()
  356. dedup2_args = ()
  357. # Arg prefixes and args that must be de-duped by returning 1
  358. dedup1_prefixes = ('-l',)
  359. dedup1_suffixes = ('.lib', '.dll', '.so', '.dylib', '.a')
  360. # Match a .so of the form path/to/libfoo.so.0.1.0
  361. # Only UNIX shared libraries require this. Others have a fixed extension.
  362. dedup1_regex = re.compile(r'([\/\\]|\A)lib.*\.so(\.[0-9]+)?(\.[0-9]+)?(\.[0-9]+)?$')
  363. dedup1_args = ('-c', '-S', '-E', '-pipe', '-pthread')
  364. compiler = None
  365. def _check_args(self, args):
  366. cargs = []
  367. if len(args) > 2:
  368. raise TypeError("CompilerArgs() only accepts at most 2 arguments: "
  369. "The compiler, and optionally an initial list")
  370. elif not args:
  371. return cargs
  372. elif len(args) == 1:
  373. if isinstance(args[0], (Compiler, StaticLinker)):
  374. self.compiler = args[0]
  375. else:
  376. raise TypeError("you must pass a Compiler instance as one of "
  377. "the arguments")
  378. elif len(args) == 2:
  379. if isinstance(args[0], (Compiler, StaticLinker)):
  380. self.compiler = args[0]
  381. cargs = args[1]
  382. elif isinstance(args[1], (Compiler, StaticLinker)):
  383. cargs = args[0]
  384. self.compiler = args[1]
  385. else:
  386. raise TypeError("you must pass a Compiler instance as one of "
  387. "the two arguments")
  388. else:
  389. raise AssertionError('Not reached')
  390. return cargs
  391. def __init__(self, *args):
  392. super().__init__(self._check_args(args))
  393. @classmethod
  394. def _can_dedup(cls, arg):
  395. '''
  396. Returns whether the argument can be safely de-duped. This is dependent
  397. on three things:
  398. a) Whether an argument can be 'overriden' by a later argument. For
  399. example, -DFOO defines FOO and -UFOO undefines FOO. In this case, we
  400. can safely remove the previous occurance and add a new one. The same
  401. is true for include paths and library paths with -I and -L. For
  402. these we return `2`. See `dedup2_prefixes` and `dedup2_args`.
  403. b) Arguments that once specified cannot be undone, such as `-c` or
  404. `-pipe`. New instances of these can be completely skipped. For these
  405. we return `1`. See `dedup1_prefixes` and `dedup1_args`.
  406. c) Whether it matters where or how many times on the command-line
  407. a particular argument is present. This can matter for symbol
  408. resolution in static or shared libraries, so we cannot de-dup or
  409. reorder them. For these we return `0`. This is the default.
  410. In addition to these, we handle library arguments specially.
  411. With GNU ld, we surround library arguments with -Wl,--start/end-group
  412. to recursively search for symbols in the libraries. This is not needed
  413. with other linkers.
  414. '''
  415. # A standalone argument must never be deduplicated because it is
  416. # defined by what comes _after_ it. Thus dedupping this:
  417. # -D FOO -D BAR
  418. # would yield either
  419. # -D FOO BAR
  420. # or
  421. # FOO -D BAR
  422. # both of which are invalid.
  423. if arg in cls.dedup2_prefixes:
  424. return 0
  425. if arg in cls.dedup2_args or \
  426. arg.startswith(cls.dedup2_prefixes) or \
  427. arg.endswith(cls.dedup2_suffixes):
  428. return 2
  429. if arg in cls.dedup1_args or \
  430. arg.startswith(cls.dedup1_prefixes) or \
  431. arg.endswith(cls.dedup1_suffixes) or \
  432. re.search(cls.dedup1_regex, arg):
  433. return 1
  434. return 0
  435. @classmethod
  436. def _should_prepend(cls, arg):
  437. if arg.startswith(cls.prepend_prefixes):
  438. return True
  439. return False
  440. def to_native(self):
  441. # Check if we need to add --start/end-group for circular dependencies
  442. # between static libraries, and for recursively searching for symbols
  443. # needed by static libraries that are provided by object files or
  444. # shared libraries.
  445. if get_compiler_uses_gnuld(self.compiler):
  446. global soregex
  447. group_start = -1
  448. for each in self:
  449. if not each.startswith('-l') and not each.endswith('.a') and \
  450. not soregex.match(each):
  451. continue
  452. i = self.index(each)
  453. if group_start < 0:
  454. # First occurance of a library
  455. group_start = i
  456. if group_start >= 0:
  457. # Last occurance of a library
  458. self.insert(i + 1, '-Wl,--end-group')
  459. self.insert(group_start, '-Wl,--start-group')
  460. return self.compiler.unix_args_to_native(self)
  461. def append_direct(self, arg):
  462. '''
  463. Append the specified argument without any reordering or de-dup
  464. '''
  465. super().append(arg)
  466. def extend_direct(self, iterable):
  467. '''
  468. Extend using the elements in the specified iterable without any
  469. reordering or de-dup
  470. '''
  471. super().extend(iterable)
  472. def __add__(self, args):
  473. new = CompilerArgs(self, self.compiler)
  474. new += args
  475. return new
  476. def __iadd__(self, args):
  477. '''
  478. Add two CompilerArgs while taking into account overriding of arguments
  479. and while preserving the order of arguments as much as possible
  480. '''
  481. pre = []
  482. post = []
  483. if not isinstance(args, list):
  484. raise TypeError('can only concatenate list (not "{}") to list'.format(args))
  485. for arg in args:
  486. # If the argument can be de-duped, do it either by removing the
  487. # previous occurance of it and adding a new one, or not adding the
  488. # new occurance.
  489. dedup = self._can_dedup(arg)
  490. if dedup == 1:
  491. # Argument already exists and adding a new instance is useless
  492. if arg in self or arg in pre or arg in post:
  493. continue
  494. if dedup == 2:
  495. # Remove all previous occurances of the arg and add it anew
  496. if arg in self:
  497. self.remove(arg)
  498. if arg in pre:
  499. pre.remove(arg)
  500. if arg in post:
  501. post.remove(arg)
  502. if self._should_prepend(arg):
  503. pre.append(arg)
  504. else:
  505. post.append(arg)
  506. # Insert at the beginning
  507. self[:0] = pre
  508. # Append to the end
  509. super().__iadd__(post)
  510. return self
  511. def __radd__(self, args):
  512. new = CompilerArgs(args, self.compiler)
  513. new += self
  514. return new
  515. def __mul__(self, args):
  516. raise TypeError("can't multiply compiler arguments")
  517. def __imul__(self, args):
  518. raise TypeError("can't multiply compiler arguments")
  519. def __rmul__(self, args):
  520. raise TypeError("can't multiply compiler arguments")
  521. def append(self, arg):
  522. self.__iadd__([arg])
  523. def extend(self, args):
  524. self.__iadd__(args)
  525. class Compiler:
  526. # Libraries to ignore in find_library() since they are provided by the
  527. # compiler or the C library. Currently only used for MSVC.
  528. ignore_libs = ()
  529. def __init__(self, exelist, version):
  530. if isinstance(exelist, str):
  531. self.exelist = [exelist]
  532. elif isinstance(exelist, list):
  533. self.exelist = exelist
  534. else:
  535. raise TypeError('Unknown argument to Compiler')
  536. # In case it's been overriden by a child class already
  537. if not hasattr(self, 'file_suffixes'):
  538. self.file_suffixes = lang_suffixes[self.language]
  539. if not hasattr(self, 'can_compile_suffixes'):
  540. self.can_compile_suffixes = set(self.file_suffixes)
  541. self.default_suffix = self.file_suffixes[0]
  542. self.version = version
  543. self.base_options = []
  544. def __repr__(self):
  545. repr_str = "<{0}: v{1} `{2}`>"
  546. return repr_str.format(self.__class__.__name__, self.version,
  547. ' '.join(self.exelist))
  548. def can_compile(self, src):
  549. if hasattr(src, 'fname'):
  550. src = src.fname
  551. suffix = os.path.splitext(src)[1].lower()
  552. if suffix and suffix[1:] in self.can_compile_suffixes:
  553. return True
  554. return False
  555. def get_id(self):
  556. return self.id
  557. def get_language(self):
  558. return self.language
  559. def get_display_language(self):
  560. return self.language.capitalize()
  561. def get_default_suffix(self):
  562. return self.default_suffix
  563. def get_exelist(self):
  564. return self.exelist[:]
  565. def get_builtin_define(self, *args, **kwargs):
  566. raise EnvironmentException('%s does not support get_builtin_define.' % self.id)
  567. def has_builtin_define(self, *args, **kwargs):
  568. raise EnvironmentException('%s does not support has_builtin_define.' % self.id)
  569. def get_always_args(self):
  570. return []
  571. def get_linker_always_args(self):
  572. return []
  573. def gen_import_library_args(self, implibname):
  574. """
  575. Used only on Windows for libraries that need an import library.
  576. This currently means C, C++, Fortran.
  577. """
  578. return []
  579. def get_options(self):
  580. return {} # build afresh every time
  581. def get_option_compile_args(self, options):
  582. return []
  583. def get_option_link_args(self, options):
  584. return []
  585. def has_header(self, *args, **kwargs):
  586. raise EnvironmentException('Language %s does not support header checks.' % self.get_display_language())
  587. def has_header_symbol(self, *args, **kwargs):
  588. raise EnvironmentException('Language %s does not support header symbol checks.' % self.get_display_language())
  589. def compiles(self, *args, **kwargs):
  590. raise EnvironmentException('Language %s does not support compile checks.' % self.get_display_language())
  591. def links(self, *args, **kwargs):
  592. raise EnvironmentException('Language %s does not support link checks.' % self.get_display_language())
  593. def run(self, *args, **kwargs):
  594. raise EnvironmentException('Language %s does not support run checks.' % self.get_display_language())
  595. def sizeof(self, *args, **kwargs):
  596. raise EnvironmentException('Language %s does not support sizeof checks.' % self.get_display_language())
  597. def alignment(self, *args, **kwargs):
  598. raise EnvironmentException('Language %s does not support alignment checks.' % self.get_display_language())
  599. def has_function(self, *args, **kwargs):
  600. raise EnvironmentException('Language %s does not support function checks.' % self.get_display_language())
  601. @classmethod
  602. def unix_args_to_native(cls, args):
  603. "Always returns a copy that can be independently mutated"
  604. return args[:]
  605. def find_library(self, *args, **kwargs):
  606. raise EnvironmentException('Language {} does not support library finding.'.format(self.get_display_language()))
  607. def get_library_dirs(self):
  608. return []
  609. def has_argument(self, arg, env):
  610. return self.has_multi_arguments([arg], env)
  611. def has_multi_arguments(self, args, env):
  612. raise EnvironmentException(
  613. 'Language {} does not support has_multi_arguments.'.format(
  614. self.get_display_language()))
  615. def get_cross_extra_flags(self, environment, link):
  616. extra_flags = []
  617. if self.is_cross and environment:
  618. if 'properties' in environment.cross_info.config:
  619. props = environment.cross_info.config['properties']
  620. lang_args_key = self.language + '_args'
  621. extra_flags += props.get(lang_args_key, [])
  622. lang_link_args_key = self.language + '_link_args'
  623. if link:
  624. extra_flags += props.get(lang_link_args_key, [])
  625. return extra_flags
  626. def _get_compile_output(self, dirname, mode):
  627. # In pre-processor mode, the output is sent to stdout and discarded
  628. if mode == 'preprocess':
  629. return None
  630. # Extension only matters if running results; '.exe' is
  631. # guaranteed to be executable on every platform.
  632. if mode == 'link':
  633. suffix = 'exe'
  634. else:
  635. suffix = 'obj'
  636. return os.path.join(dirname, 'output.' + suffix)
  637. @contextlib.contextmanager
  638. def compile(self, code, extra_args=None, mode='link'):
  639. if extra_args is None:
  640. extra_args = []
  641. try:
  642. with tempfile.TemporaryDirectory() as tmpdirname:
  643. if isinstance(code, str):
  644. srcname = os.path.join(tmpdirname,
  645. 'testfile.' + self.default_suffix)
  646. with open(srcname, 'w') as ofile:
  647. ofile.write(code)
  648. elif isinstance(code, mesonlib.File):
  649. srcname = code.fname
  650. output = self._get_compile_output(tmpdirname, mode)
  651. # Construct the compiler command-line
  652. commands = CompilerArgs(self)
  653. commands.append(srcname)
  654. commands += extra_args
  655. commands += self.get_always_args()
  656. if mode == 'compile':
  657. commands += self.get_compile_only_args()
  658. # Preprocess mode outputs to stdout, so no output args
  659. if mode == 'preprocess':
  660. commands += self.get_preprocess_only_args()
  661. else:
  662. commands += self.get_output_args(output)
  663. # Generate full command-line with the exelist
  664. commands = self.get_exelist() + commands.to_native()
  665. mlog.debug('Running compile:')
  666. mlog.debug('Working directory: ', tmpdirname)
  667. mlog.debug('Command line: ', ' '.join(commands), '\n')
  668. mlog.debug('Code:\n', code)
  669. p, p.stdo, p.stde = Popen_safe(commands, cwd=tmpdirname)
  670. mlog.debug('Compiler stdout:\n', p.stdo)
  671. mlog.debug('Compiler stderr:\n', p.stde)
  672. p.input_name = srcname
  673. p.output_name = output
  674. yield p
  675. except (PermissionError, OSError):
  676. # On Windows antivirus programs and the like hold on to files so
  677. # they can't be deleted. There's not much to do in this case. Also,
  678. # catch OSError because the directory is then no longer empty.
  679. pass
  680. def get_colorout_args(self, colortype):
  681. return []
  682. # Some compilers (msvc) write debug info to a separate file.
  683. # These args specify where it should be written.
  684. def get_compile_debugfile_args(self, rel_obj, **kwargs):
  685. return []
  686. def get_link_debugfile_args(self, rel_obj):
  687. return []
  688. def get_std_shared_lib_link_args(self):
  689. return []
  690. def get_std_shared_module_link_args(self):
  691. return self.get_std_shared_lib_link_args()
  692. def get_link_whole_for(self, args):
  693. if isinstance(args, list) and not args:
  694. return []
  695. raise EnvironmentException('Language %s does not support linking whole archives.' % self.get_display_language())
  696. # Compiler arguments needed to enable the given instruction set.
  697. # May be [] meaning nothing needed or None meaning the given set
  698. # is not supported.
  699. def get_instruction_set_args(self, instruction_set):
  700. return None
  701. def build_unix_rpath_args(self, build_dir, from_dir, rpath_paths, build_rpath, install_rpath):
  702. if not rpath_paths and not install_rpath and not build_rpath:
  703. return []
  704. # The rpaths we write must be relative, because otherwise
  705. # they have different length depending on the build
  706. # directory. This breaks reproducible builds.
  707. rel_rpaths = []
  708. for p in rpath_paths:
  709. if p == from_dir:
  710. relative = '' # relpath errors out in this case
  711. else:
  712. relative = os.path.relpath(os.path.join(build_dir, p), os.path.join(build_dir, from_dir))
  713. rel_rpaths.append(relative)
  714. paths = ':'.join([os.path.join('$ORIGIN', p) for p in rel_rpaths])
  715. # Build_rpath is used as-is (it is usually absolute).
  716. if build_rpath != '':
  717. paths += ':' + build_rpath
  718. if len(paths) < len(install_rpath):
  719. padding = 'X' * (len(install_rpath) - len(paths))
  720. if not paths:
  721. paths = padding
  722. else:
  723. paths = paths + ':' + padding
  724. args = ['-Wl,-rpath,' + paths]
  725. if get_compiler_is_linuxlike(self):
  726. # Rpaths to use while linking must be absolute. These are not
  727. # written to the binary. Needed only with GNU ld:
  728. # https://sourceware.org/bugzilla/show_bug.cgi?id=16936
  729. # Not needed on Windows or other platforms that don't use RPATH
  730. # https://github.com/mesonbuild/meson/issues/1897
  731. lpaths = ':'.join([os.path.join(build_dir, p) for p in rpath_paths])
  732. args += ['-Wl,-rpath-link,' + lpaths]
  733. return args
  734. GCC_STANDARD = 0
  735. GCC_OSX = 1
  736. GCC_MINGW = 2
  737. GCC_CYGWIN = 3
  738. CLANG_STANDARD = 0
  739. CLANG_OSX = 1
  740. CLANG_WIN = 2
  741. # Possibly clang-cl?
  742. ICC_STANDARD = 0
  743. ICC_OSX = 1
  744. ICC_WIN = 2
  745. def get_gcc_soname_args(gcc_type, prefix, shlib_name, suffix, path, soversion, is_shared_module):
  746. if soversion is None:
  747. sostr = ''
  748. else:
  749. sostr = '.' + soversion
  750. if gcc_type in (GCC_STANDARD, GCC_MINGW, GCC_CYGWIN):
  751. # Might not be correct for mingw but seems to work.
  752. return ['-Wl,-soname,%s%s.%s%s' % (prefix, shlib_name, suffix, sostr)]
  753. elif gcc_type == GCC_OSX:
  754. if is_shared_module:
  755. return []
  756. return ['-install_name', os.path.join(path, 'lib' + shlib_name + '.dylib')]
  757. else:
  758. raise RuntimeError('Not implemented yet.')
  759. def get_compiler_is_linuxlike(compiler):
  760. if (getattr(compiler, 'gcc_type', None) == GCC_STANDARD) or \
  761. (getattr(compiler, 'clang_type', None) == CLANG_STANDARD) or \
  762. (getattr(compiler, 'icc_type', None) == ICC_STANDARD):
  763. return True
  764. return False
  765. def get_compiler_uses_gnuld(c):
  766. # FIXME: Perhaps we should detect the linker in the environment?
  767. # FIXME: Assumes that *BSD use GNU ld, but they might start using lld soon
  768. if (getattr(c, 'gcc_type', None) in (GCC_STANDARD, GCC_MINGW, GCC_CYGWIN)) or \
  769. (getattr(c, 'clang_type', None) in (CLANG_STANDARD, CLANG_WIN)) or \
  770. (getattr(c, 'icc_type', None) in (ICC_STANDARD, ICC_WIN)):
  771. return True
  772. return False
  773. def get_largefile_args(compiler):
  774. '''
  775. Enable transparent large-file-support for 32-bit UNIX systems
  776. '''
  777. if get_compiler_is_linuxlike(compiler):
  778. # Enable large-file support unconditionally on all platforms other
  779. # than macOS and Windows. macOS is now 64-bit-only so it doesn't
  780. # need anything special, and Windows doesn't have automatic LFS.
  781. # You must use the 64-bit counterparts explicitly.
  782. # glibc, musl, and uclibc, and all BSD libcs support this. On Android,
  783. # support for transparent LFS is available depending on the version of
  784. # Bionic: https://github.com/android/platform_bionic#32-bit-abi-bugs
  785. # https://code.google.com/p/android/issues/detail?id=64613
  786. #
  787. # If this breaks your code, fix it! It's been 20+ years!
  788. return ['-D_FILE_OFFSET_BITS=64']
  789. # We don't enable -D_LARGEFILE64_SOURCE since that enables
  790. # transitionary features and must be enabled by programs that use
  791. # those features explicitly.
  792. return []
  793. class GnuCompiler:
  794. # Functionality that is common to all GNU family compilers.
  795. def __init__(self, gcc_type, defines):
  796. self.id = 'gcc'
  797. self.gcc_type = gcc_type
  798. self.defines = defines or {}
  799. self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage',
  800. 'b_colorout', 'b_ndebug', 'b_staticpic']
  801. if self.gcc_type != GCC_OSX:
  802. self.base_options.append('b_lundef')
  803. self.base_options.append('b_asneeded')
  804. # All GCC backends can do assembly
  805. self.can_compile_suffixes.add('s')
  806. def get_colorout_args(self, colortype):
  807. if mesonlib.version_compare(self.version, '>=4.9.0'):
  808. return gnu_color_args[colortype][:]
  809. return []
  810. def get_warn_args(self, level):
  811. args = super().get_warn_args(level)
  812. if mesonlib.version_compare(self.version, '<4.8.0') and '-Wpedantic' in args:
  813. # -Wpedantic was added in 4.8.0
  814. # https://gcc.gnu.org/gcc-4.8/changes.html
  815. args[args.index('-Wpedantic')] = '-pedantic'
  816. return args
  817. def has_builtin_define(self, define):
  818. return define in self.defines
  819. def get_builtin_define(self, define):
  820. if define in self.defines:
  821. return self.defines[define]
  822. def get_pic_args(self):
  823. if self.gcc_type in (GCC_CYGWIN, GCC_MINGW, GCC_OSX):
  824. return [] # On Window and OS X, pic is always on.
  825. return ['-fPIC']
  826. def get_buildtype_args(self, buildtype):
  827. return gnulike_buildtype_args[buildtype]
  828. def get_buildtype_linker_args(self, buildtype):
  829. if self.gcc_type == GCC_OSX:
  830. return apple_buildtype_linker_args[buildtype]
  831. return gnulike_buildtype_linker_args[buildtype]
  832. def get_pch_suffix(self):
  833. return 'gch'
  834. def split_shlib_to_parts(self, fname):
  835. return os.path.split(fname)[0], fname
  836. def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
  837. return get_gcc_soname_args(self.gcc_type, prefix, shlib_name, suffix, path, soversion, is_shared_module)
  838. def get_std_shared_lib_link_args(self):
  839. return ['-shared']
  840. def get_link_whole_for(self, args):
  841. return ['-Wl,--whole-archive'] + args + ['-Wl,--no-whole-archive']
  842. def gen_vs_module_defs_args(self, defsfile):
  843. if not isinstance(defsfile, str):
  844. raise RuntimeError('Module definitions file should be str')
  845. # On Windows targets, .def files may be specified on the linker command
  846. # line like an object file.
  847. if self.gcc_type in (GCC_CYGWIN, GCC_MINGW):
  848. return [defsfile]
  849. # For other targets, discard the .def file.
  850. return []
  851. def get_gui_app_args(self):
  852. if self.gcc_type in (GCC_CYGWIN, GCC_MINGW):
  853. return ['-mwindows']
  854. return []
  855. def get_instruction_set_args(self, instruction_set):
  856. return gnulike_instruction_set_args.get(instruction_set, None)
  857. class ClangCompiler:
  858. def __init__(self, clang_type):
  859. self.id = 'clang'
  860. self.clang_type = clang_type
  861. self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage',
  862. 'b_ndebug', 'b_staticpic', 'b_colorout']
  863. if self.clang_type != CLANG_OSX:
  864. self.base_options.append('b_lundef')
  865. self.base_options.append('b_asneeded')
  866. # All Clang backends can do assembly and LLVM IR
  867. self.can_compile_suffixes.update(['ll', 's'])
  868. def get_pic_args(self):
  869. if self.clang_type in (CLANG_WIN, CLANG_OSX):
  870. return [] # On Window and OS X, pic is always on.
  871. return ['-fPIC']
  872. def get_colorout_args(self, colortype):
  873. return clang_color_args[colortype][:]
  874. def get_buildtype_args(self, buildtype):
  875. return gnulike_buildtype_args[buildtype]
  876. def get_buildtype_linker_args(self, buildtype):
  877. if self.clang_type == CLANG_OSX:
  878. return apple_buildtype_linker_args[buildtype]
  879. return gnulike_buildtype_linker_args[buildtype]
  880. def get_pch_suffix(self):
  881. return 'pch'
  882. def get_pch_use_args(self, pch_dir, header):
  883. # Workaround for Clang bug http://llvm.org/bugs/show_bug.cgi?id=15136
  884. # This flag is internal to Clang (or at least not documented on the man page)
  885. # so it might change semantics at any time.
  886. return ['-include-pch', os.path.join(pch_dir, self.get_pch_name(header))]
  887. def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
  888. if self.clang_type == CLANG_STANDARD:
  889. gcc_type = GCC_STANDARD
  890. elif self.clang_type == CLANG_OSX:
  891. gcc_type = GCC_OSX
  892. elif self.clang_type == CLANG_WIN:
  893. gcc_type = GCC_MINGW
  894. else:
  895. raise MesonException('Unreachable code when converting clang type to gcc type.')
  896. return get_gcc_soname_args(gcc_type, prefix, shlib_name, suffix, path, soversion, is_shared_module)
  897. def has_multi_arguments(self, args, env):
  898. return super().has_multi_arguments(
  899. ['-Werror=unknown-warning-option', '-Werror=unused-command-line-argument'] + args,
  900. env)
  901. def has_function(self, funcname, prefix, env, extra_args=None, dependencies=None):
  902. if extra_args is None:
  903. extra_args = []
  904. # Starting with XCode 8, we need to pass this to force linker
  905. # visibility to obey OS X and iOS minimum version targets with
  906. # -mmacosx-version-min, -miphoneos-version-min, etc.
  907. # https://github.com/Homebrew/homebrew-core/issues/3727
  908. if self.clang_type == CLANG_OSX and version_compare(self.version, '>=8.0'):
  909. extra_args.append('-Wl,-no_weak_imports')
  910. return super().has_function(funcname, prefix, env, extra_args, dependencies)
  911. def get_std_shared_module_link_args(self):
  912. if self.clang_type == CLANG_OSX:
  913. return ['-bundle', '-Wl,-undefined,dynamic_lookup']
  914. return ['-shared']
  915. def get_link_whole_for(self, args):
  916. if self.clang_type == CLANG_OSX:
  917. result = []
  918. for a in args:
  919. result += ['-Wl,-force_load', a]
  920. return result
  921. return ['-Wl,--whole-archive'] + args + ['-Wl,--no-whole-archive']
  922. def get_instruction_set_args(self, instruction_set):
  923. return gnulike_instruction_set_args.get(instruction_set, None)
  924. # Tested on linux for ICC 14.0.3, 15.0.6, 16.0.4, 17.0.1
  925. class IntelCompiler:
  926. def __init__(self, icc_type):
  927. self.id = 'intel'
  928. self.icc_type = icc_type
  929. self.lang_header = 'none'
  930. self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage',
  931. 'b_colorout', 'b_ndebug', 'b_staticpic', 'b_lundef', 'b_asneeded']
  932. # Assembly
  933. self.can_compile_suffixes.add('s')
  934. def get_pic_args(self):
  935. return ['-fPIC']
  936. def get_buildtype_args(self, buildtype):
  937. return gnulike_buildtype_args[buildtype]
  938. def get_buildtype_linker_args(self, buildtype):
  939. return gnulike_buildtype_linker_args[buildtype]
  940. def get_pch_suffix(self):
  941. return 'pchi'
  942. def get_pch_use_args(self, pch_dir, header):
  943. return ['-pch', '-pch_dir', os.path.join(pch_dir), '-x',
  944. self.lang_header, '-include', header, '-x', 'none']
  945. def get_pch_name(self, header_name):
  946. return os.path.split(header_name)[-1] + '.' + self.get_pch_suffix()
  947. def split_shlib_to_parts(self, fname):
  948. return os.path.split(fname)[0], fname
  949. def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
  950. if self.icc_type == ICC_STANDARD:
  951. gcc_type = GCC_STANDARD
  952. elif self.icc_type == ICC_OSX:
  953. gcc_type = GCC_OSX
  954. elif self.icc_type == ICC_WIN:
  955. gcc_type = GCC_MINGW
  956. else:
  957. raise MesonException('Unreachable code when converting icc type to gcc type.')
  958. return get_gcc_soname_args(gcc_type, prefix, shlib_name, suffix, path, soversion, is_shared_module)
  959. def get_std_shared_lib_link_args(self):
  960. # FIXME: Don't know how icc works on OSX
  961. # if self.icc_type == ICC_OSX:
  962. # return ['-bundle']
  963. return ['-shared']