ymake_conf.py 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590
  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. from __future__ import print_function
  4. import base64
  5. import itertools
  6. import json
  7. import logging
  8. import ntpath
  9. import optparse
  10. import os
  11. import posixpath
  12. import re
  13. import subprocess
  14. import sys
  15. import tempfile
  16. import six
  17. logger = logging.getLogger(__name__ if __name__ != '__main__' else 'ymake_conf.py')
  18. def init_logger(verbose):
  19. logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO)
  20. def find_conf(conf_file):
  21. script_dir = os.path.dirname(__file__)
  22. full_path = os.path.join(script_dir, conf_file)
  23. if os.path.exists(full_path):
  24. return full_path
  25. return None
  26. class DebugString(object):
  27. def __init__(self, get_string_func):
  28. self.get_string_func = get_string_func
  29. def __str__(self):
  30. return self.get_string_func()
  31. class ConfigureError(Exception):
  32. pass
  33. class Platform(object):
  34. def __init__(self, name, os, arch):
  35. """
  36. :type name: str
  37. :type os: str
  38. :type arch: str
  39. """
  40. self.name = name
  41. self.os = self._parse_os(os)
  42. self.arch = arch.lower()
  43. self.is_i386 = self.arch in ('i386', 'x86')
  44. self.is_i686 = self.arch == 'i686'
  45. self.is_x86 = self.is_i386 or self.is_i686
  46. self.is_x86_64 = self.arch in ('x86_64', 'amd64')
  47. self.is_intel = self.is_x86 or self.is_x86_64
  48. self.is_armv7 = self.arch in ('armv7', 'armv7a', 'armv7ahf', 'armv7a_neon', 'arm', 'armv7a_cortex_a9', 'armv7ahf_cortex_a35', 'armv7ahf_cortex_a53')
  49. self.is_armv8 = self.arch in ('armv8', 'armv8a', 'arm64', 'aarch64', 'armv8a_cortex_a35', 'armv8a_cortex_a53')
  50. self.is_armv8m = self.arch in ('armv8m_cortex_m33', 'armv8m_cortex_m23')
  51. self.is_armv7em = self.arch in ('armv7em_cortex_m4', 'armv7em_cortex_m7')
  52. self.is_arm64 = self.arch in ('arm64',)
  53. self.is_arm = self.is_armv7 or self.is_armv8 or self.is_armv8m or self.is_armv7em
  54. self.is_armv7_neon = self.arch in ('armv7a_neon', 'armv7ahf', 'armv7a_cortex_a9', 'armv7ahf_cortex_a35', 'armv7ahf_cortex_a53')
  55. self.is_armv7hf = self.arch in ('armv7ahf', 'armv7ahf_cortex_a35', 'armv7ahf_cortex_a53')
  56. self.is_armv5te = self.arch in ('armv5te_arm968e_s')
  57. self.is_rv32imc = self.arch in ('riscv32_esp',)
  58. self.is_riscv32 = self.is_rv32imc
  59. self.is_nds32 = self.arch in ('nds32le_elf_mculib_v5f',)
  60. self.is_tc32 = self.arch in ('tc32_elf',)
  61. self.is_xtensa = self.arch in ('xtensa_hifi5',)
  62. self.armv7_float_abi = None
  63. if self.is_armv7:
  64. if self.is_armv7hf:
  65. self.armv7_float_abi = 'hard'
  66. else:
  67. self.armv7_float_abi = 'softfp'
  68. self.is_cortex_a9 = self.arch in ('armv7a_cortex_a9',)
  69. self.is_cortex_a35 = self.arch in ('armv7ahf_cortex_a35', 'armv8a_cortex_a35')
  70. self.is_cortex_a53 = self.arch in ('armv7ahf_cortex_a53', 'armv8a_cortex_a53')
  71. self.is_cortex_m33 = self.arch in ('armv8m_cortex_m33',)
  72. self.is_cortex_m23 = self.arch in ('armv8m_cortex_m23',)
  73. self.is_cortex_m4 = self.arch in ('armv7em_cortex_m4',)
  74. self.is_cortex_m7 = self.arch in ('armv7em_cortex_m7')
  75. self.is_arm968e_s = self.arch in ('armv5te_arm968e_s')
  76. self.is_power8le = self.arch == 'ppc64le'
  77. self.is_power9le = self.arch == 'power9le'
  78. self.is_powerpc = self.is_power8le or self.is_power9le
  79. self.is_wasm64 = self.arch == 'wasm64'
  80. self.is_wasm = self.is_wasm64
  81. self.is_32_bit = self.is_x86 or self.is_armv5te or self.is_armv7 or self.is_armv8m or self.is_riscv32 or self.is_nds32 or self.is_armv7em or self.is_xtensa or self.is_tc32
  82. self.is_64_bit = self.is_x86_64 or self.is_armv8 or self.is_powerpc or self.is_wasm64
  83. assert self.is_32_bit or self.is_64_bit
  84. assert not (self.is_32_bit and self.is_64_bit)
  85. self.is_linux = self.os == 'linux' or 'yocto' in self.os
  86. self.is_linux_x86_64 = self.is_linux and self.is_x86_64
  87. self.is_linux_armv8 = self.is_linux and self.is_armv8
  88. self.is_linux_armv7 = self.is_linux and self.is_armv7
  89. self.is_linux_power8le = self.is_linux and self.is_power8le
  90. self.is_linux_power9le = self.is_linux and self.is_power9le
  91. self.is_linux_powerpc = self.is_linux_power8le or self.is_linux_power9le
  92. self.is_macos = self.os == 'macos'
  93. self.is_macos_x86_64 = self.is_macos and self.is_x86_64
  94. self.is_macos_arm64 = self.is_macos and self.is_arm64
  95. self.is_iossim = self.os == 'iossim' or (self.os == 'ios' and self.is_intel)
  96. self.is_ios = self.os == 'ios' or self.is_iossim
  97. self.is_apple = self.is_macos or self.is_ios
  98. self.is_windows = self.os == 'windows'
  99. self.is_windows_x86_64 = self.is_windows and self.is_x86_64
  100. self.is_android = self.os == 'android'
  101. if self.is_android:
  102. # This is default Android API level unless `-DANDROID_API` is specified in cmdline
  103. default_android_api = 21
  104. self.android_api = int(preset('ANDROID_API', default_android_api))
  105. self.is_cygwin = self.os == 'cygwin'
  106. self.is_yocto = self.os == 'yocto'
  107. self.is_emscripten = self.os == 'emscripten'
  108. self.is_none = self.os == 'none'
  109. self.is_posix = self.is_linux or self.is_apple or self.is_android or self.is_cygwin or self.is_yocto
  110. @staticmethod
  111. def from_json(data):
  112. name = data.get('visible_name', data['toolchain'])
  113. return Platform(name, os=data['os'], arch=data['arch'])
  114. @property
  115. def os_variables(self):
  116. # 'LINUX' variable, for backward compatibility
  117. yield self.os.upper()
  118. # 'OS_LINUX' variable
  119. yield 'OS_{}'.format(self.os.upper())
  120. # yocto is linux
  121. if 'yocto' in self.os:
  122. yield 'LINUX'
  123. yield 'OS_LINUX'
  124. if self.is_macos:
  125. yield 'DARWIN'
  126. yield 'OS_DARWIN'
  127. if self.is_iossim:
  128. yield 'IOS'
  129. yield 'OS_IOS'
  130. yield 'OS_IOSSIM'
  131. @property
  132. def arch_variables(self):
  133. return select_multiple((
  134. (self.is_i386 or self.is_i686, 'ARCH_I386'),
  135. (self.is_i686, 'ARCH_I686'),
  136. (self.is_x86_64, 'ARCH_X86_64'),
  137. (self.is_armv7, 'ARCH_ARM7'),
  138. (self.is_armv7_neon, 'ARCH_ARM7_NEON'),
  139. (self.is_armv8, 'ARCH_ARM64'),
  140. (self.is_armv8m, 'ARCH_ARM8M'),
  141. (self.is_armv7em, 'ARCH_ARM7EM'),
  142. (self.is_armv5te, 'ARCH_ARM5TE'),
  143. (self.is_arm, 'ARCH_ARM'),
  144. (self.is_linux_armv8 or self.is_macos_arm64, 'ARCH_AARCH64'),
  145. (self.is_powerpc, 'ARCH_PPC64LE'),
  146. (self.is_power8le, 'ARCH_POWER8LE'),
  147. (self.is_power9le, 'ARCH_POWER9LE'),
  148. (self.is_riscv32, 'ARCH_RISCV32'),
  149. (self.is_xtensa, 'ARCH_XTENSA'),
  150. (self.is_nds32, 'ARCH_NDS32'),
  151. (self.is_tc32, 'ARCH_TC32'),
  152. (self.is_wasm64, 'ARCH_WASM64'),
  153. (self.is_32_bit, 'ARCH_TYPE_32'),
  154. (self.is_64_bit, 'ARCH_TYPE_64'),
  155. ))
  156. @property
  157. def library_path_variables(self):
  158. return ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH']
  159. def find_in_dict(self, dict_, default=None):
  160. if dict_ is None:
  161. return default
  162. for key in six.iterkeys(dict_):
  163. if self._parse_os(key) == self.os:
  164. return dict_[key]
  165. return default
  166. @property
  167. def os_compat(self):
  168. if self.is_macos:
  169. return 'DARWIN'
  170. else:
  171. return self.os.upper()
  172. @property
  173. def canonized_platform(self):
  174. os = None
  175. if self.os == 'macos':
  176. os = 'darwin'
  177. elif self.os == 'windows':
  178. os = 'win32'
  179. else:
  180. os = self.os
  181. if self.arch != 'x86_64':
  182. return '-'.join([os, self.arch])
  183. else:
  184. return os
  185. def exe(self, *paths):
  186. if self.is_windows:
  187. return ntpath.join(*itertools.chain(paths[:-1], (paths[-1] + '.exe',)))
  188. else:
  189. return posixpath.join(*paths)
  190. def __str__(self):
  191. return '{name}-{os}-{arch}'.format(name=self.name, os=self.os, arch=self.arch)
  192. def __eq__(self, other):
  193. return (self.name, self.os, self.arch) == (other.name, other.os, other.arch)
  194. def __cmp__(self, other):
  195. return cmp((self.name, self.os, self.arch), (other.name, other.os, other.arch))
  196. def __hash__(self):
  197. return hash((self.name, self.os, self.arch))
  198. @staticmethod
  199. def _parse_os(os):
  200. os = os.lower()
  201. if os == 'darwin':
  202. return 'macos'
  203. if os in ('win', 'win32', 'win64'):
  204. return 'windows'
  205. if os.startswith('cygwin'):
  206. return 'cygwin'
  207. return os
  208. def which(prog):
  209. if os.path.exists(prog) and os.access(prog, os.X_OK):
  210. return prog
  211. # Ищем в $PATH только простые команды, без путей.
  212. if os.path.dirname(prog) != '':
  213. return None
  214. path = os.getenv('PATH', '')
  215. pathext = os.environ.get('PATHEXT')
  216. # На Windows %PATHEXT% указывает на список расширений, которые нужно проверять
  217. # при поиске команды в пути. Точное совпадение без расширения имеет приоритет.
  218. pathext = [''] if pathext is None else [''] + pathext.lower().split(os.pathsep)
  219. for dir_ in path.split(os.path.pathsep):
  220. for ext in pathext:
  221. p = os.path.join(dir_, prog + ext)
  222. if os.path.exists(p) and os.path.isfile(p) and os.access(p, os.X_OK):
  223. return p
  224. return None
  225. def get_stdout(command):
  226. stdout, code = get_stdout_and_code(command)
  227. return stdout if code == 0 else None
  228. def get_stdout_and_code(command):
  229. # noinspection PyBroadException
  230. try:
  231. process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  232. stdout, _ = process.communicate()
  233. return six.ensure_str(stdout), process.returncode
  234. except Exception as e:
  235. logger.info("While run: `%s`", e)
  236. return None, None
  237. def to_strings(o):
  238. if isinstance(o, (list, tuple)):
  239. for s in o:
  240. for ss in to_strings(s):
  241. yield ss
  242. else:
  243. if o is not None:
  244. if isinstance(o, bool):
  245. yield 'yes' if o else 'no'
  246. elif isinstance(o, (str, int)):
  247. yield str(o)
  248. else:
  249. raise ConfigureError('Unexpected value {} {}'.format(type(o), o))
  250. def emit(key, *value):
  251. print('{0}={1}'.format(key, ' '.join(to_strings(value))))
  252. def emit_with_comment(comment, key, *value):
  253. print('# {}'.format(comment))
  254. emit(key, *value)
  255. def emit_with_ignore_comment(key, *value):
  256. emit_with_comment('IGNORE YMAKE CONF CONTEXT', key, *value)
  257. def append(key, *value):
  258. print('{0}+={1}'.format(key, ' '.join(to_strings(value))))
  259. def emit_big(text):
  260. prefix = None
  261. first = True
  262. for line in text.split('\n'):
  263. if prefix is None:
  264. if not line:
  265. continue
  266. prefix = 0
  267. while prefix < len(line) and line[prefix] == ' ':
  268. prefix += 1
  269. if first: # Be pretty, prepend an empty line before the output
  270. print()
  271. first = False
  272. print(line[prefix:])
  273. class Variables(dict):
  274. def emit(self, with_ignore_comment=[]):
  275. with_ignore_comment_set = set(with_ignore_comment)
  276. for k in sorted(self.keys()):
  277. if k in with_ignore_comment_set:
  278. emit_with_ignore_comment(k, self[k])
  279. else:
  280. emit(k, self[k])
  281. def update_from_presets(self):
  282. for k in six.iterkeys(self):
  283. v = preset(k)
  284. if v is not None:
  285. self[k] = v
  286. def reset_if_any(self, value_check=None, reset_value=None):
  287. if value_check is None:
  288. def value_check(v_):
  289. return v_ is None
  290. if any(map(value_check, six.itervalues(self))):
  291. for k in six.iterkeys(self):
  292. self[k] = reset_value
  293. def format_env(env, list_separator=':'):
  294. def format_value(value):
  295. return value if isinstance(value, str) else ('\\' + list_separator).join(value)
  296. def format(kv):
  297. return '${env:"%s=%s"}' % (kv[0], format_value(kv[1]))
  298. return ' '.join(map(format, sorted(six.iteritems(env))))
  299. # TODO(somov): Проверить, используется ли это. Может быть, выпилить.
  300. def userify_presets(presets, keys):
  301. for key in keys:
  302. user_key = 'USER_{}'.format(key)
  303. values = [presets.pop(key, None), presets.get(user_key)]
  304. presets[user_key] = ' '.join(filter(None, values))
  305. def preset(key, default=None):
  306. return opts().presets.get(key, default)
  307. def is_positive(key):
  308. return is_positive_str(preset(key, ''))
  309. def is_positive_str(s):
  310. return s.lower() in ('yes', 'true', 'on', '1')
  311. def is_negative(key):
  312. return is_negative_str(preset(key, ''))
  313. def is_negative_str(s):
  314. return s.lower() in ('no', 'false', 'off', '0')
  315. def to_bool(s, default=None):
  316. if isinstance(s, six.string_types):
  317. if is_positive_str(s):
  318. return True
  319. if is_negative_str(s):
  320. return False
  321. if default is None:
  322. raise ConfigureError('{} is not a bool value'.format(s))
  323. return default
  324. def select(selectors, default=None, no_default=False):
  325. for enabled, value in selectors:
  326. if enabled:
  327. return value
  328. if no_default:
  329. raise ConfigureError()
  330. return default
  331. def select_multiple(selectors):
  332. for enabled, value in selectors:
  333. if enabled:
  334. yield value
  335. def unique(it):
  336. known = set()
  337. for i in it:
  338. if i not in known:
  339. known.add(i)
  340. yield i
  341. class Options(object):
  342. def __init__(self, argv):
  343. def parse_presets(raw_presets):
  344. presets = {}
  345. for p in raw_presets:
  346. toks = p.split('=', 1)
  347. name = toks[0]
  348. value = toks[1] if len(toks) >= 2 else ''
  349. presets[name] = value
  350. return presets
  351. parser = optparse.OptionParser(add_help_option=False)
  352. opt_group = optparse.OptionGroup(parser, 'Conf script options')
  353. opt_group.add_option('--toolchain-params', dest='toolchain_params', action='store', help='Set toolchain params via file')
  354. opt_group.add_option('-D', '--preset', dest='presets', action='append', default=[], help='set or override presets')
  355. opt_group.add_option('-l', '--local-distbuild', dest='local_distbuild', action='store_true', default=False, help='conf for local distbuild')
  356. parser.add_option_group(opt_group)
  357. self.options, self.arguments = parser.parse_args(argv)
  358. argv = self.arguments
  359. if len(argv) < 4:
  360. print('Usage: ArcRoot, --BuildType--, Verbosity, [Path to local.ymake]', file=sys.stderr)
  361. sys.exit(1)
  362. self.arcadia_root = argv[1]
  363. init_logger(argv[3] == 'verbose')
  364. # Эти переменные не надо использоваться напрямую. Их значения уже разбираются в других местах.
  365. self.build_type = argv[2].lower()
  366. self.local_distbuild = self.options.local_distbuild
  367. self.toolchain_params = self.options.toolchain_params
  368. self.presets = parse_presets(self.options.presets)
  369. userify_presets(self.presets, ('CFLAGS', 'CXXFLAGS', 'CONLYFLAGS', 'LDFLAGS', 'GO_COMPILE_FLAGS', 'GO_LINK_FLAGS'))
  370. Instance = None
  371. def opts():
  372. if Options.Instance is None:
  373. Options.Instance = Options(sys.argv)
  374. return Options.Instance
  375. class Profiler(object):
  376. Generic = 'generic'
  377. GProf = 'gprof'
  378. class Arcadia(object):
  379. def __init__(self, root):
  380. self.root = root
  381. class Build(object):
  382. def __init__(self, arcadia, build_type, toolchain_params, force_ignore_local_files=False):
  383. self.arcadia = arcadia
  384. self.params = self._load_json_from_base64(toolchain_params)
  385. self.build_type = build_type
  386. platform = self.params['platform']
  387. self.host = Platform.from_json(platform['host'])
  388. self.target = Platform.from_json(platform['target'])
  389. self.tc = self._get_toolchain_options()
  390. # TODO(somov): Удалить, когда перестанет использоваться.
  391. self.build_system = 'ymake'
  392. self.ignore_local_files = False
  393. dist_prefix = 'dist-'
  394. if self.build_type.startswith(dist_prefix):
  395. self.build_system = 'distbuild'
  396. self.build_type = self.build_type[len(dist_prefix):]
  397. if force_ignore_local_files:
  398. self.ignore_local_files = True
  399. if self.is_ide_build_type(self.build_type):
  400. self.ignore_local_files = True
  401. self.pic = not is_positive('FORCE_NO_PIC')
  402. @property
  403. def host_target(self):
  404. return self.host, self.target
  405. def print_build(self):
  406. self._print_build_settings()
  407. host_os = System(self.host)
  408. host_os.print_host_settings()
  409. target_os = System(self.target)
  410. target_os.print_target_settings()
  411. if self.pic:
  412. emit('PIC', 'yes')
  413. emit('COMPILER_ID', self.tc.type.upper())
  414. if self.is_valgrind:
  415. emit('WITH_VALGRIND', 'yes')
  416. if self.is_coverage:
  417. emit('_BUILD_COVERAGE', 'yes')
  418. if self.is_debug:
  419. emit('_BUILD_DEBUG', 'yes')
  420. if self.is_fast_debug:
  421. emit('_BUILD_FAST_DEBUG', 'yes')
  422. if self.is_release:
  423. emit('_BUILD_RELEASE', 'yes')
  424. if self.is_sanitized:
  425. emit('_BUILD_SANITIZED', 'yes')
  426. if self.is_size_optimized:
  427. emit('_BUILD_SIZE_OPTIMIZED', 'yes')
  428. if self.with_ndebug:
  429. emit('_BUILD_WITH_NDEBUG', 'yes')
  430. toolchain_type, compiler_type, linker_type = Compilers[self.tc.type]
  431. toolchain = toolchain_type(self.tc, self)
  432. compiler = compiler_type(self.tc, self)
  433. linker = linker_type(self.tc, self)
  434. toolchain.print_toolchain()
  435. compiler.print_compiler()
  436. linker.print_linker()
  437. self._print_other_settings(compiler)
  438. def _print_build_settings(self):
  439. emit('BUILD_TYPE', self.build_type.upper())
  440. emit('BT_' + self.build_type.upper().replace('-', '_'), 'yes')
  441. if self.build_system == 'distbuild':
  442. emit('DISTBUILD', 'yes')
  443. elif self.build_system != 'ymake':
  444. raise ConfigureError()
  445. python_bin = preset('BUILD_PYTHON_BIN', '$(PYTHON)/python')
  446. emit('YMAKE_PYTHON', python_bin)
  447. emit('YMAKE_UNPICKLER', python_bin, '$ARCADIA_ROOT/build/plugins/_unpickler.py')
  448. @property
  449. def is_release(self):
  450. # TODO(somov): Проверить, бывают ли тут суффиксы на самом деле
  451. return self.build_type in ('release', 'relwithdebinfo', 'minsizerel', 'profile', 'gprof') or self.build_type.endswith('-release')
  452. @property
  453. def is_debug(self):
  454. return self.build_type in ('debug', 'debugnoasserts', 'fastdebug') or self.build_type.endswith('-debug')
  455. @property
  456. def is_fast_debug(self):
  457. return self.build_type == 'fastdebug'
  458. @property
  459. def is_size_optimized(self):
  460. return self.build_type == 'minsizerel'
  461. @property
  462. def is_coverage(self):
  463. return self.build_type == 'coverage'
  464. @property
  465. def is_sanitized(self):
  466. sanitizer = preset('SANITIZER_TYPE')
  467. return bool(sanitizer) and not is_negative_str(sanitizer)
  468. @property
  469. def with_ndebug(self):
  470. return self.build_type in ('release', 'minsizerel', 'valgrind-release', 'profile', 'gprof', 'debugnoasserts')
  471. @property
  472. def is_valgrind(self):
  473. return self.build_type == 'valgrind' or self.build_type == 'valgrind-release'
  474. @property
  475. def is_ide(self):
  476. return self.is_ide_build_type(self.build_type)
  477. @property
  478. def profiler_type(self):
  479. if self.build_type == 'profile':
  480. return Profiler.Generic
  481. elif self.build_type == 'gprof':
  482. return Profiler.GProf
  483. else:
  484. return None
  485. @staticmethod
  486. def is_ide_build_type(build_type):
  487. return build_type == 'nobuild'
  488. def _configure_runtime_versions(self):
  489. try:
  490. res = subprocess.check_output(['xcrun', 'simctl', 'list', '--json', 'runtimes'])
  491. except subprocess.CalledProcessError as exc:
  492. logger.warning(exc)
  493. return
  494. raw_object = json.loads(res)
  495. raw_object = raw_object['runtimes']
  496. for runtime in raw_object:
  497. if runtime['isAvailable']:
  498. if "iOS" in runtime['identifier']:
  499. emit('DEFAULT_IOS_RUNTIME', '{}'.format(runtime['identifier']))
  500. def _get_toolchain_options(self):
  501. type_ = self.params['params']['type']
  502. if self.params['params'].get('local') and type_ == 'xcode':
  503. detector = CompilerDetector()
  504. detector.detect(self.params['params']['c_compiler'], self.params['params']['cxx_compiler'])
  505. emit('LOCAL_XCODE_TOOLS', 'yes')
  506. emit('XCODE', 'yes')
  507. emit('ACTOOL_PATH', self.params['params']['actool'])
  508. emit('IBTOOL_PATH', self.params['params']['ibtool'])
  509. self._configure_runtime_versions()
  510. elif type_ == 'system_cxx':
  511. detector = CompilerDetector()
  512. detector.detect(self.params['params'].get('c_compiler'), self.params['params'].get('cxx_compiler'))
  513. type_ = detector.type
  514. else:
  515. detector = None
  516. if type_ == 'msvc':
  517. return MSVCToolchainOptions(self, detector)
  518. else:
  519. return GnuToolchainOptions(self, detector)
  520. def _print_other_settings(self, compiler):
  521. host = self.host
  522. emit('USE_LOCAL_TOOLS', 'no' if self.ignore_local_files else 'yes')
  523. ragel = Ragel()
  524. ragel.configure_toolchain(self, compiler)
  525. ragel.print_variables()
  526. swiftc = SwiftCompiler(self)
  527. swiftc.configure()
  528. swiftc.print_compiler()
  529. if host.is_linux or host.is_macos or host.is_cygwin:
  530. if is_negative('USE_ARCADIA_PYTHON'):
  531. python = Python(self.tc)
  532. python.configure_posix()
  533. python.print_variables()
  534. cuda = Cuda(self)
  535. cuda.print_()
  536. CuDNN(cuda).print_()
  537. if self.ignore_local_files or host.is_windows or is_positive('NO_SVN_DEPENDS'):
  538. emit_with_ignore_comment('SVN_DEPENDS_CACHE__NO_UID__')
  539. else:
  540. emit_with_ignore_comment('SVN_DEPENDS_CACHE__NO_UID__', '${hide;kv:"disable_cache"}')
  541. @staticmethod
  542. def _load_json_from_base64(base64str):
  543. """
  544. :rtype: dict[str, Any]
  545. """
  546. def un_unicode(o):
  547. if isinstance(o, six.text_type):
  548. return six.ensure_str(o)
  549. if isinstance(o, list):
  550. return [un_unicode(oo) for oo in o]
  551. if isinstance(o, dict):
  552. return {un_unicode(k): un_unicode(v) for k, v in six.iteritems(o)}
  553. return o
  554. return un_unicode(json.loads(base64.b64decode(base64str)))
  555. class YMake(object):
  556. def __init__(self, arcadia):
  557. self.arcadia = arcadia
  558. def print_presets(self):
  559. presets = opts().presets
  560. if is_positive_str(presets.get('EXPORT_GRADLE', 'no')):
  561. print('@import "${CONF_ROOT}/conf/export_gradle.yes.conf"')
  562. else:
  563. print('@import "${CONF_ROOT}/conf/export_gradle.no.conf"')
  564. if presets.get('CLANG_COVERAGE', None) is None:
  565. print('@import "${CONF_ROOT}/conf/coverage_full_instrumentation.conf"')
  566. else:
  567. print('@import "${CONF_ROOT}/conf/coverage_selective_instrumentation.conf"')
  568. if presets:
  569. print('# Variables set from command line by -D options')
  570. for key in sorted(presets):
  571. emit(key, opts().presets[key])
  572. @staticmethod
  573. def _print_conf_content(path):
  574. with open(path, 'r') as fin:
  575. print(fin.read())
  576. def print_core_conf(self):
  577. print('@import "${CONF_ROOT}/ymake.core.conf"')
  578. def print_settings(self):
  579. pass
  580. class System(object):
  581. def __init__(self, platform):
  582. """
  583. :type platform: Platform
  584. """
  585. self.platform = platform
  586. def print_windows_target_const(self):
  587. # TODO(somov): Remove this variables, use generic OS/arch variables in makelists.
  588. emit('WINDOWS', 'yes')
  589. emit('WIN32', 'yes')
  590. if self.platform.is_64_bit == 64:
  591. emit('WIN64', 'yes')
  592. def print_nix_target_const(self):
  593. emit('JAVA_INCLUDE', '-I{0}/include -I{0}/include/{1}'.format('/usr/lib/jvm/default-java', self.platform.os_compat))
  594. emit('UNIX', 'yes')
  595. emit('REALPRJNAME')
  596. emit('SONAME')
  597. def print_target_settings(self):
  598. emit('TARGET_PLATFORM', self.platform.os_compat)
  599. emit('CANONIZED_TARGET_PLATFORM', self.platform.canonized_platform)
  600. emit('HARDWARE_ARCH', '32' if self.platform.is_32_bit else '64')
  601. emit('HARDWARE_TYPE', self.platform.arch)
  602. for variable in self.platform.arch_variables:
  603. emit(variable, 'yes')
  604. for variable in self.platform.os_variables:
  605. emit(variable, 'yes')
  606. if self.platform.is_armv7:
  607. emit('ARM7_FLOAT_ABI', self.platform.armv7_float_abi)
  608. if self.platform.is_android:
  609. emit('ANDROID_API', str(self.platform.android_api))
  610. if self.platform.is_posix:
  611. self.print_nix_target_const()
  612. elif self.platform.is_windows:
  613. self.print_windows_target_const()
  614. def print_host_settings(self):
  615. emit('HOST_PLATFORM', self.platform.os_compat)
  616. emit('CANONIZED_HOST_PLATFORM', self.platform.canonized_platform)
  617. for variable in itertools.chain(self.platform.os_variables, self.platform.arch_variables):
  618. emit('HOST_{var}'.format(var=variable), 'yes')
  619. class CompilerDetector(object):
  620. def __init__(self):
  621. self.type = None
  622. self.c_compiler = None
  623. self.cxx_compiler = None
  624. self.version_list = None
  625. @staticmethod
  626. def preprocess_source(compiler, source):
  627. # noinspection PyBroadException
  628. try:
  629. fd, path = tempfile.mkstemp(suffix='.cpp')
  630. try:
  631. with os.fdopen(fd, 'w') as output:
  632. output.write(source)
  633. stdout, code = get_stdout_and_code([compiler, '-E', path])
  634. except Exception as e:
  635. logger.info("While writing: `%s`", e)
  636. finally:
  637. os.remove(path)
  638. return stdout, code
  639. except Exception as e:
  640. logger.debug('Preprocessing failed: %s', e)
  641. return None, None
  642. @staticmethod
  643. def get_compiler_vars(compiler, names):
  644. prefix = '____YA_VAR_'
  645. source = '\n'.join(['{prefix}{name}={name}\n'.format(prefix=prefix, name=n) for n in names])
  646. # Некоторые препроцессоры возвращают ненулевой код возврата. Поэтому его проверять нельзя.
  647. # Мы можем только удостовериться после разбора stdout, что в нём
  648. # присутствовала хотя бы одна подставленная переменная.
  649. # TODO(somov): Исследовать, можно ли проверять ограниченный набор кодов возврата.
  650. # TODO(v-korovin): Нормально прокидывать Exception-ы, оно и так упадёт
  651. stdout, _ = CompilerDetector.preprocess_source(compiler, source)
  652. if stdout is None:
  653. return None
  654. vars_ = {}
  655. for line in six.ensure_str(stdout).split('\n'):
  656. parts = line.split('=', 1)
  657. if len(parts) == 2 and parts[0].startswith(prefix):
  658. name, value = parts[0][len(prefix):], parts[1]
  659. if value == name:
  660. continue # Preprocessor variable was not substituted
  661. vars_[name] = value
  662. return vars_
  663. def detect(self, c_compiler=None, cxx_compiler=None):
  664. c_compiler = c_compiler or os.environ.get('CC')
  665. cxx_compiler = cxx_compiler or os.environ.get('CXX') or c_compiler
  666. c_compiler = c_compiler or cxx_compiler
  667. logger.debug('e=%s', os.environ)
  668. if c_compiler is None:
  669. raise ConfigureError('Custom compiler was requested but not specified')
  670. c_compiler_path = which(c_compiler)
  671. clang_vars = ['__clang_major__', '__clang_minor__', '__clang_patchlevel__']
  672. gcc_vars = ['__GNUC__', '__GNUC_MINOR__', '__GNUC_PATCHLEVEL__']
  673. msvc_vars = ['_MSC_VER']
  674. apple_var = '__apple_build_version__'
  675. compiler_vars = self.get_compiler_vars(c_compiler_path, clang_vars + [apple_var] + gcc_vars + msvc_vars)
  676. if not compiler_vars:
  677. raise ConfigureError('Could not determine custom compiler version: {}'.format(c_compiler))
  678. def version(version_names):
  679. def iter_version():
  680. for name in version_names:
  681. yield int(compiler_vars[name])
  682. # noinspection PyBroadException
  683. try:
  684. return list(iter_version())
  685. except Exception:
  686. return None
  687. clang_version = version(clang_vars)
  688. apple_build = apple_var in compiler_vars
  689. # TODO(somov): Учитывать номера версий сборки Apple компилятора Clang.
  690. _ = apple_build
  691. gcc_version = version(gcc_vars)
  692. msvc_version = version(msvc_vars)
  693. if clang_version:
  694. logger.debug('Detected Clang version %s', clang_version)
  695. self.type = 'clang'
  696. elif gcc_version:
  697. logger.debug('Detected GCC version %s', gcc_version)
  698. # TODO(somov): Переименовать в gcc.
  699. self.type = 'gnu'
  700. elif msvc_version:
  701. logger.debug('Detected MSVC version %s', msvc_version)
  702. self.type = 'msvc'
  703. else:
  704. raise ConfigureError('Could not determine custom compiler type: {}'.format(c_compiler))
  705. self.version_list = clang_version or gcc_version or msvc_version
  706. self.c_compiler = c_compiler_path
  707. self.cxx_compiler = cxx_compiler and which(cxx_compiler) or c_compiler_path
  708. class ToolchainOptions(object):
  709. def __init__(self, build, detector):
  710. """
  711. :type build: Build
  712. """
  713. self.host = build.host
  714. self.target = build.target
  715. tc_json = build.params
  716. logger.debug('Toolchain host %s', self.host)
  717. logger.debug('Toolchain target %s', self.target)
  718. logger.debug('Toolchain json %s', DebugString(lambda: json.dumps(tc_json, indent=4, sort_keys=True)))
  719. self.params = tc_json['params']
  720. self._name = tc_json.get('name', 'theyknow')
  721. if detector:
  722. self.type = detector.type
  723. self.from_arcadia = False
  724. self.c_compiler = detector.c_compiler
  725. self.cxx_compiler = detector.cxx_compiler
  726. self.compiler_version_list = detector.version_list
  727. self.compiler_version = '.'.join(map(lambda part: six.ensure_str(str(part)), self.compiler_version_list))
  728. else:
  729. self.type = self.params['type']
  730. self.from_arcadia = True
  731. self.c_compiler = self.params['c_compiler']
  732. self.cxx_compiler = self.params['cxx_compiler']
  733. # TODO(somov): Требовать номер версии всегда.
  734. self.compiler_version = self.params.get('gcc_version') or self.params.get('version') or '0'
  735. self.compiler_version_list = list(map(int, self.compiler_version.split('.')))
  736. # 'match_root' at this point contains real name for references via toolchain
  737. self.name_marker = '$(%s)' % self.params.get('match_root', self._name.upper())
  738. self.arch_opt = self.params.get('arch_opt', [])
  739. self.triplet_opt = self.params.get('triplet_opt', {})
  740. self.target_opt = self.params.get('target_opt', [])
  741. # TODO(somov): Убрать чтение настройки из os.environ.
  742. self.werror_mode = preset('WERROR_MODE') or os.environ.get('WERROR_MODE') or self.params.get('werror_mode') or 'compiler_specific'
  743. # default C++ standard is set here, some older toolchains might need to redefine it in ya.conf.json
  744. self.cxx_std = self.params.get('cxx_std', 'c++20')
  745. self._env = tc_json.get('env', {})
  746. self.android_ndk_version = self.params.get('android_ndk_version', None)
  747. logger.debug('c_compiler=%s', self.c_compiler)
  748. logger.debug('cxx_compiler=%s', self.cxx_compiler)
  749. self.compiler_platform_projects = self.target.find_in_dict(self.params.get('platform'), [])
  750. def version_at_least(self, *args):
  751. return args <= tuple(self.compiler_version_list)
  752. def version_exactly(self, *args):
  753. if not args or len(args) > len(self.compiler_version_list):
  754. return False
  755. for left, right in zip(args, list(self.compiler_version_list)[:len(args)]):
  756. if left != right:
  757. return False
  758. return True
  759. @property
  760. def is_gcc(self):
  761. return self.type == 'gnu'
  762. @property
  763. def is_clang(self):
  764. return self.type in ('clang', 'xcode')
  765. @property
  766. def is_xcode(self):
  767. return self.type == 'xcode'
  768. @property
  769. def is_from_arcadia(self):
  770. return self.from_arcadia
  771. @property
  772. def is_system_cxx(self):
  773. return self._name == "system_cxx"
  774. def get_env(self, convert_list=None):
  775. convert_list = convert_list or (lambda x: x)
  776. r = {}
  777. for k, v in six.iteritems(self._env):
  778. if isinstance(v, str):
  779. r[k] = v
  780. elif isinstance(v, list):
  781. r[k] = convert_list(v)
  782. else:
  783. logger.debug('Unexpected values in environment: %s', self._env)
  784. raise ConfigureError('Internal error')
  785. return r
  786. class GnuToolchainOptions(ToolchainOptions):
  787. def __init__(self, build, detector):
  788. super(GnuToolchainOptions, self).__init__(build, detector)
  789. self.ar = self.params.get('ar')
  790. self.ar_plugin = self.params.get('ar_plugin')
  791. self.strip = self.params.get('strip')
  792. self.objcopy = self.params.get('objcopy')
  793. self.objdump = self.params.get('objdump')
  794. self.isystem = self.params.get('isystem')
  795. self.dwarf_tool = self.target.find_in_dict(self.params.get('dwarf_tool'))
  796. # TODO(somov): Унифицировать формат sys_lib
  797. self.sys_lib = self.params.get('sys_lib', {})
  798. if isinstance(self.sys_lib, dict):
  799. self.sys_lib = self.target.find_in_dict(self.sys_lib, [])
  800. self.os_sdk = preset('OS_SDK') or self._default_os_sdk()
  801. self.os_sdk_local = False
  802. if build.host.is_apple and build.target.is_apple and to_bool(preset('APPLE_SDK_LOCAL'), default=False):
  803. self.os_sdk_local = True
  804. if build.host.is_apple and build.target.is_ios and to_bool(preset('MAPSMOBI_BUILD_TARGET'), default=False):
  805. self.os_sdk_local = True
  806. if self.os_sdk == 'local':
  807. self.os_sdk_local = True
  808. def _default_os_sdk(self):
  809. if self.target.is_linux:
  810. if self.target.is_armv8:
  811. return 'ubuntu-16'
  812. if self.target.is_armv7 and self.target.armv7_float_abi == 'hard':
  813. return 'ubuntu-16'
  814. if self.target.is_armv7 and self.target.armv7_float_abi == 'softfp':
  815. return 'ubuntu-18'
  816. # Default OS SDK for Linux builds
  817. return 'ubuntu-14'
  818. class Toolchain(object):
  819. def __init__(self, tc, build):
  820. """
  821. :type tc: ToolchainOptions
  822. :type build: Build
  823. """
  824. self.tc = tc
  825. self.build = build
  826. self.platform_projects = self.tc.compiler_platform_projects
  827. def print_toolchain(self):
  828. if self.platform_projects:
  829. emit('COMPILER_PLATFORM', list(unique(self.platform_projects)))
  830. class Compiler(object):
  831. def __init__(self, tc, compiler_variable):
  832. self.compiler_variable = compiler_variable
  833. self.tc = tc
  834. def print_compiler(self):
  835. # CLANG and CLANG_VER variables
  836. emit(self.compiler_variable, 'yes')
  837. cv = self.tc.compiler_version
  838. if '.' in cv:
  839. cv = cv[:cv.index('.')]
  840. emit('{}_VER'.format(self.compiler_variable), cv)
  841. if self.tc.is_xcode:
  842. emit('XCODE', 'yes')
  843. class GnuToolchain(Toolchain):
  844. def __init__(self, tc, build):
  845. """
  846. :type tc: GnuToolchainOptions
  847. :type build: Build
  848. """
  849. def get_os_sdk(target):
  850. sdk_native_version = 10.11 if not preset('EXPERIMENTAL_MACOS_M1_SUPPORT') else '11.1'
  851. if target.is_macos:
  852. return '$MACOS_SDK_RESOURCE_GLOBAL/MacOSX{}.sdk'.format(sdk_native_version)
  853. elif target.is_yocto:
  854. return '$YOCTO_SDK_RESOURCE_GLOBAL'
  855. return '$OS_SDK_ROOT_RESOURCE_GLOBAL'
  856. super(GnuToolchain, self).__init__(tc, build)
  857. self.tc = tc
  858. host = build.host
  859. target = build.target
  860. self.c_flags_platform = list(tc.target_opt)
  861. self.default_os_sdk_root = get_os_sdk(target)
  862. self.env = self.tc.get_env()
  863. self.env_go = {}
  864. if self.tc.is_clang and not self.tc.is_system_cxx:
  865. self.env_go = {'PATH': ['{}/bin'.format(self.tc.name_marker)]}
  866. if self.tc.is_gcc:
  867. self.env_go = {'PATH': ['{}/gcc/bin'.format(self.tc.name_marker)]}
  868. if 'PATH' in self.env_go:
  869. if target.is_linux:
  870. self.env_go['PATH'].append('$OS_SDK_ROOT_RESOURCE_GLOBAL/usr/bin')
  871. elif target.is_macos:
  872. self.env_go['PATH'].extend([
  873. '$MACOS_SDK_RESOURCE_GLOBAL/usr/bin',
  874. '$GO_FAKE_XCRUN_RESOURCE_GLOBAL',
  875. ])
  876. self.swift_flags_platform = []
  877. self.swift_lib_path = None
  878. if self.tc.is_from_arcadia:
  879. for lib_path in build.host.library_path_variables:
  880. self.env.setdefault(lib_path, []).append('{}/lib'.format(self.tc.name_marker))
  881. macos_version_min = '11.0'
  882. ios_version_min = '13.0'
  883. swift_target = select(default=None, selectors=[
  884. (target.is_iossim and target.is_x86_64, 'x86_64-apple-ios{}-simulator'.format(ios_version_min)),
  885. (target.is_iossim and target.is_x86, 'i386-apple-ios{}-simulator'.format(ios_version_min)),
  886. (target.is_iossim and target.is_armv8, 'arm64-apple-ios{}-simulator'.format(ios_version_min)),
  887. (not target.is_iossim and target.is_ios and target.is_armv8, 'arm64-apple-ios9'),
  888. (not target.is_iossim and target.is_ios and target.is_armv7, 'armv7-apple-ios9'),
  889. ])
  890. if swift_target:
  891. self.swift_flags_platform += ['-target', swift_target]
  892. if self.tc.is_from_arcadia:
  893. self.swift_lib_path = select(default=None, selectors=[
  894. (host.is_macos and target.is_iossim, '$SWIFT_XCODE_TOOLCHAIN_ROOT_RESOURCE_GLOBAL/usr/lib/swift/iphonesimulator'),
  895. (host.is_macos and not target.is_iossim and target.is_ios and (target.is_armv8 or target.is_armv7), '$SWIFT_XCODE_TOOLCHAIN_ROOT_RESOURCE_GLOBAL/usr/lib/swift/iphoneos'),
  896. ])
  897. if self.tc.is_clang:
  898. target_triple = self.tc.triplet_opt.get(target.arch, None)
  899. if not target_triple:
  900. target_triple = select(default=None, selectors=[
  901. (target.is_linux and target.is_x86_64, 'x86_64-linux-gnu'),
  902. (target.is_linux and target.is_armv8, 'aarch64-linux-gnu'),
  903. (target.is_linux and target.is_armv7 and target.armv7_float_abi == 'hard', 'armv7-linux-gnueabihf'),
  904. (target.is_linux and target.is_armv7 and target.armv7_float_abi == 'softfp', 'armv7-linux-gnueabi'),
  905. (target.is_linux and target.is_powerpc, 'powerpc64le-linux-gnu'),
  906. (target.is_iossim and target.is_x86_64, 'x86_64-apple-ios{}-simulator'.format(ios_version_min)),
  907. (target.is_iossim and target.is_x86, 'i386-apple-ios{}-simulator'.format(ios_version_min)),
  908. (target.is_iossim and target.is_armv8, 'arm64-apple-ios{}-simulator'.format(ios_version_min)),
  909. (not target.is_iossim and target.is_ios and target.is_armv8, 'arm64-apple-ios{}'.format(ios_version_min)),
  910. (not target.is_iossim and target.is_ios and target.is_armv7, 'armv7-apple-ios{}'.format(ios_version_min)),
  911. (target.is_apple and target.is_x86, 'i386-apple-darwin14'),
  912. (target.is_apple and target.is_x86_64, 'x86_64-apple-darwin14'),
  913. (target.is_apple and target.is_macos_arm64, 'arm64-apple-macos11'),
  914. (target.is_apple and target.is_armv7, 'armv7-apple-darwin14'),
  915. (target.is_apple and target.is_armv8, 'arm64-apple-darwin14'),
  916. (target.is_yocto and target.is_armv7, 'arm-poky-linux-gnueabi'),
  917. (target.is_android and target.is_x86, 'i686-linux-android'),
  918. (target.is_android and target.is_x86_64, 'x86_64-linux-android'),
  919. (target.is_android and target.is_armv7, 'armv7a-linux-androideabi'),
  920. (target.is_android and target.is_armv8, 'aarch64-linux-android'),
  921. (target.is_emscripten and target.is_wasm64, 'wasm64-unknown-emscripten'),
  922. ])
  923. if target.is_android:
  924. # Android NDK allows specification of API level in target triple, e.g.:
  925. # armv7a-linux-androideabi16, aarch64-linux-android21
  926. target_triple += str(target.android_api)
  927. if target_triple:
  928. self.c_flags_platform.append('--target={}'.format(target_triple))
  929. if self.tc.isystem:
  930. for root in list(self.tc.isystem):
  931. self.c_flags_platform.extend(['-isystem', root])
  932. if target.is_android:
  933. self.c_flags_platform.extend(['-isystem', '{}/sources/cxx-stl/llvm-libc++abi/include'.format(self.tc.name_marker)])
  934. if target.is_cortex_a9:
  935. self.c_flags_platform.append('-mcpu=cortex-a9')
  936. if target.is_cortex_a35:
  937. self.c_flags_platform.append('-mcpu=cortex-a35')
  938. elif target.is_cortex_a53:
  939. self.c_flags_platform.append('-mcpu=cortex-a53')
  940. elif target.is_cortex_m4:
  941. self.c_flags_platform.append('-mcpu=cortex-m4 -mfpu=fpv4-sp-d16')
  942. elif target.is_cortex_m7:
  943. self.c_flags_platform.append('-mcpu=cortex-m7 -mfpu=fpv5-sp-d16')
  944. elif target.is_cortex_m23:
  945. self.c_flags_platform.append('-mcpu=cortex-m23')
  946. elif target.is_cortex_m33:
  947. self.c_flags_platform.append('-mcpu=cortex-m33 -mfpu=fpv5-sp-d16')
  948. elif target.is_armv7_neon:
  949. self.c_flags_platform.append('-mfpu=neon')
  950. elif target.is_arm968e_s:
  951. self.c_flags_platform.append('-march=armv5te -mcpu=arm968e-s -mthumb-interwork -mlittle-endian')
  952. if (target.is_armv7 or target.is_armv8m or target.is_armv7em or target.is_armv5te) and build.is_size_optimized:
  953. # Enable ARM Thumb2 variable-length instruction encoding
  954. # to reduce code size
  955. self.c_flags_platform.append('-mthumb')
  956. if target.is_arm or target.is_powerpc:
  957. # On linux, ARM and PPC default to unsigned char
  958. # However, Arcadia requires char to be signed
  959. self.c_flags_platform.append('-fsigned-char')
  960. if target.is_rv32imc:
  961. self.c_flags_platform.append('-march=rv32imc')
  962. if self.tc.is_clang or self.tc.is_gcc and self.tc.version_at_least(8, 2):
  963. target_flags = select(default=[], selectors=[
  964. (target.is_linux and target.is_power8le, ['-mcpu=power8', '-mtune=power8', '-maltivec']),
  965. (target.is_linux and target.is_power9le, ['-mcpu=power9', '-mtune=power9', '-maltivec']),
  966. (target.is_linux and target.is_armv8, ['-march=armv8a']),
  967. (target.is_macos, ['-mmacosx-version-min={}'.format(macos_version_min)]),
  968. (target.is_ios and not target.is_iossim, ['-mios-version-min={}'.format(ios_version_min)]),
  969. (target.is_iossim, ['-mios-simulator-version-min={}'.format(ios_version_min)]),
  970. (target.is_android and target.is_armv7, ['-march=armv7-a', '-mfloat-abi=softfp']),
  971. (target.is_android and target.is_armv8, ['-march=armv8-a']),
  972. (target.is_yocto and target.is_armv7, ['-march=armv7-a', '-mfpu=neon', '-mfloat-abi=hard', '-mcpu=cortex-a9', '-O1'])
  973. ])
  974. if target_flags:
  975. self.c_flags_platform.extend(target_flags)
  976. if target.is_ios:
  977. self.c_flags_platform.append('-D__IOS__=1')
  978. if target.is_apple:
  979. self.setup_apple_sdk(target)
  980. if self.tc.is_from_arcadia or self.tc.is_system_cxx:
  981. if target.is_linux:
  982. if not tc.os_sdk_local:
  983. self.setup_sdk(project='build/platform/linux_sdk', var='$OS_SDK_ROOT_RESOURCE_GLOBAL')
  984. if target.is_x86_64:
  985. if host.is_linux and not self.tc.is_gcc:
  986. self.setup_tools(project='build/platform/linux_sdk', var='$OS_SDK_ROOT_RESOURCE_GLOBAL', bin='usr/bin', ldlibs='usr/lib/x86_64-linux-gnu')
  987. elif host.is_macos:
  988. self.setup_tools(project='build/platform/binutils', var='$BINUTILS_ROOT_RESOURCE_GLOBAL', bin='x86_64-linux-gnu/bin', ldlibs=None)
  989. elif target.is_powerpc:
  990. self.setup_tools(project='build/platform/linux_sdk', var='$OS_SDK_ROOT_RESOURCE_GLOBAL', bin='usr/bin', ldlibs='usr/x86_64-linux-gnu/powerpc64le-linux-gnu/lib')
  991. elif target.is_armv8:
  992. self.setup_tools(project='build/platform/linux_sdk', var='$OS_SDK_ROOT_RESOURCE_GLOBAL', bin='usr/bin', ldlibs='usr/lib/x86_64-linux-gnu')
  993. if target.is_yocto:
  994. self.setup_sdk(project='build/platform/yocto_sdk/yocto_sdk', var='${YOCTO_SDK_ROOT_RESOURCE_GLOBAL}')
  995. def setup_apple_sdk(self, target):
  996. if not self.tc.os_sdk_local:
  997. self.setup_apple_arcadia_sdk(target)
  998. else:
  999. self.setup_apple_local_sdk(target)
  1000. def setup_apple_arcadia_sdk(self, target):
  1001. if target.is_ios:
  1002. self.setup_xcode_sdk(project='build/platform/ios_sdk', var='${IOS_SDK_ROOT_RESOURCE_GLOBAL}')
  1003. self.platform_projects.append('build/internal/platform/macos_system_stl')
  1004. if target.is_macos:
  1005. self.setup_xcode_sdk(project='build/internal/platform/macos_sdk', var='${MACOS_SDK_RESOURCE_GLOBAL}')
  1006. self.platform_projects.append('build/internal/platform/macos_system_stl')
  1007. def setup_apple_local_sdk(self, target):
  1008. def get_output(*args):
  1009. return six.ensure_str(subprocess.check_output(tuple(args))).strip()
  1010. def get_sdk_root(sdk):
  1011. root = self.env.get('SDKROOT')
  1012. if root not in (None, '', ['']):
  1013. return root
  1014. root = os.environ.get('SDKROOT')
  1015. if root:
  1016. return root
  1017. return get_output('xcrun', '-sdk', sdk, '--show-sdk-path')
  1018. if target.is_iossim:
  1019. self.env['SDKROOT'] = get_sdk_root('iphonesimulator')
  1020. elif target.is_ios:
  1021. self.env['SDKROOT'] = get_sdk_root('iphoneos')
  1022. elif target.is_macos:
  1023. self.env['SDKROOT'] = get_sdk_root('macosx')
  1024. def setup_sdk(self, project, var):
  1025. self.platform_projects.append(project)
  1026. self.c_flags_platform.append('--sysroot={}'.format(var))
  1027. self.swift_flags_platform += ['-sdk', var]
  1028. def setup_xcode_sdk(self, project, var):
  1029. self.platform_projects.append(project)
  1030. self.c_flags_platform.append('-isysroot')
  1031. self.c_flags_platform.append(var)
  1032. self.swift_flags_platform += ['-sdk', var]
  1033. # noinspection PyShadowingBuiltins
  1034. def setup_tools(self, project, var, bin, ldlibs):
  1035. self.platform_projects.append(project)
  1036. self.c_flags_platform.append('-B{}/{}'.format(var, bin))
  1037. if ldlibs:
  1038. for lib_path in self.build.host.library_path_variables:
  1039. self.env.setdefault(lib_path, []).append('{}/{}'.format(var, ldlibs))
  1040. def print_toolchain(self):
  1041. super(GnuToolchain, self).print_toolchain()
  1042. emit('TOOLCHAIN_ENV', format_env(self.env, list_separator=':'))
  1043. emit('_GO_TOOLCHAIN_ENV_PATH', format_env(self.env_go, list_separator=':'))
  1044. emit('C_FLAGS_PLATFORM', self.c_flags_platform)
  1045. emit('SWIFT_FLAGS_PLATFORM', self.swift_flags_platform)
  1046. emit('SWIFT_LD_FLAGS', '-L{}'.format(self.swift_lib_path) if self.swift_lib_path else '')
  1047. emit('PERL_SDK', preset('OS_SDK') or self.tc.os_sdk)
  1048. if preset('OS_SDK') is None:
  1049. emit('OS_SDK', self.tc.os_sdk)
  1050. emit('OS_SDK_ROOT', None if self.tc.os_sdk_local else self.default_os_sdk_root)
  1051. class GnuCompiler(Compiler):
  1052. def __init__(self, tc, build):
  1053. """
  1054. :type tc: GnuToolchainOptions
  1055. :type build: Build
  1056. """
  1057. compiler_variable = 'CLANG' if tc.is_clang else 'GCC'
  1058. super(GnuCompiler, self).__init__(tc, compiler_variable)
  1059. self.build = build
  1060. self.host = self.build.host
  1061. self.target = self.build.target
  1062. self.tc = tc
  1063. self.c_foptions = [
  1064. # Enable C++ exceptions (and allow them to be throw through pure C code)
  1065. '-fexceptions',
  1066. # Enable standard-conforming behavior and generate duplicate symbol error in case of duplicated global constants.
  1067. # See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85678#c0
  1068. '-fno-common',
  1069. # Split all functions and data into separate sections for DCE and ICF linker passes
  1070. '-ffunction-sections',
  1071. '-fdata-sections'
  1072. ]
  1073. if self.tc.is_clang and self.target.is_linux:
  1074. # Use .init_array instead of .ctors (default for old clang versions)
  1075. # See: https://maskray.me/blog/2021-11-07-init-ctors-init-array
  1076. self.c_foptions.append('-fuse-init-array')
  1077. if self.target.is_xtensa:
  1078. self.c_foptions.append('-mlongcalls')
  1079. if self.tc.is_clang:
  1080. self.c_foptions += [
  1081. # Set up output colorization
  1082. '-fcolor-diagnostics',
  1083. # Enable aligned allocation
  1084. '-faligned-allocation',
  1085. '-fdebug-default-version=4',
  1086. ]
  1087. elif self.tc.is_gcc:
  1088. if self.target.is_xtensa or self.target.is_tc32:
  1089. # Xtensa and tc32 toolchains does not support this flag
  1090. pass
  1091. else:
  1092. self.c_foptions += [
  1093. # Set up output colorization
  1094. '-fdiagnostics-color=always',
  1095. # It looks like there is no way to enable aligned allocation in gcc
  1096. ]
  1097. self.c_warnings = [
  1098. # Enable default warnings subset
  1099. '-Wall',
  1100. '-Wextra',
  1101. ]
  1102. self.cxx_warnings = [
  1103. # Issue a warning if certain overload is hidden due to inheritance
  1104. '-Woverloaded-virtual',
  1105. ]
  1106. # Disable some warnings which will fail compilation at the time
  1107. self.c_warnings += [
  1108. '-Wno-parentheses',
  1109. ]
  1110. self.c_defines = ['${hide:CPP_FAKEID}']
  1111. if self.target.is_android:
  1112. self.c_defines.append('${hide:ANDROID_FAKEID}')
  1113. self.c_defines.extend([
  1114. '-DARCADIA_ROOT=${ARCADIA_ROOT}',
  1115. '-DARCADIA_BUILD_ROOT=${ARCADIA_BUILD_ROOT}',
  1116. ])
  1117. self.c_defines.extend([
  1118. '-D_THREAD_SAFE', '-D_PTHREADS', '-D_REENTRANT',
  1119. '-D_LARGEFILE_SOURCE', '-D__STDC_CONSTANT_MACROS', '-D__STDC_FORMAT_MACROS',
  1120. ])
  1121. if not self.target.is_android:
  1122. # There is no usable _FILE_OFFSET_BITS=64 support in Androids until API 21. And it's incomplete until at least API 24.
  1123. # https://android.googlesource.com/platform/bionic/+/master/docs/32-bit-abi.md
  1124. # Arcadia have API 16 for 32-bit Androids.
  1125. self.c_defines.append('-D_FILE_OFFSET_BITS=64')
  1126. if self.target.is_linux or self.target.is_android or self.target.is_cygwin or self.target.is_none:
  1127. self.c_defines.append('-D_GNU_SOURCE')
  1128. if self.tc.is_clang and self.target.is_linux and self.target.is_x86_64:
  1129. self.c_defines.append('-D_YNDX_LIBUNWIND_ENABLE_EXCEPTION_BACKTRACE')
  1130. self.c_flags = ['$CL_DEBUG_INFO', '$CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__']
  1131. self.c_flags += self.tc.arch_opt + ['-pipe']
  1132. self.sfdl_flags = ['-E', '-C', '-x', 'c++']
  1133. if self.target.is_x86:
  1134. self.c_flags.append('-m32')
  1135. if self.target.is_x86_64:
  1136. self.c_flags.append('-m64')
  1137. if self.target.is_wasm64:
  1138. # WebAssembly-specific exception handling flags
  1139. self.c_foptions += [
  1140. '-fwasm-exceptions',
  1141. ]
  1142. self.debug_info_flags = ['-g']
  1143. if self.target.is_linux:
  1144. self.debug_info_flags.append('-ggnu-pubnames')
  1145. self.cross_suffix = '' if is_positive('FORCE_NO_PIC') else '.pic'
  1146. self.optimize = None
  1147. self.configure_build_type()
  1148. if self.tc.is_clang:
  1149. self.sfdl_flags.append('-Qunused-arguments')
  1150. self.c_warnings += [
  1151. '-Wno-implicit-const-int-float-conversion',
  1152. # For nvcc to accept the above.
  1153. '-Wno-unknown-warning-option',
  1154. ]
  1155. self.cxx_warnings += [
  1156. '-Wimport-preprocessor-directive-pedantic',
  1157. '-Wno-ambiguous-reversed-operator',
  1158. '-Wno-defaulted-function-deleted',
  1159. '-Wno-deprecated-anon-enum-enum-conversion',
  1160. '-Wno-deprecated-enum-enum-conversion',
  1161. '-Wno-deprecated-enum-float-conversion',
  1162. '-Wno-deprecated-volatile',
  1163. '-Wno-pessimizing-move',
  1164. '-Wno-return-std-move',
  1165. '-Wno-undefined-var-template',
  1166. ]
  1167. elif self.tc.is_gcc:
  1168. if self.target.is_xtensa:
  1169. # Xtensa toolchain does not support this flags
  1170. pass
  1171. else:
  1172. self.c_foptions.append('-fno-delete-null-pointer-checks')
  1173. self.c_foptions.append('-fabi-version=8')
  1174. def configure_build_type(self):
  1175. if self.build.is_valgrind:
  1176. self.c_defines.append('-DWITH_VALGRIND=1')
  1177. if self.build.is_debug:
  1178. self.c_foptions.append('$FSTACK')
  1179. if self.build.is_fast_debug:
  1180. self.c_flags.append('-Og')
  1181. if self.build.is_release:
  1182. self.c_flags.append('$OPTIMIZE')
  1183. if self.build.is_size_optimized:
  1184. # -Oz is clang's more size-aggressive version of -Os
  1185. # For ARM specifically, clang -Oz is on par with gcc -Os:
  1186. # https://github.com/android/ndk/issues/133#issuecomment-365763507
  1187. if self.tc.is_clang:
  1188. self.optimize = '-Oz'
  1189. else:
  1190. self.optimize = '-Os'
  1191. # Generate sections with address significance tables for ICF linker pass
  1192. if self.tc.is_clang:
  1193. self.c_foptions.extend(['-faddrsig'])
  1194. else:
  1195. self.optimize = '-O3'
  1196. if self.build.with_ndebug:
  1197. self.c_defines.append('-DNDEBUG')
  1198. else:
  1199. self.c_defines.append('-UNDEBUG')
  1200. if self.build.profiler_type in (Profiler.Generic, Profiler.GProf):
  1201. self.c_foptions.append('-fno-omit-frame-pointer')
  1202. if self.build.profiler_type == Profiler.GProf:
  1203. self.c_flags.append('-pg')
  1204. def print_compiler(self):
  1205. super(GnuCompiler, self).print_compiler()
  1206. emit('C_COMPILER_UNQUOTED', self.tc.c_compiler)
  1207. emit('OPTIMIZE', self.optimize)
  1208. emit('WERROR_MODE', self.tc.werror_mode)
  1209. emit('_C_FLAGS', self.c_flags)
  1210. emit('_C_FOPTIONS', self.c_foptions)
  1211. emit('_CXX_STD', '-std={}'.format(self.tc.cxx_std))
  1212. append('C_DEFINES', self.c_defines)
  1213. append('C_WARNING_OPTS', self.c_warnings)
  1214. append('CXX_WARNING_OPTS', self.cxx_warnings)
  1215. emit('CXX_COMPILER_UNQUOTED', self.tc.cxx_compiler)
  1216. # TODO(somov): Убрать чтение настройки из os.environ
  1217. emit('USE_ARC_PROFILE', 'yes' if preset('USE_ARC_PROFILE') or os.environ.get('USE_ARC_PROFILE') else 'no')
  1218. emit('DEBUG_INFO_FLAGS', self.debug_info_flags)
  1219. if self.build.is_coverage:
  1220. emit('_IS_COVERAGE', 'yes')
  1221. if self.tc.is_clang and self.tc.version_at_least(9):
  1222. emit('_HAS_TIME_TRACE', 'yes')
  1223. print('@import "${CONF_ROOT}/conf/compilers/gnu_compiler.conf"')
  1224. class SwiftCompiler(object):
  1225. def __init__(self, build):
  1226. self.host = build.host
  1227. self.compiler = None
  1228. def configure(self):
  1229. if self.host.is_macos:
  1230. self.compiler = '$SWIFT_XCODE_TOOLCHAIN_ROOT_RESOURCE_GLOBAL/usr/bin/swiftc'
  1231. def print_compiler(self):
  1232. emit('SWIFT_COMPILER', self.compiler or '')
  1233. class Linker(object):
  1234. BFD = 'bfd'
  1235. LLD = 'lld'
  1236. GOLD = 'gold'
  1237. def __init__(self, tc, build):
  1238. """
  1239. :type tc: ToolchainOptions
  1240. :type build: Build
  1241. """
  1242. self.tc = tc
  1243. self.build = build
  1244. self.type = self._get_default_linker_type()
  1245. def _get_default_linker_type(self):
  1246. if not self.tc.is_from_arcadia or is_positive('EXPORT_CMAKE'):
  1247. # External (e.g. system) toolchain: disable linker selection logic
  1248. return None
  1249. if self.build.target.is_android:
  1250. # Android toolchain is NDK, LLD works on all supported platforms
  1251. return Linker.LLD
  1252. elif self.build.target.is_linux or self.build.target.is_macos or self.build.target.is_ios or self.build.target.is_wasm:
  1253. return Linker.LLD
  1254. # There is no linker choice on Windows (link.exe)
  1255. return None
  1256. def print_linker(self):
  1257. self._print_linker_selector()
  1258. def _print_linker_selector(self):
  1259. # if self.type is None then _DEFAULT_LINKER is set to empty string value
  1260. emit('_DEFAULT_LINKER_ID', self.type)
  1261. class LD(Linker):
  1262. def __init__(self, tc, build):
  1263. """
  1264. :type tc: GnuToolchainOptions
  1265. :type build: Build
  1266. """
  1267. super(LD, self).__init__(tc, build)
  1268. self.build = build
  1269. self.host = self.build.host
  1270. self.target = self.build.target
  1271. self.tc = tc
  1272. target = self.target
  1273. self.ar = preset('AR') or self.tc.ar
  1274. self.ar_plugin = self.tc.ar_plugin
  1275. self.strip = self.tc.strip
  1276. self.objcopy = self.tc.objcopy
  1277. self.objdump = self.tc.objdump
  1278. self.musl = Setting('MUSL', convert=to_bool)
  1279. if self.ar is None:
  1280. if self.tc.is_from_arcadia:
  1281. if self.tc.is_clang:
  1282. self.ar = '{}/bin/llvm-ar'.format(self.tc.name_marker)
  1283. if self.tc.is_gcc:
  1284. self.ar = '{}/gcc/bin/gcc-ar'.format(self.tc.name_marker)
  1285. else:
  1286. self.ar = 'ar'
  1287. self.ar_type = 'GNU_AR'
  1288. self.llvm_ar_format = 'None'
  1289. if 'libtool' in self.ar:
  1290. self.ar_type = 'LIBTOOL'
  1291. elif 'llvm-ar' in self.ar:
  1292. self.ar_type = 'LLVM_AR'
  1293. if target.is_apple:
  1294. self.llvm_ar_format = "darwin"
  1295. else:
  1296. self.llvm_ar_format = "gnu"
  1297. self.ld_flags = []
  1298. if self.musl.value:
  1299. self.ld_flags.extend(['-Wl,--no-as-needed'])
  1300. elif target.is_linux:
  1301. self.ld_flags.extend(['-ldl', '-lrt', '-Wl,--no-as-needed'])
  1302. if self.tc.is_gcc:
  1303. self.ld_flags.extend(('-Wl,-Bstatic', '-latomic', '-Wl,-Bdynamic'))
  1304. elif target.is_android:
  1305. self.ld_flags.extend(['-ldl', '-Wl,--no-as-needed'])
  1306. self.ld_sdk = select(default=None, selectors=[
  1307. # -platform_version <platform> <min_version> <sdk_version>
  1308. (target.is_macos, '-Wl,-platform_version,macos,11.0,11.0'),
  1309. (not target.is_iossim and target.is_ios, '-Wl,-platform_version,ios,11.0,13.1'),
  1310. (target.is_iossim, '-Wl,-platform_version,ios-simulator,14.0,14.5'),
  1311. ])
  1312. if self.build.profiler_type == Profiler.GProf:
  1313. self.ld_flags.append('-pg')
  1314. if self.ld_sdk:
  1315. self.ld_flags.append(self.ld_sdk)
  1316. self.sys_lib = self.tc.sys_lib
  1317. if target.is_android:
  1318. # Use toolchain defaults to link with libunwind/clang_rt.builtins
  1319. self.use_stdlib = '-nostdlib++'
  1320. def print_linker(self):
  1321. super(LD, self).print_linker()
  1322. emit('AR_TOOL', self.ar)
  1323. emit('AR_TYPE', self.ar_type)
  1324. emit('_LD_LLVM_AR_FORMAT', self.llvm_ar_format)
  1325. emit('_LD_AR_PLUGIN', self.ar_plugin or 'None')
  1326. emit('STRIP_TOOL_VENDOR', self.strip)
  1327. emit('OBJCOPY_TOOL_VENDOR', self.objcopy)
  1328. emit('OBJDUMP_TOOL_VENDOR', self.objdump)
  1329. emit('_LD_FLAGS', self.ld_flags)
  1330. emit('_LD_SYS_LIB', self.sys_lib)
  1331. emit('LD_SDK_VERSION', self.ld_sdk)
  1332. dwarf_tool = self.tc.dwarf_tool
  1333. if dwarf_tool is None and self.tc.is_clang and (self.target.is_macos or self.target.is_ios):
  1334. dsymutil = '{}/bin/{}dsymutil'.format(self.tc.name_marker, '' if self.tc.version_at_least(7) else 'llvm-')
  1335. dwarf_tool = '${YMAKE_PYTHON} ${input:"build/scripts/run_llvm_dsymutil.py"} ' + dsymutil
  1336. if self.tc.version_at_least(5, 0):
  1337. dwarf_tool += ' -flat'
  1338. if dwarf_tool is not None:
  1339. emit('DWARF_TOOL', dwarf_tool)
  1340. arch_flag = '--arch={arch}'.format(arch=self.target.os_compat)
  1341. emit('_LD_ARCH_FLAG', arch_flag)
  1342. print('@import "${CONF_ROOT}/conf/linkers/ld.conf"')
  1343. class MSVCToolchainOptions(ToolchainOptions):
  1344. def __init__(self, build, detector):
  1345. super(MSVCToolchainOptions, self).__init__(build, detector)
  1346. # C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.14.26428
  1347. self.vc_root = None
  1348. # C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0
  1349. self.kit_includes = None
  1350. # C:\Program Files (x86)\Windows Kits\10\Lib\10.0.14393.0
  1351. self.kit_libs = None
  1352. self.under_wine = 'wine' in self.params
  1353. self.system_msvc = 'system_msvc' in self.params
  1354. self.ide_msvs = 'ide_msvs' in self.params
  1355. self.use_clang = self.params.get('use_clang', False)
  1356. self.use_arcadia_toolchain = self.params.get('use_arcadia_toolchain', False)
  1357. self.sdk_version = None
  1358. if build.host.is_windows:
  1359. self.under_wine = False
  1360. if self.ide_msvs:
  1361. bindir = '$(VC_ExecutablePath_x64_x64)\\'
  1362. self.c_compiler = bindir + 'cl.exe'
  1363. self.cxx_compiler = self.c_compiler
  1364. self.link = bindir + 'link.exe'
  1365. self.lib = bindir + 'lib.exe'
  1366. self.masm_compiler = bindir + 'ml64.exe'
  1367. self.vc_root = None
  1368. sdk_dir = '$(WindowsSdkDir)'
  1369. self.sdk_version = '$(WindowsTargetPlatformVersion)'
  1370. self.kit_includes = os.path.join(sdk_dir, 'Include', self.sdk_version)
  1371. self.kit_libs = os.path.join(sdk_dir, 'Lib', self.sdk_version)
  1372. elif detector:
  1373. self.masm_compiler = which('ml64.exe')
  1374. self.link = which('link.exe')
  1375. self.lib = which('lib.exe')
  1376. sdk_dir = os.environ.get('WindowsSdkDir')
  1377. self.sdk_version = os.environ.get('WindowsSDKVersion').replace('\\', '')
  1378. vc_install_dir = os.environ.get('VCToolsInstallDir')
  1379. # fix for cxx_std detection problem introduced in r7740071 when running in native VS toolkit commandline:
  1380. # in that case ya make gets 'system_cxx' configuration name and cxx_std is obviously missing in that config
  1381. # so default 'c++20' is substituted and we need to hotfix it here
  1382. self.cxx_std = 'c++latest'
  1383. if any([x is None for x in (sdk_dir, self.sdk_version, vc_install_dir)]):
  1384. raise ConfigureError('No %WindowsSdkDir%, %WindowsSDKVersion% or %VCINSTALLDIR% present. Please, run vcvars64.bat to setup preferred environment.')
  1385. self.vc_root = os.path.normpath(vc_install_dir)
  1386. self.kit_includes = os.path.normpath(os.path.join(sdk_dir, 'Include', self.sdk_version))
  1387. self.kit_libs = os.path.normpath(os.path.join(sdk_dir, 'Lib', self.sdk_version))
  1388. # TODO(somov): Определять автоматически self.version в этом случае
  1389. else:
  1390. if self.version_at_least(2019):
  1391. self.sdk_version = '10.0.18362.0'
  1392. sdk_dir = '$(WINDOWS_KITS-sbr:1939557911)'
  1393. if is_positive('MSVC20'): # XXX: temporary flag, remove after DTCC-123 is completed
  1394. self.cxx_std = 'c++latest'
  1395. else:
  1396. self.sdk_version = '10.0.16299.0'
  1397. sdk_dir = '$(WINDOWS_KITS-sbr:1379398385)'
  1398. self.vc_root = self.name_marker if not self.use_clang else '$MSVC_FOR_CLANG_RESOURCE_GLOBAL'
  1399. self.kit_includes = os.path.join(sdk_dir, 'Include', self.sdk_version)
  1400. self.kit_libs = os.path.join(sdk_dir, 'Lib', self.sdk_version)
  1401. bindir = os.path.join(self.vc_root, 'bin', 'Hostx64')
  1402. tools_name = select(selectors=[
  1403. (build.target.is_x86, 'x86'),
  1404. (build.target.is_x86_64, 'x64'),
  1405. (build.target.is_armv7, 'arm'),
  1406. ])
  1407. asm_name = select(selectors=[
  1408. (build.target.is_x86, 'ml.exe'),
  1409. (build.target.is_x86_64, 'ml64.exe'),
  1410. (build.target.is_armv7, 'armasm.exe'),
  1411. ])
  1412. def prefix(_type, _path):
  1413. if not self.under_wine:
  1414. return _path
  1415. return '{wine} {type} $WINE_ENV ${{ARCADIA_ROOT}} ${{ARCADIA_BUILD_ROOT}} {path}'.format(
  1416. wine='${YMAKE_PYTHON} ${input:\"build/scripts/run_msvc_wine.py\"} $(WINE_TOOL-sbr:1093314933)/bin/wine64 -v140 ' +
  1417. '${input;hide:\"build/scripts/process_command_files.py\"} ${input;hide:\"build/scripts/process_whole_archive_option.py\"}',
  1418. type=_type,
  1419. path=_path
  1420. )
  1421. self.masm_compiler = prefix('masm', os.path.join(bindir, tools_name, asm_name))
  1422. self.link = prefix('link', os.path.join(bindir, tools_name, 'link.exe'))
  1423. self.lib = prefix('lib', os.path.join(bindir, tools_name, 'lib.exe'))
  1424. class MSVC(object):
  1425. # noinspection PyPep8Naming
  1426. class WindowsVersion(object):
  1427. """
  1428. Predefined values for _WIN32_WINNT macro.
  1429. This macro specifies minimal Windows version required by the binary being build.
  1430. A complete list of the values supported by the Windows SDK can be found at
  1431. https://docs.microsoft.com/en-us/cpp/porting/modifying-winver-and-win32-winnt
  1432. """
  1433. Windows07 = '0x0601'
  1434. Windows08 = '0x0602'
  1435. Windows10 = '0x0A00'
  1436. def __init__(self, tc, build):
  1437. """
  1438. :type tc: MSVCToolchainOptions
  1439. :type build: Build
  1440. """
  1441. if not isinstance(tc, MSVCToolchainOptions):
  1442. raise TypeError('Got {} ({}) instead of an MSVCToolchainOptions'.format(tc, type(tc)))
  1443. self.build = build
  1444. self.tc = tc
  1445. class MSVCToolchain(MSVC, Toolchain):
  1446. def __init__(self, tc, build):
  1447. """
  1448. :type tc: MSVCToolchainOptions
  1449. :param build: Build
  1450. """
  1451. Toolchain.__init__(self, tc, build)
  1452. MSVC.__init__(self, tc, build)
  1453. if self.tc.from_arcadia and not self.tc.ide_msvs:
  1454. self.platform_projects.append('build/internal/platform/msvc')
  1455. if tc.under_wine:
  1456. self.platform_projects.append('build/platform/wine')
  1457. def print_toolchain(self):
  1458. super(MSVCToolchain, self).print_toolchain()
  1459. emit('TOOLCHAIN_ENV', format_env(self.tc.get_env(), list_separator=';'))
  1460. if self.tc.sdk_version:
  1461. emit('WINDOWS_KITS_VERSION', self.tc.sdk_version)
  1462. if self.tc.under_wine:
  1463. emit('_UNDER_WINE', 'yes')
  1464. if self.tc.use_clang:
  1465. emit('CLANG_CL', 'yes')
  1466. if self.tc.ide_msvs:
  1467. emit('IDE_MSVS', 'yes')
  1468. if self.tc.use_arcadia_toolchain:
  1469. emit('USE_ARCADIA_TOOLCHAIN', 'yes')
  1470. emit('_MSVC_TC_KIT_LIBS', self.tc.kit_libs)
  1471. emit('_MSVC_TC_VC_ROOT', self.tc.vc_root)
  1472. print('@import "${CONF_ROOT}/conf/toolchains/msvc_toolchain.conf"')
  1473. class MSVCCompiler(MSVC, Compiler):
  1474. def __init__(self, tc, build):
  1475. Compiler.__init__(self, tc, 'MSVC')
  1476. MSVC.__init__(self, tc, build)
  1477. def print_compiler(self):
  1478. super(MSVCCompiler, self).print_compiler()
  1479. target = self.build.target
  1480. warns_enabled = [
  1481. 4018, # 'expression' : signed/unsigned mismatch
  1482. 4265, # 'class' : class has virtual functions, but destructor is not virtual
  1483. 4296, # 'operator' : expression is always false
  1484. 4431, # missing type specifier - int assumed
  1485. ]
  1486. warns_as_error = [
  1487. 4013, # 'function' undefined; assuming extern returning int
  1488. ]
  1489. warns_disabled = [
  1490. # While this warning corresponds to enabled-by-default -Wmacro-redefinition,
  1491. # it floods clog with abundant amount of log lines,
  1492. # as yvals_core.h from Windows SDK redefines certain
  1493. # which macros logically belong to libcxx
  1494. 4005, # '__cpp_lib_*': macro redefinition.
  1495. # Ne need to recheck this, but it looks like _CRT_USE_BUILTIN_OFFSETOF still makes sense
  1496. 4117, # macro name '_CRT_USE_BUILTIN_OFFSETOF' is reserved, '#define' ignored
  1497. 4127, # conditional expression is constant
  1498. 4200, # nonstandard extension used : zero-sized array in struct/union
  1499. 4201, # nonstandard extension used : nameless struct/union
  1500. 4351, # elements of array will be default initialized
  1501. 4355, # 'this' : used in base member initializer list
  1502. 4503, # decorated name length exceeded, name was truncated
  1503. 4510, # default constructor could not be generated
  1504. 4511, # copy constructor could not be generated
  1505. 4512, # assignment operator could not be generated
  1506. 4554, # check operator precedence for possible error; use parentheses to clarify precedence
  1507. 4610, # 'object' can never be instantiated - user defined constructor required
  1508. 4706, # assignment within conditional expression
  1509. 4800, # forcing value to bool 'true' or 'false' (performance warning)
  1510. 4996, # The POSIX name for this item is deprecated
  1511. 4714, # function marked as __forceinline not inlined
  1512. 4197, # 'TAtomic' : top-level volatile in cast is ignored
  1513. 4245, # 'initializing' : conversion from 'int' to 'ui32', signed/unsigned mismatch
  1514. 4324, # 'ystd::function<void (uint8_t *)>': structure was padded due to alignment specifier
  1515. 5033, # 'register' is no longer a supported storage class
  1516. ]
  1517. defines = [
  1518. '${hide:CPP_FAKEID}',
  1519. # FIXME: This is quick fix to let catboost build from MSVS IDE
  1520. # This place is questionable overall, see YMAKE-437
  1521. '/DARCADIA_ROOT=' + ('${ARCADIA_ROOT}' if not self.tc.ide_msvs else '.'),
  1522. '/DARCADIA_BUILD_ROOT=' + ('${ARCADIA_BUILD_ROOT}' if not self.tc.ide_msvs else '.'),
  1523. '/DWIN32',
  1524. '/D_WIN32',
  1525. '/D_WINDOWS',
  1526. # Define _CRT_*_NO_WARNINGS macros to prevent ucrt from issuing a warning whenever
  1527. # a POSIX-style function is used instead of the alternative Microsoft suggests as a secure / standard replacement
  1528. # (e. g. `strncpy()` instead of `strncpy_s()`, `access()` instead of `_access()`)
  1529. # For details see:
  1530. # https://docs.microsoft.com/en-us/cpp/c-runtime-library/security-features-in-the-crt
  1531. '/D_CRT_SECURE_NO_WARNINGS',
  1532. '/D_CRT_NONSTDC_NO_WARNINGS',
  1533. # Math constants (such as M_PI, M_E, M_SQRT2) are not defined in standard C / C++
  1534. # In order to get them defined by Windows ucrt library,
  1535. # you must first define _USE_MATH_DEFINES before #including <cmath> or math.h>.
  1536. # (NB: glibc defines these macros whenever _XOPEN_SOURCE is defined)
  1537. '/D_USE_MATH_DEFINES',
  1538. '/D__STDC_CONSTANT_MACROS',
  1539. '/D__STDC_FORMAT_MACROS',
  1540. '/D_USING_V110_SDK71_',
  1541. # Below defines are covered at
  1542. # https://docs.microsoft.com/en-us/windows/win32/winprog/using-the-windows-headers#faster-builds-with-smaller-header-files
  1543. # Exclude APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets (while including <windows.h>)
  1544. '/DWIN32_LEAN_AND_MEAN',
  1545. # Define NOMINMAX to avoid min() and max() macros definition (while including <windows.h>)
  1546. '/DNOMINMAX',
  1547. ]
  1548. cxx_defines = [
  1549. # Use builtin offsetof implementation
  1550. # instead of a crutcy macro defined in ucrt/stddef.h.
  1551. # The latter can not be used in constexpr statements.
  1552. '/D_CRT_USE_BUILTIN_OFFSETOF',
  1553. ]
  1554. if target.is_x86_64:
  1555. defines.extend(('/D_WIN64', '/DWIN64'))
  1556. if target.is_armv7:
  1557. defines.extend(('/D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE', '/D__arm__'))
  1558. winapi_unicode = False
  1559. flags = [
  1560. '/nologo', '/Zm500', '/GR', '/bigobj', '/FC', '/EHs', '/errorReport:prompt', '$MSVC_INLINE_FLAG', '/utf-8',
  1561. # enable standard conforming mode
  1562. '/permissive-'
  1563. ]
  1564. flags += self.tc.arch_opt
  1565. c_warnings = ['/we{}'.format(code) for code in warns_as_error]
  1566. c_warnings += ['/w1{}'.format(code) for code in warns_enabled]
  1567. c_warnings += ['/wd{}'.format(code) for code in warns_disabled]
  1568. cxx_warnings = []
  1569. if self.tc.use_clang:
  1570. flags += [
  1571. # Allow <windows.h> to be included via <Windows.h> in case-sensitive file-systems.
  1572. '-fcase-insensitive-paths',
  1573. # At the time clang-cl identifies itself as MSVC 19.11:
  1574. # (actual value can be found in clang/lib/Driver/ToolChains/MSVC.cpp, the syntax would be like
  1575. # ```
  1576. # MSVT = VersionTuple(19, 11);
  1577. # ```
  1578. #
  1579. # We override this value to match current value of the actual MSVC being used.
  1580. '-fms-compatibility-version=19.21',
  1581. # for msvc compatibility
  1582. # https://clang.llvm.org/docs/UsersManual.html#microsoft-extensions
  1583. '-fdelayed-template-parsing',
  1584. ]
  1585. if target.is_x86:
  1586. flags.append('-m32')
  1587. elif target.is_x86_64:
  1588. flags.append('-m64')
  1589. c_warnings.extend((
  1590. '-Wno-format',
  1591. '-Wno-parentheses',
  1592. '-Wno-unknown-warning-option',
  1593. ))
  1594. cxx_warnings += [
  1595. '-Wimport-preprocessor-directive-pedantic',
  1596. '-Woverloaded-virtual',
  1597. '-Wno-ambiguous-reversed-operator',
  1598. '-Wno-defaulted-function-deleted',
  1599. '-Wno-deprecated-anon-enum-enum-conversion',
  1600. '-Wno-deprecated-enum-enum-conversion',
  1601. '-Wno-deprecated-enum-float-conversion',
  1602. '-Wno-deprecated-volatile',
  1603. '-Wno-undefined-var-template',
  1604. ]
  1605. if self.tc.ide_msvs:
  1606. cxx_warnings += [
  1607. '-Wno-unused-command-line-argument',
  1608. ]
  1609. win_version_min = self.WindowsVersion.Windows07
  1610. defines.append('/D_WIN32_WINNT={0}'.format(win_version_min))
  1611. if winapi_unicode:
  1612. defines += ['/DUNICODE', '/D_UNICODE']
  1613. else:
  1614. defines += ['/D_MBCS']
  1615. vc_include = os.path.join(self.tc.vc_root, 'include') if not self.tc.ide_msvs else "$(VC_VC_IncludePath.Split(';')[0].Replace('\\','/'))"
  1616. if not self.tc.ide_msvs:
  1617. def include_flag(path):
  1618. return '{flag}"{path}"'.format(path=path, flag='/I ' if not self.tc.use_clang else '-imsvc')
  1619. for name in ('shared', 'ucrt', 'um', 'winrt'):
  1620. flags.append(include_flag(os.path.join(self.tc.kit_includes, name)))
  1621. flags.append(include_flag(vc_include))
  1622. if self.tc.use_clang:
  1623. emit('CLANG_CL', 'yes')
  1624. if self.tc.ide_msvs:
  1625. emit('IDE_MSVS', 'yes')
  1626. if self.tc.use_arcadia_toolchain:
  1627. emit('USE_ARCADIA_TOOLCHAIN', 'yes')
  1628. emit('CXX_COMPILER', self.tc.cxx_compiler)
  1629. emit('C_COMPILER', self.tc.c_compiler)
  1630. emit('MASM_COMPILER', self.tc.masm_compiler)
  1631. append('C_DEFINES', defines)
  1632. append('C_WARNING_OPTS', c_warnings)
  1633. emit('_CXX_DEFINES', cxx_defines)
  1634. append('CXX_WARNING_OPTS', cxx_warnings)
  1635. if self.build.is_release:
  1636. emit('CFLAGS_PER_TYPE', '$CFLAGS_RELEASE')
  1637. if self.build.is_debug:
  1638. emit('CFLAGS_PER_TYPE', '$CFLAGS_DEBUG')
  1639. if self.build.is_ide:
  1640. emit('CFLAGS_PER_TYPE', '@[debug|$CFLAGS_DEBUG]@[release|$CFLAGS_RELEASE]')
  1641. emit('_STD_CXX', '/std:{}'.format(self.tc.cxx_std))
  1642. emit('_MSVC_FLAGS', flags)
  1643. ucrt_include = os.path.join(self.tc.kit_includes, 'ucrt') if not self.tc.ide_msvs else "$(UniversalCRT_IncludePath.Split(';')[0].Replace('\\','/'))"
  1644. # clang-cl has '#include_next', and MSVC hasn't. It needs separately specified CRT and VC include directories for libc++ to include second in order standard C and C++ headers.
  1645. if not self.tc.use_clang:
  1646. emit('_CFLAGS_UCRT_VC_INCLUDES', '/DY_UCRT_INCLUDE="%s"' % ucrt_include, '/DY_MSVC_INCLUDE="%s"' % vc_include)
  1647. else:
  1648. emit('_CFLAGS_UCRT_VC_INCLUDES')
  1649. emit('WERROR_MODE', self.tc.werror_mode)
  1650. print('@import "${CONF_ROOT}/conf/compilers/msvc_compiler.conf"')
  1651. class MSVCLinker(MSVC, Linker):
  1652. def __init__(self, tc, build):
  1653. MSVC.__init__(self, tc, build)
  1654. Linker.__init__(self, tc, build)
  1655. def print_linker(self):
  1656. super(MSVCLinker, self).print_linker()
  1657. linker = self.tc.link
  1658. linker_lib = self.tc.lib
  1659. emit('LINK_LIB_CMD', linker_lib)
  1660. emit('LINK_EXE_CMD', linker)
  1661. if self.build.is_release:
  1662. emit('LINK_EXE_FLAGS_PER_TYPE', '$LINK_EXE_FLAGS_RELEASE')
  1663. if self.build.is_debug:
  1664. emit('LINK_EXE_FLAGS_PER_TYPE', '$LINK_EXE_FLAGS_DEBUG')
  1665. if self.build.is_ide and self.tc.ide_msvs:
  1666. emit('LINK_EXE_FLAGS_PER_TYPE', '@[debug|$LINK_EXE_FLAGS_DEBUG]@[release|$LINK_EXE_FLAGS_RELEASE]')
  1667. print('@import "${CONF_ROOT}/conf/linkers/msvc_linker.conf"')
  1668. # TODO(somov): Rename!
  1669. Compilers = {
  1670. 'gnu': (GnuToolchain, GnuCompiler, LD),
  1671. 'clang': (GnuToolchain, GnuCompiler, LD),
  1672. 'xcode': (GnuToolchain, GnuCompiler, LD),
  1673. 'msvc': (MSVCToolchain, MSVCCompiler, MSVCLinker),
  1674. }
  1675. class Ragel(object):
  1676. def __init__(self):
  1677. self.rlgen_flags = []
  1678. self.ragel_flags = []
  1679. self.ragel6_flags = []
  1680. def configure_toolchain(self, build, compiler):
  1681. if isinstance(compiler, MSVCCompiler):
  1682. self.set_default_flags(optimized=False)
  1683. elif isinstance(compiler, GnuCompiler):
  1684. self.set_default_flags(optimized=build.is_release and not build.is_sanitized)
  1685. else:
  1686. raise ConfigureError('Unexpected compiler {}'.format(compiler))
  1687. def set_default_flags(self, optimized):
  1688. if optimized:
  1689. self.rlgen_flags.append('-G2')
  1690. self.ragel6_flags.append('-CG2')
  1691. else:
  1692. self.rlgen_flags.append('-T0')
  1693. self.ragel6_flags.append('-CT0')
  1694. def print_variables(self):
  1695. emit('RLGEN_FLAGS', self.rlgen_flags)
  1696. emit('RAGEL_FLAGS', self.ragel_flags)
  1697. emit('RAGEL6_FLAGS', self.ragel6_flags)
  1698. class Python(object):
  1699. def __init__(self, tc):
  1700. self.python = None
  1701. self.flags = None
  1702. self.ldflags = None
  1703. self.libraries = None
  1704. self.includes = None
  1705. self.tc = tc
  1706. def configure_posix(self, python=None, python_config=None):
  1707. self.check_configuration()
  1708. python = python or preset('PYTHON_BIN') or which('python')
  1709. python_config = python_config or preset('PYTHON_CONFIG') or which('python-config')
  1710. if python is None or python_config is None:
  1711. return
  1712. # python-config dumps each option on one line in the specified order
  1713. config = get_stdout([python_config, '--cflags', '--ldflags', '--includes']) or ''
  1714. config = config.split('\n')
  1715. if len(config) < 3:
  1716. return
  1717. self.python = python
  1718. self.flags = config[0]
  1719. self.ldflags = config[1]
  1720. self.includes = config[2]
  1721. # Do not split libraries from ldflags.
  1722. # They are not used separately and get overriden together, so it is safe.
  1723. # TODO(somov): Удалить эту переменную и PYTHON_LIBRARIES из makelist-ов.
  1724. self.libraries = ''
  1725. def check_configuration(self):
  1726. if preset('USE_ARCADIA_PYTHON') == 'no':
  1727. # Set USE_LOCAL_PYTHON to enable configuration
  1728. # when we still using fixed OS SDK,
  1729. # but at the same time using Python from the local system.
  1730. #
  1731. # This configuration is not guaranteed to work,
  1732. # for example, if local and fixed OS SDKs differ much.
  1733. if preset('USE_LOCAL_PYTHON') == 'yes':
  1734. return
  1735. if not preset('USE_SYSTEM_PYTHON') and not self.tc.os_sdk_local:
  1736. raise Exception("Use fixed python (see https://clubs.at.yandex-team.ru/arcadia/15392) or set OS_SDK=local flag")
  1737. def print_variables(self):
  1738. variables = Variables({
  1739. 'PYTHON_BIN': self.python,
  1740. 'PYTHON_FLAGS': self.flags,
  1741. 'PYTHON_LDFLAGS': self.ldflags,
  1742. 'PYTHON_LIBRARIES': self.libraries,
  1743. 'PYTHON_INCLUDE': self.includes
  1744. })
  1745. variables.update_from_presets()
  1746. variables.reset_if_any(reset_value='PYTHON-NOT-FOUND')
  1747. variables.emit()
  1748. class Setting(object):
  1749. def __init__(self, key, auto=None, convert=None, rewrite=False):
  1750. self.key = key
  1751. self.auto = auto
  1752. self.convert = convert
  1753. self.preset = preset(key)
  1754. self.from_user = self.preset is not None
  1755. self.rewrite = rewrite
  1756. self._value = Setting.no_value
  1757. @property
  1758. def value(self):
  1759. if self._value is Setting.no_value:
  1760. self._value = self.calculate_value()
  1761. return self._value
  1762. def calculate_value(self):
  1763. if not self.from_user:
  1764. return self.auto if not callable(self.auto) else self.auto()
  1765. else:
  1766. return self.preset if not self.convert else self.convert(self.preset)
  1767. @value.setter
  1768. def value(self, value):
  1769. if self.from_user:
  1770. raise ConfigureError("Variable {key} already set by user to {old}. Can not change it's value to {new}".format(key=self.key, old=self._value, new=value))
  1771. self._value = value
  1772. def emit(self):
  1773. if not self.from_user or self.rewrite:
  1774. emit(self.key, self.value)
  1775. no_value = object()
  1776. class Cuda(object):
  1777. def __init__(self, build):
  1778. """
  1779. :type build: Build
  1780. """
  1781. self.build = build
  1782. self.have_cuda = Setting('HAVE_CUDA', auto=self.auto_have_cuda, convert=to_bool)
  1783. self.cuda_root = Setting('CUDA_ROOT')
  1784. self.cuda_version = Setting('CUDA_VERSION', auto=self.auto_cuda_version, convert=self.convert_major_version, rewrite=True)
  1785. self.cuda_architectures = Setting('CUDA_ARCHITECTURES', auto=self.auto_cuda_architectures, rewrite=True)
  1786. self.use_arcadia_cuda = Setting('USE_ARCADIA_CUDA', auto=self.auto_use_arcadia_cuda, convert=to_bool)
  1787. self.use_arcadia_cuda_host_compiler = Setting('USE_ARCADIA_CUDA_HOST_COMPILER', auto=self.auto_use_arcadia_cuda_host_compiler, convert=to_bool)
  1788. self.cuda_use_clang = Setting('CUDA_USE_CLANG', auto=False, convert=to_bool)
  1789. self.cuda_host_compiler = Setting('CUDA_HOST_COMPILER', auto=self.auto_cuda_host_compiler)
  1790. self.cuda_host_compiler_env = Setting('CUDA_HOST_COMPILER_ENV')
  1791. self.cuda_host_msvc_version = Setting('CUDA_HOST_MSVC_VERSION')
  1792. self.cuda_nvcc_flags = Setting('CUDA_NVCC_FLAGS', auto=[])
  1793. self.peerdirs = ['build/platform/cuda']
  1794. self.nvcc_flags = [
  1795. # Compress fatbinary to reduce size of .nv_fatbin and prevent problems with linking
  1796. #
  1797. # Idea comes from many resources, one of them is https://discourse.llvm.org/t/lld-relocation-overflows-and-nv-fatbin/58889/6
  1798. # Some sources suggest using `-Xfatbin=-compress-all`, other suggest using `-Xcuda-fatbinary --compress-all`
  1799. # We will use the same flag as in nixpkgs
  1800. # (https://github.com/NixOS/nixpkgs/pull/220402/files#diff-a38e6c4e8421c03dc6c2a60c9a172ceb4059048b65798e5d4a400a7a4a5720ffR167)
  1801. "-Xfatbin=-compress-all",
  1802. # Allow __host__, __device__ annotations in lambda declaration.
  1803. "--expt-extended-lambda",
  1804. # Allow host code to invoke __device__ constexpr functions and vice versa
  1805. "--expt-relaxed-constexpr",
  1806. # Allow to use newer compilers than CUDA Toolkit officially supports
  1807. "--allow-unsupported-compiler",
  1808. ]
  1809. if not self.have_cuda.value:
  1810. return
  1811. if self.cuda_host_compiler.value:
  1812. self.nvcc_flags.append('--compiler-bindir=$CUDA_HOST_COMPILER')
  1813. if self.use_arcadia_cuda.value:
  1814. self.cuda_root.value = '$CUDA_RESOURCE_GLOBAL'
  1815. if self.build.target.is_linux_x86_64 and self.build.tc.is_clang:
  1816. # TODO(somov): Эта настройка должна приезжать сюда автоматически из другого места
  1817. self.nvcc_flags.append('-I$OS_SDK_ROOT/usr/include/x86_64-linux-gnu')
  1818. def print_(self):
  1819. self.print_variables()
  1820. self.print_macros()
  1821. print('@import "${CONF_ROOT}/conf/compilers/nvcc.conf"')
  1822. def print_variables(self):
  1823. self.have_cuda.emit()
  1824. if not self.have_cuda.value:
  1825. return
  1826. if self.use_arcadia_cuda.value and self.cuda_host_compiler.value is None:
  1827. logger.warning('$USE_ARCADIA_CUDA is set, but no $CUDA_HOST_COMPILER')
  1828. self.setup_vc_root()
  1829. self.cuda_root.emit()
  1830. self.cuda_version.emit()
  1831. self.cuda_architectures.emit()
  1832. self.use_arcadia_cuda.emit()
  1833. self.use_arcadia_cuda_host_compiler.emit()
  1834. self.cuda_use_clang.emit()
  1835. self.cuda_host_compiler.emit()
  1836. self.cuda_host_compiler_env.emit()
  1837. self.cuda_host_msvc_version.emit()
  1838. self.cuda_nvcc_flags.emit()
  1839. emit('NVCC_UNQUOTED', self.build.host.exe('$CUDA_ROOT', 'bin', 'nvcc'))
  1840. emit('NVCC', '${quo:NVCC_UNQUOTED}')
  1841. emit('NVCC_FLAGS', self.nvcc_flags, '$CUDA_NVCC_FLAGS')
  1842. emit('NVCC_OBJ_EXT', '.o' if not self.build.target.is_windows else '.obj')
  1843. def print_macros(self):
  1844. mtime = ' '
  1845. if self.build.host_target[1].is_linux:
  1846. mtime = ' --mtime ${tool:"tools/mtime0"} '
  1847. if not self.cuda_use_clang.value:
  1848. cmd = '$YMAKE_PYTHON ${input:"build/scripts/compile_cuda.py"}' + mtime + '$NVCC $NVCC_STD $NVCC_FLAGS -c ${input:SRC} -o ${output;suf=${OBJ_SUF}${NVCC_OBJ_EXT}:SRC} ${pre=-I:_C__INCLUDE} --cflags $C_FLAGS_PLATFORM $CXXFLAGS $NVCC_STD $NVCC_CFLAGS $SRCFLAGS ${input;hide:"build/platform/cuda/cuda_runtime_include.h"} $CUDA_HOST_COMPILER_ENV ${kv;hide:"p CC"} ${kv;hide:"pc light-green"}' # noqa E501
  1849. else:
  1850. cmd = '$CXX_COMPILER --cuda-path=$CUDA_ROOT $C_FLAGS_PLATFORM -c ${input:SRC} -o ${output;suf=${OBJ_SUF}${NVCC_OBJ_EXT}:SRC} ${pre=-I:_C__INCLUDE} $CXXFLAGS $SRCFLAGS $TOOLCHAIN_ENV ${kv;hide:"p CU"} ${kv;hide:"pc green"}' # noqa E501
  1851. emit('_SRC_CU_CMD', cmd)
  1852. emit('_SRC_CU_PEERDIR', ' '.join(sorted(self.peerdirs)))
  1853. # This method is only used to set HAVE_CUDA=no automatically during ymake initialization
  1854. # (i.e. is used only in `auto_have_cuda` invocation)
  1855. def have_cuda_in_arcadia(self):
  1856. host, target = self.build.host_target
  1857. if not any((host.is_linux_x86_64, host.is_windows_x86_64)):
  1858. return False
  1859. if host != target:
  1860. if not(host.is_linux_x86_64 and target.is_linux_armv8):
  1861. return False
  1862. if not self.cuda_version.from_user:
  1863. return False
  1864. if self.cuda_version.value in ('8.0', '9.0', '9.1', '9.2', '10.0', '10.1'):
  1865. raise ConfigureError('CUDA versions 8.x, 9.x and 10.x are no longer supported.\nSee DEVTOOLS-7108 and DTCC-2118.')
  1866. if self.cuda_version.value in ('11.0', '11.1', '11.3', '11.4', '11.8', '12.1'):
  1867. return True
  1868. return False
  1869. def auto_have_cuda(self):
  1870. if is_positive('MUSL'):
  1871. return False
  1872. if self.build.is_sanitized:
  1873. return False
  1874. return self.cuda_root.from_user or self.use_arcadia_cuda.value and self.have_cuda_in_arcadia()
  1875. def auto_cuda_version(self):
  1876. if self.use_arcadia_cuda.value:
  1877. return '11.4'
  1878. if not self.have_cuda.value:
  1879. return None
  1880. nvcc_exe = self.build.host.exe(os.path.expanduser(self.cuda_root.value), 'bin', 'nvcc')
  1881. def error():
  1882. raise ConfigureError('Failed to get CUDA version from {}'.format(nvcc_exe))
  1883. version_output = get_stdout([nvcc_exe, '--version']) or error()
  1884. match = re.search(r'^Cuda compilation tools, release (\d+)\.\d+,', version_output, re.MULTILINE) or error()
  1885. return match.group(1)
  1886. def convert_major_version(self, value):
  1887. if value == '10':
  1888. return '10.1'
  1889. elif value == '11':
  1890. return '11.3'
  1891. else:
  1892. return value
  1893. def auto_cuda_architectures(self):
  1894. # empty list does not mean "no architectures"
  1895. # it means "no restriction -- any available architecture"
  1896. host, target = self.build.host_target
  1897. if not target.is_linux_x86_64:
  1898. # do not impose any restrictions, when build not for "linux 64-bit"
  1899. return ''
  1900. # Equality to CUDA 11.4 is rather strict comparison
  1901. # TODO: find out how we can relax check (e.g. to include more version of CUDA toolkit)
  1902. if self.cuda_version.value == '11.4':
  1903. # * use output of CUDA 11.4 `nvcc --help`
  1904. # * drop support for '53', '62', '72' and '87'
  1905. # (these devices run only on arm64)
  1906. # * drop support for '37'
  1907. # the single place it's used in Arcadia is https://a.yandex-team.ru/arcadia/sdg/sdc/third_party/cub/common.mk?rev=r13268523#L69
  1908. return ':'.join(
  1909. ['sm_35',
  1910. 'sm_50', 'sm_52',
  1911. 'sm_60', 'sm_61',
  1912. 'sm_70', 'sm_75',
  1913. 'sm_80', 'sm_86',
  1914. 'compute_86'])
  1915. else:
  1916. return ''
  1917. def auto_use_arcadia_cuda(self):
  1918. return not self.cuda_root.from_user
  1919. def auto_use_arcadia_cuda_host_compiler(self):
  1920. return not self.cuda_host_compiler.from_user and not self.cuda_use_clang.value
  1921. def auto_cuda_host_compiler(self):
  1922. if not self.use_arcadia_cuda_host_compiler.value:
  1923. return None
  1924. host, target = self.build.host_target
  1925. if host.is_windows_x86_64 and target.is_windows_x86_64:
  1926. return self.cuda_windows_host_compiler()
  1927. return select((
  1928. (host.is_linux_x86_64 and target.is_linux_x86_64, '$CUDA_HOST_TOOLCHAIN_RESOURCE_GLOBAL/bin/clang'),
  1929. (host.is_linux_x86_64 and target.is_linux_armv8, '$CUDA_HOST_TOOLCHAIN_RESOURCE_GLOBAL/bin/clang'),
  1930. ))
  1931. def cuda_windows_host_compiler(self):
  1932. vc_version = '14.28.29910'
  1933. env = {
  1934. 'Y_VC_Version': vc_version,
  1935. 'Y_VC_Root': '$CUDA_HOST_TOOLCHAIN_RESOURCE_GLOBAL/VC/Tools/MSVC/{}'.format(vc_version),
  1936. 'Y_SDK_Version': self.build.tc.sdk_version,
  1937. 'Y_SDK_Root': '$WINDOWS_KITS_RESOURCE_GLOBAL',
  1938. }
  1939. if not self.build.tc.ide_msvs:
  1940. self.peerdirs.append('build/internal/platform/msvc')
  1941. self.cuda_host_compiler_env.value = format_env(env)
  1942. self.cuda_host_msvc_version.value = vc_version
  1943. return '%(Y_VC_Root)s/bin/HostX64/x64/cl.exe' % env
  1944. def setup_vc_root(self):
  1945. if not self.cuda_host_compiler.from_user:
  1946. return # Already set in cuda_windows_host_compiler()
  1947. if self.cuda_host_compiler_env.from_user:
  1948. return # We won't override user setting
  1949. def is_root(dir):
  1950. return all(os.path.isdir(os.path.join(dir, name)) for name in ('bin', 'include', 'lib'))
  1951. def get_root():
  1952. path, old_path = os.path.normpath(self.cuda_host_compiler.value), None
  1953. while path != old_path:
  1954. if is_root(path):
  1955. return path
  1956. path, old_path = os.path.dirname(path), path
  1957. vc_root = get_root()
  1958. if vc_root:
  1959. self.cuda_host_compiler_env.value = format_env({'Y_VC_Root': vc_root})
  1960. class CuDNN(object):
  1961. def __init__(self, cuda):
  1962. """
  1963. :type cuda: Cuda
  1964. """
  1965. self.cuda = cuda
  1966. self.cudnn_version = Setting('CUDNN_VERSION', auto=self.auto_cudnn_version)
  1967. def have_cudnn(self):
  1968. return self.cudnn_version.value in ('7.6.5', '8.0.5')
  1969. def auto_cudnn_version(self):
  1970. return '8.0.5'
  1971. def print_(self):
  1972. if self.cuda.have_cuda.value and self.have_cudnn():
  1973. self.cudnn_version.emit()
  1974. def customization():
  1975. if not is_positive('DISABLE_YMAKE_CONF_CUSTOMIZATION'):
  1976. try:
  1977. sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'internal'))
  1978. from custom_conf import CustomConf
  1979. logger.debug('Customization extension was successfully loaded')
  1980. return CustomConf
  1981. except Exception as e:
  1982. logger.debug('Customization extension was not found; [{}]'.format(str(e)))
  1983. else:
  1984. logger.debug('Customization extension was disabled')
  1985. class DummyConf:
  1986. def __init__(self, options):
  1987. pass
  1988. def print_prologue(self):
  1989. pass
  1990. def print_epilogue(self):
  1991. pass
  1992. return DummyConf
  1993. def main():
  1994. options = opts()
  1995. CustomConfig = customization()
  1996. custom_conf = CustomConfig(options)
  1997. arcadia = Arcadia(options.arcadia_root)
  1998. ymake = YMake(arcadia)
  1999. ymake.print_core_conf()
  2000. _INTERNAL_CONF = 'internal/conf/internal.conf'
  2001. internal_conf_full_path = find_conf(_INTERNAL_CONF)
  2002. if internal_conf_full_path and not is_positive('DISABLE_YMAKE_CONF_CUSTOMIZATION'):
  2003. print('@import "${{CONF_ROOT}}/{}"'.format(_INTERNAL_CONF))
  2004. custom_conf.print_prologue()
  2005. ymake.print_presets()
  2006. ymake.print_settings()
  2007. build = Build(arcadia, options.build_type, options.toolchain_params, force_ignore_local_files=not options.local_distbuild)
  2008. build.print_build()
  2009. custom_conf.print_epilogue()
  2010. if __name__ == '__main__':
  2011. main()