c.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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 subprocess, os.path, re
  12. from .. import mlog
  13. from .. import coredata
  14. from . import compilers
  15. from ..mesonlib import (
  16. EnvironmentException, version_compare, Popen_safe, listify,
  17. for_windows, for_darwin, for_cygwin, for_haiku,
  18. )
  19. from .compilers import (
  20. GCC_MINGW,
  21. get_largefile_args,
  22. gnu_winlibs,
  23. msvc_buildtype_args,
  24. msvc_buildtype_linker_args,
  25. msvc_winlibs,
  26. vs32_instruction_set_args,
  27. vs64_instruction_set_args,
  28. ArmCompiler,
  29. ArmclangCompiler,
  30. ClangCompiler,
  31. Compiler,
  32. CompilerArgs,
  33. CrossNoRunException,
  34. GnuCompiler,
  35. ElbrusCompiler,
  36. IntelCompiler,
  37. RunResult,
  38. )
  39. class CCompiler(Compiler):
  40. library_dirs_cache = {}
  41. program_dirs_cache = {}
  42. find_library_cache = {}
  43. def __init__(self, exelist, version, is_cross, exe_wrapper=None, **kwargs):
  44. # If a child ObjC or CPP class has already set it, don't set it ourselves
  45. if not hasattr(self, 'language'):
  46. self.language = 'c'
  47. super().__init__(exelist, version, **kwargs)
  48. self.id = 'unknown'
  49. self.is_cross = is_cross
  50. self.can_compile_suffixes.add('h')
  51. if isinstance(exe_wrapper, str):
  52. self.exe_wrapper = [exe_wrapper]
  53. else:
  54. self.exe_wrapper = exe_wrapper
  55. # Set to None until we actually need to check this
  56. self.has_fatal_warnings_link_arg = None
  57. def needs_static_linker(self):
  58. return True # When compiling static libraries, so yes.
  59. def get_always_args(self):
  60. '''
  61. Args that are always-on for all C compilers other than MSVC
  62. '''
  63. return ['-pipe'] + get_largefile_args(self)
  64. def get_linker_debug_crt_args(self):
  65. """
  66. Arguments needed to select a debug crt for the linker
  67. This is only needed for MSVC
  68. """
  69. return []
  70. def get_no_stdinc_args(self):
  71. return ['-nostdinc']
  72. def get_no_stdlib_link_args(self):
  73. return ['-nostdlib']
  74. def get_warn_args(self, level):
  75. return self.warn_args[level]
  76. def get_no_warn_args(self):
  77. # Almost every compiler uses this for disabling warnings
  78. return ['-w']
  79. def get_soname_args(self, *args):
  80. return []
  81. def split_shlib_to_parts(self, fname):
  82. return None, fname
  83. # The default behavior is this, override in MSVC
  84. def build_rpath_args(self, build_dir, from_dir, rpath_paths, build_rpath, install_rpath):
  85. if self.id == 'clang' and self.clang_type == compilers.CLANG_OSX:
  86. return self.build_osx_rpath_args(build_dir, rpath_paths, build_rpath)
  87. return self.build_unix_rpath_args(build_dir, from_dir, rpath_paths, build_rpath, install_rpath)
  88. def get_dependency_gen_args(self, outtarget, outfile):
  89. return ['-MD', '-MQ', outtarget, '-MF', outfile]
  90. def depfile_for_object(self, objfile):
  91. return objfile + '.' + self.get_depfile_suffix()
  92. def get_depfile_suffix(self):
  93. return 'd'
  94. def get_exelist(self):
  95. return self.exelist[:]
  96. def get_linker_exelist(self):
  97. return self.exelist[:]
  98. def get_preprocess_only_args(self):
  99. return ['-E', '-P']
  100. def get_compile_only_args(self):
  101. return ['-c']
  102. def get_no_optimization_args(self):
  103. return ['-O0']
  104. def get_compiler_check_args(self):
  105. '''
  106. Get arguments useful for compiler checks such as being permissive in
  107. the code quality and not doing any optimization.
  108. '''
  109. return self.get_no_optimization_args()
  110. def get_output_args(self, target):
  111. return ['-o', target]
  112. def get_linker_output_args(self, outputname):
  113. return ['-o', outputname]
  114. def get_coverage_args(self):
  115. return ['--coverage']
  116. def get_coverage_link_args(self):
  117. return ['--coverage']
  118. def get_werror_args(self):
  119. return ['-Werror']
  120. def get_std_exe_link_args(self):
  121. return []
  122. def get_include_args(self, path, is_system):
  123. if path == '':
  124. path = '.'
  125. if is_system:
  126. return ['-isystem', path]
  127. return ['-I' + path]
  128. def get_std_shared_lib_link_args(self):
  129. return ['-shared']
  130. def get_library_dirs_real(self):
  131. env = os.environ.copy()
  132. env['LC_ALL'] = 'C'
  133. stdo = Popen_safe(self.exelist + ['--print-search-dirs'], env=env)[1]
  134. paths = []
  135. for line in stdo.split('\n'):
  136. if line.startswith('libraries:'):
  137. libstr = line.split('=', 1)[1]
  138. paths = [os.path.realpath(p) for p in libstr.split(':')]
  139. return paths
  140. def get_library_dirs(self):
  141. key = tuple(self.exelist)
  142. if key not in self.library_dirs_cache:
  143. self.library_dirs_cache[key] = self.get_library_dirs_real()
  144. return self.library_dirs_cache[key][:]
  145. def get_program_dirs_real(self):
  146. env = os.environ.copy()
  147. env['LC_ALL'] = 'C'
  148. stdo = Popen_safe(self.exelist + ['--print-search-dirs'], env=env)[1]
  149. paths = []
  150. for line in stdo.split('\n'):
  151. if line.startswith('programs:'):
  152. libstr = line.split('=', 1)[1]
  153. paths = [os.path.realpath(p) for p in libstr.split(':')]
  154. return paths
  155. def get_program_dirs(self):
  156. '''
  157. Programs used by the compiler. Also where toolchain DLLs such as
  158. libstdc++-6.dll are found with MinGW.
  159. '''
  160. key = tuple(self.exelist)
  161. if key not in self.program_dirs_cache:
  162. self.program_dirs_cache[key] = self.get_program_dirs_real()
  163. return self.program_dirs_cache[key][:]
  164. def get_pic_args(self):
  165. return ['-fPIC']
  166. def name_string(self):
  167. return ' '.join(self.exelist)
  168. def get_pch_use_args(self, pch_dir, header):
  169. return ['-include', os.path.basename(header)]
  170. def get_pch_name(self, header_name):
  171. return os.path.basename(header_name) + '.' + self.get_pch_suffix()
  172. def get_linker_search_args(self, dirname):
  173. return ['-L' + dirname]
  174. def get_default_include_dirs(self):
  175. return []
  176. def gen_export_dynamic_link_args(self, env):
  177. if for_windows(env.is_cross_build(), env) or for_cygwin(env.is_cross_build(), env):
  178. return ['-Wl,--export-all-symbols']
  179. elif for_darwin(env.is_cross_build(), env):
  180. return []
  181. else:
  182. return ['-Wl,-export-dynamic']
  183. def gen_import_library_args(self, implibname):
  184. """
  185. The name of the outputted import library
  186. This implementation is used only on Windows by compilers that use GNU ld
  187. """
  188. return ['-Wl,--out-implib=' + implibname]
  189. def sanity_check_impl(self, work_dir, environment, sname, code):
  190. mlog.debug('Sanity testing ' + self.get_display_language() + ' compiler:', ' '.join(self.exelist))
  191. mlog.debug('Is cross compiler: %s.' % str(self.is_cross))
  192. extra_flags = []
  193. source_name = os.path.join(work_dir, sname)
  194. binname = sname.rsplit('.', 1)[0]
  195. if self.is_cross:
  196. binname += '_cross'
  197. if self.exe_wrapper is None:
  198. # Linking cross built apps is painful. You can't really
  199. # tell if you should use -nostdlib or not and for example
  200. # on OSX the compiler binary is the same but you need
  201. # a ton of compiler flags to differentiate between
  202. # arm and x86_64. So just compile.
  203. extra_flags += self.get_cross_extra_flags(environment, link=False)
  204. extra_flags += self.get_compile_only_args()
  205. else:
  206. extra_flags += self.get_cross_extra_flags(environment, link=True)
  207. # Is a valid executable output for all toolchains and platforms
  208. binname += '.exe'
  209. # Write binary check source
  210. binary_name = os.path.join(work_dir, binname)
  211. with open(source_name, 'w') as ofile:
  212. ofile.write(code)
  213. # Compile sanity check
  214. cmdlist = self.exelist + extra_flags + [source_name] + self.get_output_args(binary_name)
  215. pc, stdo, stde = Popen_safe(cmdlist, cwd=work_dir)
  216. mlog.debug('Sanity check compiler command line:', ' '.join(cmdlist))
  217. mlog.debug('Sanity check compile stdout:')
  218. mlog.debug(stdo)
  219. mlog.debug('-----\nSanity check compile stderr:')
  220. mlog.debug(stde)
  221. mlog.debug('-----')
  222. if pc.returncode != 0:
  223. raise EnvironmentException('Compiler {0} can not compile programs.'.format(self.name_string()))
  224. # Run sanity check
  225. if self.is_cross:
  226. if self.exe_wrapper is None:
  227. # Can't check if the binaries run so we have to assume they do
  228. return
  229. cmdlist = self.exe_wrapper + [binary_name]
  230. else:
  231. cmdlist = [binary_name]
  232. mlog.debug('Running test binary command: ' + ' '.join(cmdlist))
  233. try:
  234. pe = subprocess.Popen(cmdlist)
  235. except Exception as e:
  236. raise EnvironmentException('Could not invoke sanity test executable: %s.' % str(e))
  237. pe.wait()
  238. if pe.returncode != 0:
  239. raise EnvironmentException('Executables created by {0} compiler {1} are not runnable.'.format(self.language, self.name_string()))
  240. def sanity_check(self, work_dir, environment):
  241. code = 'int main(int argc, char **argv) { int class=0; return class; }\n'
  242. return self.sanity_check_impl(work_dir, environment, 'sanitycheckc.c', code)
  243. def check_header(self, hname, prefix, env, extra_args=None, dependencies=None):
  244. fargs = {'prefix': prefix, 'header': hname}
  245. code = '''{prefix}
  246. #include <{header}>'''
  247. return self.compiles(code.format(**fargs), env, extra_args, dependencies)
  248. def has_header(self, hname, prefix, env, extra_args=None, dependencies=None):
  249. fargs = {'prefix': prefix, 'header': hname}
  250. code = '''{prefix}
  251. #ifdef __has_include
  252. #if !__has_include("{header}")
  253. #error "Header '{header}' could not be found"
  254. #endif
  255. #else
  256. #include <{header}>
  257. #endif'''
  258. return self.compiles(code.format(**fargs), env, extra_args,
  259. dependencies, 'preprocess')
  260. def has_header_symbol(self, hname, symbol, prefix, env, extra_args=None, dependencies=None):
  261. fargs = {'prefix': prefix, 'header': hname, 'symbol': symbol}
  262. t = '''{prefix}
  263. #include <{header}>
  264. int main () {{
  265. /* If it's not defined as a macro, try to use as a symbol */
  266. #ifndef {symbol}
  267. {symbol};
  268. #endif
  269. }}'''
  270. return self.compiles(t.format(**fargs), env, extra_args, dependencies)
  271. def _get_compiler_check_args(self, env, extra_args, dependencies, mode='compile'):
  272. if extra_args is None:
  273. extra_args = []
  274. elif isinstance(extra_args, str):
  275. extra_args = [extra_args]
  276. if dependencies is None:
  277. dependencies = []
  278. elif not isinstance(dependencies, list):
  279. dependencies = [dependencies]
  280. # Collect compiler arguments
  281. args = CompilerArgs(self)
  282. for d in dependencies:
  283. # Add compile flags needed by dependencies
  284. args += d.get_compile_args()
  285. if d.need_threads():
  286. args += self.thread_flags(env)
  287. elif d.need_openmp():
  288. args += self.openmp_flags()
  289. if mode == 'link':
  290. # Add link flags needed to find dependencies
  291. args += d.get_link_args()
  292. if d.need_threads():
  293. args += self.thread_link_flags(env)
  294. # Select a CRT if needed since we're linking
  295. if mode == 'link':
  296. args += self.get_linker_debug_crt_args()
  297. # Read c_args/cpp_args/etc from the cross-info file (if needed)
  298. args += self.get_cross_extra_flags(env, link=(mode == 'link'))
  299. if not self.is_cross:
  300. if mode == 'preprocess':
  301. # Add CPPFLAGS from the env.
  302. args += env.coredata.get_external_preprocess_args(self.language)
  303. elif mode == 'compile':
  304. # Add CFLAGS/CXXFLAGS/OBJCFLAGS/OBJCXXFLAGS from the env
  305. args += env.coredata.get_external_args(self.language)
  306. elif mode == 'link':
  307. # Add LDFLAGS from the env
  308. args += env.coredata.get_external_link_args(self.language)
  309. args += self.get_compiler_check_args()
  310. # extra_args must override all other arguments, so we add them last
  311. args += extra_args
  312. return args
  313. def compiles(self, code, env, extra_args=None, dependencies=None, mode='compile'):
  314. with self._build_wrapper(code, env, extra_args, dependencies, mode) as p:
  315. return p.returncode == 0
  316. def _build_wrapper(self, code, env, extra_args, dependencies=None, mode='compile', want_output=False):
  317. args = self._get_compiler_check_args(env, extra_args, dependencies, mode)
  318. return self.compile(code, args, mode, want_output=want_output)
  319. def links(self, code, env, extra_args=None, dependencies=None):
  320. return self.compiles(code, env, extra_args, dependencies, mode='link')
  321. def run(self, code, env, extra_args=None, dependencies=None):
  322. if self.is_cross and self.exe_wrapper is None:
  323. raise CrossNoRunException('Can not run test applications in this cross environment.')
  324. with self._build_wrapper(code, env, extra_args, dependencies, mode='link', want_output=True) as p:
  325. if p.returncode != 0:
  326. mlog.debug('Could not compile test file %s: %d\n' % (
  327. p.input_name,
  328. p.returncode))
  329. return RunResult(False)
  330. if self.is_cross:
  331. cmdlist = self.exe_wrapper + [p.output_name]
  332. else:
  333. cmdlist = p.output_name
  334. try:
  335. pe, so, se = Popen_safe(cmdlist)
  336. except Exception as e:
  337. mlog.debug('Could not run: %s (error: %s)\n' % (cmdlist, e))
  338. return RunResult(False)
  339. mlog.debug('Program stdout:\n')
  340. mlog.debug(so)
  341. mlog.debug('Program stderr:\n')
  342. mlog.debug(se)
  343. return RunResult(True, pe.returncode, so, se)
  344. def _compile_int(self, expression, prefix, env, extra_args, dependencies):
  345. fargs = {'prefix': prefix, 'expression': expression}
  346. t = '''#include <stdio.h>
  347. {prefix}
  348. int main() {{ static int a[1-2*!({expression})]; a[0]=0; return 0; }}'''
  349. return self.compiles(t.format(**fargs), env, extra_args, dependencies)
  350. def cross_compute_int(self, expression, low, high, guess, prefix, env, extra_args, dependencies):
  351. # Try user's guess first
  352. if isinstance(guess, int):
  353. if self._compile_int('%s == %d' % (expression, guess), prefix, env, extra_args, dependencies):
  354. return guess
  355. # If no bounds are given, compute them in the limit of int32
  356. maxint = 0x7fffffff
  357. minint = -0x80000000
  358. if not isinstance(low, int) or not isinstance(high, int):
  359. if self._compile_int('%s >= 0' % (expression), prefix, env, extra_args, dependencies):
  360. low = cur = 0
  361. while self._compile_int('%s > %d' % (expression, cur), prefix, env, extra_args, dependencies):
  362. low = cur + 1
  363. if low > maxint:
  364. raise EnvironmentException('Cross-compile check overflowed')
  365. cur = cur * 2 + 1
  366. if cur > maxint:
  367. cur = maxint
  368. high = cur
  369. else:
  370. low = cur = -1
  371. while self._compile_int('%s < %d' % (expression, cur), prefix, env, extra_args, dependencies):
  372. high = cur - 1
  373. if high < minint:
  374. raise EnvironmentException('Cross-compile check overflowed')
  375. cur = cur * 2
  376. if cur < minint:
  377. cur = minint
  378. low = cur
  379. else:
  380. # Sanity check limits given by user
  381. if high < low:
  382. raise EnvironmentException('high limit smaller than low limit')
  383. condition = '%s <= %d && %s >= %d' % (expression, high, expression, low)
  384. if not self._compile_int(condition, prefix, env, extra_args, dependencies):
  385. raise EnvironmentException('Value out of given range')
  386. # Binary search
  387. while low != high:
  388. cur = low + int((high - low) / 2)
  389. if self._compile_int('%s <= %d' % (expression, cur), prefix, env, extra_args, dependencies):
  390. high = cur
  391. else:
  392. low = cur + 1
  393. return low
  394. def compute_int(self, expression, low, high, guess, prefix, env, extra_args=None, dependencies=None):
  395. if extra_args is None:
  396. extra_args = []
  397. if self.is_cross:
  398. return self.cross_compute_int(expression, low, high, guess, prefix, env, extra_args, dependencies)
  399. fargs = {'prefix': prefix, 'expression': expression}
  400. t = '''#include<stdio.h>
  401. {prefix}
  402. int main(int argc, char **argv) {{
  403. printf("%ld\\n", (long)({expression}));
  404. return 0;
  405. }};'''
  406. res = self.run(t.format(**fargs), env, extra_args, dependencies)
  407. if not res.compiled:
  408. return -1
  409. if res.returncode != 0:
  410. raise EnvironmentException('Could not run compute_int test binary.')
  411. return int(res.stdout)
  412. def cross_sizeof(self, typename, prefix, env, extra_args=None, dependencies=None):
  413. if extra_args is None:
  414. extra_args = []
  415. fargs = {'prefix': prefix, 'type': typename}
  416. t = '''#include <stdio.h>
  417. {prefix}
  418. int main(int argc, char **argv) {{
  419. {type} something;
  420. }}'''
  421. if not self.compiles(t.format(**fargs), env, extra_args, dependencies):
  422. return -1
  423. return self.cross_compute_int('sizeof(%s)' % typename, None, None, None, prefix, env, extra_args, dependencies)
  424. def sizeof(self, typename, prefix, env, extra_args=None, dependencies=None):
  425. if extra_args is None:
  426. extra_args = []
  427. fargs = {'prefix': prefix, 'type': typename}
  428. if self.is_cross:
  429. return self.cross_sizeof(typename, prefix, env, extra_args, dependencies)
  430. t = '''#include<stdio.h>
  431. {prefix}
  432. int main(int argc, char **argv) {{
  433. printf("%ld\\n", (long)(sizeof({type})));
  434. return 0;
  435. }};'''
  436. res = self.run(t.format(**fargs), env, extra_args, dependencies)
  437. if not res.compiled:
  438. return -1
  439. if res.returncode != 0:
  440. raise EnvironmentException('Could not run sizeof test binary.')
  441. return int(res.stdout)
  442. def cross_alignment(self, typename, prefix, env, extra_args=None, dependencies=None):
  443. if extra_args is None:
  444. extra_args = []
  445. fargs = {'prefix': prefix, 'type': typename}
  446. t = '''#include <stdio.h>
  447. {prefix}
  448. int main(int argc, char **argv) {{
  449. {type} something;
  450. }}'''
  451. if not self.compiles(t.format(**fargs), env, extra_args, dependencies):
  452. return -1
  453. t = '''#include <stddef.h>
  454. {prefix}
  455. struct tmp {{
  456. char c;
  457. {type} target;
  458. }};'''
  459. return self.cross_compute_int('offsetof(struct tmp, target)', None, None, None, t.format(**fargs), env, extra_args, dependencies)
  460. def alignment(self, typename, prefix, env, extra_args=None, dependencies=None):
  461. if extra_args is None:
  462. extra_args = []
  463. if self.is_cross:
  464. return self.cross_alignment(typename, prefix, env, extra_args, dependencies)
  465. fargs = {'prefix': prefix, 'type': typename}
  466. t = '''#include <stdio.h>
  467. #include <stddef.h>
  468. {prefix}
  469. struct tmp {{
  470. char c;
  471. {type} target;
  472. }};
  473. int main(int argc, char **argv) {{
  474. printf("%d", (int)offsetof(struct tmp, target));
  475. return 0;
  476. }}'''
  477. res = self.run(t.format(**fargs), env, extra_args, dependencies)
  478. if not res.compiled:
  479. raise EnvironmentException('Could not compile alignment test.')
  480. if res.returncode != 0:
  481. raise EnvironmentException('Could not run alignment test binary.')
  482. align = int(res.stdout)
  483. if align == 0:
  484. raise EnvironmentException('Could not determine alignment of %s. Sorry. You might want to file a bug.' % typename)
  485. return align
  486. def get_define(self, dname, prefix, env, extra_args, dependencies):
  487. delim = '"MESON_GET_DEFINE_DELIMITER"'
  488. fargs = {'prefix': prefix, 'define': dname, 'delim': delim}
  489. code = '''
  490. {prefix}
  491. #ifndef {define}
  492. # define {define}
  493. #endif
  494. {delim}\n{define}'''
  495. args = self._get_compiler_check_args(env, extra_args, dependencies,
  496. mode='preprocess').to_native()
  497. with self.compile(code.format(**fargs), args, 'preprocess') as p:
  498. if p.returncode != 0:
  499. raise EnvironmentException('Could not get define {!r}'.format(dname))
  500. # Get the preprocessed value after the delimiter,
  501. # minus the extra newline at the end and
  502. # merge string literals.
  503. return CCompiler.concatenate_string_literals(p.stdo.split(delim + '\n')[-1][:-1])
  504. def get_return_value(self, fname, rtype, prefix, env, extra_args, dependencies):
  505. if rtype == 'string':
  506. fmt = '%s'
  507. cast = '(char*)'
  508. elif rtype == 'int':
  509. fmt = '%lli'
  510. cast = '(long long int)'
  511. else:
  512. raise AssertionError('BUG: Unknown return type {!r}'.format(rtype))
  513. fargs = {'prefix': prefix, 'f': fname, 'cast': cast, 'fmt': fmt}
  514. code = '''{prefix}
  515. #include <stdio.h>
  516. int main(int argc, char *argv[]) {{
  517. printf ("{fmt}", {cast} {f}());
  518. }}'''.format(**fargs)
  519. res = self.run(code, env, extra_args, dependencies)
  520. if not res.compiled:
  521. m = 'Could not get return value of {}()'
  522. raise EnvironmentException(m.format(fname))
  523. if rtype == 'string':
  524. return res.stdout
  525. elif rtype == 'int':
  526. try:
  527. return int(res.stdout.strip())
  528. except ValueError:
  529. m = 'Return value of {}() is not an int'
  530. raise EnvironmentException(m.format(fname))
  531. @staticmethod
  532. def _no_prototype_templ():
  533. """
  534. Try to find the function without a prototype from a header by defining
  535. our own dummy prototype and trying to link with the C library (and
  536. whatever else the compiler links in by default). This is very similar
  537. to the check performed by Autoconf for AC_CHECK_FUNCS.
  538. """
  539. # Define the symbol to something else since it is defined by the
  540. # includes or defines listed by the user or by the compiler. This may
  541. # include, for instance _GNU_SOURCE which must be defined before
  542. # limits.h, which includes features.h
  543. # Then, undef the symbol to get rid of it completely.
  544. head = '''
  545. #define {func} meson_disable_define_of_{func}
  546. {prefix}
  547. #include <limits.h>
  548. #undef {func}
  549. '''
  550. # Override any GCC internal prototype and declare our own definition for
  551. # the symbol. Use char because that's unlikely to be an actual return
  552. # value for a function which ensures that we override the definition.
  553. head += '''
  554. #ifdef __cplusplus
  555. extern "C"
  556. #endif
  557. char {func} ();
  558. '''
  559. # The actual function call
  560. main = '''
  561. int main () {{
  562. return {func} ();
  563. }}'''
  564. return head, main
  565. @staticmethod
  566. def _have_prototype_templ():
  567. """
  568. Returns a head-er and main() call that uses the headers listed by the
  569. user for the function prototype while checking if a function exists.
  570. """
  571. # Add the 'prefix', aka defines, includes, etc that the user provides
  572. # This may include, for instance _GNU_SOURCE which must be defined
  573. # before limits.h, which includes features.h
  574. head = '{prefix}\n#include <limits.h>\n'
  575. # We don't know what the function takes or returns, so return it as an int.
  576. # Just taking the address or comparing it to void is not enough because
  577. # compilers are smart enough to optimize it away. The resulting binary
  578. # is not run so we don't care what the return value is.
  579. main = '''\nint main() {{
  580. void *a = (void*) &{func};
  581. long b = (long) a;
  582. return (int) b;
  583. }}'''
  584. return head, main
  585. def has_function(self, funcname, prefix, env, extra_args=None, dependencies=None):
  586. """
  587. First, this function looks for the symbol in the default libraries
  588. provided by the compiler (stdlib + a few others usually). If that
  589. fails, it checks if any of the headers specified in the prefix provide
  590. an implementation of the function, and if that fails, it checks if it's
  591. implemented as a compiler-builtin.
  592. """
  593. if extra_args is None:
  594. extra_args = []
  595. # Short-circuit if the check is already provided by the cross-info file
  596. varname = 'has function ' + funcname
  597. varname = varname.replace(' ', '_')
  598. if self.is_cross:
  599. val = env.cross_info.config['properties'].get(varname, None)
  600. if val is not None:
  601. if isinstance(val, bool):
  602. return val
  603. raise EnvironmentException('Cross variable {0} is not a boolean.'.format(varname))
  604. fargs = {'prefix': prefix, 'func': funcname}
  605. # glibc defines functions that are not available on Linux as stubs that
  606. # fail with ENOSYS (such as e.g. lchmod). In this case we want to fail
  607. # instead of detecting the stub as a valid symbol.
  608. # We already included limits.h earlier to ensure that these are defined
  609. # for stub functions.
  610. stubs_fail = '''
  611. #if defined __stub_{func} || defined __stub___{func}
  612. fail fail fail this function is not going to work
  613. #endif
  614. '''
  615. # If we have any includes in the prefix supplied by the user, assume
  616. # that the user wants us to use the symbol prototype defined in those
  617. # includes. If not, then try to do the Autoconf-style check with
  618. # a dummy prototype definition of our own.
  619. # This is needed when the linker determines symbol availability from an
  620. # SDK based on the prototype in the header provided by the SDK.
  621. # Ignoring this prototype would result in the symbol always being
  622. # marked as available.
  623. if '#include' in prefix:
  624. head, main = self._have_prototype_templ()
  625. else:
  626. head, main = self._no_prototype_templ()
  627. templ = head + stubs_fail + main
  628. if self.links(templ.format(**fargs), env, extra_args, dependencies):
  629. return True
  630. # MSVC does not have compiler __builtin_-s.
  631. if self.get_id() == 'msvc':
  632. return False
  633. # Detect function as a built-in
  634. #
  635. # Some functions like alloca() are defined as compiler built-ins which
  636. # are inlined by the compiler and you can't take their address, so we
  637. # need to look for them differently. On nice compilers like clang, we
  638. # can just directly use the __has_builtin() macro.
  639. fargs['no_includes'] = '#include' not in prefix
  640. t = '''{prefix}
  641. int main() {{
  642. #ifdef __has_builtin
  643. #if !__has_builtin(__builtin_{func})
  644. #error "__builtin_{func} not found"
  645. #endif
  646. #elif ! defined({func})
  647. /* Check for __builtin_{func} only if no includes were added to the
  648. * prefix above, which means no definition of {func} can be found.
  649. * We would always check for this, but we get false positives on
  650. * MSYS2 if we do. Their toolchain is broken, but we can at least
  651. * give them a workaround. */
  652. #if {no_includes:d}
  653. __builtin_{func};
  654. #else
  655. #error "No definition for __builtin_{func} found in the prefix"
  656. #endif
  657. #endif
  658. }}'''
  659. return self.links(t.format(**fargs), env, extra_args, dependencies)
  660. def has_members(self, typename, membernames, prefix, env, extra_args=None, dependencies=None):
  661. if extra_args is None:
  662. extra_args = []
  663. fargs = {'prefix': prefix, 'type': typename, 'name': 'foo'}
  664. # Create code that accesses all members
  665. members = ''
  666. for member in membernames:
  667. members += '{}.{};\n'.format(fargs['name'], member)
  668. fargs['members'] = members
  669. t = '''{prefix}
  670. void bar() {{
  671. {type} {name};
  672. {members}
  673. }};'''
  674. return self.compiles(t.format(**fargs), env, extra_args, dependencies)
  675. def has_type(self, typename, prefix, env, extra_args, dependencies=None):
  676. fargs = {'prefix': prefix, 'type': typename}
  677. t = '''{prefix}
  678. void bar() {{
  679. sizeof({type});
  680. }};'''
  681. return self.compiles(t.format(**fargs), env, extra_args, dependencies)
  682. def symbols_have_underscore_prefix(self, env):
  683. '''
  684. Check if the compiler prefixes an underscore to global C symbols
  685. '''
  686. symbol_name = b'meson_uscore_prefix'
  687. code = '''#ifdef __cplusplus
  688. extern "C" {
  689. #endif
  690. void ''' + symbol_name.decode() + ''' () {}
  691. #ifdef __cplusplus
  692. }
  693. #endif
  694. '''
  695. args = self.get_cross_extra_flags(env, link=False)
  696. args += self.get_compiler_check_args()
  697. n = 'symbols_have_underscore_prefix'
  698. with self.compile(code, args, 'compile', want_output=True) as p:
  699. if p.returncode != 0:
  700. m = 'BUG: Unable to compile {!r} check: {}'
  701. raise RuntimeError(m.format(n, p.stdo))
  702. if not os.path.isfile(p.output_name):
  703. m = 'BUG: Can\'t find compiled test code for {!r} check'
  704. raise RuntimeError(m.format(n))
  705. with open(p.output_name, 'rb') as o:
  706. for line in o:
  707. # Check if the underscore form of the symbol is somewhere
  708. # in the output file.
  709. if b'_' + symbol_name in line:
  710. return True
  711. # Else, check if the non-underscored form is present
  712. elif symbol_name in line:
  713. return False
  714. raise RuntimeError('BUG: {!r} check failed unexpectedly'.format(n))
  715. def get_library_naming(self, env, libtype, strict=False):
  716. '''
  717. Get library prefixes and suffixes for the target platform ordered by
  718. priority
  719. '''
  720. stlibext = ['a']
  721. # We've always allowed libname to be both `foo` and `libfoo`,
  722. # and now people depend on it
  723. if strict and self.id != 'msvc': # lib prefix is not usually used with msvc
  724. prefixes = ['lib']
  725. else:
  726. prefixes = ['lib', '']
  727. # Library suffixes and prefixes
  728. if for_darwin(env.is_cross_build(), env):
  729. shlibext = ['dylib']
  730. elif for_windows(env.is_cross_build(), env):
  731. # FIXME: .lib files can be import or static so we should read the
  732. # file, figure out which one it is, and reject the wrong kind.
  733. if self.id == 'msvc':
  734. shlibext = ['lib']
  735. else:
  736. shlibext = ['dll.a', 'lib', 'dll']
  737. # Yep, static libraries can also be foo.lib
  738. stlibext += ['lib']
  739. elif for_cygwin(env.is_cross_build(), env):
  740. shlibext = ['dll', 'dll.a']
  741. prefixes = ['cyg'] + prefixes
  742. else:
  743. # Linux/BSDs
  744. shlibext = ['so']
  745. # Search priority
  746. if libtype in ('default', 'shared-static'):
  747. suffixes = shlibext + stlibext
  748. elif libtype == 'static-shared':
  749. suffixes = stlibext + shlibext
  750. elif libtype == 'shared':
  751. suffixes = shlibext
  752. elif libtype == 'static':
  753. suffixes = stlibext
  754. else:
  755. raise AssertionError('BUG: unknown libtype {!r}'.format(libtype))
  756. return prefixes, suffixes
  757. def find_library_real(self, libname, env, extra_dirs, code, libtype):
  758. # First try if we can just add the library as -l.
  759. # Gcc + co seem to prefer builtin lib dirs to -L dirs.
  760. # Only try to find std libs if no extra dirs specified.
  761. if not extra_dirs:
  762. args = ['-l' + libname]
  763. if self.links(code, env, extra_args=args):
  764. return args
  765. # Ensure that we won't modify the list that was passed to us
  766. extra_dirs = extra_dirs[:]
  767. # Search in the system libraries too
  768. extra_dirs += self.get_library_dirs()
  769. # Not found or we want to use a specific libtype? Try to find the
  770. # library file itself.
  771. prefixes, suffixes = self.get_library_naming(env, libtype)
  772. # Triply-nested loop!
  773. for d in extra_dirs:
  774. for suffix in suffixes:
  775. for prefix in prefixes:
  776. trial = os.path.join(d, prefix + libname + '.' + suffix)
  777. # as well as checking the path, we need to check compilation
  778. # with link-whole, as static libs (.a) need to be checked
  779. # to ensure they are the right architecture, e.g. 32bit or
  780. # 64-bit. Just a normal test link won't work as the .a file
  781. # doesn't seem to be checked by linker if there are no
  782. # unresolved symbols from the main C file.
  783. extra_link_args = self.get_link_whole_for([trial])
  784. extra_link_args = self.linker_to_compiler_args(extra_link_args)
  785. if (os.path.isfile(trial) and
  786. self.links(code, env,
  787. extra_args=extra_link_args)):
  788. return [trial]
  789. # XXX: For OpenBSD and macOS we (may) need to search for libfoo.x.y.z.dylib
  790. return None
  791. def find_library_impl(self, libname, env, extra_dirs, code, libtype):
  792. # These libraries are either built-in or invalid
  793. if libname in self.ignore_libs:
  794. return []
  795. if isinstance(extra_dirs, str):
  796. extra_dirs = [extra_dirs]
  797. key = (tuple(self.exelist), libname, tuple(extra_dirs), code, libtype)
  798. if key not in self.find_library_cache:
  799. value = self.find_library_real(libname, env, extra_dirs, code, libtype)
  800. self.find_library_cache[key] = value
  801. else:
  802. value = self.find_library_cache[key]
  803. if value is None:
  804. return None
  805. return value[:]
  806. def find_library(self, libname, env, extra_dirs, libtype='default'):
  807. code = 'int main(int argc, char **argv) { return 0; }'
  808. return self.find_library_impl(libname, env, extra_dirs, code, libtype)
  809. def thread_flags(self, env):
  810. if for_haiku(self.is_cross, env):
  811. return []
  812. return ['-pthread']
  813. def thread_link_flags(self, env):
  814. if for_haiku(self.is_cross, env):
  815. return []
  816. return ['-pthread']
  817. def linker_to_compiler_args(self, args):
  818. return args
  819. def has_arguments(self, args, env, code, mode):
  820. return self.compiles(code, env, extra_args=args, mode=mode)
  821. def has_multi_arguments(self, args, env):
  822. for arg in args[:]:
  823. # some compilers, e.g. GCC, don't warn for unsupported warning-disable
  824. # flags, so when we are testing a flag like "-Wno-forgotten-towel", also
  825. # check the equivalent enable flag too "-Wforgotten-towel"
  826. if arg.startswith('-Wno-'):
  827. args.append('-W' + arg[5:])
  828. if arg.startswith('-Wl,'):
  829. mlog.warning('{} looks like a linker argument, '
  830. 'but has_argument and other similar methods only '
  831. 'support checking compiler arguments. Using them '
  832. 'to check linker arguments are never supported, '
  833. 'and results are likely to be wrong regardless of '
  834. 'the compiler you are using. has_link_argument or '
  835. 'other similar method can be used instead.'
  836. .format(arg))
  837. code = 'int i;\n'
  838. return self.has_arguments(args, env, code, mode='compile')
  839. def has_multi_link_arguments(self, args, env):
  840. # First time we check for link flags we need to first check if we have
  841. # --fatal-warnings, otherwise some linker checks could give some
  842. # false positive.
  843. fatal_warnings_args = ['-Wl,--fatal-warnings']
  844. if self.has_fatal_warnings_link_arg is None:
  845. self.has_fatal_warnings_link_arg = False
  846. self.has_fatal_warnings_link_arg = self.has_multi_link_arguments(fatal_warnings_args, env)
  847. if self.has_fatal_warnings_link_arg:
  848. args = fatal_warnings_args + args
  849. args = self.linker_to_compiler_args(args)
  850. code = 'int main(int argc, char **argv) { return 0; }'
  851. return self.has_arguments(args, env, code, mode='link')
  852. @staticmethod
  853. def concatenate_string_literals(s):
  854. pattern = re.compile(r'(?P<pre>.*([^\\]")|^")(?P<str1>([^\\"]|\\.)*)"\s+"(?P<str2>([^\\"]|\\.)*)(?P<post>".*)')
  855. ret = s
  856. m = pattern.match(ret)
  857. while m:
  858. ret = ''.join(m.group('pre', 'str1', 'str2', 'post'))
  859. m = pattern.match(ret)
  860. return ret
  861. class ClangCCompiler(ClangCompiler, CCompiler):
  862. def __init__(self, exelist, version, clang_type, is_cross, exe_wrapper=None, **kwargs):
  863. CCompiler.__init__(self, exelist, version, is_cross, exe_wrapper, **kwargs)
  864. ClangCompiler.__init__(self, clang_type)
  865. default_warn_args = ['-Wall', '-Winvalid-pch']
  866. self.warn_args = {'1': default_warn_args,
  867. '2': default_warn_args + ['-Wextra'],
  868. '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  869. def get_options(self):
  870. opts = CCompiler.get_options(self)
  871. opts.update({'c_std': coredata.UserComboOption('c_std', 'C language standard to use',
  872. ['none', 'c89', 'c99', 'c11',
  873. 'gnu89', 'gnu99', 'gnu11'],
  874. 'none')})
  875. return opts
  876. def get_option_compile_args(self, options):
  877. args = []
  878. std = options['c_std']
  879. if std.value != 'none':
  880. args.append('-std=' + std.value)
  881. return args
  882. def get_option_link_args(self, options):
  883. return []
  884. def get_linker_always_args(self):
  885. basic = super().get_linker_always_args()
  886. if self.clang_type == compilers.CLANG_OSX:
  887. return basic + ['-Wl,-headerpad_max_install_names']
  888. return basic
  889. class ArmclangCCompiler(ArmclangCompiler, CCompiler):
  890. def __init__(self, exelist, version, is_cross, exe_wrapper=None, **kwargs):
  891. CCompiler.__init__(self, exelist, version, is_cross, exe_wrapper, **kwargs)
  892. ArmclangCompiler.__init__(self)
  893. default_warn_args = ['-Wall', '-Winvalid-pch']
  894. self.warn_args = {'1': default_warn_args,
  895. '2': default_warn_args + ['-Wextra'],
  896. '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  897. def get_options(self):
  898. opts = CCompiler.get_options(self)
  899. opts.update({'c_std': coredata.UserComboOption('c_std', 'C language standard to use',
  900. ['none', 'c90', 'c99', 'c11',
  901. 'gnu90', 'gnu99', 'gnu11'],
  902. 'none')})
  903. return opts
  904. def get_option_compile_args(self, options):
  905. args = []
  906. std = options['c_std']
  907. if std.value != 'none':
  908. args.append('-std=' + std.value)
  909. return args
  910. def get_option_link_args(self, options):
  911. return []
  912. class GnuCCompiler(GnuCompiler, CCompiler):
  913. def __init__(self, exelist, version, gcc_type, is_cross, exe_wrapper=None, defines=None, **kwargs):
  914. CCompiler.__init__(self, exelist, version, is_cross, exe_wrapper, **kwargs)
  915. GnuCompiler.__init__(self, gcc_type, defines)
  916. default_warn_args = ['-Wall', '-Winvalid-pch']
  917. self.warn_args = {'1': default_warn_args,
  918. '2': default_warn_args + ['-Wextra'],
  919. '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  920. def get_options(self):
  921. opts = CCompiler.get_options(self)
  922. opts.update({'c_std': coredata.UserComboOption('c_std', 'C language standard to use',
  923. ['none', 'c89', 'c99', 'c11',
  924. 'gnu89', 'gnu99', 'gnu11'],
  925. 'none')})
  926. if self.gcc_type == GCC_MINGW:
  927. opts.update({
  928. 'c_winlibs': coredata.UserArrayOption('c_winlibs', 'Standard Win libraries to link against',
  929. gnu_winlibs), })
  930. return opts
  931. def get_option_compile_args(self, options):
  932. args = []
  933. std = options['c_std']
  934. if std.value != 'none':
  935. args.append('-std=' + std.value)
  936. return args
  937. def get_option_link_args(self, options):
  938. if self.gcc_type == GCC_MINGW:
  939. return options['c_winlibs'].value[:]
  940. return []
  941. def get_std_shared_lib_link_args(self):
  942. return ['-shared']
  943. def get_pch_use_args(self, pch_dir, header):
  944. return ['-fpch-preprocess', '-include', os.path.basename(header)]
  945. class ElbrusCCompiler(GnuCCompiler, ElbrusCompiler):
  946. def __init__(self, exelist, version, gcc_type, is_cross, exe_wrapper=None, defines=None, **kwargs):
  947. GnuCCompiler.__init__(self, exelist, version, gcc_type, is_cross, exe_wrapper, defines, **kwargs)
  948. ElbrusCompiler.__init__(self, gcc_type, defines)
  949. # It does support some various ISO standards and c/gnu 90, 9x, 1x in addition to those which GNU CC supports.
  950. def get_options(self):
  951. opts = CCompiler.get_options(self)
  952. opts.update({'c_std': coredata.UserComboOption('c_std', 'C language standard to use',
  953. ['none', 'c89', 'c90', 'c9x', 'c99', 'c1x', 'c11',
  954. 'gnu89', 'gnu90', 'gnu9x', 'gnu99', 'gnu1x', 'gnu11',
  955. 'iso9899:2011', 'iso9899:1990', 'iso9899:199409', 'iso9899:1999'],
  956. 'none')})
  957. return opts
  958. # Elbrus C compiler does not have lchmod, but there is only linker warning, not compiler error.
  959. # So we should explicitly fail at this case.
  960. def has_function(self, funcname, prefix, env, extra_args=None, dependencies=None):
  961. if funcname == 'lchmod':
  962. return False
  963. else:
  964. return super().has_function(funcname, prefix, env, extra_args, dependencies)
  965. class IntelCCompiler(IntelCompiler, CCompiler):
  966. def __init__(self, exelist, version, icc_type, is_cross, exe_wrapper=None, **kwargs):
  967. CCompiler.__init__(self, exelist, version, is_cross, exe_wrapper, **kwargs)
  968. IntelCompiler.__init__(self, icc_type)
  969. self.lang_header = 'c-header'
  970. default_warn_args = ['-Wall', '-w3', '-diag-disable:remark', '-Wpch-messages']
  971. self.warn_args = {'1': default_warn_args,
  972. '2': default_warn_args + ['-Wextra'],
  973. '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  974. def get_options(self):
  975. opts = CCompiler.get_options(self)
  976. c_stds = ['c89', 'c99']
  977. g_stds = ['gnu89', 'gnu99']
  978. if version_compare(self.version, '>=16.0.0'):
  979. c_stds += ['c11']
  980. opts.update({'c_std': coredata.UserComboOption('c_std', 'C language standard to use',
  981. ['none'] + c_stds + g_stds,
  982. 'none')})
  983. return opts
  984. def get_option_compile_args(self, options):
  985. args = []
  986. std = options['c_std']
  987. if std.value != 'none':
  988. args.append('-std=' + std.value)
  989. return args
  990. def get_std_shared_lib_link_args(self):
  991. return ['-shared']
  992. def has_arguments(self, args, env, code, mode):
  993. return super().has_arguments(args + ['-diag-error', '10006'], env, code, mode)
  994. class VisualStudioCCompiler(CCompiler):
  995. std_warn_args = ['/W3']
  996. std_opt_args = ['/O2']
  997. ignore_libs = ('m', 'c', 'pthread')
  998. def __init__(self, exelist, version, is_cross, exe_wrap, is_64):
  999. CCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
  1000. self.id = 'msvc'
  1001. # /showIncludes is needed for build dependency tracking in Ninja
  1002. # See: https://ninja-build.org/manual.html#_deps
  1003. self.always_args = ['/nologo', '/showIncludes']
  1004. self.warn_args = {'1': ['/W2'],
  1005. '2': ['/W3'],
  1006. '3': ['/W4']}
  1007. self.base_options = ['b_pch', 'b_ndebug'] # FIXME add lto, pgo and the like
  1008. self.is_64 = is_64
  1009. # Override CCompiler.get_always_args
  1010. def get_always_args(self):
  1011. return self.always_args
  1012. def get_linker_debug_crt_args(self):
  1013. """
  1014. Arguments needed to select a debug crt for the linker
  1015. Sometimes we need to manually select the CRT (C runtime) to use with
  1016. MSVC. One example is when trying to link with static libraries since
  1017. MSVC won't auto-select a CRT for us in that case and will error out
  1018. asking us to select one.
  1019. """
  1020. return ['/MDd']
  1021. def get_buildtype_args(self, buildtype):
  1022. return msvc_buildtype_args[buildtype]
  1023. def get_buildtype_linker_args(self, buildtype):
  1024. return msvc_buildtype_linker_args[buildtype]
  1025. def get_pch_suffix(self):
  1026. return 'pch'
  1027. def get_pch_name(self, header):
  1028. chopped = os.path.basename(header).split('.')[:-1]
  1029. chopped.append(self.get_pch_suffix())
  1030. pchname = '.'.join(chopped)
  1031. return pchname
  1032. def get_pch_use_args(self, pch_dir, header):
  1033. base = os.path.basename(header)
  1034. pchname = self.get_pch_name(header)
  1035. return ['/FI' + base, '/Yu' + base, '/Fp' + os.path.join(pch_dir, pchname)]
  1036. def get_preprocess_only_args(self):
  1037. return ['/EP']
  1038. def get_compile_only_args(self):
  1039. return ['/c']
  1040. def get_no_optimization_args(self):
  1041. return ['/Od']
  1042. def get_output_args(self, target):
  1043. if target.endswith('.exe'):
  1044. return ['/Fe' + target]
  1045. return ['/Fo' + target]
  1046. def get_dependency_gen_args(self, outtarget, outfile):
  1047. return []
  1048. def get_linker_exelist(self):
  1049. return ['link'] # FIXME, should have same path as compiler.
  1050. def get_linker_always_args(self):
  1051. return ['/nologo']
  1052. def get_linker_output_args(self, outputname):
  1053. return ['/OUT:' + outputname]
  1054. def get_linker_search_args(self, dirname):
  1055. return ['/LIBPATH:' + dirname]
  1056. def linker_to_compiler_args(self, args):
  1057. return ['/link'] + args
  1058. def get_gui_app_args(self):
  1059. return ['/SUBSYSTEM:WINDOWS']
  1060. def get_pic_args(self):
  1061. return [] # PIC is handled by the loader on Windows
  1062. def get_std_shared_lib_link_args(self):
  1063. return ['/DLL']
  1064. def gen_vs_module_defs_args(self, defsfile):
  1065. if not isinstance(defsfile, str):
  1066. raise RuntimeError('Module definitions file should be str')
  1067. # With MSVC, DLLs only export symbols that are explicitly exported,
  1068. # so if a module defs file is specified, we use that to export symbols
  1069. return ['/DEF:' + defsfile]
  1070. def gen_pch_args(self, header, source, pchname):
  1071. objname = os.path.splitext(pchname)[0] + '.obj'
  1072. return objname, ['/Yc' + header, '/Fp' + pchname, '/Fo' + objname]
  1073. def gen_import_library_args(self, implibname):
  1074. "The name of the outputted import library"
  1075. return ['/IMPLIB:' + implibname]
  1076. def build_rpath_args(self, build_dir, from_dir, rpath_paths, build_rpath, install_rpath):
  1077. return []
  1078. def openmp_flags(self):
  1079. return ['/openmp']
  1080. # FIXME, no idea what these should be.
  1081. def thread_flags(self, env):
  1082. return []
  1083. def thread_link_flags(self, env):
  1084. return []
  1085. def get_options(self):
  1086. opts = CCompiler.get_options(self)
  1087. opts.update({'c_winlibs': coredata.UserArrayOption('c_winlibs',
  1088. 'Windows libs to link against.',
  1089. msvc_winlibs)})
  1090. return opts
  1091. def get_option_link_args(self, options):
  1092. return options['c_winlibs'].value[:]
  1093. @classmethod
  1094. def unix_args_to_native(cls, args):
  1095. result = []
  1096. for i in args:
  1097. # -mms-bitfields is specific to MinGW-GCC
  1098. # -pthread is only valid for GCC
  1099. if i in ('-mms-bitfields', '-pthread'):
  1100. continue
  1101. if i.startswith('-L'):
  1102. i = '/LIBPATH:' + i[2:]
  1103. # Translate GNU-style -lfoo library name to the import library
  1104. elif i.startswith('-l'):
  1105. name = i[2:]
  1106. if name in cls.ignore_libs:
  1107. # With MSVC, these are provided by the C runtime which is
  1108. # linked in by default
  1109. continue
  1110. else:
  1111. i = name + '.lib'
  1112. # -pthread in link flags is only used on Linux
  1113. elif i == '-pthread':
  1114. continue
  1115. result.append(i)
  1116. return result
  1117. def get_werror_args(self):
  1118. return ['/WX']
  1119. def get_include_args(self, path, is_system):
  1120. if path == '':
  1121. path = '.'
  1122. # msvc does not have a concept of system header dirs.
  1123. return ['-I' + path]
  1124. # Visual Studio is special. It ignores some arguments it does not
  1125. # understand and you can't tell it to error out on those.
  1126. # http://stackoverflow.com/questions/15259720/how-can-i-make-the-microsoft-c-compiler-treat-unknown-flags-as-errors-rather-t
  1127. def has_arguments(self, args, env, code, mode):
  1128. warning_text = '4044' if mode == 'link' else '9002'
  1129. with self._build_wrapper(code, env, extra_args=args, mode=mode) as p:
  1130. if p.returncode != 0:
  1131. return False
  1132. return not(warning_text in p.stde or warning_text in p.stdo)
  1133. def get_compile_debugfile_args(self, rel_obj, pch=False):
  1134. pdbarr = rel_obj.split('.')[:-1]
  1135. pdbarr += ['pdb']
  1136. args = ['/Fd' + '.'.join(pdbarr)]
  1137. # When generating a PDB file with PCH, all compile commands write
  1138. # to the same PDB file. Hence, we need to serialize the PDB
  1139. # writes using /FS since we do parallel builds. This slows down the
  1140. # build obviously, which is why we only do this when PCH is on.
  1141. # This was added in Visual Studio 2013 (MSVC 18.0). Before that it was
  1142. # always on: https://msdn.microsoft.com/en-us/library/dn502518.aspx
  1143. if pch and version_compare(self.version, '>=18.0'):
  1144. args = ['/FS'] + args
  1145. return args
  1146. def get_link_debugfile_args(self, targetfile):
  1147. pdbarr = targetfile.split('.')[:-1]
  1148. pdbarr += ['pdb']
  1149. return ['/DEBUG', '/PDB:' + '.'.join(pdbarr)]
  1150. def get_link_whole_for(self, args):
  1151. # Only since VS2015
  1152. args = listify(args)
  1153. return ['/WHOLEARCHIVE:' + x for x in args]
  1154. def get_instruction_set_args(self, instruction_set):
  1155. if self.is_64:
  1156. return vs64_instruction_set_args.get(instruction_set, None)
  1157. if self.version.split('.')[0] == '16' and instruction_set == 'avx':
  1158. # VS documentation says that this exists and should work, but
  1159. # it does not. The headers do not contain AVX intrinsics
  1160. # and the can not be called.
  1161. return None
  1162. return vs32_instruction_set_args.get(instruction_set, None)
  1163. def get_toolset_version(self):
  1164. # See boost/config/compiler/visualc.cpp for up to date mapping
  1165. try:
  1166. version = int(''.join(self.version.split('.')[0:2]))
  1167. except ValueError:
  1168. return None
  1169. if version < 1310:
  1170. return '7.0'
  1171. elif version < 1400:
  1172. return '7.1' # (Visual Studio 2003)
  1173. elif version < 1500:
  1174. return '8.0' # (Visual Studio 2005)
  1175. elif version < 1600:
  1176. return '9.0' # (Visual Studio 2008)
  1177. elif version < 1700:
  1178. return '10.0' # (Visual Studio 2010)
  1179. elif version < 1800:
  1180. return '11.0' # (Visual Studio 2012)
  1181. elif version < 1900:
  1182. return '12.0' # (Visual Studio 2013)
  1183. elif version < 1910:
  1184. return '14.0' # (Visual Studio 2015)
  1185. elif version < 1920:
  1186. return '14.1' # (Visual Studio 2017)
  1187. return None
  1188. def get_default_include_dirs(self):
  1189. if 'INCLUDE' not in os.environ:
  1190. return []
  1191. return os.environ['INCLUDE'].split(os.pathsep)
  1192. class ArmCCompiler(ArmCompiler, CCompiler):
  1193. def __init__(self, exelist, version, is_cross, exe_wrapper=None, **kwargs):
  1194. CCompiler.__init__(self, exelist, version, is_cross, exe_wrapper, **kwargs)
  1195. ArmCompiler.__init__(self)
  1196. def get_options(self):
  1197. opts = CCompiler.get_options(self)
  1198. opts.update({'c_std': coredata.UserComboOption('c_std', 'C language standard to use',
  1199. ['none', 'c90', 'c99'],
  1200. 'none')})
  1201. return opts
  1202. def get_option_compile_args(self, options):
  1203. args = []
  1204. std = options['c_std']
  1205. if std.value != 'none':
  1206. args.append('--' + std.value)
  1207. return args