ymake_conf.py 96 KB

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