ymake_conf.py 96 KB

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