ymake_conf.py 93 KB

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