ymake_conf.py 93 KB

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